0

From the wait() man page

The wait() system call suspends execution of the calling thread until one of its children terminates.

Regarding why to use wait(), it says

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

So, it is a good practice to use wait() & wait() is blocking command. That is what I derive from the man page.

How to use wait() but in a non-blocking way so that the calling thread can go about its business & when child state changes, it gets notified.

KharoBangdo
  • 321
  • 5
  • 14
  • 2
    From wait man page "WNOHANG return immediately if no child has exited." (use `waitpid()`, `wait()` is obsolete) – Stargateur Jun 29 '18 at 05:47
  • @Stargateur if I use **wait()** it will always be blocking but if I use **waitpid()** I have the option of making it non-blocking right? – KharoBangdo Jun 29 '18 at 05:53
  • 1
    *"when child state changes, it gets notified"* – That's what `SIGCHLD` is for. – Martin R Jun 29 '18 at 06:45
  • @MartinR so, you are saying I should use **SIGCHLD** to ignore all children so that I don't have to **wait()**. If my parent has a loop of instructions it's supposed to perform, then call **wait()** at the end to see if any child is dead & if yes than release resource of that child. Is that correct? – KharoBangdo Jun 29 '18 at 07:02
  • 2
    What I (roughly) mean is that you register a signal handler for SIGCHLD, and set a flag if it is called. In your main event loop check if the flag is set – then you can safely call wait(). – Martin R Jun 29 '18 at 07:07
  • See also https://stackoverflow.com/questions/7171722/how-can-i-handle-sigchld-in-c. – Martin R Jun 29 '18 at 07:20

1 Answers1

1

wait() is always blocking.
waitpid() can be used for blocking or non-blocking.

we can use waitpid() as a non-blocking system call with the following format:

int pid = waitpid(child_pid, &status, WNOHANG);

WNOHANG-->Returns immediately regardless of the child’s status.

Reference:https://www-users.cs.umn.edu/~kauffman/4061/04-making-processes.pdf
Page no:13 (Non-Blocking waitpid()).

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26