KharoBangdo
KharoBangdo

Reputation: 321

How can I use wait() as a non-blocking command in Unix?

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.

Upvotes: 0

Views: 6033

Answers (1)

Krishna Kanth Yenumula
Krishna Kanth Yenumula

Reputation: 2567

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

Upvotes: 2

Related Questions