`nanosleep()` async-signal safety on Linux

560 Views Asked by At

I need to use the nanosleep function in my user-space threads library to achieve waits of the approximately desired amount, as it can save the remaining time in case of an interrupt by async signals. I use SIGALRM to switch threads preemptively; therefore, it is important to consider the possible side effects of using non-reentrant functions. For that reason, in case a nanosleep call is interrupted by a thread switch and it is called again from another thread or signal handler, I wonder if this situation would cause problems or not.

Apparently, nanosleep function is not async-signal safe by as it is not listed here; however, sleep(3) is said to be async-signal safe. On the other hand, sleep(3) seems to be implemented using nanosleep on Linux. Can I take this as proof that nanosleep is safe for what I am trying to achieve?

EDIT: According to this resource, it is indeed AS-safe.

1

There are 1 best solutions below

2
On

No, you can't safely assume that unless it's specifically documented. The reason is that using nanosleep is an implementation detail of sleep. If the two functions were refactored to use some common internal function in glibc that were async-signal safe but nanosleep's implementation changed such that it were not, your code would be broken.

You cannot rely on the implementation details of functions in glibc, since they can and do change across versions. Notably, all Adobe Flash versions broke on certain machines because glibc changed memcpy to copy down instead of up, which is permitted by the standard and the documentation.

Also, just because glibc does things a certain way doesn't mean other Linux libcs do (or other non-Linux libcs), and your code wouldn't work there.