I need an example of waitpid
, WNOHANG
and SIGCHLD
combined in C, and how I can use them all with fore\background?
signal( SIGCHLD, SIG_IGN );
waitpid(child, status, 0);
WNOHANG. Demands status information immediately. If status information is immediately available on an appropriate child process, waitpid() returns this information. Otherwise, waitpid() returns immediately with an error code indicating that the information was not available.
The wait() system call suspends execution of the current process until one of its children terminates. The call wait(&status) is equivalent to: waitpid(-1, &status, 0); The waitpid() system call suspends execution of the current process until a child specified by pid argument has changed state.
The pid parameter specifies the set of child processes for which to wait. If pid is -1, the call waits for any child process.
Only one status is returned per waitpid function call. If pid is equal to -1, status is requested for any child process. If status information is available for two or more processes, the order in which their status is reported is not specified. If pid is greater than 0, status is requested for a single process.
Taken from http://voyager.deanza.edu/~perry/sigchld.html
#include <stdio.h> /************ Handling SIGCHLD!! ******************/
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h> /***** For waitpid. *****/
#include <setjmp.h> /***** For sigsetjmp and siglongjmp. *****/
sigjmp_buf env;
main()
{
pid_t pid;
int n = 20;
struct sigaction sa;
void delete_zombies(void);
sigfillset(&sa.sa_mask);
sa.sa_handler = delete_zombies;
sa.sa_flags = 0;
sigaction(SIGCHLD, &sa, NULL);
sigsetjmp(env, 1);
if ((pid = fork()) < 0)
{
perror("Bad fork!");
exit(1);
}
if (pid > 0) /***** Parent *****/
{
printf("Created child %ld\n", pid);
sleep(n -= 2);
kill(0, SIGKILL);
}
else /***** Child *****/
{
sleep(2);
exit(0); /****** Not necessary here but... ******/
}
}
void delete_zombies(void)
{
pid_t kidpid;
int status;
printf("Inside zombie deleter: ");
while ((kidpid = waitpid(-1, &status, WNOHANG)) > 0)
{
printf("Child %ld terminated\n", kidpid);
}
siglongjmp(env,1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With