linux - 如何在我的 shell 脚本中终止 'play' 进程?

标签 linux bash shell kill linux-mint

我正在编写一个脚本,当我的笔记本电脑电池电量达到 15% 时通知我并播放声音,但问题是,当您插入充电器时,声音会继续播放。如何从 sound.sh 脚本终止播放进程,甚至从 batmon.sh 脚本终止整个 sound.sh 脚本?

我希望在插入充电器的情况下发生这种情况。我的整个脚本都有效,但是,似乎在执行播放过程时它会等待完成该过程,然后再继续脚本的其余部分,所以我最好的选择似乎是在充电器插入计算机的情况下从 batmon.sh 脚本中删除 sound.sh 脚本。我该怎么做呢? (我正在运行 Linux Mint 17.1,以防万一。)

这是我的脚本:

#!/bin/bash
#batmon.sh

while true
do

    PLUG=`acpi | awk {'print $3'}`

    while [ $PLUG = "Discharging," ]
    do
        BATSTAT=`acpi | cut -d , -f 2`
        if [ $BATSTAT = "15%" ]
        then
            sh sound.sh &
            xcowsay --time=10 "Plug that shit in!" | sleep 100
        else
            PLUG=`acpi | awk {'print $3'}`
        fi
    done
done

#!/bin/bash
#sound.sh

x=1
SOUND=`play -q /home/greg/Documents/deththeme.wav &`

while [ $x = 1 ]
do
    $SOUND
    SOUND_PID=$!

    PLUG=`acpi | awk {'print $3'}`

    if [ $PLUG = "Charging," ] || [ $PLUG = "Unknown," ]
    then
        Kill $SOUND_PID
    else
        :
    fi
done

最佳答案

我认为可能发生的事情是......

当你这样做的时候,

SOUND=`play -q /home/greg/Documents/deththeme.wav &`

它在后台执行播放并将该进程的标准输出存储到 SOUND,即“”。

这可能表明:

#!/usr/bin/env bash

SOUND=`play -q /tmp/wav.wav &`
echo SOUND = "$SOUND"
$SOUND

输出:

# ./sound.sh 
SOUND = 

对我来说,$!不适用于 VAR=$(cmd)。如果你想终止进程,它可能看起来像:

play -q /home/greg/Documents/deththeme.wav &
PID="$!"
...
kill "$PID"

如果您没有 pid 并且知道只有一个播放进程将被执行,则另一种方法是使用 pkill play,它将按名称查找进程。

此外,您可以在循环结束时使用 sleep,它可能会阻止它如此剧烈地旋转。

这里是你的代码的一个稍微修改的版本:

#!/usr/bin/env bash

SOUNDFILE="/home/greg/Documents/deththeme.wav"

while true ; do
        PLUG=$(acpi | cut -d' ' -f3)
        if [ "$PLUG" = "Discharging," ] ; then
                BATSTAT=$(acpi | cut -d, -f2)
                if [ "$BATSTAT" = "15%" ] ; then
                        play -q "$SOUNDFILE" &
                        PID="$!"
                        xcowsay --time=10 "Plug that shit in!"

                        # spin until play subprocess is done executing
                        while ps -p "$PID" >/dev/null ; do
                                PLUG=$(acpi | cut -d' ' -f3)
                                if [ "$PLUG" = "Charging," ] || [ "$PLUG" = "Unknown," ] ; then
                                        kill "$PID"
                                        break
                                fi
                        done
               fi
        fi
done

关于linux - 如何在我的 shell 脚本中终止 'play' 进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27974127/

相关文章:

bash - Linux 命令在 shell 命令行中表现异常

c - Linux:从一个线程调用 wait() 是否会导致所有其他线程也进入休眠状态?

linux - wget 下载未完成所有页面

bash - 在 bash 中测试程序

linux - 使用此语法分配 bash 变量值时有什么区别?

bash - 导出 `/bin/bash -c` 内的变量

linux - 如果我中断 Linux 内核的 make 进程会发生什么?

linux - 为什么在 golang、linux 中使用 archive/zip 时文件名会变得困惑?

shell - 如何像在 bash 中那样动态地重新加载 Fish 配置文件?

c# - 调用时,.exe 进程未从 C# 应用程序运行