Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if the child exits before the parent calls wait()?

Tags:

c

unix

I am learning the wait() method in C. And I know that it blocks the parent process until one of its child processes terminates. But what if the kernel decides to schedule the child first and the child process terminates before parent can call the wait()? Is that the parent will wait there forever(without other interrupts) since it can not observe the return of a child?

In the photo, if the execution sequence is: fork --> HC --> exit -->HP-->wait, then the situation I describe will happen. enter image description here

like image 633
folkboat Avatar asked May 06 '19 13:05

folkboat


2 Answers

No, the parent will not wait forever.

The documentation on wait states:

All of these system calls are used to wait for state changes in a child of the calling process, and obtain information about the child whose state has changed. A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal. In the case of a terminated child, performing a wait allows the system to release the resources associated with the child; if a wait is not performed, then the terminated child remains in a "zombie" state .

If a child has already changed state, then these calls return immediately.

like image 57
P.W Avatar answered Oct 19 '22 22:10

P.W


But what if the kernel decides to schedule the child first and the child process terminates before parent can call the wait()?

It is a pretty possible case. If one of the wait family functions is used by the parent or signal(SIGCHLD, SIG_IGN); is called explicitly before forking, it does not turn the child into a zombie even if the parent process is preempted(=not permitted to use CPU at that time).

Moreover, the need of wait or signal-ignorance mentioned is to clean process's unused datas. While using one of the methods, the kernel is told that the child(ren) process is not used anymore. So, you can cleanup unused system resources.

like image 2
snr Avatar answered Oct 19 '22 22:10

snr