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 - send SIGKILL
  • kill -2 - sends SIGINT
  • kill -15 - sends SIGTERM

The complete list is as follows.

1
2
# kill -l
HUP INT QUIT ILL TRAP ABRT EMT FPE KILL BUS SEGV SYS PIPE ALRM TERM URG STOP TSTP CONT CHLD TTIN TTOU IO XCPU XFSZ VTALRM PROF WINCH INFO USR1 USR2

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

1
echo 123 &            

(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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
    "time"
    "os/exec"
)

func main(){
    cmd := exec.Command("sleep", "100000")
    cmd.Start()
    time.Sleep(time.Second * 99999)
    return
}

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.