Python - os.kill(pid, SIGTERM) 使我的进程变成僵尸进程
我有一个 Python
脚本,它可以启动一个 daemon
进程。我是通过使用这个链接里的代码实现的:https://gist.github.com/marazmiki/3618191。
这个代码能按预期启动 daemon
进程。不过,有时候,当 daemon
进程被停止时,正在运行的任务会变成“僵尸进程”。
代码中的 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)
1 个回答
你可能方向搞错了。出问题的代码不是在 stop 这个函数里,而是在 start 里(如果你用的是那段代码)。双重分叉是正确的方法,但第一个分叉应该等着子进程,而不是直接退出。
正确的命令顺序(以及为什么要用双重分叉)可以在这里找到:http://lubutu.com/code/spawning-in-unix(看看“Double fork”这一部分)。
你提到的 有时候 发生的情况是因为第一个父进程在收到 SIGCHLD 信号之前就死掉了,这样它就没法把信息传给 init 了。
据我记得,init 应该定期读取它的子进程的退出代码,除了处理信号,但 upstart 版本只是依赖于后者(这就是问题所在,看看关于类似错误的评论:https://bugs.launchpad.net/upstart/+bug/406397/comments/2)。
所以解决办法就是重写第一个分叉,让它真正等待子进程。
更新:
好吧,你想要一些代码。这里来了:pastebin.com/W6LdjMEz 我更新了 daemonize、fork 和 start 方法。