views:

449

answers:

3

Hi Everyone:

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.

+1  A: 

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

Brian Ramsay
Hi Brian:Thanks for that code. :) I really appreciate it. A few questions, as I'm not that good in AppleScript... First of all, does that quit my launchd process or simply look if my app is running? Also, how would I integrate this into my launchd file so it doesn't run my UNIX code first?Thanks the help!
PF1
You would need to fill in the lines to start and stop your launchd process - I don't really know launchd so I'm not sure what the exact command would be. I updated the code to fill in a little more.
Brian Ramsay
Hey Brian: Thanks for your help. I finally figured out a way so that it can work without having to morph results into UNIX, etc... Parse the UNIX into the Applescript. :) I have to thank you for that idea.
PF1
+2  A: 

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.

Peter Hosey
A: 

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