Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of waitpid, WNOHANG, and SIGCHLD

Tags:

c

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);
like image 775
michael Avatar asked Aug 23 '11 02:08

michael


People also ask

What does Wnohang do in Waitpid?

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.

What is the use of wait () and waitpid () function?

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.

What does Waitpid 1 mean?

The pid parameter specifies the set of child processes for which to wait. If pid is -1, the call waits for any child process.

What is status in Waitpid?

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.


1 Answers

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);
}
like image 156
Ottavio Campana Avatar answered Oct 24 '22 03:10

Ottavio Campana