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.

6
  • 2
    From wait man page "WNOHANG return immediately if no child has exited." (use waitpid(), wait() is obsolete) Commented Jun 29, 2018 at 5: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? Commented Jun 29, 2018 at 5:53
  • 1
    "when child state changes, it gets notified" – That's what SIGCHLD is for. Commented Jun 29, 2018 at 6: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? Commented Jun 29, 2018 at 7: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(). Commented Jun 29, 2018 at 7:07

1 Answer 1

2

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()).

Sign up to request clarification or add additional context in comments.

1 Comment

If there is anything wrong with my answer, please tell me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.