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
.
Do you have any explanation of this behaviour ? How can I do what I want (be able to know in parent process whether the child has done, without hanging it) ?
I have the following code
#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);
}
}
Be tolerant please, I don't have a deep knowledge in C and am still learning.
CodePudding user response:
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.
The status isn't available until the child process terminates. So if you call waitpid
with WNOHANG
before the child process has terminated, you can't get the status.
How can I do what I want (be able to know in parent process whether the child has done, without hanging it) ?
That's what your code did. It told you the process wasn't done, so you didn't get its status.
Either call waitpid
with WNOHANG
after the child process is done or wait for it to finish to get the status.