首页 > 解决方案 > C:如何使用信号(ctrl + \,ctrl + c)杀死一个子进程,就像在bash中一样

问题描述

我想在 bash 中模拟信号,但使用 C。

我想使用信号函数(void (*signal(int sig, void (*func)(int)))(int);)杀死一个子进程。

我面临的问题是如何在不使用全局变量的情况下传递子函数的 PID?

我到目前为止:

#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

volatile sig_atomic_t is_child = 0;

void signal_handler(int sig) {
    char parent_str[] = "this is ctrl + c in the parent prosess\n";
    char child_str[] = "this is ctrl + c in the child prosess\n";
    signal(sig, signal_handler);
    if (sig == SIGINT) {
        if (is_child) {
            write(STDOUT_FILENO, child_str, sizeof(child_str) - 1);
        } else {
            write(STDOUT_FILENO, parent_str, sizeof(parent_str) - 1);
        }
    }
    else if (sig == SIGQUIT)
    {
        if (is_child) {
            write(STDOUT_FILENO, "this is ctrl + \\ in the child prosess\n", sizeof("this is ctrl + \\ in the child prosess\n") - 1);
        } else {
            write(STDOUT_FILENO, "this is ctrl + \\ in the parent prosess\n", sizeof("this is ctrl + \\ in the parent prosess\n") - 1);
        }
    }
}

int main(int argc, char **argv) {
    pid_t pid, pgid;

    (void)argv;
    signal(SIGINT, signal_handler);
    signal(SIGQUIT, signal_handler);
    pid = fork();
    assert(pid != -1);
    if (pid == 0) {
        is_child = 1;
        printf("child pid, pgid = %ju, %ju\n", (uintmax_t)getpid(), (uintmax_t)getpgid(0));
        while (1);
        exit(EXIT_SUCCESS);
    }
    printf("parent pid, pgid = %ju, %ju\n", (uintmax_t)getpid(), (uintmax_t)pgid);
    while (1);
}

但正如你所见,我使用了一个全局变量......

没有全局变量我怎么能做到这一点

标签: cbash

解决方案


推荐阅读