Macos – Why does kill -9 0 on a mac simply kill the bash shell

macos

I'm trying to see what happens when I try to kill the kernel_task process. Since kill -9 pid is the command to force quit a process, and kernel_task's pid is 0, I simply ran kill -9 0.

Instead of getting Permission Denied or a Operation not permitted when killing a root process, you simply get this:

Last login: Thu Jun 18 16:55:10 on ttys005
MacBook-Air:~ james$ kill -9 0

[Process completed]

… which is weird because trying to kill launchd (one level below kernel_task) gives you this:

-bash: kill: (1) - Operation not permitted

and all other root processes.

Why the heck does it just terminate the process that called the command, instead of sending Operation not permitted, like all the other root processes?

Bonus points if you can tell me the answer to this question:
If you create a script that tries to kill kernel_task (and ignores SIGTERM), running it will output Killed: 9 and return to bash. Why does it put that into stdout when it kills it? Why not something more descriptive?

Best Answer

and kernel_task's pid is 0

They probably use the PID 0, because it is a reserved PID and as such you cannot send signals to the process.

I simply ran kill -9 0.

The *nix command kill is more or less a direct front-end for the kill system call. From the documentation of the system call:

If pid is zero:
      Sig is sent to all processes whose group ID is equal to the process group ID of the sender, and
      for which the process has permission; this is a variant of killpg(2).

In other words, in your case, kill -9 0 is just a fancy way to send the (fatal) signal to itself. (More about process groups.)

Why the heck does it just terminate the process that called the command

The kill (unless you have tweaked the shell settings) is a built-in shell command. In other words, the shell calls the kill syscall and that causes it to kill itself.

Try the same but with the external kill command, e.g. /bin/kill -9 0. In that case only the /bin/kill would be killed.

Related Question