Search code examples
csignalsforkkill-process

Capture signal in C and kill all children


I need to capture CTRL+C and finish the children, the main process have to wait until the finish its stuff, and then the program have to finish. This is my code:

 void sigint_handler()
{
    /*do something*/
    printf("killing process %d\n",getpid());
    exit(0);
}

int main ()
{
  signal(SIGINT, sigint_handler);


  printf ("This is the parent. PID=%d\n",getpid ());

  int num_children = 4;

  int i;

  while (1){

  for (i=0; i<num_children ;i++){

   if (fork()==0){

    printf ("This is children %d\n",getpid()); 

    sleep(1);

    exit(0);

   }

  }

  //Rest Parent code
  sleep (1);

  printf ("This is the parent again %d, children should have finished\n",getpid());

  //Do stuff

  }

}

And this is the output:

This is the parent. PID=19317
This is children 19318
This is children 19319
This is children 19321
This is children 19320
^Ckilling process 19321
killing process 19320
killing process 19317
killing process 19318
killing process 19319

How can I handle this ¿? I don't want to kill the parent, just the children, thank you in advance !


Solution

  • Now is much better like this:

        void sigint_handler()
        {
            /*do something*/
            printf("killing process %d\n",getpid());
            exit(0);
        }
    
        int main ()
        {
            int num_children = 4;
            int i, pid, status;
            printf ("This is the parent. PID=%d\n", getpid());
    
            while (1) {
                for (i = 0; i < num_children; i++) {
                    if ((pid = fork()) == 0) {
                        signal(SIGINT, sigint_handler);
                        printf("This is children %d\n", getpid()); 
                        sleep(1);
                        exit(0);
                    }
                }
    
                // Rest Parent code
                sleep (1);
                waitpid(pid, &status, 0); 
                printf ("This is the parent again %d, children should have finished\n", getpid());
            }
        }
    

    It finishes killing first the children but the waitpid seems do nothing, this is the output:

    This is the parent. PID=20048
    This is children 20049
    This is children 20050
    This is children 20051
    This is children 20052
    This is the parent again 20048, children should have finished
    This is children 20053
    This is children 20054
    This is children 20056
    This is children 20055
    ^Ckilling process 20056
    killing process 20055
    killing process 20053
    killing process 20054
    

    And what I want is to print at the end : This is the parent again 20048, children should have finished and then finish. Thank you very much