Keep processes running after SSH session disconnects

Use nohup to make your process ignore the hangup signal:

$ nohup long-running-process &
$ exit

You want to be using GNU Screen. It is super awesome!

ssh [email protected]
screen               #start a screen session
run-a-long-process

CTRL+a , d to detatch from your screen session

exit                 #disconnect from the server, while run-a-long-process continues

When you come back to your laptop:

ssh [email protected]
screen -r            #resume the screen session

Then check out the progress of your long-running process!

screen is a very comprehensive tool, and can do a lot more than what I've described. While in a screen session, try ctrl+a,? to learn a few common commands. Probably the most common are:

  • CTRL+a , c to create a new window
  • CTRL+a , n to switch to the next window in your screen session
  • CTRL+a , p to switch to the previous window in your screen session
  • if you log in from a bunch of different systems, you may have accidentally left yourself attached to an active screen session on a different computer. for that reason, I always resume with screen -d -r to ensure that if another shell is attached to my screen session, it will be detached before I resume it on my current system.

If you haven't planned ahead and setup screen, etc. just do the following:

  1. If your process is running in the background: goto #3, else: Ctrl-Z to suspend foreground process. This will report the job # of the suspended process, for example:

    [1]+  Stopped                 processName
    
  2. Send processName to the background with bg %1 (using whatever the job # is following the %). This will resume processName in the background.

  3. Disown processName with disown %1 or disown PID. Use the -h flag if you want to maintain ownership until you terminate your current shell.