Python:如何在Linux中编写守护进程

3

我有一个.py文件,通过以下方式运行:

python a.py &

我使用ssh运行该命令,之后必须注销。过一段时间后,我发现进程已退出。我怀疑是Linux向其发送了某个信号?如果我能将其设置为守护程序,那么就可以避免这种情况。

5个回答

7
虽然 nohup 可以工作,但这只是一个快速而不够优雅的解决方案。要创建一个适当的守护进程,您需要使用 SysV init 或(如果您正在运行 Ubuntu 6.10+ 或 Fedora 9+)upstart。
以下是一个简单的脚本,它启动 a.py 并在每次被杀死时重新启动它(在 5 分钟内最多重启 5 次):
respawn

respawn limit 5 300

exec python /path/to/a.py

然后只需将该脚本放置在 /etc/init/ 中。

Upstart 还有更多选项。请查看快速入门教程。



4

3

使用“nohup”运行它,以忽略当您的shell退出时的信号:

nohup python a.py &

2

您还可以使用screen工具,在单个终端窗口或远程终端会话中访问多个独立的终端会话。

这意味着,您可以设置一个带有自定义名称的屏幕会话,在其中启动一个程序(例如使用&),从会话中分离,并在以后重新连接。

要启动未命名的屏幕,请执行以下操作。

$ screen

要创建一个指定名称的新会话,请使用以下命令:

$ screen -S backup

-这两个命令都会创建一个新的持久会话,您可以像使用常规终端窗口一样使用它,即发出命令并运行脚本。

如果您想离开会话但不终止它,请使用:

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

查看正在运行的屏幕列表:

$ screen -ls 

将正在运行的屏幕附加到控制台:

$ screen -R

当屏幕运行并连接到控制台时,可以使用以下组合键。所有组合键都以同时按下控制和 A 键开始。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接