[英]How do I get the status of a child process from a parent, i.e. has it stopped, continued, or exited? For Linux, C lang
这是 Linux (ubuntu) 中的 C 语言程序。 我一直在试图弄清楚如何从父母那里获得子进程的状态。
我编写了一个简单的子进程,它在 25 秒内计数为 25,并将滴答计数输出到标准 output。 在父进程中,我1> 停止子进程几秒钟。 2> 继续它几秒钟,然后3> 杀死子进程。 我想获取子进程的状态,为此我一直在使用waitpid() function。 但是,我发现如果我使用这些标志:
等待条件 = WUNTRACED | W续
它确实返回“停止”状态,但是当它处于继续 state 时它会挂起。
相反,如果我将标志设置为:
等待条件= WUNTRACED | W续 | 万航
停止状态未注册,但继续状态由 waitpid() 注册。
我试图让父母在 state 停止、继续或退出时识别它。
我有下面的代码。 有没有人对此有任何想法? 谢谢!
int waiting4pid()(pid_t processID)
{
int waitCondition = WUNTRACED | WCONTINUED;
int currentState;
while (waitpid(processID,¤tState,waitCondition) > 0){
if(WIFCONTINUED(currentState)){
printf("\n currentState = continued!\n");
}
if(WIFSIGNALED(currentState)){
printf("\n currentState = signaled!\n");
}
if(WIFSTOPPED(currentState)){
printf("\n currentState = stopped!\n");
}
}
}
void sigTest()
{
pid_t processID;
processID = fork();
if(processID ==0) { // child
// tmp/loop is an application that counts to 25 in 25 seconds and then exits.
execlp("tmp/loop", "tmp/loop", NULL);
}else{
sleep(2);
printf("\n Stop!");
kill(processID, SIGSTOP);
waiting4pid()(processID);
sleep(2);
printf("\n Continue!");
kill(processID,SIGCONT);
waiting4pid()(processID);
sleep(2);
printf("\n Kill!");
kill(processID, SIGKILL);
waiting4pid()(processID);
}
}
void main()
{
sigTest();
}
为了检查进程是否退出,请执行以下操作:
if(WIFEXITED(status) {
// do your stuff
// you can also check the exit status
if(WEXITSTATUS(status) != EXIT_SUCCESS) {
// the child process exited with error
}
}
正如@kaylum 在问题下的评论中已经提到的那样, waitpid()
调用会阻塞,直到孩子更改 state。 但是您可以通过设置WNOHANG
标志调用waitpid()
waitpid()
修改此行为(如果您需要监视子进程但同时在父进程中执行一些其他操作,这将很有用;或者您可以在单独的线)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.