Killing unknown pid with AppleScript

I have this simple script to show the screensaver in the Desktop’s Background:

display dialog "Set ScreenSaver as Background?" buttons {"Yes", "Nevermind"} default button "Nevermind"
set DeskSaver to button returned of the result
if DeskSaver = "Yes" then do shell script "/System/Library/Frameworks/Screensaver.framework/Resources/ScreensaverEngine.app/Contents/MacOS/ScreenSaverEngine -background"
end

I’m wanting to add a “Stop” or “Kill” button in this script, but if you paste this into your own script, you’ll see that you won’t be able to get back into the script without going into Terminal and killing the process. Basically, it’s pretty much impossible to guess which pid the screensaver engine is going to hold, so how could I tell AppleScript to do this?

Hi,

Your script seems to hang in my Script Editor after setting the scrrensaver to the background. To quit the screensaver try this.

tell application "System Events" to do shell script "kill " & (unix id of first process whose name is "ScreenSaverEngine")

Best wishes

John M

But if all you want to do is stop the ScreenSaver, then this simulates what you would normally do:

tell application "System Events" to keystroke space

Sorry, I should clarify.

To quit the screensaver, running as a Desktop (that is behind other running applications) try this.

tell application "System Events" to do shell script "kill " & (unix id of first process whose name is "ScreenSaverEngine")

John M

Missed the “running as a desktop part”. Thanks for the clarity.

Activate:

do shell script "/System/Library/Frameworks/Screensaver.framework/Resources/ScreensaverEngine.app/Contents/MacOS/ScreenSaverEngine -background > /dev/null 2>&1 &"

Kill:

do shell script "killall ScreenSaverEngine"

I came up with this a while ago:

property action : "Start"

display dialog "Set screensaver as background." buttons {"Cancel", action} default button 2

try
	if (button returned of result) is "Start" then
		do shell script "/System/Library/Frameworks/Screensaver.framework/Resources/ScreensaverEngine.app/Contents/MacOS/ScreenSaverEngine -background > /dev/null 2>&1 &"
		set action to "Stop"
	else
		try
			do shell script "killall ScreenSaverEngine"
		end try
		set action to "Start"
	end if
on error errorMsg number errorNum
	display dialog "Error (" & errorNum & "):" & return & return & errorMsg buttons "Cancel" default button 1 with icon caution
end try

I had tried to get the PID by changing the redirects, but I didn’t get it to work.

Actually, “killall” would be better than this. If you happened to have two processes called ScreenSaverEngine, this one might not kill the correct process [the first time].