Will a job put in background continue running after an SSH session is closed?

7

2

I have an AWS instance, and there I some tasks that I need to complete that will take some time.

If I run these before commuting to/from work (e.g. wget <someStuff>), then commit it to background CtrlZ » bg to check it starts properly), then exit my SSH session, will the wget command carry on in the background?

Or does it stop with my session closure?

MHibbin

Posted 2012-09-13T15:45:37.433

Reputation: 195

Answers

10

Just putting it in the background won't cause it to stay in the background after you exit the ssh session.

Backgrounding it just detaches the stdin pipe from the console. The process is still a child of the shell process, e.g. bash. Standard procedure on Linux/UNIX is that terminating a parent shell process gracefully causes all child processes to receive a SIGHUP signal. Almost all standard processes will process that signal as a request to terminate the process, although a process can ignore the SIGHUP signal and continue running. It could also do something completely different, like turn on your microwave, or make a rover on the moon drill into the ground, or start your car, or delete all files on the system. It's a signal, meaning that it's just a type of advisory command sent to the process. The process can do whatever it wants with that.

This is what you need to understand: because processing SIGHUP is equivalent to saying "please terminate your program now", something can easily ignore that "nice request" and continue running. So there are several dedicated programs that are designed specifically to allow the process to keep running even if the shell terminates. When your SSH connection disconnects, by the way, the shell process does terminate as part of your logout sequence.

GNU screen is one such command; nohup is another. screen is more flexible in general and very useful for this particular task. bg is not suitable because the child process will "honor" SIGHUP if it's not wrapped in a process that is designed to ignore SIGHUP, such as screen. nohup is the most basic SIGHUP-ignoring process, as that is basically its only functionality, other than writing the child process's output to a file.

Also see this question which is basically an exact duplicate but on ServerFault.

allquixotic

Posted 2012-09-13T15:45:37.433

Reputation: 32 256

4Also worth checking out disown – slhck – 2012-09-13T15:52:56.973

3

Wget in particular will automatically continue in the background if you just close the SSH session, without any need for further actions. It even creates a wget-log file, as if you started it with the -b switch.

In general, programs that are stopped or in the background will exit when you close the SSH session.

Dennis

Posted 2012-09-13T15:45:37.433

Reputation: 42 934

Interesting. I did not know that wget ignores SIGHUP. – allquixotic – 2012-09-13T15:58:07.343