5

Weird question here, but I'm playing with a python chat server/client combo on my Linux server. Currently, if I do this:

$: cd /path/to/chat/server
$: sudo python ChatServer_Listen.py

This starts the python app run loop and the server listens for incoming TCP connections.

My problem is, if I close my terminal window, the ssh session quits and the python app stops running, and clients can no longer connect. I'd rather not run a terminal instance 24/7 locally. Can I set up this python app as something that can run in the background on Linux? If so, how? Ideally it would be sort of like Apache which just runs as a service.

Thanks for helping me out!

EEAA
  • 108,414
  • 18
  • 172
  • 242
Daddy
  • 237
  • 1
  • 4
  • 10

5 Answers5

8

You can use nohup python ChatServer_Listen.py &

nohup will log your program output to nohup.out file.

To stop your program you have to use kill your_pid command.

1

You want to use Supervisor. It's made exactly for this purpose, plus it will do things like restart the process if it dies, provide a web-based GUI to control it, etc.

jamieb
  • 3,387
  • 4
  • 24
  • 36
1

An easy way to keep a process alive after you log off is to use screen.

AnonymousLurker
  • 141
  • 1
  • 5
  • When I try this, sudo screen python Chatserver_Listen.py, the next line says "[screen is terminating]". The python app begins as normal, but using another terminal instance and "sudo screen -r python" returns "There is no screen to be resumed matching python." – Daddy Jul 21 '12 at 23:30
1

Like explained here :

https://stackoverflow.com/questions/625409/how-do-i-put-an-already-running-process-under-nohup

"

Using the Job Control of bash to send the process into the background:

[crtl]+z

bg

And as Sam/Jan mentioned you have to execute disown to avoid killing the process after you close the terminal.

disown -h

"

denizeren
  • 329
  • 3
  • 11
  • This is what works for me. Can you explain the disown -h command and what it actually does? My flowchart was like this: 1) run python app, 2) press ctrl+z [app is suspended?],3) type bg [console prints something regarding python], 4) type disown -h [console prints nothing]. It seems to be working though, I closed the terminal window and the server is still listening and accepting clients – Daddy Jul 21 '12 at 23:37
1

The right way to do this is to change the code to daemonize the process correctly. One way to do this is to use the daeminize module.

The expedient way to do this, which also works with software that you cannot modify, is to start it like this

nohup python ChatServer_Listen.py >logfile.txt 2>&1 </dev/null &

Note that I didn't use sudo. That is because you should put the above line in a shell script and run the shell script with sudo.

Michael Dillon
  • 1,809
  • 13
  • 16