I know that I can append &
to a command to run the process in the background.
I'm SSH'ing into an Ubuntu 12.04 box and running a python program with $python program.py &
-- but when I go to close the terminal window I get a message saying that closing the terminal will kill the running process.
Why is this? I am using the ampersand to run the process in the background. How can I get it to run regardless of if I am SSH'ed in?
When you close a terminal window, the terminal emulator sends a SIGHUP to the process it is running, your shell. Your shell then forwards that SIGHUP to everything it's running. On your local system, this is the ssh. The ssh then forwards the SIGHUP to what it's running, the remote shell. So your remote shell then sends a SIGHUP to all its processes, your backgrounded program.
There are 2 ways around this.
disown
command after backgrounding your process. This will make the shell forget about it.nohup
(nohup $python program.py &
). This accomplishes the same thing, but by using an intermediate process. Basically it ignores the SIGHUP signal, and then forks & executes your program which inherits the setting, and then exits. Because it forked, the program being launched is not a child of the shell, and the shell doesn't know about it. And unless it installs a signal handler for SIGHUP, it keeps the ignore action anyway.logout
instead of closing the terminal window. When you use logout
, this isn't a SIGHUP, and so the shell won't send a SIGHUP to any of its children.Additionally you must make sure that your program doesn't write to the terminal through STDOUT or STDERR, as both of those will no longer exist once the terminal exits. If you don't redirect them to something like /dev/null
, the program will still run, but if it tries to write to them, it'll get a SIGPIPE, and the default action of SIGPIPE is to kill the process).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments