加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

让bash脚本一直运行但是可以中止

发布时间:2020-12-15 22:00:27 所属栏目:安全 来源:网络整理
导读:我有一个像这样的bash脚本: #!/bin/bashstartsomeservice echo $! service.pidwhile true; do # dosomething in repeat all the time here foo bar sleep 5done# cleanup stuff on abort hererm tmpfileskill $(cat service.pid) 这个脚本的问题是,我不能中
我有一个像这样的bash脚本:

#!/bin/bash
startsomeservice &
echo $! > service.pid

while true; do
    # dosomething in repeat all the time here
    foo bar
    sleep 5
done

# cleanup stuff on abort here
rm tmpfiles
kill $(cat service.pid)

这个脚本的问题是,我不能中止它.如果按ctrl c我就进入下一个循环……
是否可以运行这样的脚本但让它可以流产?

解决方法

由于您使用Bash执行脚本,因此可以执行以下操作:

#!/bin/bash

startsomeservice &
echo $! > service.pid

finish()
{
    rm tmpfiles
    kill $(cat service.pid)
    exit
}
trap finish SIGINT

while :; do
    foo bar
    sleep 5
done

请注意,此行为是特定于Bash的,例如,如果您使用Dash运行它,您将看到两个不同之处:

>你无法捕获SIGINT
>中断信号将破坏shell循环.

另请注意,即使您正在运行Bash,当您直接从交互式提示执行循环时,也将使用单个C-c中断shell循环.有关从shell处理SIGINT的信息,请参见this detailed discussion.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读