python - 在 Python 中产生不确定的守护进程

标签 python fork subprocess daemon spawn

我正在尝试构建一个 Python 守护进程来启动其他完全独立的进程。

一般的想法是对于给定的 shell 命令,每隔几秒轮询一次,并确保恰好 k 个命令实例正在运行。我们保留一个 pidfile 目录,当我们轮询时,我们删除 pid 文件,其 pid 不再运行并启动(并为其创建 pidfile)无论我们需要达到 k 个进程。 p>

子进程也需要完全独立,这样如果父进程死了,子进程就不会被杀死。从我读过的内容来看,似乎没有办法用 subprocess 模块来做到这一点。为此,我使用了此处提到的代码段:

http://code.activestate.com/recipes/66012-fork-a-daemon-process-on-unix/

我做了一些必要的修改(您会在附加的代码片段中看到注释掉的行):

  1. 原始父进程无法退出,因为我们需要启动器守护进程无限期地存在。
  2. 子进程需要使用与父进程相同的 cwd 启动。

这是我的 spawn fn 和测试:

import os
import sys
import subprocess
import time

def spawn(cmd, child_cwd):
    """
    do the UNIX double-fork magic, see Stevens' "Advanced 
    Programming in the UNIX Environment" for details (ISBN 0201563177)
    http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
    """
    try: 
        pid = os.fork() 
        if pid > 0:
            # exit first parent
            #sys.exit(0) # parent daemon needs to stay alive to launch more in the future
            return
    except OSError, e: 
        sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
        sys.exit(1)

    # decouple from parent environment
    #os.chdir("/") # we want the children processes to 
    os.setsid() 
    os.umask(0) 

    # do second fork
    try: 
        pid = os.fork() 
        if pid > 0:
            # exit from second parent
            sys.exit(0) 
    except OSError, e: 
        sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
        sys.exit(1) 

    # redirect standard file descriptors
    sys.stdout.flush()
    sys.stderr.flush()
    si = file('/dev/null', 'r')
    so = file('/dev/null', 'a+')
    se = file('/dev/null', 'a+', 0)
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())

    pid = subprocess.Popen(cmd, cwd=child_cwd, shell=True).pid

    # write pidfile       
    with open('pids/%s.pid' % pid, 'w') as f: f.write(str(pid))
    sys.exit(1)

def mkdir_if_none(path):
    if not os.access(path, os.R_OK):
        os.mkdir(path)

if __name__ == '__main__':
    try:
        cmd = sys.argv[1]
        num = int(sys.argv[2])
    except:
        print 'Usage: %s <cmd> <num procs>' % __file__
        sys.exit(1)
    mkdir_if_none('pids')
    mkdir_if_none('test_cwd')

    for i in xrange(num):
        print 'spawning %d...'%i
        spawn(cmd, 'test_cwd')
        time.sleep(0.01) # give the system some breathing room

在这种情况下,事情似乎工作正常,即使父进程被杀死,子进程仍然存在。但是,我仍然遇到了原始 parent 的产卵限制。在 ~650 次生成后(不是同时发生,子进程已经完成),父进程因错误而窒息:

spawning 650...
fork #2 failed: 35 (Resource temporarily unavailable)

有什么方法可以重写我的生成函数,以便我可以无限期地生成这些独立的子进程吗?谢谢!

最佳答案

感谢your list of processes我愿意说这是因为您遇到了一些基本限制之一:

  • rlimit nproc 允许给定用户执行的最大进程数 -- 请参阅 setrlimit(2)bash(1) ulimit 内置,和 /etc/security/limits.conf 了解每个用户进程限制的详细信息。
  • rlimit nofile 允许给定进程一次打开的最大文件描述符数。 (每个新进程可能会在 parent 中为子进程的 stdinstdoutstderr 创建三个新管道描述符。)
  • 系统范围内的最大进程数;参见 /proc/sys/kernel/pid_max
  • 系统范围内打开文件的最大数量;参见 /proc/sys/fs/file-max

因为您没有收割死去的 child ,所以这些资源中的许多资源的开放时间都超过了应有的时间。您的 second child 正在由 init(8) 正确处理——他们的 parent 已经死了,所以他们被重新交给 init(8),并且 init(8) 将在它们死后清理它们 (wait(2))。

但是,您的程序负责在第一 组子级之后进行清理。 C 程序通常为调用 wait(2)waitpid(2)SIGCHLD 安装 signal(7) 处理程序> 获取 child 的退出状态,从而从内核内存中删除其条目。

但是脚本中的信号处理有点烦人。如果您可以将 SIGCHLD 信号处置显式设置为 SIG_IGN,内核就会知道您对退出状态不感兴趣,并会为您收割 child _。

尝试添加:

import signal
signal.signal(signal.SIGCHLD, signal.SIG_IGN)

靠近程序的顶部。

请注意,我不知道这对 Subprocess 有何作用。它可能不高兴。如果是这种情况,那么您需要 install a signal handler为您调用 wait(2)

关于python - 在 Python 中产生不确定的守护进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8425116/

相关文章:

python - 从嵌套字典中检索分支

c - POSIX:您如何确定您自己的进程的文件镜像以便您可以执行自己?

c - 为什么这个带 fork 的程序会打印两次?

python - 何时对 Python 子进程模块使用 Shell=True

python - Linux 管道读完但想丢弃其余部分

python - 仅针对大文件从 python 调用 zgrep 系统后出错

python - 我是否缺少在 Ubuntu 9.04 上使用 Python2.6 绑定(bind)构建/安装 VTK-5.4 的步骤?

python - pymongo 使用字符串代替字典进行查询

c - 多进程管道

python - 通过 'relationship' 中定义的链接对结果进行排序