且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在OSX上的崩溃自动重启程序

更新时间:2023-10-12 21:24:04

 #!/斌/庆典〜/ 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