Detach processes from terminal

GNU screen/tmux

The best solution is simply to use a terminal multiplexer, like GNU screen or tmux. Simply launch a session, tape your command and then detach it (Ctrl-a d for screen). Easy and clean 😉

setsid

Debian contains a binary called setsid in the util-linux package. setsid can be use to start a process and detach it from the current shell (basically it create a new shell for the ‘orphaned’ process).

setsid doesn’t redirect the standard files descriptors (stdin, stdout and stderr) so you loose any process output except if you make a stdout+stderr redirection to a file:

setsid <command> > /tmp/output.txt &2>1

nohup

nohup as the name implies, makes your command ignore SIGHUP signal. Also by default nohup redirects the standard output and error to the file nohup.out, so the program won’t fail for writing to standard output when the shell is closed. Note that nohup doesn’t remove the process from the shell’s job control and also doesn’t put it in the background. Usage:

nohup <command> > /tmp/output.txt &

disown

Last option (and the more interesting) is the built-in bash command disown. disown removes the process from the shell’s job control, but still leaves it connected to the terminal. The results is that the shell won’t send it a SIGHUP when closed, but in the meantime you still get the output. The advantage is you can disown a already running program.

Simply suspend the program using Ctrl-z then use bg to put it in background. Then detach it:

disown %n

where n is the job number (use the command job to get it).