首页 文章

udev规则多次运行bash脚本

提问于
浏览
4

我创建了一个udev规则来在插入usb设备后执行bash脚本

SUBSYSTEMS=="usb", ATTRS{serial}=="00000000", SYMLINK+="Kingston", RUN+="/bin/flashled.sh"

然而,脚本运行了几次而不是一次,我认为它是检测到硬件的方式?我尝试将睡眠10放入脚本和fi但它没有任何区别 .

1 回答

  • 0

    这不是解决方案,而是一种解决方法:
    一种方法(简单)是像这样开始你的脚本"/bin/flashled.sh"

    #!/bin/bash
    #this file is /bin/flashled.sh
    
    #let's exit if another instance is already running
    if [[ $(pgrep -c "$0" ) -gt 1 ]]; then exit ;fi
    
    ... ... ...
    

    但是,在某些边界情况下,这可能会有点竞争条件(bash有点慢,因此无法确定这将始终有效)但它可能在您的情况下完美地工作 .

    另一个(更稳固但更多的代码)是这样开始“/bin/flashled.sh”:

    #!/bin/bash
    #this file is /bin/flashled.sh
    #write in your /etc/rc.local: /bin/flashled.sh & ; disown
    #or let it start by init.    
    
    while :
    do
        kill -SIGSTOP $$ # halt and wait
        ... ...          # your commands here
        sleep $TIME      # choose your own value here instead of $TIME
    done
    

    在启动过程中启动它(例如,通过/etc/rc.local),这样它就会等待信号继续...无论它有多少“继续”信号(它们没有排队),只要它们在$ TIME内

    相应地更改您的udev规则:

    SUBSYSTEMS=="usb", ATTRS{serial}=="00000000", SYMLINK+="Kingston", RUN+="/usr/bin/pkill -SIGCONT flashled.sh"
    

相关问题