【问题标题】:Kill Command in linuxlinux中的kill命令
【发布时间】:2014-04-01 05:36:02
【问题描述】:

我有一个 bash 脚本 abcd.sh,我想在 5 秒后杀死这个命令(/usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat') 但在这个脚本中它会杀死 sleep 命令5 秒后。

#!/bin/sh
/usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' &
sleep 5
kill $! 2>/dev/null && echo "Killed command on time out"

【问题讨论】:

    标签: linux bash command sleep kill


    【解决方案1】:

    试试

    #!/bin/sh
    /usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' &
    pid=$!
    sleep 5
    kill $pid 2>/dev/null && echo "Killed command on time out"
    

    更新:

    一个工作示例(没有特殊命令)

    #!/bin/sh
    set +x
    ping -i 1 google.de &
    pid=$!
    echo $pid
    sleep 5
    echo $pid
    kill $pid 2>/dev/null && echo "Killed command on time out"
    

    【讨论】:

    • +1 这解决了 shell 脚本中的直接问题。使用timeout 可以说是更好的选择。
    • @drkunibar 脚本不工作,脚本在 5 秒后运行命令
    • 抱歉,我无法重现您的问题。 5秒后启动什么命令?我已经用一个应该适用于每个系统的示例更新了我的答案(用ping 更改了你的命令)
    • @drkunibar /usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' 恢复工作。5 秒后它显示echo 消息并恢复工作。
    • @Tomas 你的 echo pid 可以像例子中一样,我们可以看看kill 是否调用了正确的pid。也许您需要致电kill -9 $pid
    【解决方案2】:

    您应该改用timeout(1) 命令:

    timeout 5 /usr/local/bin/wrun \
          'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat'
    

    【讨论】:

    • +1,这是带有timeout 的系统的正确答案。可悲的是,timeout 仅在 coreutils 7 中引入,这意味着它在例如CentOS 5.
    • ubuntu 10.04 上都没有
    【解决方案3】:

    然后尝试构建自己的机制,为什么不使用timeout 命令。

    示例

    $ date; timeout 5 sleep 100; date
    Tue Apr  1 03:19:56 EDT 2014
    Tue Apr  1 03:20:01 EDT 2014
    

    在上面您可以看到timeout 仅在 5 秒(即持续时间)后终止了 sleep 100

    你的例子

    $ timeout 5 /usr/local/bin/wrun \
        'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat'
    

    【讨论】:

      【解决方案4】:

      试试这个:

      #!/bin/sh
      /usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' &
      sleep 5
      pkill "wrun" && echo "Killed command on time out"
      

      【讨论】:

        【解决方案5】:

        这是因为变量$! 包含最近的后台命令的PID。这个后台命令在你的情况下是sleep 5。这应该有效:

        #!/bin/sh
        /usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' &
        PID=$!
        sleep 5
        kill $PID 2>/dev/null && echo "Killed command on time out"
        

        【讨论】:

        • 对,后台命令。睡眠没有在后台执行。
        • @chaos 脚本不工作。脚本在 5 秒后运行命令
        • 什么是/usr/local/bin/wrun?是这个gist.github.com/orgoj/5326037 吗?
        【解决方案6】:

        你可以使用类似的东西:

        #!/bin/sh
        /usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat' &
        PID=`ps -ef | grep /usr/local/bin/wrun | awk '{print $1}'`
        sleep 5
        kill $PID 2>/dev/null && echo "Killed command on time out"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-14
          相关资源
          最近更新 更多