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

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?


Solution 1:

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.

Solution 2:

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.