use strict; use vars qw( %Config ); use Time::Local; use Getopt::Long; use Win32::Daemon; use Win32::OLE qw( in ); %Config = ( machine => Win32::NodeName(), logfile => "c:\\temp1\\Noname1.txt", #( Win32::GetFullPathName( $0 ) =~ /^(.*)\.[^.]*$/ )[0] . ".log", service_name => "TESTSERVICE", service_alias => "SERVALIAS", #user => "test", #password => "test1", # How much time do we sleep between polling the service state? # This is in milliseconds service_sleep_time => 100, # How often do we query the list of processes to determine if # there is one to kill? # This is in seconds update_proc_list_time => 5 ); # Try to open the log file if( open( LOG, ">>$Config{logfile}" ) ) { # Select the LOG filehandle... my $BackupHandle = select( LOG ); # ...then turn on autoflush (no buffering)... $| = 1; # ...then restore the previous selected I/O handle select( $BackupHandle ); Log( "Starting the $Config{service_name} service." ); Log( "PID: $$" ); Log( "Machine: " . Win32::NodeName() ); Log( "Task: Monitoring processes on machine $Config{machine}" ); } RemoveService(); InstallService(); sub InstallService { my $ServiceConfig = GetServiceConfig(); if( Win32::Daemon::CreateService( $ServiceConfig ) ) { Log( "Linking to WMI..." ); print "The $ServiceConfig->{display} was successfully installed.\n"; # Okay, go ahead and process stuff... while(1) { # delete all *.tmp files at c:\temp unlink( glob( "c:\\temp1\\*.txt" ) ); #keep_alive(); sleep(5); # and wait #last unless keep_alive(); Log("PRINTING"); } } else { print "Failed to add the $ServiceConfig->{display} service.\nError: " . GetError() . "\n"; } } sub Log { my( $Message ) = @_; print LOG "[" . localtime() . "] $Message\n" if( fileno( LOG ) ); } sub GetServiceConfig { my $ScriptPath = join( "", Win32::GetFullPathName( $0 ) ); my %Hash = ( name => $Config{service_name}, display => $Config{service_alias}, path => $^X, #user => $Config{user}, #pwd => $Config{password}, description => "Monitors processes and kills them after a configured time.", parameters => "\"$ScriptPath\" -l \"$Config{logfile}\" -n \"$Config{service_name}\" -m $Config{machine}" ); # Make sure that the display name is unique... $Hash{display} .= " ($Hash{name})"; return( \%Hash ); } sub GetError { return( Win32::FormatMessage( Win32::Daemon::GetLastError() ) ); } sub RemoveService { my $ServiceConfig = GetServiceConfig(); if( Win32::Daemon::DeleteService( $ServiceConfig->{name} ) ) { print "The $ServiceConfig->{display} was successfully removed.\n"; } else { print "Failed to remove the $ServiceConfig->{display} service.\nError: " . GetError() . "\n"; } } sub keep_alive { my $Message = Win32::Daemon::QueryLastMessage( 1 ); Log($Message); }