How do you find or stop processes by name using pgrep and pkill?
pgrep prints the PIDs of processes whose names match a pattern, and pkill sends them a signal (SIGTERM by default). Use -f to match the full command line and -u to limit to a user. Always run pgrep first to see what would be hit.
Explain it simply
Looking up a PID with ps aux | grep and then copying it into kill is slow and error-prone. pgrep and pkill do the lookup and action in one step.
pgrep nginx prints PIDs of processes whose name contains nginx. pgrep -l nginx adds the names. pgrep -a nginx shows the full command lines.
pkill nginx sends SIGTERM to all matches. Change the signal with pkill -9 name or pkill -HUP nginx.
By default the pattern matches only the process name (up to 15 characters). With -f it matches the entire command line, which is needed to tell two Python scripts apart: pkill -f report.py. With -u amit you limit it to one user's processes, and -x demands an exact name match.
Because a pattern may match more than you expect, run the same pattern with pgrep first. killall name is a similar command, but on some Unix systems it kills everything, so pkill is the safer habit.
Example
pgrep -af "python3 report.py"
# 7312 python3 report.py --daily
pkill -f "python3 report.py"
pgrep -af "python3 report.py" || echo "stopped"
# stoppedWhat to say in the interview
"pgrep finds PIDs by name and pkill signals them. I check with pgrep -af first, use -f to match the full command line when names are shared, and prefer SIGTERM before SIGKILL."
Common mistakes
- Running pkill python and stopping unrelated Python services.