Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Equivalent of Windows Hooks

I would like to know how to express something like a windows hook in Linux.

I have a Linux application with various threads. The main thread currently installed a signal handler for ctrlc, catches it and shuts down the application.

I would like another thread in the application to process the ctrlc event first and then pass on to the main thread.

like image 391
Medicine Avatar asked Mar 21 '26 11:03

Medicine


1 Answers

As far as I know this would be tricky to do. Unix signals are primitive.

Signals get delivered to a random thread by default. To get around this the trick usually employed is to block signals in all the threads except one. The easiest way to do this is to block all the signals in main with pthread_sigmask, then create the threads (which will inherit the signal mask), and then have a separate thread that does a sigwait/sigwaitinfo on the blocked signals. This forces the signals to be delivered to that thread.

After consuming the signal in the signal-catching thread you would need to do a pthread_kill with main's thread id and the caught signal number to forward the signal to main. The problem is that main would have it blocked.

You can't really unblock main and block the signal-catching thread before forwarding the signal because it is a race condition - there is nothing stopping a second signal from coming in and the signal-catching thread not seeing it. That defeats the whole effort.

You could have the signal-thread send a message to main through some other form of IPC (pipe or whatever) saying "caught XX, take appropriate action". Maybe that is sufficient?

Maybe someone has some clever idea but I suspect the bottom line is that this just isn't how it is normally done in unix.

like image 151
Duck Avatar answered Mar 23 '26 23:03

Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!