Sign up ×
Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.

Is there a way to periodically check if a process is running with (probably with Apple script, or some other shell script) and if not then to execute it in Terminal?

I have a PHP script that is needs to run, but after some time it breaks, so I need to start it again.


share|improve this question
possible duplicate of How to run something automatically when the system boots or a use logs on? – user588 Mar 18 '11 at 16:26
possible duplicate of:… – user588 Mar 18 '11 at 16:28

3 Answers 3

In OSX use launchd to to this. launchd will start a command at login or boot and if the process dies it will restart it.

The process is controlled by a .plist file formatted as defined in Apple docs the example in that manual page is for the case you ask for.

  <?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN >
   <plist version="1.0">

If you want to to start when a user logs in the this file goes in ~/Library/LaunchAgents. If when the machine boots then /Library/LaunchDaemons (which can't have access to the GUI) but this will run as root unless you add a UserName key. (Thanks to @Gordon Davisson for the correction and a reread of Apple definitions)

For ease of setting the .plist up you can use available from the Mac AppStore

share|improve this answer
Correction: to run it at boot, put the file in /Library/LaunchDaemons. – Gordon Davisson Mar 18 '11 at 14:36
@jherran see meta and many in meta stack overflow - don't use code formatting in plain text just for code – Mark Mar 19 at 10:13

If you wanted to do this via a shell script I'd do something like this:

PROCESS=`ps A | grep PROCESS_NAME | grep -v grep`
if [ "$?" -ne "0" ]; then
        echo "not running"
        exit 1

You could call that via cron every minute or so.

share|improve this answer

Why you need to actively poll for the script? Why not just put it in a shell script loop and restart it when it fails.


let c=1
while ! php -f myscript.php; do
    echo "The script has crashed $c times so far..."
    let "c=c+1"

In the case it doesn't fail gracefully, polling for a running process won't save you either. It may as well keep running while not doing its job.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.