Search code examples
csignalsforkkillzombie-process

How to send a signal to a child several times avoiding zombie state? C language


I need to send a signal to a child process 3 times.

The problem is that the child only receives the signal once and then transforms into a zombie.

The expected output would be:

 I'm the child 11385 and i received SIGUSR1

 I'm the child 11385 and i received SIGUSR1

 I'm the child 11385 and i received SIGUSR1

But the real output is:

 I'm the child 11385 and i received SIGUSR1

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

void my_handler()
{
  printf("\n I'm the child %i and i received SIGUSR1\n", getpid());
}


int main (int argc, char **argv) {
    int *array;
    int N = 10;
    int i;
    pid_t pid1;
    array=(int*)malloc(sizeof(int)*N);


    signal(SIGUSR1,my_handler);

    for (i = 0; i< N; i++) 
    {
        pid1 = fork();
        if(pid1 < 0)
        {
            exit(EXIT_FAILURE);
        }
        else if (pid1 > 0)
        {
            array[i]= pid1;
        }

        else
        {   
            sleep(100);
            exit(EXIT_SUCCESS);
        }
    }

    i=0;
    while(i<3) // I need to call the son 3 times
    {
        kill(array[1], SIGUSR1);
        i++;
    }
}

Solution

  • When the child receives the signal, it is probably waiting for the sleep to terminate. The first signal will interrupt the sleep even if the time hasn't expired, causing it to return with errno set to EINTR. If you want it to keep sleeping, you need to call sleep again.