我使用waitpid来获取子状态改变状态时返回的状态代码。我正在使用:
if (WIFEXITED(code)){
if (WEXITSTATUS(code)==0){
//worked correctly
}
else{
//failed, throw error
}
}
else{
..
}
在底部,我想检查孩子是否在没有终止的情况下改变状态并等待它使用循环终止。我怎么能这样做?
答案 0 :(得分:1)
假设您没有ptrace
子进程,则必须使用WUNTRACED
和WCONTINUED
标记等待它:
waitpid(pid, &code, WUNTRACED | WCONTINUED);
如果你ptrace
WUNTRACED
,ptrace
是不必要的,但由于if (WIFEXITED(code)) {
// process ended normally with exit status WEXITSTATUS(code)
} else if(WIFSIGNALLED(code)) {
// process was terminated by signal WTERMSIG(code)
} else if(WIFSTOPPED(code)) {
// child was stopped by signal WSTOPSIG(code)
} else if(WIFCONTINUED(code)) {
// child was continued
}
完全不同,所以我不会详细介绍它。
然后,您可以查看发生的事情:
#include <stddef.h>
#include <stdio.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid;
pid = fork();
if(pid == -1) {
fputs("fork failed\n", stderr);
} else if(pid == 0) {
int i;
for(i = 0; i < 100; ++i) {
usleep(1000000);
puts("child");
}
} else {
int status;
printf("%d\n", pid);
do {
waitpid(pid, &status, WUNTRACED | WCONTINUED);
printf("exited: %d status: %d\n"
"signalled: %d signal: %d\n"
"stopped: %d signal: %d\n"
"continued: %d\n",
WIFEXITED(status),
WEXITSTATUS(status),
WIFSIGNALED(status),
WTERMSIG(status),
WIFSTOPPED(status),
WSTOPSIG(status),
WIFCONTINUED(status));
} while(!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 0;
}
要了解其工作方式,您可以使用这段代码:
waitpid
这将是fork,父进程将打印子进程的进程ID,当您发送子进程信号时,父进程将打印它从WTERMSIG
获取的状态属性(并非所有这些都将理解,自然;如果进程停止,SIGSTOP
不返回任何有意义的东西)。以下是我发送子进程SIGCONT
,SIGTERM
和38167
child
child
child
child
exited: 0 status: 19
signalled: 0 signal: 127
stopped: 1 signal: 19
continued: 0
exited: 0 status: 255
signalled: 0 signal: 127
stopped: 0 signal: 255
continued: 1
child
child
child
exited: 0 status: 0
signalled: 1 signal: 15
stopped: 0 signal: 0
continued: 0
的会话的示例输出:
{{1}}