Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading shared data inside a signal handler

I am in a situation where I need to read a binary search tree (BST) inside a signal handler (SIGSEGV signal handler, which according to my knowledge is per thread base). The BST can be modified by the other threads in the application.

Now since a signal handler can't use semaphores, mutexes etc. and therefore can't access shared data, How do I solve this problem? Note that my application is multithreaded and running on a multicore system.

like image 464
MetallicPriest Avatar asked Feb 03 '23 10:02

MetallicPriest


2 Answers

You shouldn't access shared data from signal handler. You can find out more information about signals in following articles:

Linux Signals for the Application Programmer

The Linux Signals Handling Model

All about Linux signals

Looks like the safest way to deal with signals in linux so far is signalfd.

like image 93
ILYA Khlopotov Avatar answered Feb 05 '23 16:02

ILYA Khlopotov


I can see two quite clean solutions:

  1. Linux-specific: Create a dedicated thread handling signals. Catch signals using signalfd(). This way you will handle signals in a regular thread, not any limited handler.
  2. Portable: Also use a dedicated thread that sleeps until signal is received. You may use a pipe to create a pair of file descriptors. The thread may read(2) from the first descriptor and in a signal handler you may write(2) to the second descriptor. Using write() in a signal handler is legal according to POSIX. When the thread reads something from the pipe it knows it must perform some action.
like image 27
Daper Avatar answered Feb 05 '23 15:02

Daper