diff --git a/content/posts/2019-08-28-how-to-background-a-running-process-over-ssh.md b/content/posts/2019-08-28-how-to-background-a-running-process-over-ssh.md new file mode 100644 index 0000000..ad9b434 --- /dev/null +++ b/content/posts/2019-08-28-how-to-background-a-running-process-over-ssh.md @@ -0,0 +1,42 @@ ++++ +date = "2019-08-28" +title = "How to background a running process over SSH" +tags = ["linux", "freebsd", "devops", "bash", "zsh"] +description = "I know about screen, and tmux, and nohup, but sometimes I'm working and start a command that is running longer than expected. What to do?" ++++ + +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 `screen`. And `tmux`. And `nohup`. Even about ` &`. 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). + +## 1. Background your running process + +Your process is probably running in the foreground, so you'll need to background it. There are two steps to this. + + 1. Stop your process with `Ctrl-Z`. This basically pauzes the process, it does not kill it. + 2. Background the process by issueing the `bg` command. This will continue the process where it left off in the background. No harm done. + +## 2. Disown the process + +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` (or `jobs -l` on FreeBSD) to see a list of current jobs and their process ID. To disown a process, use `disown -h `. + +That's all. Your process has now been removed from your shell session and is running happily in the background. + +## Bonus action: Background your process from _another_ SSH session + +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. + + 1. Sign in with another session and use `ps` to find the process ID. + 2. `kill -SIGSTOP ` to stop the process + 3. `kill -SIGCONT ` to continue the process in the background. + 4. Use `disown` as described above to disconnect the process from it's parent shell process. + +## Disclaimer + +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.