How to kill a process and all of its children in C when executing the process by execv()?

流过昼夜 提交于 2021-02-16 20:00:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!