0

I have to write a C program that creates 10 child processes, which each write a message when created. Also the Parent should print a message when one of the Childs terminates.

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

void CHLDhandler(int);


int main(int argc, char const *argv[]){

  pid_t p;

  signal(SIGCHLD,&CHLDhandler);

  for(int i=0; i < 10; i++){
    p = fork();
    if ( p == (pid_t) 0 ) {
      /* child */

      signal(SIGCHLD, SIG_IGN);

      printf("Child number %d was born!\n",i);
      return 0;
    }
    else if ( p > (pid_t) 0 ) {
      /* parent */
    }
  }


}

void CHLDhandler(int sig){
  printf("Child finished\n");
}

This is my code so far. On Linux it runs fine but on MacOS I get an Illegal Hardware Instruction Error.Error Message

  • 1
    What goes in `/* parent */`? See [How to avoid using `printf()` in a signal handler?](https://stackoverflow.com/questions/16891019/) for information about why using `printf()` in a signal handler is not strictly supported. You'd normally get away with it, though. Is that really the complete MCVE ([MCVE])? Which compiler are you using on your Mac? (When I run it on my Mac, it works OK (`clang` and GCC 8.1.0). I get fewer 'finished' messages than there are children, but that's not a surprise. The code doesn't wait for the kids to finish.) – Jonathan Leffler May 10 '18 at 14:32
  • 1
    You could make it easier to see where the problem occurs by adding process ID values to the print out. In your image, you have process 12133 generating the illegal instruction fault; is that the parent or a child? Adding PIDs to the printout would help. – Jonathan Leffler May 10 '18 at 14:38
  • Experiment with removing the printf in the signal handler, and with using the system call `write` instead. Does the problem happen with only two children? – Arndt Jonasson May 10 '18 at 23:07
  • using write instead fixed the error and the parent now waits for all childs to terminate @JonathanLeffler but I still don't get all 10 "Child finished" messages because apparently not all signals are handled? – TheKickpuncher May 11 '18 at 13:38
  • You can’t expect to see all the signals unless the parent stays around long enough to ensure that they are all delivered. It heads for the exit without caring about whether its children are all dead. – Jonathan Leffler May 11 '18 at 14:36
  • I updated my code so that the parent waits long enough but the problem is that some signals get lost. My friend asked a more specific question here: https://stackoverflow.com/questions/50294137/why-does-a-sigaction-handler-not-handle-every-signal-even-if-the-sa-nodefer-flag – TheKickpuncher May 11 '18 at 16:05

0 Answers0