29

I have some applications that need to run on my laptop all the time.

I use a bash script to start these applications. In my script I have a loop that looks similar to this:

while true;
do
    xterm
done

This runs an application (xterm in this case) and if the application crashes, the loop starts it again.

This has a disadvantage that there is no "clean" exit from this loop. So even if the intention of the user is to close xterm, the loop starts it again.

Is there a way to start an application from bash script, watch whether it is running, to re-run it if script crashed or do nothing if the user closed it properly ?

4 Answers 4

46

Try this:

while true; do xterm && break; done

Applications have exit status codes so that if something exits fine it returns zero... And if something went wrong, it throws out another number. This allows people to hook in and find out the exact issue. This is what the other answer is doing.

&& just checks that the previous command was a zero-status exit and if it was, breaks the loop. If it crashes, it'll throw out something other than 0 and the && ... clause won't trigger; it'll simply loop back around and run xterm.

6
  • 8
    That's quite elegant.
    – Oli
    Jan 12, 2015 at 14:02
  • 1
    @muru: This works for me: while ! xterm; do :; done
    – Cyrus
    Jan 12, 2015 at 15:24
  • 1
    @Cyrus Ah, yes. forgot the !.
    – muru
    Jan 12, 2015 at 15:26
  • 6
    I've created a monster. How do I kill it?
    – Tony Ruth
    Oct 25, 2019 at 20:27
  • 2
    In response to the follow-up question from @Tony Ruth: "I've created a monster. How do I kill it?": You can attach to the process using gdb and its process id: sudo gdb -p <pid>. Then from within GDB, run call exit(0) and the process will exit with status 0. Not the most elegant, maybe, but it'll get you out.
    – sova
    Dec 18, 2020 at 23:33
9

In the while condition you can test whether exit status of xterm was successful or not with something like this:

result=1
while [ $result -ne 0 ]; do
    xterm
    result=$?
done

$? variable holds exit status of last executed command.

0

Try use supervisor it very simple and easy to add program or script to run. In you case as minimal you need command and maybe exitcodes in programx-section to configure.

Default exitcodes is 0,2 so it means:

supervisord will restart the process if it exits with an exit code that is not defined in this list

In general it`s that you want: re-run it if script crashed or do nothing if the user closed it properly(or script completed successfuly)

try the simplest configuration first:

[program:you_app_name]
command=/path/to/you/app

To more flexibility see configuration File documentation.

0

I will suggest you to use.

until xterm ;  do  echo "program ended with status $?" ; done

This will re-run your program if it is killed.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .