AppleScript : Start a background process and get the pid to kill it

Like so:

do shell script ("cd /Users/myName/Sites/FitNesse ; java -jar fitnesse-standalone.jar -p 5555  &> fitNesse.log & echo $!")
set pid to the result
open location "http://localhost:5555/"
display dialog "Press okay to shutdown FitNesse (" & pid & ")" buttons {"OK"}
do shell script ("kill " & pid)

To see it work, open AppleScript Editor, and paste in the script.
Save it first as a script, then Export it as an Application.

A couple of tricks are involved, the two least well-known are perhaps:

  • $! will return the pid of the most recently started background process
  • You may not need to log output but you still apparently need an output redirection clause such as &> /dev/null". Otherwise AppleScript waits for the stdout / stderr to free up. Which never happens.
  • You usually want to cd to the right directory when you run a shell script from AppleScript

AppleScript : Start a background process…

by Chris F Carroll read it in 1 min
0