Python - os.kill(pid, SIGTERM) 导致我的进程变成僵尸

标签 python operating-system daemon

我有一个 Python 脚本,用于启动 daemon 进程。我可以通过使用以下位置的代码来做到这一点:https://gist.github.com/marazmiki/3618191 .

代码完全按照预期启动守护进程进程。但是,有时,并且仅有时,当守护进程停止时,正在运行的作业就会陷入僵尸状态。

该代码的stop函数为:

    def stop(self):
        """
            Stop the daemon
        """
        # Get the pid from the pidfile
        try:
            pf = file(self.pidfile, 'r')
            pid = int(pf.read().strip())
            pf.close()
        except:
            pid = None

        if not pid:
            message = "pidfile %s does not exist. Daemon not running?\n"
            sys.stderr.write(message % self.pidfile)
            return # not an error in a restart

        # Try killing the daemon process
        try:
            while 1:
                os.kill(pid, SIGTERM)
                time.sleep(1.0)
        except OSError, err:
            err = str(err)
            if err.find("No such process") > 0:
                if os.path.exists(self.pidfile):
                    os.remove(self.pidfile)
            else:
                print str(err)
                sys.exit(1)

当运行此 stop() 方法时,进程 (pid) 似乎挂起,当我 Control+C 退出时,我看到脚本在 time.sleep(1.0) 行上是 KeyboardInterrupted,这让我相信该行:

os.kill(pid, SIGTERM)

是有问题的代码。

有谁知道为什么会发生这种情况吗?为什么这个 os.kill() 会强制进程变成僵尸进程?

我在 Ubuntu linux 上运行它(如果重要的话)。

更新:我根据 @paulus 的答案添加了我的 start() 方法。

    def start(self):
        """
            Start the daemon
        """
        pid = None
        # Check for a pidfile to see if the daemon already runs
        try:
            pf = file(self.pidfile, 'r')
            pid = int(pf.read().strip())
            pf.close()
        except:
            pid = None

        if pid:
            message = "pidfile %s already exist. Daemon already running?\n"
            sys.stderr.write(message % self.pidfile)
            sys.exit(1)

        # Start the daemon
        self.daemonize()
        self.run()

更新 2:这是 daemonize() 方法:

def daemonize(self):
        """
            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)
        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("/")
        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()

        sys.stdout = file(self.stdout, 'a+', 0)
        si = file(self.stdin, 'r')
        so = file(self.stdout, 'a+')
        se = file(self.stderr, 'a+', 0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        # write pidfile
        atexit.register(self.delpid)
        pid = str(os.getpid())
        file(self.pidfile, 'w+').write("%s\n" % pid)

最佳答案

你看错了方向。有缺陷的代码不是 stop 例程中的代码,而是 start 例程中的代码(如果您使用的是 gist 中的代码)。双fork是正确的方法,但是第一次fork应该等待子进程,而不是简单地退出。

正确的命令顺序(以及执行双 fork 的原因)可以在这里找到:http://lubutu.com/code/spawning-in-unix (参见“双叉”部分)。

您提到的有时是在第一个父级在获得 SIGCHLD 之前死亡并且无法初始化时发生的。

据我记得,除了信号处理之外,init 还应该定期从其子级读取退出代码,但是 upstart 版本只是依赖于后者(因此问题,请参阅类似 bug 的评论: https://bugs.launchpad.net/upstart/+bug/406397/comments/2 )。

所以解决方案是重写第一个 fork 来实际等待子进程。

更新: 好的,你想要一些代码。在这里:pastebin.com/W6LdjMEz 我已经更新了 daemonize、fork 和 start 方法。

关于Python - os.kill(pid, SIGTERM) 导致我的进程变成僵尸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22815514/

相关文章:

python - 无法使用 python eventlet 库超时(eventlet.timeout.Timeout)

python - 从python中的 pickle 中排除对象的字段

file - os.File、io.Reader 和 os.Stdin 之间的区别

java - 如何访问线程中 Runnable 对象的字段

java - JTextPane 文本在 Mac 操作系统中滚动时折叠

python - 在 Python 中将名称列表拆分为字母字典

docker - 在 Openshift 中运行的 Docker 容器中安装并运行 docker

iphone - 如何在iphone sdk 3.0中实现后台任务的Daemon进程?

c++ - init.d 守护程序脚本 (linux) 中的 lockfile 用途

python - 如何将选择显示名称传递给 Django REST 框架中的模型序列化?