Using appropriate POSIX signals
I am currently working on a project which has a daemon process that looks at a queue of tasks, runs those tasks, and then collects information about those tasks. In some cases, the daemon must "kill" a task if it has taken too long to run.
The explanation for SIGTERM is "termination signal" but that's not very informative. I would like to use the most appropriate signal for this.
What is the most appropriate POSIX signal number to use for telling a process "you took too much time to run so you need to stop now"?
If you're in control of the child processes, you can pretty much do as you please, but SIGTERM
is the self-documenting signal for this. It asks a process to terminate, politely: the process chooses how to handle the signal and may perform cleanup actions before actually exiting (or may ignore the signal).
The standard way to kill a process, then, is to first send a SIGTERM
; then wait for it to terminate with a grace period of, say, five seconds (longer if termination can take a long time, eg because of massive disk I/O). If the grace period has expired, send a SIGKILL
. That's the "hard" version of SIGTERM
and cannot be ignored, but also leaves the process no chance of neatly cleaning up after itself. Having to send a SIGKILL
should be considered an issue with the child process and reported as such.
Usually you'll first send SIGTERM
to a process. When the process recives this signal it is able to clean up some things an then terminate itself:
kill -15 PID_OF_PROCESS # 15 means SIGTERM
You can check if the process is still running by sending the 0
signal to it's pid.
kill -0 PID_OF_PROCESS # 0 means 0 :)
if [ "$?" == "0" ] ; then
echo "the process is still running"
fi
However, you'll need some grace period to let the process clean up. If the process didn't terminated itself after a grace period, you kill it using SIGKILL
this signal can't be handled by the process and the OS will terminate the process immediately.
kill -9 PID_OF_PROCESS # 9 means SIGKILL, means DIE!
链接地址: http://www.djcxy.com/p/50024.html
上一篇: 在linux c编程中的信号
下一篇: 使用适当的POSIX信号