Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.6k views
in Technique[技术] by (71.8m points)

python - What subprocess preexec_fn=os.setpgrp does

I am a little confused on what subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setpgrp) does.

where cmd is something like ["mybashscript", "arg1", "arg2"]

Initially I was just using subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE), but I had an issue, where I run the bash script in a subprocess. And that if I interrupt (ctr+c) the python script, it will kill the bash script as well, but it does not do the clean up. The clean up is in the bash script itself.

But if I run the bash script directly, and hit ctr+c, it will stop the script and execute the clean up.

I tried assigning my own signal_handler and assign it to signal.signal(signal.SIG_INT, signal_handler) that then performs p.send_signal(signal.SIG_INT) to the subprocess but didnt seem to work.

Adding preexec_fn=os.setpgrpto the subprocess command, did do the job. Interrupting the python script, stops the bash script while still executing the clean up. But was just wondering what it really does? Or how it works? Some state that this detaches the child from the parent, and unable to receive signal, but then how did it work?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...