title: How can an OS X application get itself restarted when it crashes
body: <p>There are quite a few hints about how to keep programs alive, and restart them when they crash:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/7247543">By using a shell script</a></li>
  <li><a href="http://hints.macworld.com/article.php?story=20071220095645567" rel="nofollow noreferrer">By using launchd</a></li>
  </ul>
  
  <p>They all have one restriction in common, though: They all need to be run <em>before</em> the to-be-monitored program.</p>
  
  <p>In my case, though, I have a <strong>faceless background app</strong> that has to decide on its own whether it wants to be restarted in case it crashes. So, my app would be launched <em>first</em> and cannot be quit to become a child of a monitoring process (for explanation see below).</p>
  
  <p>I've tried the <code>launchd</code> solution by writing a plist file like this:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
  &lt;plist version="1.0"&gt;
  &lt;dict&gt;
      &lt;key&gt;KeepAlive&lt;/key&gt;
      &lt;dict&gt;
          &lt;key&gt;SuccessfulExit&lt;/key&gt;
          &lt;false/&gt;
      &lt;/dict&gt;
      &lt;key&gt;Label&lt;/key&gt;
      &lt;string&gt;com.mydomain.myapp.restartAfterCrash&lt;/string&gt;
      &lt;key&gt;ProgramArguments&lt;/key&gt;
      &lt;array&gt;
          &lt;string&gt;/Applications/MyApp.app/Contents/MacOS/MyApp&lt;/string&gt;
      &lt;/array&gt;
  &lt;/dict&gt;
  &lt;/plist&gt;
  </code></pre>
  
  <p>It nearly does what I need, but in order to activate it from my app, by invoking it with <code>launchctl load /path/to/file.plist</code>, it wants to launch my app once more, so that my originally running app would have to quit to let the new instance run.</p>
  
  <p>However, I cannot pass control to another instance of my app, because it's causing several new problems if the app was launched by double clicking a document the Finder or if it was launched by an AppleScript that wants to communicate further with my app. In those cases, my originally launched app must keep running, and thus the <code>launchd</code> method is not viable, nor is any other method that requires my app to run a new instance instead.</p>
  
  <p><strong>In short, are there other tested (reliable) methods that a Mac application can use to have itself restarted only if it crashes?</strong></p>
  
  <p>The only method I can think of is launching another faceless background application that monitors the first program's lifetime, e.g. via its PID.</p>
  
  <p>I also wonder if it can be done with a simple shell command invocation that would periodically check whether my app is still alive, as those always run as a child process and would die along with the primary app, won't they?</p>