I have been learning about UNIX processes and could not understand one point. Say we have code like this,

void fork_child()
    if (fork() == 0) {
       /* Child */
       printf("Running Child, PID = %d\n",
       while (1)
           ; /* Infinite loop */
    } else {
       /* Parent */
       printf("Terminating Parent, PID = %d\n",

I know that we kill the child process explicitly because the parent dies before but when I run the code the shell does not wait for the while loop in the child process, it is more like running in background. What is the main reason of this issue?


  • The shell waits for its child, not for its child and any descendants that its child may have spawned. – Andy Dalton Feb 20 '18 at 18:52

You need to call wait()in the parent to block until the child is killed

See: http://man7.org/linux/man-pages/man2/waitpid.2.html


The shell itself doesn't really know about the children of the processes it starts. Say, the shell starts process A, which then starts process B and then A exits. What happens now, is that B continues running, but is made a child of init, PID 1. It doesn't become a child of the shell.

_exit(2) man page on Linux (there's similar wording in POSIX):

Any children of the process are inherited by init(1). The process's parent is sent a SIGCHLD signal.

Having parentless processes inherited by their grandparents would not be a good idea, as the new parent would need to be responsible for receiving SIGCHLD signals from and calling wait() on the child. Any program that executed any other program would then need to be prepared for handling arbitrary amounts of children.

Of course, if the child is holding on to a pipe the shell is still reading from, e.g. from command substitution, then the shell will have to wait, since it can know it has received all input only after the pipe closes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.