MetallicPriest
MetallicPriest

Reputation: 30765

What to take care of in the presence of signals

I saw that semaphores in my application were not always working as expected. Then I was told that this unexpected behavior can be caused when a signal interrupts the sem_wait call.

So, my question is what care needs to be taken by the programmer in the presence of signals. For sem_wait, we can check for the return values, but is this the same for all non-async safe functions? And what else we should keep in mind when expecting signals to interrupt our code?

Upvotes: 0

Views: 113

Answers (1)

user964970
user964970

Reputation:

UNIX signals is a can of worm, just to have said that.

There's 2 camps regarding syscalls and signals.

  • SysV/Posix semantics: syscalls are interrupted by a signal, they return an error and sets errno to EINTR
  • BSD semantics syscalls are auto restarted if a signal occurs (well, most of them are anyway, some are not, e.g. select/poll/sleep).

When using the signal(), the default is one of the two above, with BSD systems and Linux defaulting to BSD semantics, and everyone[citation needed..] else have the SysV semantics. (On Linux, this depends on many things, e.g. compiling with -std=c99 gives SysV semantics, with -std=gnu99 gives BSD semantics. See e.g. http://www.gnu.org/s/hello/manual/libc/Interrupted-Primitives.html)

When you install a signal handler with sigaction(), you get to chose which semantics with the SA_RESTART flags.

Basically:

  • Don't use signals if you can help it.
  • Use the BSD semantics if you can.
  • On code that needs to be portable and handles signals, you need to wrap each and every system call in a loop that checks the call for failure, inspects errno for EINTR and perform the syscall again (or do something based on the caught signal ).
  • library calls can use signals, even if your code don't.
  • syscalls in general, with SysV/Posix semantics, will return -1 and set errno to EINTR. But read the documenation to learn what the error condition is.

EDIT: edited, as I mixed up BSD vs Sysv semantics.

Upvotes: 2

Related Questions