0

I recently read code in unp(),in chp 5.9, on the book, when handling zombies, the author use

signal(SIGCHLD, sig_chld);

Also, inside the sig_chld, the code is as following:

void sig_chld(int signo){
    pid_t pid;
    int stat;
    pid = wait(&stat);
    printf("child %d terminated\",pid); 
    return;
}

I have tried this, and I successfully handled zombies, but the function printf can't work normally. Why? If more information is needed, just comment. Thanks!!!

LimingFang
  • 131
  • 9
  • 1
    you shouldn't be using `printf()` inside signal handler `sig_chld` as they are not signal safe. Between `\ ` --> `\n` inside `printf()`. – Achal Aug 18 '19 at 14:28
  • 2
    Possible duplicate of [Printf is not working in C signal handler](https://stackoverflow.com/questions/9547949/printf-is-not-working-in-c-signal-handler). Also read [How to avoid using printf in a signal handler?](https://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler) – Achal Aug 18 '19 at 14:29
  • ok, man. I will try it. Thanks – LimingFang Aug 18 '19 at 14:54

1 Answers1

0

Only async-signal safe functions can be used in a signal handler. See the explanation and the list of such functions in man signal-safety.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • 1
    And even most of those cannot be used safely since they set `errno`, causing error code loss. –  Aug 18 '19 at 14:32
  • @StaceyGirl You can save `errno` and restore it at the end of the signal handler. – Maxim Egorushkin Aug 18 '19 at 14:36
  • thanks, man. I'm going to see it – LimingFang Aug 18 '19 at 14:54
  • Since `errno` is of type `int` rather than `volatile sig_atomic_t` I suspect that accessing it in both normal code and signal handlers is *technically* undefined behavior, though I suspect that even on a machine where `int` is not inherently written atomically it would be very difficult for a (non explicitly malicious) compiler to cause this undefined behavior to express itself. – EOF Aug 19 '19 at 21:18
  • @EOF `errno` shows its age, but still works as expected, and I see no reason why it wouldn't. – Maxim Egorushkin Aug 20 '19 at 09:16