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

后端 未结 18 2663
孤独总比滥情好
孤独总比滥情好 2020-11-28 17:10

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
         


        
相关标签:
18条回答
  • 2020-11-28 17:58

    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.

    0 讨论(0)
  • 2020-11-28 17:59

    Strange, but I haven't seen the solution like this:

    kill -9 `pidof firefox`
    

    it can also kill multiple processes (multiple pids) like:

    kill -9 `pgrep firefox`
    

    I prefer pidof since it has single line output:

    > pgrep firefox
    6316
    6565
    > pidof firefox
    6565 6316
    
    0 讨论(0)
  • 2020-11-28 18:04

    I was asking myself the same question but the problem with the current answers is that they don't safe check the processes to be killed so... it could lead to terrible mistakes :)... especially if several processes matches the pattern.

    As a disclaimer, I'm not a sh pro and there is certainly room for improvement.

    So I wrote a little sh script :

    #!/bin/sh
    
    killables=$(ps aux | grep $1 | grep -v mykill | grep -v grep)
    if [ ! "${killables}" = "" ]
    then
      echo "You are going to kill some process:"
      echo "${killables}"
    else
      echo "No process with the pattern $1 found."
      return
    fi
    echo -n "Is it ok?(Y/N)"
    read input
    if [ "$input" = "Y" ]
    then
      for pid in $(echo "${killables}" | awk '{print $2}')
      do
        echo killing $pid "..."
        kill $pid 
        echo $pid killed
      done
    fi
    
    0 讨论(0)
  • 2020-11-28 18:06

    I normally use the killall command.

    Check this link for details of this command.

    0 讨论(0)
  • 2020-11-28 18:07

    The default kill command accepts command names as an alternative to PID. See kill (1). An often occurring trouble is that bash provides its own kill which accepts job numbers, like kill %1, but not command names. This hinders the default command. If the former functionality is more useful to you than the latter, you can disable the bash version by calling

    enable -n kill

    For more info see kill and enable entries in bash (1).

    0 讨论(0)
  • 2020-11-28 18:08

    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.

    0 讨论(0)
提交回复
热议问题