c - execv() 执行进程时,如何在 C 中杀死进程及其所有子进程?

标签 c signals child-process

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

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;

}

我按如下方式使用此实用程序:

./timeout example

示例 程序运行了几秒钟并 fork 了几个进程。当计时器在 timeout 时到期,只有 example 的父进程被杀死,其子进程继续在控制台上打印。

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

谁能告诉我如何在我的timeout 程序中解决这个问题?

最佳答案

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

然而,这仅在被 fork()/exec*() 处理(或其子进程)不改变其(它们的)的情况下才有效进程组本身。

来自 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.

关于c - execv() 执行进程时,如何在 C 中杀死进程及其所有子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31738216/

相关文章:

Django 应用程序 post_save 与 sender=get_user_model()

node.js - 如何在nodejs命令行应用程序中存储有关分 ionic 进程的信息

c - 开头的随机数组大小?

c - 为什么结构的大小应反射(reflect)其对齐方式?

c - 在 Mac 上找不到库 rt,同时配置 sfft(稀疏快速傅里叶变换)

c++ - 计时器和 pthreads (POSIX)

signals - 如何在Vala中编写button_press_event信号处理程序?

c - C 中的基本 pi 搜索,出了什么问题?

c - 多个管道和进程

node.js - 为使用 child_process 的 Node 服务编写单元测试