6

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

folkboat
  • 167
  • 1
  • 7

2 Answers2

5

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.

P.W
  • 26,289
  • 6
  • 39
  • 76
2

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.

  • Thanks! It's good to now that the child can still be reaped by the parent's call of wait() even the child exits before. But is it more proper to say that "it turns the child into a zombie for a short period of time if the parent is preempted, but when the parent calls wait(), the child can then be reaped by the parent(so not a zombie anymore)"? – folkboat May 06 '19 at 14:24
  • @folkboat yes, well-said. – Soner from The Ottoman Empire May 06 '19 at 15:51
  • @folkboat en passant, where do you get the image? I like its representation. – Soner from The Ottoman Empire May 06 '19 at 15:52
  • It's taken from the lecture slides of CSAPP from CMU. You can get more information from its website: [link](http://csapp.cs.cmu.edu/3e/home.html). It provides course videos and slides. And if you only want the slides, you can just download from this page:[link](http://cs.cmu.edu/afs/cs/academic/class/15213-f15/www/schedule.html) – folkboat May 07 '19 at 01:57