Is int puts(const char*);
re-entrant? Can I safely put it into a signal handler?
Asked
Active
Viewed 672 times
4

Šimon Tóth
- 35,456
- 20
- 106
- 151
2 Answers
4
Here is a table with all functions considered safe for signal handling:
"The following table defines a set of functions that shall be either reentrant or non-interruptible by signals and shall be async-signal-safe."
puts
does not seem to be in that list, however per this, it is deemed reentrant, but not async-safe, perhaps why it is not in the above mentioned list.

Tony The Lion
- 61,704
- 67
- 242
- 415
-
1Hmm, where is the difference between `puts` and `write`? – Šimon Tóth May 09 '11 at 09:52
-
@Let_Me_Be: don't know for sure, but `puts()` is part of stdio, which in itself is not async-signal-safe. Possibly, but not limited to, features like output buffering. – Christian.K May 09 '11 at 10:01
-
@Christian Yeah you are right, I totally forgot that the whole stdio is working on top of `FILE` structures not file descriptors. – Šimon Tóth May 09 '11 at 10:06
-
The issue is the memory buffering; `puts()` may buffer, which may require a new buffer to be allocated, which may require calling `sbrk()` or `mmap()` to allocate memory. Those two functions are not async-signal-safe. (The actual underlying `write()` to the stdout FD is fine though.) – Donal Fellows May 09 '11 at 10:07
2
No it is not, you can however use write()
, which is async signal safe, to output messages from a signal handler:
#include <unistd.h>
const char* msg = "The message to print.";
write(STDOUT_FILENO, msg, strlen(msg));

Christian.K
- 47,778
- 10
- 99
- 143
-
-
1I [think](http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html) it is. "The following table defines a set of functions that shall be async-signal-safe. Therefore, applications can call them, without restriction, from signal-catching functions." ... and later ... "strlen". – Christian.K Oct 08 '18 at 04:29
-