AKZN Notes

Archives for My Lazy and Forgetful Mind

Keep Processes Running After Ending SSH Session

Problem

Let's say I launch a bunch of processes from a ssh session. Is it possible to terminate the ssh session while keeping those processes running on the remote machine?

Solution

1. Using built-in bash command

For new task nohup
nohup long-running-command &

It was made specifically for this, it even logs stdout to nohup.log.

man nohup
For task that already running bg + disown
ctrl+z
bg
disown -h [process pid optional, defaults to last]

If you want to "background" already running tasks, then Ctrl+Z then run bg to put your most recent suspended task to background, allowing it to continue running. disown will keep the process running after you log out. The -h flag prevents hangup.

2. Using tmux (need install tmux first)

you would need to do the following:

  • ssh into the remote machine
  • start tmux by typing tmux into the shell
  • start the process you want inside the started tmux session
  • leave/detach the tmux session by typing Ctrl+b and then d

You can now safely log off from the remote machine, your process will keep running inside tmux. When you come back again and want to check the status of your process you can use tmux attach to attach to your tmux session.

If you want to have multiple sessions running side-by-side, you should name each session using Ctrl+b and $. You can get a list of the currently running sessions using tmux list-sessions, now attach to a running session with command tmux attach-session -t <session-name>.

tmux can do much more advanced things than handle a single window in a single session. For more information have a look in man tmux or the tmux GitHub page. In particular, here's an FAQ about the main differences between screen and tmux.


source stackoverflow

Leave a Reply

Your email address will not be published.