c - 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);
}
但正如你所见,我使用了一个全局变量......
没有全局变量我怎么能做到这一点
解决方案
推荐阅读
- python - 为什么用 Python 重写辛普森的积分规则会给出不同的结果?
- json - Golang 将 S3 中的 JSON 读入内存中的 struct
- ios - 计时器从时间戳开始计算时间
- flutter - 如何在颤动的列中展开容器而不溢出?
- r - 编写函数,计算列子集的行均值并创建列名
- grafana - 如何将查询结果传递到 Grafana 中的可视化 URL?
- amazon-dynamodb - 使用 FilterExpression 更新 DynamoDb 中的表
- c# - ShouldQuote 将引号放在一行中的所有字段周围,而不是我需要的那些
- django - Django Api 项目(邮递员方法抛出错误)
- docker - docker zookeeper 和 kafka 中的 SASL 身份验证