Lesson 39: kill Command
In this lesson, you'll learn how to use the kill command to send signals to running processes in Linux.
The kill command sends a signal β a specified signal β to a currently running process. The kill command can be executed in several ways, directly or from a shell script.
Using the kill command from /usr/bin provides you with some extra features to kill a process by process name using pkill.
kill Command Syntax
The common syntax for a kill command is:
# kill [SIGNAL or OPTION] PID(s)
kill Command Signals
| Signal Name | Signal Value | Behaviour |
|---|---|---|
SIGHUP |
1 | Hangup |
SIGKILL |
9 | Kill Signal |
SIGTERM |
15 | Terminate |
Clearly, from the behavior above, SIGTERM is the default and safest way to kill a process.
SIGHUP is a less secure way of killing a process than SIGTERM. SIGKILL is the most unsafe way among the above three β it terminates a process without saving.
In order to kill a process, we need to know the Process ID of the process. A process is an instance of a program.
Every time a program starts, a unique PID is automatically generated for that process.
Every process in Linux has a PID. The first process that starts when a Linux system is booted is the init process, it is assigned a value of "1" in most cases.
init is the master process and cannot be killed this way, which ensures that the master process doesn't get killed accidentally.
init decides and allows itself to be killed, where kill is merely a request for a shutdown.
1. List All Running Linux Processes
To know all the processes and correspondingly their assigned PID, run the following ps command.
# ps -A
PID TTY TIME CMD
1 ? 00:00:42 systemd
2 ? 00:00:00 kthreadd
3 ? 00:00:00 rcu_gp
4 ? 00:00:00 rcu_par_gp
5 ? 00:00:00 slub_flushwq
6 ? 00:00:00 netns
8 ? 00:00:00 kworker/0:0H-events_highpri
10 ? 00:00:00 mm_percpu_wq
11 ? 00:00:00 rcu_tasks_kthread
12 ? 00:00:00 rcu_tasks_rude_kthread
13 ? 00:00:00 rcu_tasks_trace_kthread
14 ? 00:00:03 ksoftirqd/0
15 ? 00:01:09 rcu_preempt
16 ? 00:00:03 migration/0
17 ? 00:00:00 idle_inject/0
19 ? 00:00:00 cpuhp/0
20 ? 00:00:00 cpuhp/1
21 ? 00:00:00 idle_inject/1
You can also customize the above output using the pidof command to find the PID of a specific process.
# pidof mysqld
1684
Another way to achieve the above goal is to use the following syntax:
# ps aux | grep mysqld
root 1582 0.0 0.0 5116 1408 ? S 09:49 0:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --socket=/var/lib/mysql/mysql.sock --pid-file=/var/run/mysqld/mysqld.pid --basedir=/usr --user=mysql
mysql 1684 0.1 0.5 136884 21844 ? Sl 09:49 1:09 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --user=mysql --log-error=/var/log/mysqld.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/lib/mysql/mysql.sock
root 20844 0.0 0.0 4356 740 pts/0 S+ 21:39 0:00 grep mysqld