C++ waitpid的早期调用未正确收集退出状态
C++ waitpid的早期调用未正确收集退出状态,c++,fork,waitpid,exitstatus,C++,Fork,Waitpid,Exitstatus,我使用下面的代码来分叉一个进程,并向它发出信号,让它稍后停止 #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/types.h> #include <iostream> using namespace std; sig_atomic_t stopFlag = 0; void measurementSignalHandler(int
我使用下面的代码来分叉一个进程,并向它发出信号,让它稍后停止
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <iostream>
using namespace std;
sig_atomic_t stopFlag = 0;
void measurementSignalHandler(int sig) {
stopFlag = 1;
}
int main(int argc, char **argv) {
pid_t measurementPid = fork();
switch(measurementPid) {
case -1:
// fork failed
cerr << "Failed to create measurement process." << endl;
exit(1);
case 0:
// child
signal(SIGUSR1, measurementSignalHandler);
while(stopFlag == 0) {
sleep(1);
}
cout << "Done with measurements." << endl;
return 42;
default:
// parent
sleep(5);
// I do not understand why this sleep is necessary.
kill(measurementPid, SIGUSR1);
cout << "Giving measurement process some time to clean up."
<< endl;
sleep(3);
int childExitStatus;
waitpid(measurementPid, &childExitStatus, 1);
if(WIFEXITED(childExitStatus)) {
cout << "Measurement process returned "
<< WEXITSTATUS(childExitStatus)
<< "." << endl;
}
else if(WIFSIGNALED(childExitStatus)) {
cout << "Measurement process was terminated by signal "
<< WTERMSIG(childExitStatus)
<< "." << endl;
}
else {
cout << "Measurement process ended neither on its own "
<< "nor by signal." << endl;
}
return 0;
}
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
sig_原子停止标志=0;
无效度量信号处理器(int sig){
stopFlag=1;
}
int main(int argc,字符**argv){
pid_t measurementPid=fork();
开关(测量ID){
案例1:
//fork失败了
cerr您正在将1传递给waitpid
。我猜1是WAITNOHANG
,这意味着它不会等到所有子项都完成。谢谢,RedX,这似乎解决了这个问题。这个错误是由于只扫描手册页而没有仔细阅读详细信息造成的。