How to catch pkill signal in LINUX/C++?

Hi,

I crontab a process kill like
pkill -9 MyApp

In my codes, I tried to catch the signal so I can ensure all destructors called.

The codes is like this


void handler(int s)
{
cout << "SIG " << s << endl;;

exit(0);
}

int main(int a, const char ** ac)
{
signal(SIGKILL, handler);
signal(SIGINT, handler);
while(true){
sleep(1);
}

It seems that I can only catch Ctrl-C event, but not the kill event.
Anything wrong in the codes?

Thanks

Chris
SIGKILL cannot be caught, nor SIGSTOP / SIGCONT, according to POSIX.

nope, no can do.

be careful with pkill too.
it searches on a pattern, you may find yourself killing stuff you don't want to.
you should use -x at least really.
better still don't use it on a production system.

also some implementations (solaris?) have length limits on the string.


I've killed a load of important daemons on a production box with
injudicious pkills in my youth!
Last edited on
Thanks for the reply. Here is my issues:

I usually use pkill to crontab autorestart my app and intra day restart (I could use -x as bigearsbilly suggested). My problem is that I found the destructors are not invoked in this case and my clean up work was not done properly.

I was thinking to use signal to catch the kill message so I can clean up something before it is down. Is there a better way to do it in LINUX?

Thanks
Use another signal like SIGTERM instead. SIGTERM and SIGKILL essentially do the same thing, except
the kernel does not allow processes to catch or block SIGKILL.

EDIT: So pkill -SIGTERM <process-name>
Last edited on
this works great! thanks a lot
Topic archived. No new replies allowed.