在OSX上的崩溃自动重启程序 [英] Restarting program automatically on crash in OSX

查看:121
本文介绍了在OSX上的崩溃自动重启程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/696839/how-do-i-write-a-bash-script-to-restart-a-process-if-it-dies\">How我写一个bash脚本,如果它死了重新启动的过程?


我做了一个C程序崩溃偶尔,我不能修复它(有一些的getaddrinfo问题,这是相当自发似乎)。我想在死机重启程序。我认为这会很容易。我正想有问题的libcurl code用叉子分开,并期待如何从关闭,因此它可以被再次分叉检测过程。不过我去试图重新启动整个程序,并从文件中恢复数据简单的选项。

我试过这样:

 #!/ bin / sh的
而真实的;做
    CD〜/ PROGRAMDIR
    EXEC〜/ PROGRAMDIR /程序
DONE

但是,当程序退出上的失败它开始下一个执行输出到终端输入,如果这是很有意义的。所以,如果我pretend我的程序仅仅是一个Hello World程序,然后它会做这样的事情:

 的bash-3.2 $ start.sh
你好,世界!
你好,世界!
总线错误
庆典-3.2 $的Hello World!
-bash:您好:命令未找到
庆典-3.2 $的Hello World!
-bash:您好:命令未找到

它不会像以前那样继续运行程序。终端认为该方案已退出但随后将在下次执行的输出端子输入

什么是做到这一点的正确方法?


解决方案

 #!/斌/庆典〜/ PROGRAMDIR /程序|| EXEC$ 0

该脚本将运行〜/ PROGRAMDIR /程序,等待它的退出状态。如果状态为0(这意味着在bash成功),那么脚本本身终止。否则,如果程序返回一个非0值,或者人为地终止(例如,其被杀),脚本将再次启动本身,就像在C尾递归。

编辑: code根据与R更新..的评论

Possible Duplicate:
How do I write a bash script to restart a process if it dies?

I've made a C program that occasionally crashes and I can't fix it (Some problem with getaddrinfo which is rather spontaneous seeming). I would like to restart the program upon the crash. I thought this would be easy. I was going to separate the problematic libcurl code with a fork and look up how I can detect a process from closing so it can be forked again. However I went with the "easy" option of trying to restart the entire program and recover data from a file.

I tried this:

#!/bin/sh
while true; do
    cd "~/ProgramDir"
    exec "~/ProgramDir/Program"
done

But when the program exits on a failure it starts outputting the next execution to the terminal input if that makes sense. SO if I pretend my program is just a Hello World program then it would do something like this:

bash-3.2$ start.sh
Hello World!
Hello World!
bus error
bash-3.2$ Hello World!
-bash: Hello: command not found
bash-3.2$ Hello World!
-bash: Hello: command not found

It wont continue the program as before. The terminal thinks the program has exited but then takes the output of the next execution to the terminal input.

What is the proper way to do this?

解决方案

#!/bin/bash

~/ProgramDir/Program || exec "$0"

This script would run "~/ProgramDir/Program" and wait for its exit status. If the status is 0 (which means "success" in bash), then the script itself terminates. Otherwise, if the program returns a non-0 value or it terminates unnaturally (e.g. it get killed), the script would launch itself again, like a tail recursion in C.

Edit: code updated according to R..'s comment

这篇关于在OSX上的崩溃自动重启程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆