Restarting program automatically on crash in OSX [duplicate]
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
When you use exec
the shell will replace itself entirely with the program it starts. Unless the program fails even to load the first time around, there will be no shell left to continue the while
loop after the program dies.
I'm not sure how this could produce the further behavior you describe, though.
精彩评论