3

I am spawning some processes with Popen (Python 2.7, with Shell=True) and then sending SIGINT to them. It appears that the process group leader is actually the Python process, so sending SIGINT to the PID returned by Popen, which is the PID of bash, doesn't do anything.

So, is there a way to make Popen create a new process group? I can see that there is a flag called subprocess.CREATE_NEW_PROCESS_GROUP, but it is only for Windows.

I'm actually upgrading some legacy scripts which were running with Python2.6 and it seems for Python2.6 the default behavior is what I want (i.e. a new process group when I do Popen).

user16367
  • 263
  • 2
  • 9
  • This post gives you the secret sauce [How to terminate a python subprocess launched with shell=True](http://stackoverflow.com/a/4791612/642070). – tdelaney Aug 15 '13 at 15:40
  • @tdelaney Oh, thanks. That seems to work. So, I guess it creates a new session. In Python3 there is a flag for this. – user16367 Aug 15 '13 at 15:47

1 Answers1

2

bash does not handle signals while waiting for your foreground child process to complete. This is why sending it SIGINT does not do anything. This behaviour has nothing to do with process groups.

There are a couple of options to let your child process receive your SIGINT:

  1. When spawning a new process with Shell=True try prepending exec to the front of your command line, so that bash gets replaced with your child process.
  2. When spawning a new process with Shell=True append the command line with & wait %-. This will cause bash to react to signals while waiting for your child process to complete. But it won't forward the signal to your child process.
  3. Use Shell=False and specify full paths to your child executables.
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • Thanks. solution 1 doesn't seem to do anything for me. Solution 2 kills the shell but leaves the other processes, like you said. I prefer to use Shell=True because it's easier at this point. – user16367 Aug 15 '13 at 15:46