如何在不挂起父亲的情况下检索子进程的状态?

How to retrieve status of a child process without hanging father?

我想在执行另一项工作时启动子进程,并能够在父进程中检查子进程是否已完成。我发现 waitpid 的 WNOHANG 选项有助于在能够跟踪它的同时不等待子项完成。但是,status 变量在使用此选项时根本没有改变,就像我将其替换为 0 时一样。

你对这种行为有什么解释吗?怎么才能如愿以偿(能够在父进程中知道子进程是否已经完成,而不用挂掉)?

我有以下代码

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include<sys/wait.h>
int main(){
    int status;
    printf("status=%d\n",status);
  pid_t p = fork();
  
 if(p==0){
     printf("je suis dans le fils\n");
     exit(0);
  }
  else if(p>0){
     printf("je suis dans le père\n");
     waitpid(p,&status,WNOHANG);
     sleep(5);
     printf("status= %d",status);
     exit(0);
  }
}

请大家多多包涵,本人C语言不深,还在学习中

I'd like to launch a child process while doing another job and be able to check whether the child process has finished or not in the father process. I found that the WNOHANG option of waitpid helped not to wait for child completion while being able to track it. However, the status variable doesn't change at all when using this option as it does when I replace it by 0.

在子进程终止之前状态不可用。因此,如果在子进程终止之前用 WNOHANG 调用 waitpid,则无法获取状态。

How can I do what I want (be able to know in parent process whether the child has done, without hanging it) ?

这就是您的代码所做的。它告诉您该过程未完成,因此您没有得到它的状态。

在子进程完成后用 WNOHANG 调用 waitpid 或等待它完成以获取状态。