0

Say I am a utility routine; I might have been called from a signal handler or from 'normal' (possibly multithreaded) code.

Now if I want to print some debug-message, I should use printf/fprintf as they are thread-friendly.

But if I was called from a signal-handler, I should call sprintf+write.

Now is there a way to find this out programatically?

Note: this question was motivated by this: How can I debug runtime library interpositioned process?

Edit: let me summarize the problem this way: a routine wants to write a debug-message, is it supposed to use high-level-IO (FILE) or low-level-IO (write)? High-level is thread-friendly, but not to be used in signal-handler; low-level is the opposite: usable in signal-handler, but not thread-friendly.

Lorinczy Zsigmond
  • 1,749
  • 1
  • 14
  • 21
  • 2
    I added an answer to the other question. IMO, this is a "wrong" question: functions shouldn't have to know whether it's called from signal handler or normal function. The general rule is that signal handlers shouldn't call functions that are not async-signal-safe functions. If it has to, then make those functions async-signal-safe. – P.P Nov 30 '19 at 13:41
  • @usr Thank you for your valuable insight; I've added a summary to make the question more clear. – Lorinczy Zsigmond Dec 01 '19 at 07:47
  • 1
    Use some argument to distinguish the case. – Jean-Baptiste Yunès Dec 02 '19 at 09:26
  • You can use a `volatile sig_atomic_t` flag to differentiate whether it's called from a signal handler or not (but I still maintain that it's a "wrong solution" as noted earlier). There are no hard and fast rules when debugging. So you can try whatever it takes to figure out the issue. "low-level is the opposite: usable in signal-handler, but not thread-friendly" - `write(2)` is thread-safe. – P.P Dec 09 '19 at 13:32
  • Off: By 'thread-friendly' I meant cooperates with locked-stdio; that is desirable in normal code, but impossible in a signal handler. – Lorinczy Zsigmond Dec 11 '19 at 04:58
  • I am not sure what you mean by 'cooperates with locked-stdio' (do you mean sync/order output with stdio?). `write(2)` doesn't interact with stdio. When in signal handler, you are already in a *very* constrained environment. So ordering isn't really an issue. Even if it is, there's not much you can do about it (e.g., you can't safely flush stdio streams in a signal handler before `write(2)` to keep the output order). – P.P Dec 23 '19 at 16:37
  • Well, I'll try it again: in signal handler, write(2) is the only option, when not in signal handler, printf(3) is better than write(2) -- also I cannot find out which is the case. – Lorinczy Zsigmond Dec 23 '19 at 18:34

0 Answers0