Reputation: 4007
I want a way to kill a random process with a name (eg a random perl process).
What would be the best way of doing this?
I was thinkign of using something like this:
ps aux | grep PROCESS-NAME
to a file, then find a random line number, get the second column (process ID?) and kill that.
For my use it doesn't actually need to be a random one, as long as it kills one of the processes. Making it random just makes it better.
Upvotes: 3
Views: 4458
Reputation: 1
Maybe off topic, but I use this on Cygwin. Inspired by Lev Victorovich Priyma’s answer
ps -W | awk '/calc.exe/,NF=1' | xargs kill -f
or
ps -W | awk '$0~z,NF=1' z=calc.exe | xargs kill -f
Upvotes: 0
Reputation: 29
kill process with name "my_proc_name" :
kill -9 `ps xf | grep my_proc_name | grep -v grep | cut -d " " -f 1`
Upvotes: 0
Reputation: 11
How about using pgrep and pkill. They allow lot of options to select the processes.
Upvotes: 0
Reputation: 29
There's also the 'pidof' command, which can be used to kill with:
kill `pidof processname`
To get just one process when there are multiple with the same name, use -s for "single shot".
Upvotes: 2
Reputation: 342433
with recent bash shell
#!/bin/bash
declare -a pid
pid=( $(pidof myprocess) )
length=${#pid}
rnumber=$((RANDOM%length+1))
rand=$((rnumber-1))
kill ${pid[$rand]}
Upvotes: 0
Reputation: 342433
just kill and awk.
kill $(ps -eo cmd,pid|awk '/zsh/&&!/awk/{pid[$NF]}END{for(i in pid){print i;exit}}')
the for loop in the END block will give you you a random pid to kill
Upvotes: 0
Reputation: 6150
It sounded like you were already on the right track.
you can use the following perl script, save it as randomline.pl, which will return a random line from whats piped into it
#!/usr/bin/perl
srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip`);
while (<>) { push(@_,$_); } print @_[rand()*@_];
then run the following command to send the kill command
kill `ps aux | grep PROCESS-NAME | perl randomline.pl | awk '{print $2}'`
You might also want to add in some checking, perhaps with an inverted grep for root to make sure you don't try to kill root level processes that match your process name.
Upvotes: 0
Reputation: 38526
Bash one-liner :-p
kill `ps auxww | grep zsh | awk '{print $2}' | while read line; do echo "$RANDOM $line"; done | sort | cut -d ' ' -f 2 | head -n 1`
Upvotes: 4