如何杀死没有pid 12345的名为“shairport”的所有进程

时间:2015-11-25 09:20:01

标签: linux bash

我在工作中使用shairport来传播音乐。我在Debian机器上运行它(树莓)。在它的/etc/init.d/shairport文件中,它只有start | stop命令。 我想添加一个重启。这是迄今为止的代码:

case "$1" in
  restart)
    service shairport stop
    service shairport start
    ;;
  start)
    /usr/local/bin/shairport -d -a "$NAME" -p 5002 -k "madafaka" -w -B "mpc stop"
    ;;
  stop)
    killall shairport
    ;;
  *)
    echo "Usage: /etc/init.d/shairport {start|stop|restart}"
    exit 1
    ;;
esac

exit 0

问题是,当我运行“service shairport restart”时,服务停止,从而运行“killall shairport”并终止bash脚本进程。所以“开始”永远不会被执行。

除当前脚本外,如何使killall杀死每个shairport?

我的想法是获得pid并将其排除,但我无法找到如何做到这一点。

3 个答案:

答案 0 :(得分:2)

开始部分应记下已启动过程的PID。 像layout_tolerance<double>(0.01)这样的东西会。

停止部分脚本将使用我们创建的.pid文件中的PID,并终止正确的进程。就我所知,大多数Linux服务都是这样做的。

答案 1 :(得分:1)

在linux中,您可以通过以下方式了解脚本文件运行的进程ID: $$

你只需要检查一下你是不是要自杀:

stop)
for pid in $(pgrep shairport); do
    if[$pid != $$]
        kill $pid
    fi
done

答案 2 :(得分:0)

由于我选择的答案没有直接开箱即用,这里是我最终得到的代码:

case "$1" in
  restart)
    for pid in $(pgrep shairport); do
            if [ "$pid" != $$ ]; then
                kill $pid
            fi
    done
    /usr/local/bin/shairport -d -a "$NAME" -p 5002 -k "madafaka" -w -B "mpc stop"
    ;;
  start)
    /usr/local/bin/shairport -d -a "$NAME" -p 5002 -k "madafaka" -w -B "mpc stop"
    ;;
  stop)
        killall shairport
    ;;
  *)
    echo "Usage: /etc/init.d/shairport {start|stop|restart}"
    exit 1
    ;;
esac
相关问题