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.
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...
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.
you cannot pass an argument to the handler - since you are not the one calling the handler. The handler will be called from somewhere outside your control.
you register a handler either with a call to signal
or sigaction
.
hth
Mario
Signals normally come asynchronously, meaning not from specific spots in the program, and therefore you can't pass arguments normally. If I were to press control-C while the program was running, what pointers should the signal handler get?
You could only pass meaningful arguments (if C would allow that, which it doesn't) if you constructed a signal within your program and deliberately raised it, and in such a case you should call a function instead.
So, if you want to call something in your program, use a function. If you want a function called if there's an external event, which will know nothing of what you're processing, use a signal handler.
精彩评论