Reputation: 11044
Program:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
int main()
{
int pid=fork();
if(pid==0){
printf("Child Executing: PID = %d\n",getpid());
pause();
}
else{
printf("Parent waiting: PID = %d\n",getpid());
int status;
waitpid(pid,&status,WNOHANG);
if(WIFEXITED(status))
printf("Child Terminates Normally\n");
else if(WIFSIGNALED(status))
printf("Child terminated by signal\n");
}
}
In the above program, I passed the WNOHANG macro to the option argument of waitpid function. It doesn't wait for the child process to complete. So, what is the use of wnohang. The man page contains the following statement,
WNOHANG return immediately if no child has exited.
I didn't understand the exact meaning. So, What is the use of WNOHANG and where we use it. Is there any realtime use cases of WNOHANG.
Thanks in Advance.
Upvotes: 0
Views: 2639
Reputation: 121407
It's (WNOHANG
) useful when you want to the parent process to continue to do some useful work if the child state hasn't changed.
A common example is the implementation of job control in shells.
Typically, the shell (parent process) periodically checks the status of any background processes (children processes) state change by calling waitpid()
without blocking itself. See Stopped and Terminated Jobs for a contrived example of this.
Upvotes: 1
Reputation: 781716
You would use this if you're polling periodically to see if the process has exited. If it hasn't you continue on with the rest of your program:
while (some_condition) {
result = waitpid(pid, &status, WNOHANG);
if (result > 0) {
// clean up the process
} else if (result < 0) {
perror("waitpid");
}
// do other processing
}
Upvotes: 4