SSH Signals – When SIGHUP is Not Sent to a Job on Logout

signalssshtty

I read an answer from a user who claimed that running

foo 2>&1 >& output.log &

would result in foo continuing to run even when they log out. According to this user, this even worked over SSH connections.

I didn't really believe that, as I was under the impression that in the case of disconnecting from SSH, or terminating the TTY, the shell and therefore its processes would receive a SIGHUP, causing them to terminate. This, under my assumption, was the sole reason for using nohup in such cases, or tmux, screen et al.

I then looked into glibc's manual:

This signal is also used to report the termination of the controlling process on a terminal to jobs associated with that session; this termination effectively disconnects all processes in the session from the controlling terminal.

This seems to confirm my thoughts. But looking further, it says:

If the process is a session leader that has a controlling terminal, then a SIGHUP signal is sent to each process in the foreground job, and the controlling terminal is disassociated from that session.

So, does this mean jobs put in background will not receive SIGHUP?

To my further confusion, I ran an interactive Zsh session, ran yes >& /dev/null &, and typed exit, when Zsh warned me that I had running jobs, and after typing exit for a second time, told me that it had SIGHUPed one job. Doing exactly the same in Bash leaves the job running…

Best Answer

Bash seems to send the SIGHUP only if it self received a SIGHUP, which for example occurs when a virtual terminal is closed or when the SSH connection is interrupted. From the documentation:

The shell exits by default upon receipt of a SIGHUP. Before exiting, an interactive shell resends the SIGHUP to all jobs, running or stopped. Stopped jobs are sent SIGCONT to ensure that they receive the SIGHUP. To prevent the shell from sending the SIGHUP signal to a particular job, it should be removed from the jobs table with the disown builtin (see Job Control Builtins) or marked to not receive SIGHUP using disown -h.

So if you type exit or press Ctrl+D all background process will remain, since this does not send a hang up signal to the Bash.

You can force Bash to warn you about the fact that there are still running background processes with

shopt -s checkjobs

There is an option to send the SIGHUP on exit if you are in an interactive shell(see here). But it doesn't work on my machine with Bash 4.2.25. Maybe it works for you

shopt -s huponexit
Related Question