Andy
Andy

Reputation: 3692

Wait for PID to exit using AppleScript

I'm new to AppleScript but I have to recreate a batch file which I have written for Windows in OSX and AppleScript seems the best way to do this. Basically, the script will created by another program dynamically and then executed. The AppleScript simply needs to wait for a process, which I want to identify by its process ID, and display a message if the process is still running after a specific amount of time.

Is this possible, and if so, how?

Thanks in advance

Upvotes: 0

Views: 1545

Answers (2)

CRGreen
CRGreen

Reputation: 3429

Here are some things to (hopefully) get you on your way:

  • shell scripts in terminal, and 'do shell script' command: don't know how well you know Unix, but you definitely want to go there, and learn basics of bash. with some limitations, you can run shell scripts via AS through the 'do shell script' command.
  • writing the script dynamically: osascript and osacompile will probably come in handy. see the man pages. osascript can execute scripts or script text, and osacompile can (!) compile text into script form (non-text form), among other things.
  • script waiting for/watching process: more shell script stuff, or using the Finder (what used to be called the Scriptable Finder!), that is, the Finder's scripting capabilities (dictionary), like tell application "Finder" to get name of processes. The shell version (which can be called via the 'do shell script' AS command) might be "ps ax | grep Safari | grep -v grep | awk '{print $1}'" (taken from stackoverflow post. I like it because it returns empty string if no match). Depending on how your main script will run, learn how the idle handler works in a script application, and how that differs from using an xcode-built app (if that's the route you go), or just a script.
  • displaying a message: 'display dialog' is the super simple method, complete with timeout ("gives up" after n seconds). (Sorry if this is so basic I just insulted your intelligence :-) )
  • other: Check out (unless you're already wedded to a script editing environment) Smile. It's my primary script editor.

Upvotes: 1

Andy
Andy

Reputation: 3692

I eventually found a solution to my given problem after searching online a bit more. Here is the AppleScript code I use to check if a process with a given id pid is running

tell application "System Events"
    set runningApplications to (unix id of every process)
        if (runningApplications contains (pid as integer)) is false then
           -- process is not running
        else
           -- process still running
        end if
end tell

This is just a snippet obviously. Personally I have the above the statement in a repeat loop, but this offers a solution to checking a process id (which is the unix id).

Hope this helps others

Upvotes: 2

Related Questions