简体   繁体   中英

How to kill all processes named “shairport” that do not have the pid 12345

I am using shairport at work to stream music. I am running it on a Debian machine(a raspberry). In its /etc/init.d/shairport file it has only the start|stop commands. I want to add a restart one. Here is the code so far:

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

The issue is that when I run "service shairport restart", the service is stopped, thus running "killall shairport" and killing the bash script process itself. So "start" is never executed.

How do I make killall kill every shairport except the current script?

My idea was to get the pid and exclude it, but I cant find how to do that.

The start part should write down the PID of the started process. Something like echo $? > /var/run/shairport.pid echo $? > /var/run/shairport.pid will do.

Stop part of your script will use the PID from the .pid file we have created, and kill the right process. This is what most of Linux services do as far as I know.

In linux you can know the process ID that the script file is running under with : $$ .

You just have to check you're not killing yourself with :

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

Since the answer I chose did not work straight out of the box, here is the code I ended up with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM