signal - asynchronous recycling mechanism 2

Foreword: The processing method of the previous article can solve all recycling problems, but if we do not consider the return status of the child process, then the kernel can be used to recycle the child process

code show as below:

//If you don't need to care about the end state of the process, you can set that no zombie process will be generated when the child process ends. There will be kernel values ​​and then recycling
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types .h>
#include <signal.h>

#define NR 40


int main(void)
{
     pid_t pid;

#if 0
     //The child process ends or stops or SIGCHLD signal occurs from stop to continue
     //Some platforms set the SIGCHLD signal If the behavior is ignored, no zombie process will be generated
     if(signal(SIGCHLD,SIG_IGN)==SIG_ERR)
     {
         perror("signal");
         return 2;
     }
#else
     struct sigaction ac={.sa_handler= SIG_IGN };//ignore the signal
     sigemptyset( &ac.sa_mask);//Do not expect to mask other signals
     ac.sa_flags=SA_NOCLDWAIT;// Do not generate zombie processes
     sigaction(SIGCHLD,&ac,NULL);
#endif //

     int i;
     for(i=0;i<NR;i++)
     {
        pid=fork();
        if(pid==-1)   return 1;//error
        else if(pid==0)//child
        {
            printf("%dth child <%d> start work.\n",i,getpid());
            sleep(3);
            printf("%dth child <%d> end   work.\n",i,getpid());
            exit(0);
        }
     }
     //parent
     while(1)
     {
         getchar();
         printf("parent working....\n");
     }

     return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324782898&siteId=291194637