1

I call write() in my SIGCHLD signal handler.

But write() may sometimes set errno. Will this break my program?

Should I save and then restore errno like the following?

void sigchld_hanlder(int)
{
  int old_errno = errno;
  write(...);
  errno = old_errno;
}
porton
  • 5,214
  • 11
  • 47
  • 95
  • 1
    Are you allowed to use `write` in a signal handler? I thought it was a restricted function. Also see [How to avoid using printf in a signal handler?](https://stackoverflow.com/a/16891065/608639), [Print int from signal handler using write or async-safe functions](https://stackoverflow.com/q/14573000/608639), [Is there a way to use errno safely in a multi-threaded application?](https://stackoverflow.com/q/449778/608639) and [Is errno thread-safe?](https://stackoverflow.com/q/1694164/608639) – jww Jan 28 '18 at 01:28
  • 1
    You would be wise to do as little as possible in signal handlers, such as setting a volatile flag that will be detected in the non-signal-handler part of your code and acted on accordingly. – paxdiablo Jan 28 '18 at 01:40
  • @paxdiablo I am allowed to use `write()` by http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04 (actually I send only one byte with this write, to "awake" a `poll()` in the same process – porton Jan 28 '18 at 03:45
  • 1
    Myself, I would still do that with threads. Have the signal handler set a flag and have a dedicated thread monitoring that flag and doing the writing. That way, you bypass a whole slew of possible problems (what happens if your `write` blocks in a sig-handler, for example). – paxdiablo Jan 29 '18 at 01:12
  • Related: [How to deal with errno and signal handler in Linux](https://stackoverflow.com/questions/48378213/how-to-deal-with-errno-and-signal-handler-in-linux) – Mark Plotnick Jan 29 '18 at 20:05
  • 1
    It's a common practice to save the errno inside a signal handler. – Emil Terman Jan 30 '18 at 10:11

1 Answers1

3

Writing one character to a pipe is a common way to communicate from a signal handler to a poll loop. Yes, you should[1] save errno and restore it in the signal handler. It is also a good idea to put the pipe (or other file descriptor) you are writing to in NON BLOCKING mode so that the write call cannot block (which could happen if the signal handler is called many times before some thread has a chance to read it).

signalfd is another way to safely communicate a signal to a poll loop.

[1]https://www.gnu.org/software/libc/manual/html_node/POSIX-Safety-Concepts.html

Acorn
  • 768
  • 6
  • 15