Monday, February 19, 2018

Kill orphaned processes with awk

I use Behat to create some ham-handed load scenarios fairly regularly.  PhpStorm can help me spin up to get concurrency if I want a crushing load.  But PhpStorm on Mac seems to disconnect from these running tests if I lock my computer or leave them to run too long.  Killing them is a pain.  I have to run `ps`, find the pid, then kill it.

When the list gets too long, I like to use awk to comb through the list and kill anything that is found.  It's easy to search and parse out the tokens like so:

ps -ef | awk '/behat/ {system("kill -9 " $2)}'

ps -ef delivers a verbose list of processes.  This is piped to awk where I can specify a command using awk's scripting language.  In this command, I first search for 'behat'.  Then I  run a command pulls the second token, the process ID from each line of the result and inserts it into the `kill` command.