孩子还活着时的c ++循环

时间:2011-02-20 12:50:20

标签: c++ posix fork

在我分叉c ++程序之后。在子进程终止之前运行while循环的语法是什么。

int value = fork();
if( value = 0 ) {
    //do something
} else {
    while(childIsAlive) {
        //do something
    }
}
做某些事情是独立的。

1 个答案:

答案 0 :(得分:5)

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

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

如果子进程正常退出,

WIFEXITED(Stat)将为真

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

编辑:示例代码。

#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;
  }
}