3

I have a blocking read in linux running in a thread.

During program shutdown I want to break the thread out of this read. Unfortunately I can't use poll or select and write proper code because the file that is read from is a device driver that does not implement poll/select functionality.

As a temporary solution I currently send a SIGUSR1 signal via pthread_kill to the thread and call pthread_exit from the handler. This kills the thread and works so far, but I'm not satisfied with the solution because the signal could occur anywhere, not only within the read.

Is there any mechanism to interrupt a blocking read on linux?

Btw - I tried closing the file-handle from a different thread in hope that this would give a IO-error of some sorts. Unfortunately this simple solution didn't worked at all.

Nils Pipenbrinck
  • 83,631
  • 31
  • 151
  • 221
  • 5
    A signal is the only way to interrupt a blocking read. – Peter G. Mar 06 '11 at 16:47
  • 1
    a signal that calls pthread_exit is morally equivalent to just pthread_cancel'ing the thread fwiw (assuming the thread is cancellable). read is a cancellation point. This isn't any better than your current solution but it might simplify the code some. – Logan Capaldo Mar 06 '11 at 17:02

1 Answers1

4

If you only want the signal to affect the read, use pthread_sigmask() to keep the signal blocked until just before the read and to block it again afterwards.

mark4o
  • 58,919
  • 18
  • 87
  • 102