通过execv()执行进程时,如何在C中杀死进程及其所有子进程? [英] How to kill a process and all of its children in C when executing the process by execv()?

查看:68
本文介绍了通过execv()执行进程时,如何在C中杀死进程及其所有子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在基于 unix 的操作系统上实现类似于 timeout 的命令,如下所示:

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

example 程序运行几秒钟,并分叉几个进程.当计时器在 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.

当我在没有 timeout 的情况下运行 example 并按 Ctrl + C 时,父级及其所有子级将被成功杀死.

When I run the example without timeout, and press Ctrl+C, the parent and all its children get killed successfully.

任何人都可以让我知道如何在我的 timeout 程序中解决此问题吗?

Can anyone please let me know how could I fix this in my timeout program?

推荐答案

您要在pid 0 上调用 kill().这会将信号发送到调用进程的进程组的所有成员.

You want to call kill() on pid 0. This sends the signal to all members of the calling process' process group.

但这仅在经过 fork()/ exec *()'(或其子项)的进程不更改其(其子进程)的情况下才有效进程组本身.

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.

来自 man 2 kill :

如果pid为0,则sig应发送到其进程组ID等于发送者的进程组ID的所有进程(不包括未指定的系统进程集)有权发送信号.

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.

这篇关于通过execv()执行进程时,如何在C中杀死进程及其所有子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆