14
votes
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>

int main(){
pid_t pid;
pid = fork();
if(pid<0){
   fprintf(stderr, "fork failed");
   return 1;    }
else if(pid == 0){  
   execlp("bin/ls", "ls", NULL);}
else{
   wait(NULL);
   printf("child complete\n");
   }
return 0;
}

Here as far as I could understand, a child process is created and since its pid returned by fork is "0", it enters the block containing execlp and executes it, and then the parent waits till the child exits and then prints "child complete". Please correct me if I'm wrong. But I didnt understand how execlp() works here. Can someone explain this?

2

2 Answers

29
votes

fork creates a new process, it is called once by the parent but returns twice in the parent and in the child.

In the child process the call execlp executes the specified command ls.

This replaces the child process with the new program file (ls program file) which means following.

When a process calls the execlp or one of the other 7 exec functions, that process is completely replaced by the new program, and the new program starts executing at its main function.

The process ID does not change across an exec, because a new process is not created. exec merely replaces the current process's text, data, heap, and stack segments with a brand new program from disk.

The combination of fork followed by exec is called spawning a new process on some operating systems.

Hopefully it was more or less clear. Let me know if you have more questions.

1
votes

The exec() family of functions replaces the current process image with a new process image.