Shell – Is using “while true” to keep a script alive a good idea

perlshell

I'm just jumping into unix from a different world, and wanted to know if

while true
do
  /someperlscript.pl
done

The perl script itself internally has a folder/file watcher that executes when files are changed in the target location.

Is this (while true) a good idea? If not, what is a preferred robust approach?

TIA

EDIT : Since this seems to have generated a fair bit of interest, here is the complete scenario. The perl script itself watches a directory using a file watcher. Upon receiving new files (they arrive via rsync), it picks up the new one and processes it. Now the incoming files may be corrupt (don't ask.. coming from a raspberry pi), and sometimes the process may not be able to deal with it. I don't know exactly why, because we aren't aware of all the scenarios yet.

BUT – if the process does fail for some reason, we want it to be up and running and deal with the next file, because the next file is completely unrelated to the previous one that might have caused the error.

Usually I would have used some sort of catch all and wrapped the entire code around it so that it NEVER crashes. But was not sure for perl.

From what I've understood, using something like supervisord is a good approach for this.

Best Answer

That depends on how fast the perl script returns. If it returns quickly, you might want to insert a small pause between executions to avoid CPU load, eg:

while true
do
  /someperlscript.pl
  sleep 1
done

This will also prevent a CPU hog if the script is not found or crashes immediately.

The loop might also better be implemented in the perl script itself to avoid these issues.

Edit:

As you wrote the loop only purpose is to restart the perl script should it crashes, a better approach would be to implement it as a monitored service but the precise way to do it is OS dependent. Eg: Solaris smf, Linux systemd or a cron based restarter.