Kill random process with name

2019-05-13 22:00发布

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.

9条回答
相关推荐>>
2楼-- · 2019-05-13 22:23

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".

查看更多
老娘就宠你
3楼-- · 2019-05-13 22:23

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.

查看更多
趁早两清
4楼-- · 2019-05-13 22:24

with recent bash shell

#!/bin/bash
declare -a pid
pid=( $(pidof myprocess) )
length=${#pid}
rnumber=$((RANDOM%length+1))
rand=$((rnumber-1))
kill ${pid[$rand]}
查看更多
叼着烟拽天下
5楼-- · 2019-05-13 22:25

How about using pgrep and pkill. They allow lot of options to select the processes.

查看更多
Summer. ? 凉城
6楼-- · 2019-05-13 22:29

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`
查看更多
beautiful°
7楼-- · 2019-05-13 22:29

look at the -r option of the killall command!

查看更多
登录 后发表回答