我有一个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
退出时,我看到脚本是keyboardInterrupted
在time.sleep(1.0)
行上,这使我相信该行:
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中的代码)。Double fork是正确的方法,但是第一个fork应该等待子进程,而不是简单地退出。
可以在这里找到正确的命令序列(以及执行double fork的原因):http://lubutu.com/code/spawning-in-unix(请参阅“double fork”部分)。
你提到的有时发生在第一个父母在得到SIGCHLD之前去世,而它没有到达init的时候。
据我所记得,除了信号处理之外,init应该定期从它的子级读取退出代码,但是新启动版本仅仅依赖于后者(因此,问题是,请参阅对类似错误的评论:https://bugs.launchpad.net/upstart/+bug/406397/comments/2)。
所以解决方法是重写第一个fork以实际等待孩子。
更新: 好吧,你需要一些代码。这里是:pastebin.com/W6LdjMEz我已经更新了daemonize、fork和start方法。
相关问题 更多 >
编程相关推荐