How do I kill a process and all its children in C while executing an execv () process?

I am trying to implement a command timeout

in the operating system unix

like this:

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 like this:

./timeout example

      

The program example

runs for a couple of seconds and deploys several processes. When the timer expires in timeout

, only the parent process example

is killed and its children continue to print to the console.

When I run example

without timeout

and click Ctrl+C

, the parent and all of its children are killed successfully.

Can someone please let me know how I can fix this in my program timeout

?

+3


source to share


1 answer


You want to call kill()

on pid 0

. This sends a signal to all members of the calling process's process group.

However, this only works if the process that was fork()

/ exec*()

'ed (or its children) does not itself change its process group.



From man 2 kill

:

If pid is 0, sig must be sent to all processes (except for an unspecified set of system processes) whose process group ID is equal to the sender's process group ID and for which the process has permission to send a signal.

+5


source







All Articles