繁体   English   中英

孩子活着时的c ++循环

[英]c++ loop while child is alive

在我插入一个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等待状态的改变。 如果返回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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM