我使用以下代码来分叉一个进程并发出信号以便稍后停止。
#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;
}
}
此代码打印(如预期):
给测量过程一些时间进行清理
完成测量。
测量过程返回42.
但是,如果我在kill语句之后省略了sleep语句,我会改为:
给测量过程一些时间进行清理
测量过程由信号80终止
完成测量。
为什么结果取决于我是否等待三秒钟?难道不等待孩子回来吗?这对我的应用程序(现在)并不重要,但我想了解如何正确执行。我想表示孩子的过程停止,然后等到它完成了#34;正确&#34;。
感谢您的帮助,
鲁兹