UNIX Process Creation

As discussed in the classroom, UNIX process creation is a bit of a weird process, since the only available system call is target at cloning the calling process. If a distinct process is to be created, the cloned process must itself replace its image with that of the target process. The following three programs exemplify the process.

Source Code

Parent Process Program

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
   pid_t pid;
   
   pid = fork();
   if(pid == -1) { /* fork has failed */
      printf("Error: can't create child process!\n");
      return -1;
   } else if(pid == 0) /* child */
      execl("child","child", (char *)0);
   else { /* parent */
      printf("Parent: I'm the parent process!\n");
      printf("Parent: My pid is %d.\n", getpid());
   }
   return 0;
}

Child Process Program

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
   pid_t pid, ppid;
   
   pid = getpid();
   ppid = getppid();
   printf("Child: I'm the child process!\n");
   printf("Child: My pid is %d.\n", pid);
   printf("Child: My parent's pid is %d.\n", ppid);
   return 0;
}

While reading the code, you should refer to the fork and execve system call man pages (i.e., man 2 fork and man 2 execve). In summary, line 9 in the parent program invokes the fork system call to clone the calling process. The unique difference between parent and child processes is the value returned by the system call, which will be "0" for the child process and the PID of the child process for the parent (or "-1" in case of failure).

Based on the return value of fork, the if in line 13 of the parent program identifies child and parent processes, letting the child invoke execl, a variant of the execve system call, to replace the image of the just created process by that of the child program.

You can download a compilable version of the example here. Simply extract the archive, call make and then run parent.

Exercise

Run parent several times and eventually the scheduler will change the execution order of parent and child, bringing about an unexpected behavior: child reporting its parent's PID as "1".

Try to explain this behavior and than modify the programs as to prevent it.

Solution

One solution to the problem raised above can be found here.