c++ - 使用 SIGABRT linux C++ 杀死父进程时子进程中止
问题描述
我有一个场景,当父进程被 SIGABRT 杀死时,生成的子进程被杀死。在我的理解中,孩子应该继续跑步。为了模仿实际的代码,我创建了两个文件,分别代表孩子和父母。父级写入管道,子级从读取端(STDIN_FILENO)读取。
父代码-> parent.cpp
#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
int main() {
int pipefd[2];
std::string message = "test\n";
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
int pid = fork();
if (0 == pid) {
std::cout << "Inside child process\n";
close(pipefd[1]);
char *args[] = {"./CHILD", NULL};
char *envp[] = {NULL};
if (dup2(pipefd[0], STDIN_FILENO) == -1) {
std::cout << "dup2 failed\n";
}
close(pipefd[0]);
close(pipefd[1]);
execve(args[0], args, envp);
} else {
close(pipefd[0]);
while (1) {
sleep(1);
std::cout << "parent writing -> " << message;
write(pipefd[1], message.c_str(), message.length());
}
}
return 0;
}
子代码-> child.cpp
#include <iostream>
#include <string>
#include <unistd.h>
int main() {
std::string str;
char buf;
std::cout << "[child] started\n";
while (read(STDIN_FILENO, &buf, sizeof(buf)) > 0) {
if (buf != '\n')
str += buf;
else {
write(STDOUT_FILENO, str.c_str(), str.length());
str.clear();
write(STDOUT_FILENO, "\n", 1);
}
}
std::cout << "[child] Exiting the application\n";
return 0;
}
如果父母被 SIGABRT 杀死,孩子也会收到同样的信息。当管道代码被移除时,信号不会被传播。
你能提供一些见解吗?
解决方案
推荐阅读
- r - 混合效应模型不返回所有系数
- jquery - 在向下/向上滚动时向下/向上滚动标题徽标
- logstash - 翻译过滤器外部字典中的正则表达式
- html - 将css添加到jsx react脚本的最佳方法?
- java - 如何通过转储文件中的值过滤变量?
- java - 如何防止线程被杀死(以及可能的替代方案)?
- unetstack - 如何在代理的 processRequest 中使用 RemoteGetParamReq 获取远程节点的参数
- maven - Gradle -- Maven 中的干运行等效项
- testing - 您如何测试涉及通过电子邮件确认的用户流程?
- java - 更改模块架构以正确处理事务