即使使用 nohup 子进程也会被杀死 [英] subprocess gets killed even with nohup

查看:33
本文介绍了即使使用 nohup 子进程也会被杀死的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 subprocess.Popen 来启动多个进程.

I'm using subprocess.Popen to launch several processes.

代码是这样的:

while flag > 0:
   flag = check_flag()
   c = MyClass(num_process=10)
   c.launch()

MyClass 如果类似于以下内容:

MyClass if something like the following:

MyClass(object)
   def __init__(self, num_process):
      self.num_process = num_process

   def launch(self):
      if self.check_something() < 10:
         for i in range(self.num_process):
             self.launch_subprocess()

   def launch_subprocess(self):
      subprocess.Popen(["nohup",
                       "python",
                       "/home/mypythonfile.py"],
                       stdout=open('/dev/null', 'w'),
                       stderr=open('logfile.log', 'w'),
                       shell=False)

在大多数情况下,启动的子进程会终止,有时会在运行过程中终止.在某些情况下,它会完成.

In most of the cases, the launched subprocess dies, sometimes in the middle of the run. In some cases, it completes.

但是,如果我在 while 循环中直接使用 subprocess.Popen ,该过程会继续并及时完成.

However, if I use subprocess.Popen directly in the while loop, the process continues and finished timely.

有人能告诉我如何通过使用子进程来让进程在后台运行吗?

Could someone tell me how can I get the processes to run in the background by using subprocess in the way as I described above?

推荐答案

nohup 仅在主进程正常退出时停止 SIGHUP 信号.对于 SIGINT 或 SIGTERM 等其他信号,子进程接收到与父进程相同的信号,因为它在同一个进程组中.有两种使用 Popen 的 preexec_fn 参数的方法.

The nohup only stop the SIGHUP signal when your master process exits normally. For other signal like SIGINT or SIGTERM, the child process receives the same signal as your parent process because it's in the same process group. There're two methods using the Popen's preexec_fn argument.

subprocess.Popen(['nohup', 'python', '/home/mypythonfile.py'],
                 stdout=open('/dev/null', 'w'),
                 stderr=open('logfile.log', 'a'),
                 preexec_fn=os.setpgrp )

更多信息参见另一篇帖子.

def preexec_function():
    signal.signal(signal.SIGINT, signal.SIG_IGN)
subprocess.Popen( ... , preexec_fn=preexec_function)

这篇关于即使使用 nohup 子进程也会被杀死的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆