gpt4 book ai didi

c++循环,而 child 还活着

转载 作者:搜寻专家 更新时间:2023-10-31 00:46:30 27 4
gpt4 key购买 nike

在我 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) 将为真

如果子进程被信号终止,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;
}
}

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com