【发布时间】:2018-08-30 08:07:09
【问题描述】:
我正在为一个研究项目编写代码。我有以下要求: 1. 主二进制执行从 main() 开始 2. main() fork() 3. 子进程使用 execvp() 运行 linpack 基准二进制文件 4.父进程运行一些监控进程,等待子进程退出。
代码如下:
main.cpp
extern ServerUncorePowerState * BeforeStates ;
extern ServerUncorePowerState * AfterStates;
int main(int argc, char *argv[]) {
power pwr;;
procstat st;
membandwidth_t data;
int sec_pause = 1; // sample every 1 second
pid_t child_pid = fork();
if (child_pid >= 0) { //fork successful
if (child_pid == 0) { // child process
int exec_status = execvp(argv[1], argv+1);
if (exec_status) {
std::cerr << "execv failed with error "
<< errno << " "
<< strerror(errno) << std::endl;
}
} else { // parent process
int status = 1;
waitpid(child_pid, &status, WNOHANG);
write_headers();
pwr.init();
st.init();
init_bandwidth();
while (status) {
cout << " Printing status Value: " << status << endl;
sleep (sec_pause);
time_t now;
time(&now);
struct tm *tinfo;
tinfo = localtime(&now);
pwr.loop();
st.loop();
data = getbandwidth();
write_samples(tinfo, pwr, st, data.read_bandwidth + data.write_bandwidth);
waitpid(child_pid, &status, WNOHANG);
}
wait(&status); // wait for child to exit, and store its status
//--------------------This code is not executed------------------------
std::cout << "PARENT: Child's exit code is: "
<< WEXITSTATUS(status)
<< std::endl;
delete[] BeforeStates;
delete[] AfterStates;
}
} else {
std::cerr << "fork failed" << std::endl;
return 1;
}
return 0;
}
预计孩子会退出,然后父母会退出,但在 16 分钟后由于某些未知原因,父母退出但孩子仍在运行。
通常说当父母退出时,孩子会自动死亡。
这种奇怪行为的原因可能是什么???
【问题讨论】:
-
你应该检查
wait的返回值。它可能会因某种原因而中断。