Kill shell script when host program not running/disk unmounted

I have my Mac OS X program executing a shell script (a script that copies files to a drive). I want to make it so that the shell script automatically kills itself if it finds that the host .app is not running OR kill itself if the drive that it is copying files to has been unmounted. Right now what I have is the shell script polls using the UNIX "ps" command every time before it executes a command, and then kills itself if the app, and then also uses the "df" utility to check if the disk is mounted. like this:

#!/bin/sh

checkrunning()
{
	PS=$( /bin/ps -aex )
	if [[ $PS != */Contents/MacOS/MyAppBinary* ]]
		then
		exit 0
	fi
	DISKS=$( /bin/df | grep "$VOLPATH" )
	if [[ $DISKS != *"$1"* ]]
		then
		exit 0
	fi
}

checkrunning
cp /something /something/here/

checkrunning
cp /anothersomething /something/here/

However this polling wastes resources, so is there a better way to do this?

I'm using Mac OS X 10.6 using the default shell.

I wouldn't call this a waste of resources. All it takes is a ps and df commands which are not known as being particularly greedy.

You could maybe better target the .app application by using the -C option if provided by your OS:

if ps -C firefox-bin ;then
   echo "Firefox running"
fi

Just to make sure that I understand your question correctly: the application you are checking, is that the script itself or an external application?

If it is the very same script you want to check the running status of, you can just use a file as a lock. You create a empty file at the beginning of the script and rm it at the end.

Its an external application. And you are right, I don't notice a hit in performance, so this should be OK :slight_smile:

Thanks