29

I have a requirement to write to a log file on reception of any terminate command like SIGTERM AND SIGKILL.

I can register for SIGTERM but how can handle the SIGKILL signal?

Sirish
  • 9,183
  • 22
  • 72
  • 107
  • suggested reading: [Trying to handle SIGKILL](http://stackoverflow.com/questions/3689403/how-do-i-send-a-signal-to-perl-on-windows) – Ben Voigt Oct 11 '10 at 18:10
  • 1
    possible duplicate of [How to gracefully handle the SIGKILL signal](http://stackoverflow.com/questions/2541597/how-to-gracefully-handle-the-sigkill-signal-in-java) – Ben Voigt Oct 11 '10 at 18:13
  • @Ben Voigt: I'm hesitant to mark this as a duplicate of the "How to gracefully handle the SIGKILL signal" as that question contains misinformation suggesting the Control-C sends a KILL signal when in fact it sends an INTR signal. – Omnifarious Oct 11 '10 at 20:12
  • @Omnifarious: the answers in that question make no such mistake, and answers to this question are going to be 100% redundant with existing answers. That's good enough for a dupe vote for me. – Ben Voigt Oct 11 '10 at 21:10
  • This is why I discourage people from using `kill -9` unless they absolutely have to. Processes should have a chance to clean things up unless you think they are malicious instead of simply off-the-rails or unwanted. – Omnifarious Oct 11 '10 at 23:06

1 Answers1

38

You cannot, at least not for the process being killed.

What you can do is arrange for the parent process to watch for the child process's death, and act accordingly. Any decent process supervision system, such as daemontools, has such a facility built in.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 2
    Using the parent process is easiest, but not required. Any process that holds the other end of a pipe or fifo will be notified when its peer is killed. – Ben Voigt Oct 11 '10 at 18:12
  • 1
    @Ben: The pipe can be closed via some other means than the process's death, and so isn't quite as reliable. But if you don't control the parent process, that may be the only option you have. (daemontools has a `fghack` program that works on that premise.) – C. K. Young Oct 11 '10 at 18:24