如何杀死“&”发起的进程在bash?

时间:2014-08-08 11:39:18

标签: bash

我想在bash中运行脚本./startMegaTrolling.sh 100000000000000000000000

#!/bin/bash
if [ "$#" -ne 0 ];then 
    let "LAST = $1 - 1"
    for i in `seq 0 $LAST`
    do
        php trolling.php --processNumber=$1 &     #here
    done
fi

但是如何通过这种方法获得所有已启动进程的pid? 我尝试了>> pids.txt #here,但它不起作用。我希望有第二个脚本来杀死所有已启动的进程。

3 个答案:

答案 0 :(得分:2)

使用$!访问最近启动的后台进程的pid。因此:

#!/bin/bash
# ^- shebang is mandatory since we use bash-only features
if (( $# )); then
  for (( i=$1; i>0; i-- )); do
    php trolling.php --threadNumber="$1" &
    echo "$!" >>pids.txt
  done
fi

答案 1 :(得分:1)

您可以在启动流程时收集流程ID,然后稍后将其全部删除。

#!/bin/bash
if [ "$#" -ne 0 ];then 
    LAST=$(( $1 - 1 ))   # let is a bit antiquated
    for i in `seq 0 $LAST`
    do
        php trolling.php --threadNumber=$1 &
        pids="$pids $!"
    done
fi

# Later on
kill $pids

从技术上讲,数组比空格分隔的字符串更好收集 一系列项目,但由于进程ID保证是一个简单的整数, 它在这里工作正常。


对于完整的POSIX合规性(问题不需要,基于bash标记),您不能使用seq或C风格的{{ 1}}循环,而不得不使用for循环。

while

答案 2 :(得分:0)

您可以尝试这样的事情:

pid:ps aux | grep <NAME_OF_YOUR_APP> | awk '{print $2}'

然后:

kill -9 $pid  > /dev/null 2>&1 &
相关问题