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.
1.
|
#include <sys/types.h> |
1.
|
#include <sys/types.h> |
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
.
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.
One solution to the problem raised above can be found here.