首页 > 解决方案 > 使用 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 杀死,孩子也会收到同样的信息。当管道代码被移除时,信号不会被传播。

你能提供一些见解吗?

标签: c++linux

解决方案


推荐阅读