python 子进程退出,Python产生一个子子进程,分离并退出

I'm wondering if this is the correct way to execute a system process and detach from parent, though allowing the parent to exit without creating a zombie and/or killing the child process. I'm currently using the subprocess module and doing this...

os.setsid()

os.umask(0)

p = subprocess.Popen(['nc', '-l', '8888'],

cwd=self.home,

stdout=subprocess.PIPE,

stderr=subprocess.STDOUT)

os.setsid() changes the process group, which I believe is what lets the process continue running when it's parent exits, as it no longer belongs to the same process group.

Is this correct and also is this a reliable way of performing this?

Basically, I have a remote control utility that communicate through sockets and allows to start processes remotely, but I have to ensure that if the remote control dies, the processes it started continue running unaffected.

I was reading about double-forks and not sure if this is necessary and/or subprocess.POpen close_fds somehow takes care of that and all that's needed is to change the process group?

Thanks.

Ilya

解决方案

popen on Unix is done using fork. That means you'll be safe with:

you run Popen in your parent process

immediately exit the parent process

When the parent process exits, the child process is inherited by the init process (launchd on OSX) and will still run in the background.

The first two lines of your python program are not needed, this perfectly works:

import subprocess

p = subprocess.Popen(['nc', '-l', '8888'],

cwd="/",

stdout=subprocess.PIPE,

stderr=subprocess.STDOUT)

I was reading about double-forks and not sure if this is necessary

This would be needed if your parent process keeps running and you need to protect your children from dying with the parent. This answer shows how this can be done.

How the double-fork works:

create a child via os.fork()

in this child call Popen() which launches the long running process

exit child: Popen process is inherited by init and runs in the background

Why the parent has to immediately exit? What happens if it doesn't exit immediately?

If you leave the parent running and the user stops the process e.g. via ctrl-C (SIGINT) or ctrl-\ (SIGQUIT) then it would kill both the parent process and the Popen process.

What if it exits one second after forking?

Then, during this 1s period your Popen process is vulnerable to ctrl-c etc. If you need to be 100% sure then use the double forking.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值