How can I kill a process by name instead of PID?

2020-01-27 08:43发布

Sometimes when I try to start Firefox it says "a Firefox process is already running". So I have to do this:

jeremy@jeremy-desktop:~$ ps aux | grep firefox
jeremy    7451 25.0 27.4 170536 65680 ?        Sl   22:39   1:18 /usr/lib/firefox-3.0.1/firefox
jeremy    7578  0.0  0.3   3004   768 pts/0    S+   22:44   0:00 grep firefox
jeremy@jeremy-desktop:~$ kill 7451

What I'd like is a command that would do all that for me. It would take an input string and grep for it (or whatever) in the list of processes, and would kill all the processes in the output:

jeremy@jeremy-desktop:~$ killbyname firefox

I tried doing it in PHP but exec('ps aux') seems to only show processes that have been executed with exec() in the PHP script itself (so the only process it shows is itself.)

标签: linux bash shell
18条回答
看我几分像从前
2楼-- · 2020-01-27 09:13

Also possible to use:

pkill -f "Process name"

For me, it worked up perfectly. It was what I have been looking for. pkill doesn't work with name without the flag.

When -f is set, the full command line is used for pattern matching.

查看更多
一夜七次
3楼-- · 2020-01-27 09:13

Kill all processes having snippet in startup path. You can kill all apps started from some directory by for putting /directory/ as a snippet. This is quite usefull when you start several components for the same application from the same app directory.

ps ax | grep <snippet> | grep -v grep | awk '{print $1}' | xargs kill

* I would preffer pgrep if available

查看更多
Root(大扎)
4楼-- · 2020-01-27 09:13

If you run GNOME, you can use the system monitor (System->Administration->System Monitor) to kill processes as you would under Windows. KDE will have something similar.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-01-27 09:15

awk oneliner, which parses the header of ps output, so you don't need to care about column numbers (but column names). Support regex. For example, to kill all processes, which executable name (without path) contains word "firefox" try

ps -fe | awk 'NR==1{for (i=1; i<=NF; i++) {if ($i=="COMMAND") Ncmd=i; else if ($i=="PID") Npid=i} if (!Ncmd || !Npid) {print "wrong or no header" > "/dev/stderr"; exit} }$Ncmd~"/"name"$"{print "killing "$Ncmd" with PID " $Npid; system("kill "$Npid)}' name=.*firefox.*
查看更多
Rolldiameter
6楼-- · 2020-01-27 09:17

I normally use the killall command.

Check this link for details of this command.

查看更多
Melony?
7楼-- · 2020-01-27 09:19

Using #killall command:

#killall -9 <processname>
查看更多
登录 后发表回答