How to background a running process over SSH
Today I was logged in on my FreeNAS server to setup Duplicity backups. After initial success on a small dataset of about 100MB, I cloned my configuration to backup my long term storage dataset. It contains about 50GB of data - or so I thought. It turns out there’s over 500GB there.
I let the job run throughout the day, not minding it much. But then time comes to close my SSH connection, and I know what that means: the process will be killed. And I really do not want to kill this running backup.
I know about
nohup. Even about
<command> &. But alas it’s too late for that.
Luckily, there’s solution to this (if you’re running Bash or Zsh at least, I didn’t do a compatibility chec).
Your process is probably running in the foreground, so you’ll need to background it. There are two steps to this.
- Stop your process with
Ctrl-Z. This basically pauzes the process, it does not kill it.
- Background the process by issueing the
bgcommand. This will continue the process where it left off in the background. No harm done.
The final step is to use
disown to remove the job from the current shell. This means than when the shell is killed when you sign off, the process is not killed as well.
You can use
jobs -l on FreeBSD) to see a list of current jobs and their process ID. To disown a process, use
disown -h <process id>.
That’s all. Your process has now been removed from your shell session and is running happily in the background.
In case you can’t use
Ctrl-Z, you can log in with another SSH session and use the
kill command to stop and continue the process that way.
- Sign in with another session and use
psto find the process ID.
kill -SIGSTOP <process id>to stop the process
kill -SIGCONT <process id>to continue the process in the background.
disownas described above to disconnect the process from it’s parent shell process.
This approach does not with all processes, namely those that require access to the TTY to function.
vim is a good example of this. If you background Vim, it will be stopped and you cannot disown it.