Coder's Cat

How to Keep A Program Running with Ssh logout

2021-11-25

Some times we need to keep jobs running without a ssh session, here there are three ways to achieve this. I suggest to learn a terminal multiplexer in long term, it’s really useful when you have long time working on Linux/Unix system.

Option 1: nohup

The best and simplest way is:

nohup long-running-command &

It was made specifically for this, by default it will log stdout to nohup.log, if standard output is not a terminal, logs will be appended to ~/nohup.log. If you want to specify the output log into a different file:

nohup COMMAND > FILE

More details can refer to man nohup. What nohup does, is to effectively separate the process from the terminal:

  • It closes standard input (the program will not be able to read any input, even if it is run in the foreground. it is not halted, but will receive an error code or EOF).
  • It redirects standard output and standard error to the file nohup.out, so the program won’t fail for writing to standard output if the terminal fails, so whatever the process writes is not lost.
  • It prevents the process from receiving a SIGHUP (thus the name).

Option 2: bg and disown

If you already have started the program and don’t want restart it, we can use ctrl+z to stop current execution and then use bg to resume it and switch the running program to background (We can use fg to pull the job to frontground)

Finally we use disown to remove the process from the shell’s job control.

So, even you logout from a ssh session, the program will still keep running in background.

ctrl+z
bg
disown -h

Option 3: Use terminal multiplexer

We have three choices for this, [[screen]], [[tmux]], and [[byobu]].

screen and tmux is mostly used ones. On Ubuntu or Debian system, we install it with:

sudo apt-get install screen 
sudo apt-get install tmux

Byobu is an enhancement for the GNU Screen, you can install it with this commands:

sudo add-apt-repository ppa:byobu/ppa
sudo apt-get update
sudo apt-get install byobu

From my user experience, tmux will be enough for daily usage, if you would like to have a try, refer to this guide: Gentle Guide to Get Started With tmux | Pragmatic Pineapple 🍍

Join my Email List for more insights, It's Free!😋