我经常需要在编程期间终止一个进程。

我现在的做法是:

[~]$ ps aux | grep 'python csp_build.py'
user    5124  1.0  0.3 214588 13852 pts/4    Sl+  11:19   0:00 python csp_build.py
user    5373  0.0  0.0   8096   960 pts/6    S+   11:20   0:00 grep python csp_build.py
[~]$ kill 5124

如何自动提取进程id并在同一行中杀死它?

是这样的:

[~]$ ps aux | grep 'python csp_build.py' | kill <regex that returns the pid>

当前回答

在bash的一行中找到并杀死所有进程。

kill -9 $(ps -ef | grep '<exe_name>' | grep -v 'grep' | awk {'print $2'})

ps -ef | grep '<exe_name>' -给出匹配模式的运行进程详细信息(uname, pid等)的列表。输出列表还包括搜索它的grep命令。现在,对于kill,我们需要忽略这个grep命令过程。 ps -ef | grep' <exec_name>' | grep -v 'grep' -使用-v 'grep'添加另一个grep将删除当前的grep进程。 然后使用awk单独获取进程id。 然后将此命令保存在$(…)中,并将其传递给kill命令,以杀死所有进程。

其他回答

一个衬套:

Ps aux | grep -i csp_build | awk '{print $2}' | xargs sudo kill -9

打印列2:awk '{Print $2}' Sudo是可选的 运行kill -9 5124, kill -9 5373等(kill -15更优雅,但稍慢)


奖金:

我还在.bash_profile中定义了2个快捷函数 (~ /。Bash_profile是用于osx的,你必须看看什么适用于你的*nix机器)。

p关键字 列出所有包含关键字的进程 用法例如:p csp_build, p python等

bash_profile代码:

# FIND PROCESS
function p(){
        ps aux | grep -i $1 | grep -v grep
}

ka关键字 杀死所有具有此关键字的进程 用法例如:ka csp_build, ka python等 可选的kill级别,例如:ka csp_build 15, ka python 9

bash_profile代码:

# KILL ALL
function ka(){

    cnt=$( p $1 | wc -l)  # total count of processes found
    klevel=${2:-15}       # kill level, defaults to 15 if argument 2 is empty

    echo -e "\nSearching for '$1' -- Found" $cnt "Running Processes .. "
    p $1

    echo -e '\nTerminating' $cnt 'processes .. '

    ps aux  |  grep -i $1 |  grep -v grep   | awk '{print $2}' | xargs sudo kill -klevel
    echo -e "Done!\n"

    echo "Running search again:"
    p "$1"
    echo -e "\n"
}

这里有很多很好的答案-我使用了op接受的答案。只是添加了一个关于pkill和pgrep的小警告。正如你可能从他们的手册页看到的,在你的操作系统上,一些操作系统对进程名有15个字符的限制。-f选项绕过了我的操作系统,但我遇到了麻烦,直到我找到了这个选项!

如果你有pkill,

pkill -f csp_build.py

如果您只想根据进程名(而不是完整的参数列表)进行grep,则取消-f。

根据https://stackoverflow.com/a/3510879/15603477的回答。小的优化。

ps aux | grep 'python csp_build.py' | head -1 | tr -s ' ' | cut -d " " -f 2 | xargs kill

使用tr -s ' '将多个空白(如果有的话)压缩为一个空白。

如果你遇到不允许的行动,请跟着>> https://unix.stackexchange.com/questions/89316/how-to-kill-a-process-that-says-operation-not-permitted-when-attempted

对于基本bash版本

Kill $(pidof <my_process>)