python - 检查python脚本是否正在运行

标签 python process daemon

我有一个 python 守护程序作为我的网络应用程序的一部分运行/我如何快速检查(使用 python)我的守护程序是否正在运行,如果没有,启动它?

我想这样做来修复守护程序的任何崩溃,因此脚本不必手动运行,它会在调用时自动运行,然后继续运行。

如果我的脚本正在运行,我如何检查(使用 python)?

最佳答案

在 Linux 系统上很方便的一种技术是使用域套接字:

import socket
import sys
import time

def get_lock(process_name):
    # Without holding a reference to our socket somewhere it gets garbage
    # collected when the function exits
    get_lock._lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)

    try:
        # The null byte (\0) means the socket is created 
        # in the abstract namespace instead of being created 
        # on the file system itself.
        # Works only in Linux
        get_lock._lock_socket.bind('\0' + process_name)
        print 'I got the lock'
    except socket.error:
        print 'lock exists'
        sys.exit()


get_lock('running_test')
while True:
    time.sleep(3)

它是原子的,并且避免了如果您的进程收到 SIGKILL 时出现锁定文件的问题

您可以read in the documentation for socket.close垃圾收集时套接字会自动关闭。

关于python - 检查python脚本是否正在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/788411/

相关文章:

python - 您可以在 Databricks 池节点上预安装库吗?

ruby - 多处理器/多线程Ruby Web服务器如何工作?

c++ - 从内存中运行进程 C/C++

php - 在 Ubuntu 上启动简单的 php 守护进程

python - 如何加入字符串列表并删除重复的字母(使它们保持链接状态)

python - 在数组/序列中找到等于总和的最短组合

python - matplotlib 中的 Widget 可以自动定位吗?

c++ - 如何在 C++ 中运行另一个应用程序并与之通信,跨平台

python - Python进程作为适当的守护程序(以及Windows服务)

testing - 在各种配置下测试守护进程的黑盒行为