Terminating a process is a crucial part of process management in Linux.
Since process management is a topic of its own, I am not going in the details of managing user processes and signal handling in this post.
I am going to focus on using the SIGTERM and SIGKILL signals to terminate a process. I’ll also discuss about why you should avoid using SIGKILL.
What is SIGTERM?
In UNIX-like systems, the SIGTERM signal is used for terminating a program. You can pretty much guess that from its name which is made up of SIGnal and TERMinate.
The SIGTERM can also be referred as soft kill because the process that receives the SIGTERM signal may choose to ignore it.
In other words, it’s the polite way of killing a process.
How to send SIGTERM to a process in Linux?
The kill command in Linux is used for sending all such signals to processes.
By default, kill command sends the SIGTERM signal. You may explicitly mention it with -15 but that’s redundant.
You’ll need to know the pid of the process in order to use this command in the following manner:
You can use the ps command in Linux to get the process ID.
What is SIGKILL?
The SIGKILL is used for immediate termination of a process. This signal cannot be ignored or blocked. The process will be terminated along with its threads (if any).
It is the brutal way of killing a process and it should only be used as the last resort. Suppose you have an unresponsive process that you want to close. The SIGKILL can be used in such a case.
How to send SIGKILL to a process in Linux?
You can use the option -9 to send the SIGKILL signal with the kill command and kill the process immediately:
kill -9 <process_id>
SIGTERM vs SIGKILL: Why should you prefer using SIGTERM over SIGKILL?
Though both of these signals are used for killing a process, there are some differences between the two:
- SIGTERM gracefully kills the process whereas SIGKILL kills the process immediately.
- SIGTERM signal can be handled, ignored and blocked but SIGKILL cannot be handled or blocked.
- SIGTERM doesn’t kill the child processes. SIGKILL kills the child processes as well.
Some Linux users get habitual of using ‘kill -9’ and that’s something you should avoid. Unless you have an unresponsive process, you don’t need to use SIGKILL.
With SIGTERM, a process gets the time to send the information to its parent and child processes. It’s child processes are handled by init.
Use of SIGKILL may lead to the creation of a zombie process because the killed process doesn’t get the chance to tell its parent process that it has received a kill signal.
This comic from Turnoff humerously explains the difference between SIGTERM and SIGKILL.
I hope you have a better understanding of killing a process using SIGTERM or SIGKILL now.
If you have any questions or suggestions, please feel free to leave a comment.