0

For the following code, the possible outputs are ABBCE4E, ABs7E, and ABCBs7E. I'm not sure why the first one doesn't have a 7 in it. When it sends the interrupt signal to the child, wouldn't "s" and "7" be printed? For the second, I don't understand how "s" and "7" are printed but no "C". Does that mean the kill signal reached the child before it could print "C"? For the last one, I'm not also not sure why a 4 would be printed in any case.

void handler(int sig){
    printf("s");
    exit(7);
}

int forker(int x){
    int pid,status;
    signal(SIGINT, handler);
    printf("A");
    if(x > 0) {
        pid = fork();
        printf("B");
        if(pid == 0) {
            printf("C");
        } else {
            kill(pid,SIGINT);
            waitpid(pid,&status,0);
            printf("%d", WEXITSTATUS(status));
          }
    }
    printf("E");
    exit(4);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
78t66
  • 63
  • 3
  • You should read [How to avoid using `printf()` in a signal handler?](http://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler/) It probably isn't immediately critical, but you should at least know which rules you're breaking before you break them. – Jonathan Leffler May 10 '17 at 23:08
  • Yes, it is perfectly possible for the parent process to send the signal to the child before the child gets to print the `C`. I'm puzzled that you don't see two `A`'s — and if you see a `C`, you should see two `B`'s before it. In my testing, I only got `AsAB7E` as the output. If I add a 1 millisecond `usleep()` before the `kill()`, I get `AB4E` and `ABCE` as results. – Jonathan Leffler May 10 '17 at 23:19
  • In the last results, I had replaced the `printf("E");` with `printf("E\n");`. When run with the millisecond delay 100 times, I got each output string 100 times. Note that if the child gets to print A, B, and C before the parent sends the signal, it will exit with 4 and the parent will pick that exit status up — that's what happens with the millisecond delay. – Jonathan Leffler May 10 '17 at 23:29

0 Answers0