Question

I'm wondering if there is some way I can stop a launchd task when a application is open, and then start it again when the application is closed. My launchd task is set to be notified when a file is changed and then do some UNIX code with the file. However, my application makes a lot of changes to this file so I can't have the task running when my app is open (or else it will run the UNIX code every time that the file is changed, which isn't good). Are there pros and cons to the different methods to do this (even though I haven't found any methods)?

Thanks for any help.

Was it helpful?

Solution

You could use applescript to check and see if an app is running.

I found this post that describes an applescript that will monitor an application's startup and shutdown: http://macosx.com/forums/1199085-post2.html

global wasLoaded

on run
    set wasLoaded to isAppLoaded("Safari")

    idle
end run

on idle
    set x to isAppLoaded("Safari")
    if x and not wasLoaded then
        do shell script "SOME BASH COMMAND" -- stop your launchd task
        set wasLoaded to true
    else if wasLoaded and not x then
        do shell script "SOME BASH COMMAND" -- start your launchd task
        set wasLoaded to false
    end if
    return 1 --will wait 1 second before checking again
end idle

on isAppLoaded(app_name)
    tell application "System Events"
        set app_list to every application process whose name contains app_name
        if the (count of app_list) > 0 then
            return true
        else
            return false
        end if
    end tell
end isAppLoaded

I am sure an accomplished bash scripter could tell you a way to do the same thing by parsing the output from top.

Apple documentation for do shell script

OTHER TIPS

If you're feeling adventurous, you might try launchd's own API, which is in /usr/include/launch.h. Check out the implementation of launchd_stop_job in launchctl.cpp.

Please consult the launchd.plist man page for the KeepAlive and PathState keywords.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top