It's for implementing notifications like the following for background jobs:
$ cmd_1 &
$ cmd_2
$ cmd_3
[1]+ Done cmd_1
$
(Something like sleep 5
is a good cmd_1
to try this out with.)
In the above, it's assumed that the backgrounded cmd_1
job finishes while cmd_3
is being typed in or run. The notification is delivered afterwards, just before printing the last prompt above.
waitpid(2)
is used to wait for processes to change state (either terminate or stop or start, as in what e.g. Ctrl-Z
and fg
does).
To implement the display above, the shell can call waitpid(2)
to check if the background job has changed state each time before prompting for a new command. If it does this without passing WNOHANG
, then the waitpid()
call will block until the background job actually changes state, meaning the shell will be stuck until cmd_1
finishes before printing the second prompt. WNOHANG
makes the waitpid()
call non-blocking and allows the shell to "poll" for state changes in the job instead.