Handle hostnames with upper-case letters
[webmin.git] / init / win32.pl
1 #!/usr/local/bin/perl
2 # A wrapper which runs some Perl script or command as a service
3
4 BEGIN { open(ERR, ">c:/temp/win32.err");
5         print ERR "Starting ..\n"; };
6
7 use Win32::Daemon;
8
9 # Tell the OS to start processing the service...
10 Win32::Daemon::StartService();
11
12 # Note: Added for convenience: The numeric codes for the Windows
13 # Service states:
14 #
15 # SERVICE_NOT_READY = 0
16 # SERVICE_STOPPED = 1
17 # SERVICE_START_PENDING = 2
18 # SERVICE_STOP_PENDING = 3
19 # SERVICE_RUNNING = 4
20 # SERVICE_CONTINUE_PENDING = 5
21 # SERVICE_PAUSE_PENDING = 6
22 # SERVICE_PAUSED = 7
23 # Wait until the service manager is ready for us to continue...
24
25 while( SERVICE_START_PENDING != Win32::Daemon::State() ) {
26         sleep( 1 );
27         }
28
29 # Now let the service manager know that we are running...
30 # This needs to be here, not after the client process exits, 
31 # otherwise the service will be in SERVICE_START_PENDING when
32 # it is up.
33 Win32::Daemon::State( SERVICE_RUNNING );
34         
35 # Added (CRH): We need to replace the forward slashes with double 
36 # backslashes only in the first argument to the function. For some
37 # reason the service manager expects double backslashes.
38 $argone=shift @ARGV;
39 $argone=~s/\//\\\\/g;
40 unshift @ARGV, $argone;
41
42 # Start the program in a sub-process
43 %before = map { $_, 1 } &get_procs();
44 $pid = fork();
45 if (!$pid) {
46         system(@ARGV);
47         exit(1);
48         }
49
50 $pid = -$pid;
51 print ERR "pid = $pid\n";
52 @after = &get_procs();
53 @new = grep { !$before{$_} } @after;
54
55
56 # Wait for messages
57 while(1) {
58         sleep(5);
59         if (Win32::Daemon::State() == SERVICE_STOP_PENDING ||
60             Win32::Daemon::State() == SERVICE_CONTROL_SHUTDOWN) {
61                 # Need to kill it
62                 foreach $p (@new) {
63                         print ERR "Killing process $p\n";
64                         system("process.exe -k $p");
65                         }
66                 last;
67                 }
68         }
69
70 # Tell the OS that the service is terminating...
71 Win32::Daemon::StopService();
72
73 # Returns a list of process IDs
74 sub get_procs
75 {
76 local @rv;
77 open(PROC, "process.exe |");
78 while(<PROC>) {
79         if (/^\s*(\S+)\s+(\d+)\s+(\d+)/) {
80                 push(@rv, $2);
81                 }
82         }
83 close(PROC);
84 return @rv;
85 }
86