c - 保持父进程处于活动状态,而子进程将被 SIGINT 信号终止
问题描述
当我深入研究 C 中的 SIGNAL 时,我想知道是否有可能在接收到 SIGINT 信号后保持父进程处于活动状态,但我对在线研究感到有些困惑,因为他们对此没有太多讨论。
是否可以通过忽略父进程的 SIGINT 信号来使用信号处理程序使父进程保持活动状态。
如果是,我应该如何实施?
解决方案
@Erdal Küçük 已经回答了您的问题,但这里有一段示例代码,以便您更好地理解它。
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void handler(int _) {
(void)_;
printf("\nEnter a number: ");
ffush(stdout);
}
int main(void) {
pid_t pid;
pid = fork();
int n = 0;
if (pid < 0) {
perror("Can't fork");
} else if (pid == 0) {
// Child process
kill(getpid(), SIGKILL); // Killing the child process as we don't need it
} else {
// Parent process
struct sigaction sg;
sg.sa_flags = SA_RESTART;
sg.sa_handler = handler;
sigaction(SIGINT, &sg, NULL);
printf("Enter a number: ");
scanf("%d", &n);
}
printf("Value of n = %d", n);
return 0;
}
推荐阅读
- python-3.x - 如何在 Google Cloud Composer 中设置 chromedriver 的路径
- excel - 从工作表填充的列表框,找不到原始值
- javascript - 读取所选选项的文本 [具体化]
- javascript - 为什么继续使迭代停止?
- json - 修改 vscode 中的 settings.json 以在 Latex 工作坊中为 pdflatex 添加 shell 转义标志
- javascript - 根据其他接口的属性创建接口
- javascript - 我正在尝试从 AJAX 调用的返回中创建一组结果。我怎么做?
- java - 对每个 API 调用进行身份验证
- apache-spark - 在配置单元查询中使用 scala 集合
- c# - 如何使用 PowerShell 脚本在多行中列出 C# 编译选项