On linux systems, you can kill processes by typing <Ctrl+C>
in bash or by using the command kill -9 $pid
, but they are very different.
Let’s put the conclusion first: kill command will only kill the target process, while bash shortcut will kill the whole foreground process group!
linux process killing methods
Regardless of the method used, killing processes is done by sending a signal. The kill command actually sends a signal to the target pid process.
kill -9
- sendSIGKILL
kill -2
- sendsSIGINT
kill -15
- sendsSIGTERM
The complete list is as follows.
The bash shortcuts send signals in the following manner.
- INT -
<Ctrl+C>
- KILL -
<Ctrl+\>
Foreground process groups
A session is a collection of one or more process groups. Each login to a terminal is equivalent to a new session, and a session can have one foreground process group and multiple background process groups.
By default, programs started via bash are placed in the foreground process group, including the child processes of this program.
To place a group in the background, you can use &
to specify
|
|
(Also, only foreground starts are bound to standard input and output.)
Killing a process via <Ctrl+C>
or <Ctrl+\>
in bash sends a signal to every process in the foreground process group.
Whereas killing a program by kill, the signal will only be sent to the target pid process.
Verification
Program 1:
The above program is the same as program 1, except that a separate process group is set up for the child processes (which are not in the foreground process group at this point).
Test results.
- Kill the main process with kill -9, -2, -15 respectively, and sleep the child process to survive.
- Use
<Ctrl+C>
and<Ctrl+\>
to kill the main process and sleep the child process.