gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:17 25 4
gpt4 key购买 nike

我正在编写一个脚本,当我的笔记本电脑电池电量达到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com