Website Vidya
Linux & ServersStep-by-Step Guide

How to Kill a Process in Linux: kill, killall, and pkill Guide

Learn kill a process in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
11 min read
PDF Cheat Sheet
How to Kill a Process in Linux: kill, killall, and pkill Guide
AI Executive SummaryWebsiteVidya AI

11 min read

Learn kill a process in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What kill Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Knowing how to kill a process in linux safely and accurately is an essential skill for every developer and system administrator. Whether a runaway worker script is exhausting CPU cores, a web server child process is deadlocked on an I/O socket, or a background job is holding a port open, Linux provides granular signal mechanisms to stop processes without restarting the entire host.

Despite its name, the kill command does not merely destroy processes—it is a general-purpose signal dispatcher that invokes the kernel's kill(2) system call to send any of the 64 standard or real-time POSIX signals to one or more processes or process groups. By default, kill PID sends SIGTERM (signal 15), which asks the application to close open files, flush buffers, and exit cleanly.

In addition to targeting numeric Process IDs with kill, Linux offers pattern-based and name-based companions: pkill (which matches process names, command lines, users, or sessions) and killall (which terminates all instances matching an exact binary name). Mastering the escalation ladder from SIGTERM to SIGINT, SIGHUP, and finally SIGKILL (-9) prevents data corruption on production systems.

Advertisement
How to Kill a Process in Linux: kill, killall, and pkill Guide — syntax, flags, and practical terminal workflow diagram
How to Kill a Process in Linux: kill, killall, and pkill Guide — command syntax, key options, and production workflow reference.

What kill Does and When to Use It

Under the hood, almost every interactive shell (bash, zsh, dash, ksh) implements kill as a shell built-in command in addition to the standalone /bin/kill binary provided by util-linux or procps-ng. The shell built-in allows you to reference shell job specifiers such as %1 or %2 alongside numeric PIDs, and it still works even if the system process table (RLIMIT_NPROC) is completely full and no new external binaries can be forked.

When the kernel delivers a signal via kill(2), it sets a pending bit in the target task's task_struct inside the kernel scheduler. Catchable signals like SIGTERM (15), SIGHUP (1), and SIGINT (2) invoke the process's registered user-space signal handler upon its next return from a system call or scheduler tick. By contrast, SIGKILL (9) and SIGSTOP (19) cannot be caught, blocked, or ignored by user space; the kernel immediately tears down the process's virtual memory mappings, closes its file descriptors, and notifies its parent via SIGCHLD.

Under the hood, kill gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -l, -s, -15, -9 turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The kill utility is packaged in util-linux across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether kill is installed and inspect which binary path and version your shell resolves:

type -a kill
kill --version 2>/dev/null || man -f kill

# Illustrative output (reviewed against documentation)
kill is /usr/bin/kill
kill (util-linux)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y util-linux

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y util-linux

# Arch Linux
sudo pacman -S --noconfirm util-linux

# Alpine Linux
sudo apk add --no-cache util-linux

Command Syntax, Arguments, and Exit Status Codes

kill [-s SIGNAL | -SIGNAL] PID... | pkill [OPTIONS] PATTERN | killall [OPTIONS] NAME

The kill utility accepts a signal specification (either by number like -9 or -15, by short name like -TERM or -KILL, or via -s SIGTERM) followed by one or more space-separated targets. Targets can be positive integers (specific PIDs), 0 (all processes in the caller's current process group), -1 (all processes owned by the user except PID 1 and the killer itself), or negative integers like -PGID (every process belonging to Process Group ID PGID).

When you prefer to stop processes by name rather than looking up PIDs manually, pkill [OPTIONS] PATTERN matches a regular expression against process names (or full command lines with -f), whereas killall [OPTIONS] NAME requires an exact match on the executable name (up to 15 characters in /proc/PID/comm unless -e is specified).

  • 0 — Successful execution with no runtime or permission errors.
  • 1 — Operational failure, unmatched condition, or permission restriction.
  • 2 — Invalid command-line option or malformed syntax.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-l--list [SIGNAL]Lists all supported signal names and numbers, or translates a specific signal number/exit status into its name.
-s--signal SIGNALSpecifies the signal to send by name (SIGTERM, SIGKILL, SIGHUP) or number (15, 9, 1).
-15-SIGTERMDefault polite termination signal allowing the process to run cleanup handlers and close files before exiting.
-9-SIGKILLUnconditional kernel termination signal that cannot be caught, blocked, or ignored by the target process.
-1-SIGHUPHangup signal; terminates interactive terminal processes or instructs daemons (nginx, sshd) to reload configuration.
-2-SIGINTInterrupt signal equivalent to pressing Ctrl+C in the controlling terminal.
-19 / -18-SIGSTOP / -SIGCONTPauses (freezes) a running process at the scheduler level (-SIGSTOP) or resumes its execution (-SIGCONT).
-q--queue VALUEUses sigqueue(3) rather than kill(2) to attach an integer value payload alongside the signal (util-linux /bin/kill).

Always follow a disciplined escalation order when stopping a process: start with kill -15 PID (or simply kill PID), wait 3 to 5 seconds for the application to flush state and release locks, verify whether it is still alive using kill -0 PID, and only escalate to kill -9 PID if the process refuses to exit.

Advertisement

Passing signal 0 (kill -0 PID) is a special POSIX idiom: no signal is actually delivered to the target process, but the kernel still performs full existence and permission checks. If kill -0 PID returns exit code 0, the process exists and you have permission to signal it—making it the cleanest way to poll process liveness in bash scripts.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. List Available Signals and Find a Process ID to Terminate Gracefully

Inspect the standard Linux signals with kill -l, locate the target process ID with pgrep, and send the default SIGTERM (15) signal.

kill -l | head -n 3
pgrep -a python3
kill 18420

# Illustrative output (reviewed against documentation)
1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
 6) SIGABRT      7) SIGBUS       8) SIGFPE       9) SIGKILL     10) SIGUSR1
11) SIGSEGV     12) SIGUSR2     13) SIGPIPE     14) SIGALRM     15) SIGTERM
18420 python3 /opt/app/worker.py --queue=emails

Running kill 18420 without a signal flag sends SIGTERM (15), allowing worker.py to finish its current job and close database connections cleanly.

2. Forcefully Kill an Unresponsive Process with SIGKILL (-9)

When a hung process ignores SIGTERM and remains running, send signal 9 (SIGKILL) so the kernel terminates it immediately.

kill -9 18420
# Equivalent named signal syntax:
kill -s SIGKILL 18420

# Illustrative output (reviewed against documentation)
[1]+  Killed                  python3 /opt/app/worker.py --queue=emails

SIGKILL bypasses user-space signal handlers entirely; the kernel reclaims the process's memory pages and closes all open sockets and file descriptors.

3. Reload a Daemon Configuration Without Dropping Connections Using SIGHUP (-1)

Send SIGHUP (-1) to a background daemon's master PID so it re-reads its configuration file and spawns new worker processes gracefully.

sudo kill -HUP $(cat /run/nginx.pid)
sudo ps -ef | grep '[n]ginx'

# Illustrative output (reviewed against documentation)
root        1104       1  0 Oct20 ?        00:00:00 nginx: master process /usr/sbin/nginx
www-data   29410    1104  0 19:12 ?        00:00:00 nginx: worker process
www-data   29411    1104  0 19:12 ?        00:00:00 nginx: worker process

Most Unix daemons (including Nginx, Apache, and rsyslog) trap SIGHUP as a signal to reload configuration files and reopen log files without interrupting active client requests.

4. Kill All Processes Matching a Name Using pkill and killall

Instead of looking up individual PIDs, stop all processes matching an exact binary name with killall or a command-line pattern with pkill.

# Stop all processes whose exact binary name is 'redis-benchmark'
killall -v redis-benchmark

# Stop a specific script by matching its full command line with pkill -f
pkill -f "python3 /opt/app/sync_job.py"

# Illustrative output (reviewed against documentation)
Killed redis-benchmark(21044) with signal 15
Killed redis-benchmark(21045) with signal 15

killall -v confirms each PID it signals, while pkill -f matches against the entire /proc/PID/cmdline argument string rather than just the 15-character executable name.

5. Kill an Entire Process Group (Parent and All Child Processes)

When a shell script spawns multiple child workers, negate the Process Group ID (PGID) to signal the entire tree simultaneously.

ps -o pid,pgid,comm -C backup-runner.sh
# Send SIGTERM to every member of process group 31200
kill -TERM -- -31200

# Illustrative output (reviewed against documentation)
PID    PGID COMMAND
  31200   31200 backup-runner.s

Passing a negative PID (-31200) after -- instructs kill(2) to deliver the signal to every process whose PGID equals 31200, preventing orphaned child processes.

6. Pause and Resume a CPU-Intensive Process with SIGSTOP and SIGCONT

Temporarily freeze a heavy compilation or compression job during peak traffic without losing its in-memory progress, then resume it later.

kill -STOP 24510
ps -o pid,stat,comm -p 24510
# Resume execution later:
kill -CONT 24510
ps -o pid,stat,comm -p 24510

# Illustrative output (reviewed against documentation)
PID STAT COMMAND
  24510 T    ffmpeg
    PID STAT COMMAND
  24510 Rl   ffmpeg

SIGSTOP places the process into the stopped state (T), removing it from CPU scheduling while keeping its memory intact until SIGCONT restores it to running (R).

Real-World Workflows, Pipelines, and Shell Automation

Graceful-to-Forceful Process Termination Function with Timeout

In production deployment scripts, use a reusable bash function that sends SIGTERM, polls with kill -0 for up to 10 seconds, and escalates to SIGKILL only if the process hangs.

#!/usr/bin/env bash
set -euo pipefail

terminate_pid_safely() {
  local pid="$1"
  local timeout="${2:-10}"

  if ! kill -0 "$pid" 2>/dev/null; then
    echo "Process $pid is not running."
    return 0
  fi

  echo "Sending SIGTERM to PID $pid..."
  kill -TERM "$pid"

  for ((i = 1; i <= timeout; i++)); do
    if ! kill -0 "$pid" 2>/dev/null; then
      echo "Process $pid exited cleanly after ${i}s."
      return 0
    fi
    sleep 1
  done

  echo "Timeout (${timeout}s) reached; escalating to SIGKILL (-9) for PID $pid."
  kill -KILL "$pid" 2>/dev/null || true
}

terminate_pid_safely 18420 5

# Illustrative output (reviewed against documentation)
Sending SIGTERM to PID 18420...
Process 18420 exited cleanly after 2s.

This pattern guarantees fast shutdowns when applications cooperate while still bounding maximum deployment time when a worker process deadlocks.

Find and Kill the Process Blocking a Specific TCP Port

When starting a web service fails with 'Address already in use', identify the process holding the port with ss or lsof and terminate it cleanly.

# Inspect which PID is listening on TCP port 8080
sudo ss -lptn 'sport = :8080'

# Extract the PID with lsof -t and send SIGTERM
PORT_PID=$(sudo lsof -t -iTCP:8080 -sTCP:LISTEN)
if [ -n "$PORT_PID" ]; then
  echo "Stopping PID $PORT_PID listening on :8080"
  sudo kill -15 "$PORT_PID"
fi

# Illustrative output (reviewed against documentation)
State   Recv-Q  Send-Q   Local Address:Port   Peer Address:Port  Process
LISTEN  0       511            0.0.0.0:8080        0.0.0.0:*      users:(("node",pid=26104,fd=19))
Stopping PID 26104 listening on :8080

Combining lsof -t -iTCP:8080 -sTCP:LISTEN with kill targets only the listening server socket rather than accidentally killing client connections.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding kill inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

The Linux kernel enforces strict permission checks on kill(2): an unprivileged process can only send signals to target processes whose real or saved set-user-ID matches the caller's real or effective user ID. To signal processes owned by another user or system daemon, the caller must either run as root (via sudo) or hold the CAP_KILL POSIX capability.

Even with root privileges or CAP_KILL, PID 1 (systemd or init) is protected by the kernel against unhandled signals: sending kill -9 1 is ignored by the kernel so an administrator cannot accidentally panic the system by killing the init process.

GNU/Linux, BSD, and BusyBox Implementation Differences

While the kill command is standardized by POSIX.1-2017, the standalone binary path and extra flags differ across platforms. On Linux with util-linux, /bin/kill supports --timeout to automatically escalate signals; the bash built-in kill does not support --timeout unless you invoke /bin/kill explicitly by path.

CRITICAL PORTABILITY WARNING: On Linux, FreeBSD, and macOS, killall name kills only processes matching name. However, on commercial System V Unix operating systems (such as Oracle Solaris and AIX), running killall kills all active processes on the entire machine (similar to System V shutdown).

Troubleshooting Common Errors and Diagnostics

kill -9 <PID> does not kill a process in 'Z' (Zombie) or 'D' (Uninterruptible Sleep) state

Root Cause: A zombie process (Z) is already dead and only retains a PID entry waiting for its parent to call waitpid(2). A process in uninterruptible sleep (D) is blocked inside a kernel system call (typically waiting on dead NFS storage or failing disk hardware) and cannot process signals until the syscall returns.

Resolution: Inspect the process state with ps -o pid,ppid,stat,wchan,comm -p <PID>. For zombies, signal or restart the parent process (PPID). For D-state processes, fix or lazily unmount the hung storage mount.

ps -o pid,ppid,stat,wchan:24,comm -p 27900
# If STAT is Z, notify or restart the parent PID (PPID):
kill -CHLD <PPID>

bash: kill: (18420) - Operation not permitted

Root Cause: The target process belongs to root or another system user account, and your current shell lacks CAP_KILL privileges.

Resolution: Verify process ownership with ps -u -p <PID> and re-run the kill command with sudo.

ps -u -p 18420
sudo kill -15 18420

Killed process immediately respawns with a new PID

Root Cause: The process is managed by a supervisor such as systemd (with Restart=always), supervisord, Docker, or Kubernetes, which automatically restarts crashed processes.

Resolution: Check the process's control group with ps -o pid,cgroup,comm -p <PID> and stop the governing systemd service rather than killing the raw PID.

ps -o pid,unit,comm -p 18420
sudo systemctl stop myapp.service

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
SIGTERM (signal 15) is a polite termination request that the application can catch to flush buffers, roll back transactions, remove PID lock files, and close connections cleanly. SIGKILL (signal 9) is handled directly by the Linux kernel, which immediately terminates the process without allowing any cleanup code to run.
A zombie process (marked with STAT 'Z' in ps or top) has already terminated and released all its memory and CPU resources. Only its exit status remains in the kernel process table waiting for its parent process to read it via wait(). To clear a zombie, send SIGCHLD to or restart its parent process (PPID).
Use kill -0 <PID> 2>/dev/null. Signal 0 performs kernel existence and permission checks without sending any actual signal, returning exit status 0 if the process is alive and 1 if it does not exist.
kill targets processes by numeric Process ID (PID) or shell job ID (%1). pkill signals processes matching a regular expression pattern, user, or session. killall signals all processes that match an exact executable name.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout