How to Deal with Errno and Signal Handler in Linux

How to deal with errno and signal handler in Linux?

The glibc documentation says:

signal handlers that call functions that may set errno or modify the floating-point environment must save their original values, and restore them before returning.

So go ahead and do that.

If you're writing a multi-threaded program using pthreads, there's a workaround that requires less effort. errno will be in thread-local storage. If you dedicate one thread to handle process-directed signals, blocking the signal in all other threads, you don't have to worry about assignments to errno in the signal handler.

errno is signal handler

Writing one character to a pipe is a common way to communicate from a signal handler to a poll loop. Yes, you should[1] save errno and restore it in the signal handler. It is also a good idea to put the pipe (or other file descriptor) you are writing to in NON BLOCKING mode so that the write call cannot block (which could happen if the signal handler is called many times before some thread has a chance to read it).

signalfd is another way to safely communicate a signal to a poll loop.

[1]https://www.gnu.org/software/libc/manual/html_node/POSIX-Safety-Concepts.html

Issue with signal handling, interrupt handling

Signal is executed in user mode, but with a different user context, then return to kernel, which return to user_mode with ret_from_syscall.
The behaviour of system call when signal handler are installed with SA_RESTART depends on the system call.

A description of which system call are restarted is available in recent version of the signal overview manpage :

man 7 signal

If the SA_RESTART flag is not used, system call is not restarted.



Related Topics



Leave a reply



Submit