Print int from signal handler using write or async-safe functions

后端 未结 3 1658
粉色の甜心
粉色の甜心 2020-11-28 13:44

I want to print a number into log or to a terminal using write (or any async-safe function) inside a signal handler. I would prefer not to use buffered I/O.

3条回答
  •  时光说笑
    2020-11-28 14:22

    If you really insist on doing the printing from a signal handler, you basically have 2 options:

    1. Block the signal except in a dedicated thread you create for handling the signal. This special thread can simply perform for (;;) pause(); and since pause is async-signal-safe, the signal handler is allowed to use any functions it wants; it's not restricted to only async-signal-safe functions. On the other hand, it does have to access shared resources in a thread-safe way, since you're now dealing with threads.

    2. Write your own code for converting integers to decimal strings. It's just a simple loop of using %10 and /10 to peel off the last digit and storing them to a short array.

    However, I would highly recommend getting this operation out of the signal handler, using the self-pipe trick or similar.

提交回复
热议问题