Kill random process with name

旧街凉风 提交于 2019-12-07 12:14:44

问题


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.


回答1:


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`



回答2:


look at the -r option of the killall command!




回答3:


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




回答4:


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.




回答5:


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




回答6:


with recent bash shell

#!/bin/bash
declare -a pid
pid=( $(pidof myprocess) )
length=${#pid}
rnumber=$((RANDOM%length+1))
rand=$((rnumber-1))
kill ${pid[$rand]}



回答7:


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




回答8:


kill process with name "my_proc_name" :

kill -9 `ps xf | grep my_proc_name | grep -v grep | cut -d " " -f 1`



回答9:


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


来源:https://stackoverflow.com/questions/1895830/kill-random-process-with-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!