Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interrupt read() on signal

I have a thread that continuously reads a serial port for data. If the main program receives a SIGINT it calls g_thread_join() on the serial port thread.

However, since the read is blocking the serial port thread won't return and program stalls untill i get a byte on the serial line and then it can exit.

Is there a way to pass the SIGINT on to read() so that it can be forced to return when the main thread demands it?

like image 258
evading Avatar asked Feb 21 '14 15:02

evading


People also ask

Can a signal handler be interrupted?

Signal handlers can be interrupted by signals, including their own. If a signal is not reset before its handler is called, the handler can interrupt its own execution. A handler that always successfully executes its code despite interrupting itself or being interrupted is async-signal-safe.

Which Sigaction flag is used to prevent a system call from being interrupted?

You can set sa_mask in your sigaction call to block certain signals while a particular signal handler runs. This way, the signal handler can run without being interrupted itself by signals.

What is Eintr?

EINTR is the error which so-called interruptible system calls may return. If a signal occurs while a system call is running, that signal is not ignored. If a signal handler was defined for it without SA_RESTART set and this handler handles that signal, then the system call will return the EINTR error code.


1 Answers

To have read() return EINTR, unset SA_RESTART in the member sa_flags of the struct sigaction passed into the call to sigaction() when installing the signal handler for SIGINT.


An alternative approach woud be to avoid a blocking read() at all. Please see the answers to this question: how to avoid blocking from the read function?

like image 109
alk Avatar answered Oct 05 '22 12:10

alk