When a child process is fork()
ed , then the parent process can wait()
for the child process to complete . Suppose , just for experimenting , instead of wait()
ing , if we make the parent process sleep()
, then why does not it work ?
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t child_id ;
child_id = fork() ;
if (child_id == 0)
{
printf("\nChild process");
printf("\nChild process exiting");
}
else
{
printf("\nParent process");
sleep(10);
printf("\nParent process exiting");
}
}
I guess SIGCHLD
signal is causing the the parent process to wake from sleep()
. But why , it is a child process , they have different address space and resources , then how can it interfere in the matters of parent process ?
Beware differences between systems. With this minor adaptation of your code, running on Mac OS X 10.9, the child dying does not affect the
sleep(10)
in the parent:As you can see, the parent exited 10 seconds or so later than the child did.
I got the same behaviour on a VM running an ancient version of Linux (2.6.16.60 kernel from 2008); the parent died 10 seconds after the child did.
So, if the behaviour you are asking "why does it not work?" is 'the parent exits immediately child dies', then your code does not prove that it does exit on either of two systems. I can't categorically say the parent doesn't die promptly on your system, but it would be unexpected.
You might find this program useful for studying the behaviour of SIGCHLD signals:
On Mac OS X 10.9 again, it produced:
The behaviour on Linux is similar — not quite identical:
Please read carefully the man pages of fork(2), execve(2), wait(2) ...
The
wait
syscall do much more than just passively waiting for a child process. It cleans internal kernel state to avoid zombie processes.Use also strace(1) e.g. as
strace -f
on your program.And take several hours to read a good book like e.g. Advanced Linux Programming. Understanding processes need many hours, and we have not that much time to teach it to you. Please read books and continue experimenting like you do! Also, take some time to read the source code of free software (like the source code of some shell -e.g.
bash
orsash
)BTW, you program is wrong on another point: you should always test for failure of
fork
(so always handle the three possible returns offork
:==0
in child process,>0
in parent process,<0
on failure). Consider using ulimit (which calls setrlimit(2) inside the shell) to trigger such an error condition for testing purposes.