本文介绍了如何检查一个进程是否已经完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我以前用 C/cC++ 语言检查子进程是否已完成的方式:
This is how I used to check if a child process has been finished in C/cC++ language:
waitpid(job.pid,&tmp,WNOHANG)>=0;
但经过一些阅读后,我认为这是错误的,因为我问的是 waitpid 是否成功完成,而不是问进程是否完成.
But after some reading I think it's wrong since I am asking if waitpid finished successfully or not and not asking if the process was finished or not.
我该如何解决这个问题?
How can I fix this?
推荐答案
当这样调用时,waitpid
可以返回三个东西
When called like that, waitpid
can return three things
- 0:状态不可用.这意味着该进程仍在运行.
- -1:错误.
errno
应该被检查.它可以是EINTR
,在这种情况下,您应该再次尝试调用waitpid
.它也可以是ECHILD
,在这种情况下,您要么已经确定该进程已提前结束,要么是无效/不相关的 pid.如果发生这种情况,则说明您的程序逻辑有问题. - 您要求的 pid.在这种情况下,过程结束.确切地如何结束,您可以使用第二个参数中返回的值进行检查,在您的情况下为
tmp
.手册页中解释了有关此值的各种宏.
- 0: Status is not available. That means the process is still running.
- -1: An error.
errno
should be checked. It can beEINTR
, in which case you should just try callingwaitpid
again. It can also beECHILD
, in which case you either already established the process had ended earlier, or it is an invalid/unrelated pid. If this happens, something is wrong in your program's logic. - The pid you asked for. In this case the process ended. Exactly how it ended, you can check using the value returned in the second argument,
tmp
in your case. There are various macros explained in the man page about this value.
因此,无需关心进程退出状态,您可以这样检查:
Thus, without caring for the process exit status, you can check it like this:
bool isdone(pid_t pid)
{
int status;
while((pid_t r = waitpid(pid, &status, WNOHANG) != pid)
{
if(r == 0) return false;
if(errno == EINTR) continue;
// handle errors
}
return true;
}
这篇关于如何检查一个进程是否已经完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!