macosplistlaunchctl

Keeping Program alive after manual close and start from /Applications


I have written a plist file. The intention is to keep the program alive which is working fine. The problem that I discover is the following. If I close the app and start it from the /Applications folder, the helper.plist which I created is not valid for it anymore. Now I know I can run a script that unloads and loads launchtctl. But this starts my program for a second time with the bundleId of the helper.

Is there any way to reattach the program to the helper if I close the app manually or is this not possible? Or would I have to code a wrapper app that only runs the script and has the real program in it's sources? Is there maybe a smarter solution how this can easily be done? I attached the plist below

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com   
/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.test.helper</string>
    <key>Program</key>
    <string>/Applications/test.app/Contents/MacOS/test</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
    </dict>
</dict>
</plist>

Solution

  • I ended up writing a wrapper function that has no other function than to start the Program if it is not running.

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        print("starting app")
        //check if application is running. if so terminate
        let apps = NSWorkspace.sharedWorkspace().runningApplications
        for app in apps{
            if let bundle = app.bundleIdentifier{
                if(bundle.hasPrefix("com.CostumApp.main")){
                    print("already running")
                    //activating gui
                    showFront()
                    NSApplication.sharedApplication().terminate(self)
                }
            }
        }
        //checks if the plist file exists and start reset deamon
        let daemon = checkDeamon()
        if(daemon){
            let helper = getUserLibrary() + "/LaunchAgents/com.CostumApp.helper.plist"
            callShell("/bin/launchctl", arguments: ["unload","-w",helper])
            callShell("/bin/launchctl", arguments: ["load","-w",helper])
            NSApplication.sharedApplication().terminate(self)
        }else{
            print("no helper file")
            NSApplication.sharedApplication().terminate(self)
        }
    }