簡體   English   中英

waitpid,WNOHANG和SIGCHLD的示例

[英]Example of waitpid, WNOHANG, and SIGCHLD

我需要在C中結合使用waitpidWNOHANGSIGCHLD的示例,以及如何在fore \\ background中使用它們?

 signal( SIGCHLD, SIG_IGN );

 waitpid(child, status, 0);

取自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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM