Prevent control-c from sending SIGINT to all proce

2019-06-14 10:25发布

问题:

I'm trying to interface with a really crappy, completely opaque API that creates two subprocesses within a POSIX-like environment (OS X/Linux) in C. Basically, it starts an external program and provides rudimentary support for passing messages back and forth. The process tree looks something like this:

+ My_program
 \
  + an initiation shell script (csh -f -c external_program_startup_script)
   \
    - the external program instance

When I press control-c in the terminal while My_program is running, the controlling terminal sends SIGINT to all processes in its process group — all three above processes. I want SIGINT to get to the program instance, but if it also hits the shell script then that middle process is terminated and the communication link is severed.

Within My_program, I can setup a signal handler to ignore SIGINTs. But I have absolutely no control over the two child processes (the API doesn't even expose their PIDs), so existing solutions such as changing their process group or attaching handlers won't work. Is there a way to prevent the controlling terminal from sending SIGINT to all processes in the foreground process group?

(The API in question is MATLAB's libeng, which allows an external C program to process commands within MATLAB. But it has absolutely no functionality for sending interrupts beyond that which the OS provides.)

回答1:

You need to run sub-processes in separate control group. You can achieve that by proper usage of setpgid() function. After fork() call, in the child process run setpgid(), then exec the program you want to be run in separate group.