4

Many POSIX blocking functions return EINTR in case of a signal. The idea is that signal handler sets a flag first (say 'stop' flag in case of SIGINT), then the blocking function unblocks returning EINTR and the application sees the flag and performs orderly shutdown (or whatever).

However, there is no EINTR error for some blocking functions like pthread_mutex_lock and pthread_cond_wait.

What's the idea behind that? How are the applications using these functions supposed to handle signals (Ctrl+C, specifically)?

Martin Sustrik
  • 783
  • 10
  • 22
  • 1
    Well, imagine that `pthread_mutex_lock()` were interruptible. If it gets interrupted, what assumptions should the following code make? Is the mutex locked, or unlocked? Or maybe it's halfway in between... How could the surrounding code restart an operation? EINTR isn't always intended to request shutdown, many times re-trying is an appropriate action... – twalberg Oct 29 '12 at 20:33
  • 1
    pthread_cond_wait() is of more interest here as it is intended to wait for unlimited amount of time. – Martin Sustrik Oct 30 '12 at 05:17

2 Answers2

1

No answer. My assumption is that pthread_cond_wait() and SIGINT cannot be combined to perform a clean shutdown. Use sem_wait() or similar instead of pthread_cond_wait().

Martin Sustrik
  • 783
  • 10
  • 22
0

In general, only system calls (low level OS calls) return EINTR. Higher level standard library calls do not. So for example, read and write may return EINTR, but printf and gets will not.

Generally, the right thing to do on receiving an EINTR is to redo the call -- that's whythe SA_RESTART flag on signal handlers exists. If you want to handle Ctrl-C, you need to just not ignore the signal. The default action of exiting may be what you want, or you can write your own signal handler to do something else.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • Well, you can write a signal handler, but then what? Main thread is still blocked in pthread_cond_wait() and cannot check any flags you happen to set in the handler. Is it intended that you call pthread_cond_signal() in the handler? – Martin Sustrik Oct 30 '12 at 06:23
  • On Linux, man signal(7) doesn't list pthread_cond_signal among signal-safe functions. Is there any other way to unblock the main thread? – Martin Sustrik Oct 31 '12 at 06:42