问题
I'm trying to implement a timeout
-like command on a unix
-based operating system as follows:
int pid;
timer_t timer_id;
struct sigevent timer_event;
struct itimerspec timer_value;
void timeout_signal_handler(int sig_no)
{
kill(pid, SIGKILL);
}
int create_timer() { /* implementation */ }
int start_timer_oneshot(int interval_ms) { /* implementation */ }
int main(int argc, char* argv[])
{
int status, pid_return;
void *signal_return;
if (argc < 2)
return EXIT_FAILURE;
signal_return = signal(SIGUSR1, timeout_signal_handler);
if (signal_return == SIG_ERR)
return EXIT_FAILURE;
create_timer();
start_timer_oneshot(TIMEOUT);
if ((pid = fork()) == 0)
{
execv(argv[1], &argv[1]);
return EXIT_FAILURE;
}
else
{
status = -1;
while (status == -1)
status = wait(&pid_return);
}
return EXIT_SUCCESS;
}
And I use this utility as follows:
./timeout example
The example
program runs for a couple of seconds and forks a couple of processes. When the timer expires in timeout
, only the parent process of example
gets killed and its children keep printing on the console.
When I run the example
without timeout
, and press Ctrl+C
, the parent and all its children get killed successfully.
Can anyone please let me know how could I fix this in my timeout
program?
回答1:
You want to call kill()
on pid 0
. This sends the signal to all members of the calling process' process group.
This however only works if the process, which had been fork()
/exec*()
'ed (or its children) does not change its (their) process group by itself.
From man 2 kill:
If pid is 0, sig shall be sent to all processes (excluding an unspecified set of system processes) whose process group ID is equal to the process group ID of the sender, and for which the process has permission to send a signal.
来源:https://stackoverflow.com/questions/31738216/how-to-kill-a-process-and-all-of-its-children-in-c-when-executing-the-process-by