#!/usr/bin/perl # showLaunchdEnviron # This script shows the environment (variables, etc) that is used # for scripts run via 'launchd'. # Cameron Hayne (macdev@hayne.net) March 2009 use strict; use warnings; use File::Temp qw(tempfile); # if you supply a command-line argument to this script, # an environment variable named 'FOOBAR' will be defined with that value # and put into the 'launchd' environment my $fooBarEnvStr = ''; if (@ARGV) { $fooBarEnvStr = <EnvironmentVariables FOOBAR $ARGV[0] EOT } # create a script that we will run via 'launchd': my $bashScriptText = <<'EOT'; #!/bin/bash echo "--------------------------------------------" echo "This script is running via 'launchd' with the following user id:" /usr/bin/id echo "" echo "Environment Variables:" /usr/bin/printenv echo "" echo "Current Directory:" /bin/pwd echo "--------------------------------------------" EOT #print "$bashScriptText\n"; # write the embedded Bash script to a temp file my ($bashScriptFH, $bashScriptFile) = tempfile(); print $bashScriptFH $bashScriptText; close($bashScriptFH); # get another temp file to send the script output to my ($bashScriptOutputFH, $bashScriptOutputFile) = tempfile(); close($bashScriptOutputFH); #print "bashScriptFile: $bashScriptFile\n"; #print "bashScriptOutputFile: $bashScriptOutputFile\n"; # make the script file executable chmod 0700, $bashScriptFile or die "Can't make script file executable: $!\n"; # create a plist for a 'launchd' job to run the above script: my $plistLabel = 'test.foo.bar'; my $plistText = < Label $plistLabel ProgramArguments $bashScriptFile StandardOutPath $bashScriptOutputFile StandardErrorPath $bashScriptOutputFile RunAtLoad $fooBarEnvStr EOT #print "$plistText\n"; # write the embedded plist text to a temp file my ($plistFH, $plistFile) = tempfile(); print $plistFH $plistText; close($plistFH); # ask 'launchctl' to load the plist (so that 'launchd' will run the script) system("/bin/launchctl load $plistFile"); # wait a bit to allow the script time to run sleep 1; # ask 'launchctl' to remove the script from 'launchd' system("/bin/launchctl remove $plistLabel"); # show the output from the script system("/bin/cat $bashScriptOutputFile"); # remove the temp files unlink($bashScriptFile); unlink($bashScriptOutputFile); unlink($plistFile);