在另一个进程中运行程序并在Python中接收pid

时间:2015-10-14 07:29:56

标签: python unix process subprocess

我想在另一个进程中运行一个程序,得到pid这个程序,子进程不应该依赖于父进程。请参阅以下Python代码:

cmd = 'myPythonProgramm -p param'
pid = subprocess.Popen(cmd, shell = True).pid

但是如果我杀死父进程那么也会杀死子进程。
如果我使用:

,则不存在此问题
os.system('nohup myPythonProgramm -p param &')

但在这种情况下,我无法获得子进程pid。
如何在另一个进程中运行程序,获取pid这个程序和子进程不应该依赖于父进程?

1 个答案:

答案 0 :(得分:3)

您正在进行Unix进程组管理。特别是,当您将进程组的会话负责人连接到终端时(就像您的脚本一样),当该进程组中的所有进程都会收到<?php /* Intercept the POST request, do whatever processing required and echo a response */ if( $_SERVER['REQUEST_METHOD']=='POST' ){ /* Remove any previous output from our reply */ ob_clean(); /* send the response */ if( isset( $_POST["test"] ) ) echo $_POST["test"]; /* The `exit` statement prevents the rest of the page being sent in response */ exit(); } ?> <html> <head> <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> <script> $(document).ready(function() { $("#button").click(function() { var test = "Hallo Welt"; $.ajax({ url: "ajax.php", type: "post", data: { test: test }, success: function (response) { alert(response); document.getElementById('out').innerHTML=response; }, error: function(jqXHR, textStatus, errorThrown) { alert(textStatus, errorThrown); } }); }); }); </script> </head> <body> <form> <input type="button" id="button" value="Test" style="width:200x"> <output id='out'></output> </form> </body> </html> 时,默认情况下会导致终止。

一种解决方案是使用SIGHUP为孩子建立一个新会话。在Python 3中os.setsid()接受subprocess.Popen()为您执行此操作。对于Python 2,我们可以使用start_new_session=True获得类似的解决方案:

preexec_fn