3

Possible Duplicates:
How to keep program running after ssh disconnection.
How can I use ssh to run a command on a remote Unix machine and exit before the command completes?

I am running a mongo server on a production machine. I access it via an ssh console. If I run the mongo server, it runs in the foreground. If I close the SSH window on my client, the mongo process dies on the server.

Even if I run it as "mongod &" in the background, it still dies if the connection is lost.

How do I run this daemon correctly so that it does not depend on an active SSH session?

edit: using ubuntu 10 console as the server

1
  • yes duplicate...there were good answers on that link - check them out Jan 21, 2011 at 12:52

2 Answers 2

6

When you close a shell out, it sends SIGHUP signal to all jobs that it's spawned. By default, SIGHUP will terminate any process.

If you know you need to 'keep it running' when you spawn the process, you can use nohup to spawn your process. As a side effect, it will redirect stdout and stderr to a file nohup.out if these streams were pointing to the terminal. You may want to redirect these yourself if you don't want this file.

You can also run it using setsid, which creates a new process group. Your shell will no longer send SIGHUP to it since it's not in the shell's process group.

If you've already started your program, and you happen to be running bash or zsh (very likely on Linux), you can use disown.

Either run the command with & to force background, or run it normally type Ctrl-Z to suspend it, then bg %1 (assuming it's job #1) to take it out of suspension and run it as a background process. Then you type disown %1 to make bash/zsh forget about it.

disown is my usual method, I don't need to remember to mess with output streams like nohup requires.

1
  • +1 for setsid. I don't understand it fully, but it looks like it Just Works (TM). Sep 14, 2014 at 10:52
2

Try using nohup mongod &. This will prevent the program from receiving SIGHUP signals which are sent when the shell exits (after the connection is lost). This is a standard shell builtin in all shells.

You could also use setsid mongod & which would disassociate the program from the terminal, so when the shell exits, a SIGHUP signal is not sent. (Other things happen as well, but this is the primary side-effect.) Setsid is not standard in all shells, but it is in bash on Ubuntu 10.

You could also start gnu-screen, which will keep the session running after the connection is lost, allowing you to reconnect and interact with the shell again. The state of the program will not change, it will continue running while disconnected.

Not the answer you're looking for? Browse other questions tagged .