V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
keary
V2EX  ›  问与答

Linux下如何实现关闭程序后自动关机?

  •  
  •   keary · 2013-11-20 08:50:20 +08:00 · 4058 次点击
    这是一个创建于 3812 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如题,Linux开机后会启动一个程序,我希望当该程序被关闭后,Linux也就自动关机。请问这个如何实现?最好是用Shell脚本来写,谢谢各位!
    5 条回复    1970-01-01 08:00:00 +08:00
    AstroProfundis
        1
    AstroProfundis  
       2013-11-20 10:02:08 +08:00
    pids="$($_CMD pgrep some-program)"
    if [ ! $pids ]; then
    shutdown now
    fi

    然后做个cron每分钟执行一次
    klion26
        2
    klion26  
       2013-11-20 10:02:52 +08:00
    ps查看进程,然后如果进程没有了,就shutdown。不知可行否
    ritksm
        3
    ritksm  
       2013-11-20 10:40:21 +08:00
    检测pid也可,或者如果能改程序的话检测/tmp底下一个文件更好一些我觉得,如果意外退出也不会直接关机
    ceyes
        4
    ceyes  
       2013-11-20 10:44:51 +08:00
    很简单啊:

    cmd="your command xxx"
    $cmd & cmd_pid=$!

    while kill -0 $cmd_pid; do
    sleep 5;
    done

    shutdown -h now
    NStal
        5
    NStal  
       2013-11-20 17:33:34 +08:00
    运行 sudo crontab -e

    在编辑器里输入
    @reboot /path/to/you/command;shutdown -hp now;

    保存退出.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5411 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 08:43 · PVG 16:43 · LAX 01:43 · JFK 04:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.