user/kill.c
About this file
kill pid ... asks the kernel to terminate each process whose PID (process ID) is given. xv6
has no ps command, but you can see the PIDs by typing Ctrl-P at the console, which
makes the kernel print its process table (procdump).
“Kill” in xv6 is a request, not an instant stop. sys_kill calls
kkill, which only sets the victim’s killed flag and, if the victim is
sleeping, makes it runnable. The victim notices the flag itself: usertrap
checks it at the start of every system call (kernel/trap.c:57) and after handling
any trap, just before returning to user space (kernel/trap.c:81), and long waits such as
sys_pause, consoleread and kwait check it after
waking. The victim then calls kexit with status -1 (exit status). This
way the process never dies in the middle of a kernel operation, while holding locks or
halfway through a file system update.
There are no signals in xv6: kill cannot be caught, ignored, or used to send anything
other than “terminate”.
Read before: user/zombie.c. Read next: kernel/proc.c (kkill).
Headers
user/user.h declares kill and atoi. kernel/stat.h is not used.
At least one PID is required
char **argv is the same type as char *argv[] in the other utilities: in a
parameter list, an array declaration means a pointer. With no PID the usage message
goes to standard error and the program exits with status 1.
Kill each PID, ignoring errors
Each argument is converted from text to a number with atoi and passed to
the kill system call. Nothing is checked:
atoistops at the first non-digit and returns 0 for something likeabc.kkillrejects PID 0 (it marks unused process slots) and returns -1.killreturns -1 for a PID that does not exist, and that result is discarded.
So kill abc and kill 999 both succeed silently with status 0.
One PID is special. kill 1 targets init (user/init.c). Its wait call
returns, usertrap sees the flag and calls kexit, which refuses
to let init exit and stops the whole kernel with panic: init exiting. Trying it
in QEMU confirms that the machine stops.
Convert the argument to a number and ask the kernel to kill that process
(sys_kill → kkill). The return value is ignored.
Exit with status 0 regardless of what happened.