user1384377
user1384377

Reputation: 147

Who waits for a shell background process?

I was wondering about this question:

If I type the following command in bash

# sleep 100 &

How come the shell knows to wait for it to end?

When the shell forks itself in order to exec the sleep command, doesn't the ampersand technically means it's not going to wait for that newly forked process? Nevertheless, it still waits for it (otherwise I would've seen it as a zombie, and I don't)

Feeling confused here :\

Upvotes: 2

Views: 1934

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295443

The shell gets a SIGCHLD when its child process exits; thus, it can immediately call wait4() in the signal handler to reap it.

If you run strace bash, you'll see something like the following:

--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=13708, si_status=0, si_utime=0, si_stime=0} ---
wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], WNOHANG, NULL) = 13708
wait4(-1, 0x7fffbca63110, WNOHANG, NULL) = -1 ECHILD (No child processes)

That is to say: The shell gets a signal that a child process exited; it calls wait4() without a PID, thus reaping the first dead child from its process table; and calls that again, and is informed that no dead children remain to be reaped.

This differs from the case where a process is run in the foreground, where a blocking wait() is run immediately.

Upvotes: 2

Related Questions