Bin Chen
Bin Chen

Reputation: 63299

python: how to write daemon in Linux

I have a .py file that is ran by:

python a.py &

I am using a ssh to run the command, after it I have to log off. I find after some time the process is exited. I suspect it's Linux send some signal to it? I think if I can make the daemon then I can avoid this?

Upvotes: 3

Views: 3805

Answers (5)

AzP
AzP

Reputation: 1101

You can also use the screen utility, allowing you to access multiple separate terminal sessions inside a single terminal window or remote terminal session.

This means that you can setup a screen session (with a name of your choice), start a program within it (for example using &), detach from the session, and reconnect at a later time.

To start an unnamed screen.

$ screen

To create a new session with a specific name use:

$ screen -S backup

-these both commands create a new persistent session, and you can use it as a regular terminal window, i.e., issue commands and run scripts.

If you want to leave the session without terminating it, use:

Ctrl+a d command (press and hold Ctrl, press and hold a, then press d) to detach from the session.

To see the list of runnging screens:

$ screen -ls 

To attach a running screen to the console:

$ screen -R

The following key-combinations can be used, when a screen is running, and is attached to the console. All key kombinations begin with pressing control and a simultaneously.

ctrl+a d - detach the screen, and let it run without user interface (as described above)
ctrl+a c - create a new terminal
ctrl+a A - set the name of the current terminal
ctrl+a n - switch to next terminal
ctrl+a p - switch to prev terminal
ctrl+a " - list the of terminals

Upvotes: 2

Martin Carpenter
Martin Carpenter

Reputation: 5951

I've been very happy with daemonize.py from Brian Clapper, based on FreeBSD's daemon(1):

http://software.clapper.org/daemonize/

http://github.com/bmc/daemonize

Since January 2009 there is PEP 3143 which contains links to a proposed reference implementation, design goals, citations (Stevens) and other sources.

Upvotes: 4

Maxim Razin
Maxim Razin

Reputation: 9466

This implementation looks reasonable: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/

Upvotes: 5

wm_eddie
wm_eddie

Reputation: 3958

Although nohup will work, it's a quick and dirty solution. To make a proper daemon process you need to use SysV init or (If you are running Ubuntu 6.10+ or Fedora 9+) upstart.

Here's a simple script that starts a.py and restarts it whenever it gets killed (up to 5 times inside a 5 minute span):

respawn

respawn limit 5 300

exec python /path/to/a.py

Then just put that script in /etc/init/.

Upstart has a lot more options too. Checkout the Quick Start tutorial.

Upvotes: 7

Adam Hupp
Adam Hupp

Reputation: 1573

Run it with 'nohup' to ignore signals when your shell exits:

nohup python a.py &

Upvotes: 3

Related Questions