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条回答
Anthone
3楼-- · 2020-01-27 09:27

more correct would be:

export pid=`ps aux | grep process_name | awk 'NR==1{print $2}' | cut -d' ' -f1`;kill -9 $pid
查看更多
Summer. ? 凉城
4楼-- · 2020-01-27 09:28

A bit longer alternative:

kill `pidof firefox`
查看更多
Anthone
5楼-- · 2020-01-27 09:39

To kill with grep:

kill -9 `pgrep myprocess`
查看更多
地球回转人心会变
6楼-- · 2020-01-27 09:40

You can kill processes by name with killall <name>

killall sends a signal to all processes running any of the specified commands. If no signal name is specified, SIGTERM is sent.

Signals can be specified either by name (e.g. -HUP or -SIGHUP ) or by number (e.g. -1) or by option -s.

If the command name is not regular expression (option -r) and contains a slash (/), processes executing that particular file will be selected for killing, independent of their name.

But if you don't see the process with ps aux, you probably won't have the right to kill it ...

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

The easiest way to do is first check you are getting right process IDs with:

pgrep -f [part_of_a_command]

If the result is as expected. Go with:

pkill -f [part_of_a_command]
查看更多
登录 后发表回答