What does GNU mean by this line (from here)?
The shell must also check on the status of background jobs so that it can report terminated and stopped jobs to the user; this can be done by calling waitpid with the
WNOHANG
option.
I don't understand why the shell should alert the user about background processes before executing. What would that look like too? Like, call ls, but a background process completed, so that process' status is printed before ls?
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.