当父进程被SIGABRT linux C ++杀死时,子进程终止

时间:2020-10-15 14:20:54

标签: c++ linux

我有一个场景,当使用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杀死,孩子也将收到同样的信息。删除管道代码后,信号不会传播。

能否请您提供一些见解?

0 个答案:

没有答案