C++在 child 还活着时循环

标签 c++ posix fork

在我 fork 一个 C++ 程序之后。运行 while 循环直到子进程终止的语法是什么。

int value = fork();
if( value = 0 ) {
    //do something
} else {
    while(childIsAlive) {
        //do something
    }
}

所做的事情是独立的。

最佳答案

int Stat;
if (waitpid(PidOfChild, &Stat, WNOHANG) == PidOfChild) {
  if (WIFEXITED(Stat) || WIFSIGNALED(Stat)) {
    childAlive = false;
  }
}

waitpid 等待waitpid 中的状态更改。如果它返回 PidOfChild,则存在更改,并且 Stat 会更新。

如果子进程正常退出,WIFEXITED(Stat) 将为 true

如果子进程被信号终止,WIFSIGNALED(Stat) 将为 true。

编辑:示例代码。

#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>

#include <iostream>
#include <cstdlib>

using namespace std;

int main() {

  srand(time(0));

  pid_t pid = fork();

  if (pid == 0) {
    int Seconds = rand() % 3 + 1;
    cout << "child: Sleeping " << Seconds << " seconds" << endl;
    sleep(Seconds);
    if (rand() % 2) {
      cout << "child: Killing" << endl;
      kill(getpid(), SIGTERM);
    } else {
      int ExitCode = rand() % 3;
      cout << "child: Exiting with exit code " << ExitCode << endl;
      exit(ExitCode);
    }
  } else if (pid > 0) {
    for (;;) {
      cout << "parent: spinning waiting for child to exit" << endl;
      int Stat;
      while (waitpid(pid, &Stat, WNOHANG) != pid);
      if (WIFEXITED(Stat)) {
        cout << "parent: Child exited with exit code " << WEXITSTATUS(Stat) << endl;
        break;
      } else if (WIFSIGNALED(Stat)) {
        cout << "parent: Child killed with signal " << WTERMSIG(Stat) << endl;
        break;
      } else {
        cout << "parent: Something else happened to child, e.g. STOPPED" << endl;
      }
    }

  } else {
    cout << "Error forking: " << strerror(errno) << endl;
  }
}

关于C++在 child 还活着时循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5057137/

相关文章:

C++ 传递 STL 容器项作为引用

c++ - 在 Rcpp 和 C++ 之间转换 vector (使用 Rcpp::as 或 Rcpp::wrap)是否会创建一个新 vector 并复制元素?

bash - 排序实用程序的字母顺序是什么?

c++ - Linux : pthread_cond_signal() is not working inside a Signal Handler()

管道多个命令的 C 程序

c++ - 在 C++ 中的堆中删除从 Char[] 创建的堆上的字符串

C 和 POSIX Pthreads

c++ - 是否可以在C++中将列表分配到共享内存中?

c - Fork-exec 管道重定向问题

c++ - 在堆或堆栈上分配对象