Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to pass arguments to a signal handler? [duplicate]

Tags:

c

I'm registering in the main an handler for the SIGTERM like this:

signal(SIGTERM, sigterm_handler);

And the handler is a simple:

void sigterm_handler()
{    exit(1);    }

What if I need to pass to the handler a few arguments like a 2 pointers or anything else? How do I register the handler in the signal function? Or at least... is there anyway to achieve that?

Notice: the process is killed by a third party process, not by itself. But before closing I need to manually free some structures and write them on files.

like image 863
Damiano Barbati Avatar asked May 03 '11 20:05

Damiano Barbati


People also ask

Do signal handlers run concurrently?

Signal handlers run concurrently with main program (in same process). <= 1 pending signal per type per process No Queue! Just a bit per signal type.

Can signal handlers be interrupted by other signal handlers?

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.

Does Sigaction call the signal handler?

sigaction() can be called with a NULL second argument to query the current signal handler. It can also be used to check whether a given signal is valid for the current machine by calling it with NULL second and third arguments.

Are signal handlers per thread?

signal is a per process call, not a per thread one, if you call it it sets the handler for all threads in the process.


2 Answers

Where do you intend to pass the arguments from? The only time sending a signal would be a reasonable way to do what you're doing is when the process you're terminating is not the process itself, but in that case, pointers would be meaningless. You can pass a pointer with the sigqueue function and SA_SIGINFO type signal handlers, but it looks to me like you don't understand signals or have any good reason for using them in the first place. Just make a function call when you want to exit rather than raising signals...

like image 198
R.. GitHub STOP HELPING ICE Avatar answered Sep 28 '22 08:09

R.. GitHub STOP HELPING ICE


Simply use a global variable. As others have pointed out, your signal handler will be invoked by a call stack not under your control.

You might consider using setjmp() and longjmp() to transfer control from your signal handler to a previously-executed code path. This old-school approach could be really fun for you.

like image 32
Heath Hunnicutt Avatar answered Sep 28 '22 10:09

Heath Hunnicutt