#!/usr/local/bin/perl
# A wrapper which runs some Perl script or command as a service

BEGIN { open(ERR, ">c:/temp/win32.err");
	print ERR "Starting ..\n"; };

use Win32::Daemon;

# Tell the OS to start processing the service...
Win32::Daemon::StartService();

# Wait until the service manager is ready for us to continue...
while( SERVICE_START_PENDING != Win32::Daemon::State() ) {
	sleep( 1 );
	}

# Start the program in a sub-process
%before = map { $_, 1 } &get_procs();
$pid = fork();
if (!$pid) {
	exec(@ARGV);
	exit(1);
	}
$pid = -$pid;
print ERR "pid = $pid\n";
@after = &get_procs();
@new = grep { !$before{$_} } @after;

# Now let the service manager know that we are running...
Win32::Daemon::State( SERVICE_RUNNING );

# Wait for messages
while(1) {
	sleep(5);
	if (Win32::Daemon::State() == SERVICE_STOP_PENDING ||
	    Win32::Daemon::State() == SERVICE_CONTROL_SHUTDOWN) {
		# Need to kill it
		foreach $p (@new) {
			print ERR "Killing process $p\n";
			system("process.exe -k $p");
			}
		last;
		}
	}

# Tell the OS that the service is terminating...
Win32::Daemon::StopService();

# Returns a list of process IDs
sub get_procs
{
local @rv;
open(PROC, "process.exe |");
while(<PROC>) {
	if (/^\s*(\S+)\s+(\d+)\s+(\d+)/) {
		push(@rv, $2);
		}
	}
close(PROC);
return @rv;
}

