Context
I was making some live changes in a review environment and to test I needed to restart the web server. Since the web server was running multiple processes in parallel, killing each one manually was too cumbersome.
Implementation
Let’s use Passenger web server as an example. Assume that you have the following Passenger processes running on the server:
ps aux | grep Passenger
root 17 0.0 0.0 303940 14660 ? Ssl 18:24 0:00 Passenger watchdog
root 20 2.4 0.1 1693060 21144 ? Sl 18:24 1:45 Passenger core
root 168 0.4 4.9 1517332 800028 ? Sl 18:25 0:18 Passenger RubyApp: /hello (review)
root 190 0.0 3.5 1308056 569668 ? Sl 18:25 0:00 Passenger RubyApp: /hello (review)
root 211 0.0 3.4 1308156 556684 ? Sl 18:25 0:00 Passenger RubyApp: /hello (review)
root 234 0.0 3.4 1308256 556692 ? Sl 18:25 0:00 Passenger RubyApp: /hello (review)
root 255 0.0 3.4 1308356 556700 ? Sl 18:25 0:00 Passenger RubyApp: /hello (review)
root 276 0.0 3.4 1308456 556708 ? Sl 18:25 0:00 Passenger RubyApp: /hello (review)
Then, a potential one-liner to kill all the above processes is:
ps aux | grep -i "Passenger RubyApp" | grep -v grep | awk '{ print $2 }' | xargs kill -9
Here’s what the above commands do:
ps auxlists all current processes.grep -i "Passenger RubyApp"filters this list to include only lines that contain “Passenger RubyApp” (the -i flag makes the search case-insensitive).grep -v grepis used to exclude the grep process itself from the list.awk '{ print $2 }'prints only the second field (by default, fields in awk are separated by whitespace), which for theps auxcommand is the PID (Process ID).xargs kill -9takes the PIDs piped from the previous command and useskill -9to terminate these processes.
Notes
Using kill -9 immediately kills the process and may lead to data loss (if the process was in the middle of I/O operations). It’s generally better to use kill -15 (or kill without any signal which defaults to -15) first, which sends the TERM (terminate) signal allowing the process to finish its current task and clean up before exiting