/Win32-Daemon/Daemon.pm

http://libwin32.googlecode.com/ · Perl · 1110 lines · 788 code · 234 blank · 88 comment · 55 complexity · 3812c6d05148c72099168fab47f50b91 MD5 · raw file

  1. #//////////////////////////////////////////////////////////////////////////////
  2. #//
  3. #// Daemon.pm
  4. #// Win32::Daemon Perl extension package file
  5. #//
  6. #//////////////////////////////////////////////////////////////////////////////
  7. package Win32::Daemon;
  8. $PACKAGE = $Package = "Win32::Daemon";
  9. $VERSION = 20110117;
  10. require Exporter;
  11. require DynaLoader;
  12. my @OSVerInfo = Win32::GetOSVersion();
  13. my $OSVersion = "$OSVerInfo[1].$OSVerInfo[2]";
  14. my $RECOGNIZED_CONTROLS;
  15. @ISA= qw( Exporter DynaLoader );
  16. # Items to export into callers namespace by default. Note: do not export
  17. # names by default without a very good reason. Use EXPORT_OK instead.
  18. # Do not simply export all your public functions/methods/constants.
  19. @EXPORT = qw(
  20. SERVICE_CONTROL_USER_DEFINED
  21. SERVICE_NOT_READY
  22. SERVICE_STOPPED
  23. SERVICE_RUNNING
  24. SERVICE_PAUSED
  25. SERVICE_START_PENDING
  26. SERVICE_STOP_PENDING
  27. SERVICE_CONTINUE_PENDING
  28. SERVICE_PAUSE_PENDING
  29. SERVICE_CONTROL_NONE
  30. SERVICE_CONTROL_STOP
  31. SERVICE_CONTROL_PAUSE
  32. SERVICE_CONTROL_CONTINUE
  33. SERVICE_CONTROL_INTERROGATE
  34. SERVICE_CONTROL_SHUTDOWN
  35. SERVICE_CONTROL_PARAMCHANGE
  36. SERVICE_CONTROL_NETBINDADD
  37. SERVICE_CONTROL_NETBINDREMOVE
  38. SERVICE_CONTROL_NETBINDENABLE
  39. SERVICE_CONTROL_NETBINDDISABLE
  40. SERVICE_CONTROL_DEVICEEVENT
  41. SERVICE_CONTROL_HARDWAREPROFILECHANGE
  42. SERVICE_CONTROL_POWEREVENT
  43. SERVICE_CONTROL_SESSIONCHANGE
  44. SERVICE_CONTROL_USER_DEFINED
  45. SERVICE_CONTROL_RUNNING
  46. SERVICE_CONTROL_PRESHUTDOWN
  47. SERVICE_CONTROL_TIMER
  48. SERVICE_CONTROL_START
  49. SERVICE_ACCEPT_DEVICEEVENT
  50. SERVICE_ACCEPT_HARDWAREPROFILECHANGE
  51. SERVICE_ACCEPT_POWEREVENT
  52. SERVICE_ACCEPT_SESSIONCHANGE
  53. USER_SERVICE_BITS_1
  54. USER_SERVICE_BITS_2
  55. USER_SERVICE_BITS_3
  56. USER_SERVICE_BITS_4
  57. USER_SERVICE_BITS_5
  58. USER_SERVICE_BITS_6
  59. USER_SERVICE_BITS_7
  60. USER_SERVICE_BITS_8
  61. USER_SERVICE_BITS_9
  62. USER_SERVICE_BITS_10
  63. SERVICE_ACCEPT_STOP
  64. SERVICE_ACCEPT_PAUSE_CONTINUE
  65. SERVICE_ACCEPT_SHUTDOWN
  66. SERVICE_ACCEPT_PARAMCHANGE
  67. SERVICE_ACCEPT_NETBINDCHANGE
  68. SERVICE_WIN32_OWN_PROCESS
  69. SERVICE_WIN32_SHARE_PROCESS
  70. SERVICE_KERNEL_DRIVER
  71. SERVICE_FILE_SYSTEM_DRIVER
  72. SERVICE_INTERACTIVE_PROCESS
  73. SERVICE_BOOT_START
  74. SERVICE_SYSTEM_START
  75. SERVICE_AUTO_START
  76. SERVICE_DEMAND_START
  77. SERVICE_DISABLED
  78. SERVICE_DISABLED
  79. SERVICE_ERROR_NORMAL
  80. SERVICE_ERROR_SEVERE
  81. SERVICE_ERROR_CRITICAL
  82. SC_GROUP_IDENTIFIER
  83. NO_ERROR
  84. );
  85. @EXPORT_OK = qw(
  86. );
  87. bootstrap $Package;
  88. sub AUTOLOAD
  89. {
  90. # This AUTOLOAD is used to 'autoload' constants from the constant()
  91. # XS function. If a constant is not found then control is passed
  92. # to the AUTOLOAD in AutoLoader.
  93. my( $Constant ) = $AUTOLOAD;
  94. my( $Result, $Value );
  95. $Constant =~ s/.*:://;
  96. $Result = Constant( $Constant, $Value );
  97. if( 0 == $Result )
  98. {
  99. # The extension could not resolve the constant...
  100. $AutoLoader::AUTOLOAD = $AUTOLOAD;
  101. goto &AutoLoader::AUTOLOAD;
  102. return;
  103. }
  104. elsif( 1 == $Result )
  105. {
  106. # $Result == 1 if the constant is valid but not defined
  107. # that is, the extension knows that the constant exists but for
  108. # some wild reason it was not compiled with it.
  109. $pack = 0;
  110. ($pack,$file,$line) = caller;
  111. print "Your vendor has not defined $Package macro $constname, used in $file at line $line.";
  112. }
  113. elsif( 2 == $Result )
  114. {
  115. # If $Result == 2 then we have a string value
  116. $Value = "'$Value'";
  117. }
  118. # If $Result == 3 then we have a numeric value
  119. eval "sub $AUTOLOAD { return( $Value ); }";
  120. goto &$AUTOLOAD;
  121. }
  122. # For a module, you *always* return TRUE...
  123. return( 1 );
  124. END
  125. {
  126. # Stop the service only if we are in the main thread (not in a forked process)
  127. Win32::Daemon::StopService() if $$ > 0;
  128. }
  129. __END__
  130. =head1 NAME
  131. Win32::Daemon - Extension enabling Win32 Perl scripts to run as a true Win32 service.
  132. =head1 SYNOPSIS
  133. use Win32::Daemon;
  134. Win32::Daemon::StartService();
  135. # ...process Perl code...
  136. Win32::Daemon::StopService();
  137. =head1 DESCRIPTION
  138. This extension enables a Win32 Perl script to act as a true Win32 service.
  139. =head1 FUNCTIONS
  140. =head2 Function List
  141. =over 4
  142. C<AcceptedControls()>
  143. C<CallbackTimer()>
  144. C<CreateService()>
  145. C<ConfigureService()>
  146. C<QueryServiceConfig()>
  147. C<DeleteService()>
  148. C<GetLastError()>
  149. C<GetSecurity()>
  150. C<GetServiceHandle()>
  151. C<HideService()>
  152. C<QueryLastMessage()>
  153. C<RegisterCallbacks()>
  154. C<RestoreService()>
  155. C<SetSecurity()>
  156. C<SetServiceBits()>
  157. C<ShowService()>
  158. C<StartService()>
  159. C<State()>
  160. C<StopService()>
  161. C<Timeout()>
  162. =back
  163. =head2 Function Descriptions
  164. =over 4
  165. =item AcceptedControls( [$NewControls] )
  166. This function queries (and optionally sets) the current list of controls that the service registers for.
  167. By registering for a control the script is notifying the SCM that it is accepting the specified
  168. control messages. For example, if you specify the C<SERVICE_ACCEPT_PAUSE_CONTINUE> control then
  169. the SCM knows that the script will accept and process any attempt to pause and continue (resume
  170. from paused state) the service.
  171. Recognized accepted controls:
  172. SERVICE_ACCEPT_STOP............The service accepts messages to stop.
  173. SERVICE_ACCEPT_PAUSE_CONTINUE..The service accepts messages to pause
  174. and continue.
  175. SERVICE_ACCEPT_SHUTDOWN........The service accepts messages to
  176. shutdown the system: when the OS is
  177. shutting down the service will be
  178. notified when it has accepted this
  179. control.
  180. Following controls are only recognized on Windows 2000 and higher:
  181. SERVICE_ACCEPT_PARAMCHANGE.....The service accepts messages
  182. notifying it of any parameter change
  183. made to the service.
  184. SERVICE_ACCEPT_NETBINDCHANGE...The service accepts messages
  185. notifying it of any network binding
  186. changes.
  187. By default all of these controls are accepted. To change this pass in a value consisting of
  188. any of these values OR'ed together.
  189. B<NOTE:> You can query and set these controls at any time. However it is only supported to
  190. set them before you start the service (calling the C<StartService()> function).
  191. =item CallbackTimer( [ $NewTimerValue ] )
  192. This function returns the value of the callback timer. The value is in milliseconds.
  193. This value indicates how often the "Running" callback subroutine will be called. Note
  194. that the calling of this routine will be blocked by any other callback.
  195. If you pass in a value it will reset the timer to the specified frequency. Passing in
  196. a 0 will disable all "Running" callbacks. Passing in -1 will toggle the state between
  197. calling the "Running" callback subroutine and not calling it.
  198. =item CreateService ( \%ServiceInfo )
  199. This function creates a new service in the system configuration. The
  200. return is TRUE if the service was created, and FALSE otherwise. If an error
  201. occurred, call GetLastError to retrieve the actual error code.
  202. The hash describes the service to be created. The keys are:
  203. =over 4
  204. =item C<name>
  205. The 'internal' service name; that is, the name of the
  206. registry key used to store the information on this service.
  207. =item C<display>
  208. The 'display' service name; that is, the name displayed
  209. by the services control panel or MMC plugin.
  210. =item C<path>
  211. The full path name to the executable. This should be the path to your Perl
  212. executable, which will normally be the contents of C<$^X>.
  213. B<NOTE:> If you are using a compiled perl script (such as one
  214. generated with PerlApp) as opposed to a text based perl script file then this
  215. value must point to the actual compiled script's executable (eg. F<MyCompiledPerlService.exe>)
  216. instead of (C<$^X> which usually points to F<perl.exe>). You can specify
  217. any parameters to pass into the service using the C<parameters> key.
  218. =item C<user>
  219. The username the service is to run under; this is optional.
  220. =item C<password>
  221. The password to be used to log in the service; this is
  222. technically optional, but needs to be specified if C<user> is.
  223. =item C<parameters>
  224. The parameters to be passed to Perl; in other words, the command line you
  225. would execute interactively, but without the leading ``perl ''. The C<parameters> key
  226. value is appended to the C<path> key when starting the service.
  227. Typically this will be something like:
  228. MyPerlScript.pl /a /b /c
  229. =item C<machine>
  230. The name of the machine to create the service on. Omission
  231. or an empty string specify the machine executing the call.
  232. =item C<service_type>
  233. An integer representing the type of the service;
  234. defaults to C<SERVICE_WIN32_OWN_PROCESS>.
  235. =item C<start_type>
  236. An integer specifying how (or whether) the service is
  237. to be started. The default is C<SERVICE_AUTO_START>.
  238. =item C<error_control>
  239. An integer specifying how the Service Control Manager
  240. is to react if the service fails to start. The default is
  241. C<SERVICE_ERROR_IGNORE>, which in fact gets you an error log entry.
  242. =item C<load_order>
  243. The name of the load order group of which this service
  244. is a member. The default is membership in no group. See value
  245. C<ServiceGroupOrder> in registry key
  246. C<HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control>
  247. for the names.
  248. =item C<tag_id>
  249. An integer representing the startup order of the service
  250. within its load ordering group.
  251. =item C<dependencies>
  252. A reference to the I<internal> names of services and/or
  253. load ordering groups upon which this service depends. The default is
  254. no dependencies. Load order group names are prefixed with a '+' to
  255. distinguish them from service names.
  256. =item C<description>
  257. A short text description of the service, displayed
  258. (at least) as flyover help by the MMC "services" plugin.
  259. =back
  260. =item ConfigureService( \%ServiceInfo )
  261. Modify a service created with C<CreateService>. Same arguments as
  262. C<CreateService>.
  263. If you specify a C<parameters> key you MUST specify a C<path> key.
  264. =item DeleteService ($Machine, $ServiceName )
  265. This function deletes an existing service. The return is TRUE if the
  266. service was deleted, and FALSE otherwise. If an error occurred, call
  267. GetLastError to retrieve the actual error code.
  268. The arguments are the name of the machine (an empty string specifies
  269. the machine executing the call), and the 'internal' service name (i.e.
  270. the string passed in the C<name> element when the service was created).
  271. A running service may not be deleted.
  272. =item GetSecurity( $Machine, $ServiceName )
  273. This will return a binary Security Descriptor (SD) that is associated with the
  274. specified service on the specified machine.
  275. The SD is in self-relative format. It can be imported into a C<L<Win32::Perms>> object using
  276. the C<Win32::Perms> object's C<Import()> method.
  277. =item RegisterCallbacks( $CodeRef | \%Hash )
  278. This will register specified code subroutines that will be called when specified
  279. events take place. For example if you register a subroutine with the
  280. C<pause> event then this routine will be called when there is an attempt to pause the
  281. service. Not all events must have callbacks registered.
  282. If only a reference to a subroutine is passed in then it will be called for each and every
  283. event. You can pass in a hash containing particular key names (listed below) with
  284. code references.
  285. Possible hash key names:
  286. Key Name Event
  287. ------------- --------------------------------------
  288. start....................The service is starting.
  289. pause....................The service is entering a paused state.
  290. continue.................The service is resuming from a paused
  291. state.
  292. stop.....................The service is stopping (see note below).
  293. running..................The service is running (see note below).
  294. interrogate..............The service is being queried for
  295. information.
  296. shutdown.................The system is being shut down.
  297. preshutdown..............The system is about to begin shutting
  298. down (Vista+ only).
  299. param_change.............There has been a parameter change to
  300. the system.
  301. net_bind_add.............A new network binding has been made.
  302. net_bind_remove..........A network binding has been removed.
  303. net_bind_enable..........A network binding has been enabled.
  304. net_bind_disable.........A network binding has been disabled.
  305. device_event.............A device has generated some event.
  306. hardware_profile_change..A change has been made to the system's
  307. hardware profile.
  308. power_event..............A power event has occured (eg change to
  309. battery power).
  310. session_change...........There has been a change in session.
  311. user_defined.............A user defined event has been sent to
  312. the service.
  313. B<NOTES:>
  314. =over 4
  315. =item The C<Stop> state
  316. When a service calls into the registered "stop" callback routine
  317. the script should call the C<StopService()> function. This tells the service to terminate
  318. and return back to the Perl script. This is the only way for the service to know that it
  319. must stop.
  320. =item The C<Running> state
  321. Periodically the extension will call into a registered
  322. "Running" subroutine. This allows the script to process data. This routine should be fast
  323. and return quickly otherwise it will block other callback events from being run. The
  324. frequency of calling the "Running" subroutine is dictated by the callback timer value
  325. passed into C<StartService()> and any changes made to this value by calling into
  326. C<CallbackTimer()>.
  327. =back
  328. =item SetSecurity( $Machine, $ServiceName, $BinarySD | $Win32PermsObject )
  329. This applies the specified Security Descriptor (SD) to the specified service on the
  330. specified machine. You must have appropriate permissions to call this function.
  331. The specified SD can be either a binary SD (in self-relative or absolute format) or
  332. it can be a Win32::Perms object.
  333. This only sets the DACL and SACL. The owner and group are not set even if they are
  334. specified in the SD.
  335. =item StartService( [ \%Context, $CallbackTimer ] )
  336. This starts a new service thread. The script should call this as soon as possible. When
  337. the service manager starts the service Perl is started and the script is loaded.
  338. This function returns the thread handle of the service thread. If you call into this more
  339. than once it will only return the thread handle (it won't create another new service thread).
  340. =over 4
  341. =item Callback Mode
  342. If the script has already registered callback routines (using C<RegisterCallbacks()>) then
  343. the call into C<StartService()> will not return until the service has stopped. However
  344. callbacks will be made for each state change and callback timer timeout (refer to C<RegisterCallbacks()>).
  345. =back
  346. =item StopService()
  347. This will instruct the service to terminate.
  348. =item Timeout( [$TimeoutValue] )
  349. This function sets the new timeout value indicating how long a command will wait before
  350. Win32::Daemon tells the Service Control Manager that the command failed.
  351. =item QueryLastMessage( [$fResetMessage] )
  352. This function returns the last message that the service manager has sent to the service.
  353. Pass in a non zero value to reset the pending message to C<SERVICE_CONTROL_NONE>. This way
  354. your script can tell when two of the same messages come in.
  355. Occasionally the service manager will send messages to the service. These messages
  356. typically request the service to change from one state to another. It is important that
  357. the Perl script responds to each message otherwise the service manager becomes confused
  358. about the current state of the service. For example, if the service manager is submits
  359. a C<SERVICE_PAUSE_PENDING> then it expects the Perl script to recognize the change to a paused
  360. state and submit the new state by calling C<State( SERVICE_PAUSED )>.
  361. You can update the service manager with the current status using the C<State()> function.
  362. Possible values returned are:
  363. Valid Service Control Messages
  364. ------------------------------
  365. SERVICE_CONTROL_NONE............No message is pending.
  366. SERVICE_CONTROL_STOP............The SCM is requesting the service to
  367. stop. This results in State()
  368. reporting SERVICE_STOP_PENDING.
  369. SERVICE_CONTROL_PAUSE...........The SCM is requesting the service to
  370. pause. This results in State()
  371. reporting SERVICE_PAUSE_PENDING.
  372. SERVICE_CONTROL_CONTINUE........The SCM is requesting the service to
  373. continue from a paused state. This
  374. results in State() reporting
  375. SERVICE_CONTINUE_PENDING.
  376. SERVICE_CONTROL_INTERROGATE.....The service manager is querying the
  377. service's state
  378. SERVICE_CONTROL_USER_DEFINED....This is a user defined control.
  379. There are 127 of these beginning
  380. with SERVICE_CONTROL_USER_DEFINED
  381. as the base.
  382. Windows 2000 specific messages:
  383. SERVICE_CONTROL_SHUTDOWN........The machine is shutting down. This
  384. indicates that the service has
  385. roughly 20 seconds to clean up and
  386. terminate. This time can be extended
  387. by submitting SERVICE_STOP_PENDING
  388. via the State() function.
  389. SERVICE_CONTROL_PARAMCHANGE.....Service parameters have been
  390. modified.
  391. SERVICE_CONTROL_NETBINDADD......A network binding as been added.
  392. SERVICE_CONTROL_NETBINDREMOVE...A network binding has been removed.
  393. SERVICE_CONTROL_NETBINDENABLE...A network binding has been enabled.
  394. SERVICE_CONTROL_NETBINDDISABLE..A network binding has been disabled.
  395. SERVICE_CONTROL_DEVICEEVENT.....A device has generated some event.
  396. SERVICE_CONTROL_HARDWAREPROFILECHANGE
  397. A change has been made to the
  398. system's hardware profile.
  399. SERVICE_CONTROL_POWEREVENT......A power event has occured (eg change
  400. to battery power).
  401. SERVICE_CONTROL_SESSIONCHANGE...There has been a change in session.
  402. Windows Vista+ specific messages:
  403. SERVICE_CONTROL_PRESHUTDOWN ....The machine is about to shut down.
  404. This provides the service much more
  405. time to shutdown than
  406. SERVICE_CONTROL_SHUTDOWN.
  407. B<Note:> When the system shuts down it will send a C<SERVICE_CONTROL_SHUTDOWN> message. The
  408. Perl script has approximately 20 seconds to perform any shutdown activities before the
  409. Control Manger stops the service. If more time is needed call the C<State()> function
  410. passing in the C<SERVICE_STOP_PENDING> control message along with how many seconds it will
  411. take to shutdown the service. This time value is only an estimate. When the service is
  412. finally ready to stop it must submit the C<SERVICE_STOPPED> message as in:
  413. if( SERVICE_CONTROL_SHUTDOWN == State() )
  414. {
  415. Win32::Daemon::State( SERVICE_STOP_PENDING, 30 );
  416. #...process code...
  417. Win32::Daemon::State( SERVICE_STOPPED );
  418. }
  419. =item State([$NewState [, $Hint ] || \%Hash ] )
  420. This function returns the current state of the service. It can optionally update the
  421. status of the service as well. This is the last status reported to the service manager.
  422. Optionally you can pass in a value that will be sent to the service manager.
  423. Optionally you can pass in a numeric value indicating the "hint". This is the number of
  424. milliseconds the SCM can expect to wait before the service responds to the request. For example,
  425. if your service script reports a hint of 30,000 milliseconds means that the SCM will have to wait
  426. for 30 seconds for the script to change the service's state before deciding that the
  427. script is non responsive.
  428. If you are setting/updating the state instead of passing in the state and wait hint you could
  429. pass in a hash reference. This allows you to specify the state, wait hint and error state. You
  430. can use the following keys:
  431. Hash Key
  432. --------
  433. state..........Valid service state (see table below).
  434. waithint.......A wait hint explained above. This is in milliseconds.
  435. error..........Any 32 bit error code. This is what will be reported
  436. if an application queries the error state of the
  437. service. It is also what is reported if a call to
  438. start the services fails.
  439. To reset an error state pass in NO_ERROR.
  440. The only invalid error value is 0xFFFFFFFF.
  441. Example of passing in an error:
  442. Win32::Daemon::State( { error => 0x12345678 } );
  443. # Later to reset the error:
  444. Win32::Daemon::State( { error => NO_ERROR } );
  445. Possible values returned (or submitted):
  446. Valid Service States
  447. --------------------
  448. SERVICE_NOT_READY..........The SCM has not yet been initialized. If
  449. the SCM is slow or busy then this value
  450. will result from a call to State().
  451. If you get this value, just keep calling
  452. State() until you get
  453. SERVICE_START_PENDING.
  454. SERVICE_STOPPED............The service is stopped.
  455. SERVICE_RUNNING............The service is running.
  456. SERVICE_PAUSED.............The service is paused.
  457. SERVICE_START_PENDING......The service manager is attempting to
  458. start the service.
  459. SERVICE_STOP_PENDING.......The service manager is attempting to
  460. stop the service.
  461. SERVICE_CONTINUE_PENDING...The service manager is attempting to
  462. resume the service.
  463. SERVICE_PAUSE_PENDING......The service manager is attempting to
  464. pause the service.
  465. =back
  466. =head1 Callbacks
  467. Callbacks were introduced in version v20030617.
  468. The Win32::Daemon supports the concept of event callbacks. This allows a script to
  469. register a particular subroutine with a particular event. When the event occurs it
  470. will call the Perl subroutine registered with that event. This can make it very simple
  471. to write scripts.
  472. You register a callback subroutine by calling into the C<RegisterCallbacks()> function.
  473. You can pass in a code reference or a hash. A code reference will register the specified
  474. subroutine with all events. A hash allows you to pick which events you want to
  475. register for which subroutines. You do not have to register all events. If an event is
  476. not registered for a subroutine then the script will not be notified when the event
  477. occurs.
  478. At a minimum a script should register for the 'Start' and 'Running' states. This enables
  479. the script to actually start and to periodically process data.
  480. When an event callback occurs the subroutine should change the state accordingly by
  481. passing in the new state into C<State()>. For example the 'Start' callback would call
  482. C<State( SERVICE_RUNNING )> to inform the service that it is officially running. Another
  483. example is the 'Pause' state should call C<State( SERVICE_PAUSED )> to inform the service
  484. that it is offically paused.
  485. Once callback subroutines are registered the script enters the service mode by calling
  486. C<StartService()>. This will being the process of calling the event callback routines.
  487. Note that when callback routines are registered the C<StartService()> function will not
  488. return until a callback routine calls C<StopService()> (typically the 'Stop' event callback
  489. would call C<StopService()>.
  490. When calling into C<StartService()> you can pass in a hash reference. This reference is known as
  491. a "context" hash. For every callback the hash will be passed into the callback routine. This enables
  492. a script to query and set data in the hash--essentially letting you pass information across to
  493. different callback events. This context hash is not required.
  494. When a callback is made it always passes two parameters in: $State and $Context. $State is simply
  495. the state change that caused the callback. This represents the event that took place (e.g. C<SERVICE_PAUSE_PENDING>,
  496. C<SERVICE_START_PENDING>, etc). The $Context is a reference to the context hash that was passed into
  497. the C<StartService()> function.
  498. A typical callback routine should look similar to:
  499. sub Callback_Start
  500. {
  501. my( $Event, $Context ) = @_;
  502. $Context->{last_event} = $Event;
  503. # ...do some work here...
  504. # Tell the service manager that we have now
  505. # entered the running state.
  506. Win32::Daemon::State( SERVICE_RUNNING );
  507. return();
  508. }
  509. Refer to C<Example 4: Using a single callback> and C<Example 5: Using different callback routines> for an example of using callbacks.
  510. =head1 COMPILED PERL APPLICATIONS
  511. Many users like to compile their perl scripts into executable programs. This way it is much easier to copy them around
  512. from machine to machine since all necessary files, packages and binaries are compiled into one .exe file. These compiled
  513. perl scripts are compatible with Win32::Deamon as long as you install it correctly.
  514. If you are going to compile your Win32::Daemon based perl script into an .exe there is nothing unique you need to do
  515. to your Win32::Daemon code with one single exception of the call into Win32::Daemon::C<CreateService()>. When passing in
  516. the 'path' and 'parameters' values into C<CreateService()> observe the following simple rules:
  517. =over 4
  518. =item If using a Perl script
  519. path........The full path to the Perl interpeter ($^X).
  520. This is typically:
  521. c:\perl\bin\perl.exe
  522. parameters..This value MUST start with the full path to the perl
  523. script file and append any parameters
  524. that you want passed into the service. For
  525. Example:
  526. c:\scripts\myPerlService.pl -param1 -param2 "c:\\Param2Path"
  527. =item If using a compiled Perl application
  528. path........The full path to the compiled Perl application.
  529. For example:
  530. c:\compiledscripts\myPerlService.exe
  531. parameters..This value is just the list of parameters
  532. that you want passed into the service. For
  533. Example:
  534. -param1 -param2 "c:\\Param2Path"
  535. =back
  536. Refer to L</Example 3: Install the service> for an example.
  537. =head1 EXAMPLES
  538. =head2 Example 1: Simple Service
  539. This example service will delete all .tmp files from the c:\temp directory every
  540. time it starts. It will immediately terminate.
  541. use Win32::Daemon;
  542. # Tell the OS to start processing the service...
  543. Win32::Daemon::StartService();
  544. # Wait until the service manager is ready for us to continue...
  545. while( SERVICE_START_PENDING != Win32::Daemon::State() )
  546. {
  547. sleep( 1 );
  548. }
  549. # Now let the service manager know that we are running...
  550. Win32::Daemon::State( SERVICE_RUNNING );
  551. # Okay, go ahead and process stuff...
  552. unlink( glob( "c:\\temp\\*.tmp" ) );
  553. # Tell the OS that the service is terminating...
  554. Win32::Daemon::StopService();
  555. This particular example does not really illustrate the capabilities of a Perl based service.
  556. =head2 Example 2: Typical skeleton code
  557. # This style of Win32::Daemon use is obsolete. It still works but the
  558. # callback model is more efficient and easier to use. Refer to examples 4
  559. #and 5.
  560. use Win32;
  561. use Win32::Daemon;
  562. $SERVICE_SLEEP_TIME = 20; # 20 milliseconds
  563. $PrevState = SERVICE_START_PENDING;
  564. Win32::Daemon::StartService();
  565. while( SERVICE_STOPPED != ( $State = Win32::Daemon::State() ) )
  566. {
  567. if( SERVICE_START_PENDING == $State )
  568. {
  569. # Initialization code
  570. Win32::Daemon::State( SERVICE_RUNNING );
  571. $PrevState = SERVICE_RUNNING;
  572. }
  573. elseif( SERVICE_STOP_PENDING == $State )
  574. {
  575. Win32::Daemon::State( SERVICE_STOPPED );
  576. }
  577. elsif( SERVICE_PAUSE_PENDING == $State )
  578. {
  579. # "Pausing...";
  580. Win32::Daemon::State( SERVICE_PAUSED );
  581. $PrevState = SERVICE_PAUSED;
  582. next;
  583. }
  584. elsif( SERVICE_CONTINUE_PENDING == $State )
  585. {
  586. # "Resuming...";
  587. Win32::Daemon::State( SERVICE_RUNNING );
  588. $PrevState = SERVICE_RUNNING;
  589. next;
  590. }
  591. elsif( SERVICE_STOP_PENDING == $State )
  592. {
  593. # "Stopping...";
  594. Win32::Daemon::State( SERVICE_STOPPED );
  595. $PrevState = SERVICE_STOPPED;
  596. next;
  597. }
  598. elsif( SERVICE_RUNNING == $State )
  599. {
  600. # The service is running as normal...
  601. # ...add the main code here...
  602. }
  603. else
  604. {
  605. # Got an unhandled control message. Set the state to
  606. # whatever the previous state was.
  607. Win32::Daemon::State( $PrevState );
  608. }
  609. # Check for any outstanding commands. Pass in a non zero value
  610. # and it resets the Last Message to SERVICE_CONTROL_NONE.
  611. if( SERVICE_CONTROL_NONE != ( my $Message = Win32::Daemon::QueryLastMessage( 1 ) ) )
  612. {
  613. if( SERVICE_CONTROL_INTERROGATE == $Message )
  614. {
  615. # Got here if the Service Control Manager is requesting
  616. # the current state of the service. This can happen for
  617. # a variety of reasons. Report the last state we set.
  618. Win32::Daemon::State( $PrevState );
  619. }
  620. elsif( SERVICE_CONTROL_SHUTDOWN == $Message )
  621. {
  622. # Yikes! The system is shutting down. We had better clean up
  623. # and stop.
  624. # Tell the SCM that we are preparing to shutdown and that we
  625. # expect it to take 25 seconds (so don't terminate us for at
  626. # least 25 seconds)...
  627. Win32::Daemon::State( SERVICE_STOP_PENDING, 25000 );
  628. }
  629. }
  630. # Snooze for awhile so we don't suck up cpu time...
  631. Win32::Sleep( $SERVICE_SLEEP_TIME );
  632. }
  633. # We are done so close down...
  634. Win32::Daemon::StopService();
  635. =head2 Example 3: Install the service
  636. For the 'path' key the $^X equates to the full path of the
  637. perl executable.
  638. Since no user is specified it defaults to the LocalSystem.
  639. use Win32::Daemon;
  640. # If using a compiled perl script (eg. myPerlService.exe) then
  641. # $ServicePath must be the path to the .exe as in:
  642. # $ServicePath = 'c:\CompiledPerlScripts\myPerlService.exe';
  643. # Otherwise it must point to the Perl interpreter (perl.exe) which
  644. # is conviently provided by the $^X variable...
  645. my $ServicePath = $^X;
  646. # If using a compiled perl script then $ServiceParams
  647. # must be the parameters to pass into your Perl service as in:
  648. # $ServiceParams = '-param1 -param2 "c:\\Param2Path"';
  649. # OTHERWISE
  650. # it MUST point to the perl script file that is the service such as:
  651. my $ServiceParams = 'c:\perl\scripts\myPerlService.pl -param1 -param2 "c:\\Param2Path"';
  652. my %service_info = (
  653. machine => '',
  654. name => 'PerlTest',
  655. display => 'Oh my GOD, Perl is a service!',
  656. path => $ServicePath,
  657. user => '',
  658. pwd => '',
  659. description => 'Some text description of this service',
  660. parameters => $ServiceParams
  661. );
  662. if( Win32::Daemon::CreateService( \%service_info ) )
  663. {
  664. print "Successfully added.\n";
  665. }
  666. else
  667. {
  668. print "Failed to add service: " . Win32::FormatMessage( Win32::Daemon::GetLastError() ) . "\n";
  669. }
  670. =head2 Example 4: Using a single callback
  671. In this example only one subroutine is used for all callbacks. The CallbackRoutine()
  672. subroutine will receive all event callbacks. Basically this callback routine will
  673. have to do essentially the same thing that the main while loop in
  674. L</Example 2: Typical skeleton code> does.
  675. use Win32::Daemon;
  676. Win32::Daemon::RegisterCallbacks( \&CallbackRoutine );
  677. %Context = (
  678. count => 0,
  679. start_time => time(),
  680. );
  681. # Start the service passing in a context and
  682. # indicating to callback using the "Running" event
  683. # every 2000 milliseconds (2 seconds).
  684. Win32::Daemon::StartService( \%Context, 2000 );
  685. sub CallbackRoutine
  686. {
  687. my( $Event, $Context ) = @_;
  688. $Context->{last_event} = $Event;
  689. if( SERVICE_RUNNING == $Event )
  690. {
  691. # ... process your main stuff here...
  692. # ... note that here there is no need to
  693. # change the state
  694. }
  695. elsif( SERVICE_START_PENDING == $Event )
  696. {
  697. # Initialization code
  698. # ...do whatever you need to do to start...
  699. $Context->{last_state} = SERVICE_RUNNING;
  700. Win32::Daemon::State( SERVICE_RUNNING );
  701. }
  702. elsif( SERVICE_PAUSE_PENDING == $Event )
  703. {
  704. $Context->{last_state} = SERVICE_PAUSED;
  705. Win32::Daemon::State( SERVICE_PAUSED );
  706. }
  707. elsif( SERVICE_CONTINUE_PENDING == $Event )
  708. {
  709. $Context->{last_state} = SERVICE_RUNNING;
  710. Win32::Daemon::State( SERVICE_RUNNING );
  711. }
  712. elsif( SERVICE_STOP_PENDING == $Event )
  713. {
  714. $Context->{last_state} = SERVICE_STOPPED;
  715. Win32::Daemon::State( SERVICE_STOPPED );
  716. # We need to notify the Daemon that we want to stop callbacks
  717. # and the service.
  718. Win32::Daemon::StopService();
  719. }
  720. else
  721. {
  722. # Take care of unhandled states by setting the State()
  723. # to whatever the last state was we set...
  724. Win32::Daemon::State( $Context->{last_state} );
  725. }
  726. return();
  727. }
  728. =head2 Example 5: Using different callback routines
  729. use Win32::Daemon;
  730. Win32::Daemon::RegisterCallbacks( {
  731. start => \&Callback_Start,
  732. running => \&Callback_Running,
  733. stop => \&Callback_Stop,
  734. pause => \&Callback_Pause,
  735. continue => \&Callback_Continue,
  736. } );
  737. my %Context = (
  738. last_state => SERVICE_STOPPED,
  739. start_time => time(),
  740. );
  741. # Start the service passing in a context and
  742. # indicating to callback using the "Running" event
  743. # every 2000 milliseconds (2 seconds).
  744. Win32::Daemon::StartService( \%Context, 2000 );
  745. sub Callback_Running
  746. {
  747. my( $Event, $Context ) = @_;
  748. # Note that here you want to check that the state
  749. # is indeed SERVICE_RUNNING. Even though the Running
  750. # callback is called it could have done so before
  751. # calling the "Start" callback.
  752. if( SERVICE_RUNNING == Win32::Daemon::State() )
  753. {
  754. # ... process your main stuff here...
  755. # ... note that here there is no need to
  756. # change the state
  757. }
  758. }
  759. sub Callback_Start
  760. {
  761. my( $Event, $Context ) = @_;
  762. # Initialization code
  763. # ...do whatever you need to do to start...
  764. $Context->{last_state} = SERVICE_RUNNING;
  765. Win32::Daemon::State( SERVICE_RUNNING );
  766. }
  767. sub Callback_Pause
  768. {
  769. my( $Event, $Context ) = @_;
  770. $Context->{last_state} = SERVICE_PAUSED;
  771. Win32::Daemon::State( SERVICE_PAUSED );
  772. }
  773. sub Callback_Continue
  774. {
  775. my( $Event, $Context ) = @_;
  776. $Context->{last_state} = SERVICE_RUNNING;
  777. Win32::Daemon::State( SERVICE_RUNNING );
  778. }
  779. sub Callback_Stop
  780. {
  781. my( $Event, $Context ) = @_;
  782. $Context->{last_state} = SERVICE_STOPPED;
  783. Win32::Daemon::State( SERVICE_STOPPED );
  784. # We need to notify the Daemon that we want to stop callbacks and the service.
  785. Win32::Daemon::StopService();
  786. }
  787. =head1 NOTES
  788. =head2 Timer/Running Callbacks:
  789. Starting with build 20080321 the "running" callback is deprecated and replaced with the
  790. "timer" callback. Scripts should no longer test for a state of SERVICE_RUNNING but instead check
  791. for the state of SERVICE_CONTROL_TIMER to indicate whether or not a callback has occurred
  792. due to a timer.
  793. If a script...
  794. =over 4
  795. =item *
  796. ...registers for the "running" callback it will continue to work
  797. as expected: timer expiration results in a callback to the subroutine registered for the "running"
  798. callback passing in a value of SERVICE_RUNNING.
  799. =item *
  800. ...registers for the "timer" callback then timer expiration results in a callback to the
  801. subroutine registered for the "timer" callback, passing in a value of SREVICE_CONTROL_TIMER.
  802. =item *
  803. ...registers for both "running" and "timer" then only Win32::Daemon treats it as if only
  804. "timer" was registered (see above for behavior).
  805. =item *
  806. ...registers for everything by passing one subroutine reference into Win32::Daemon::Callback()
  807. then both "running" and "timer" are registered and only "timer" is recognized (see previous
  808. 2 behaviors above).
  809. =back
  810. Legacy scripts which call Win32::Daemon::Callback() passing in only one catchall subroutine reference
  811. will be most impacted as they will expect.
  812. =head1 SEE ALSO
  813. L<MSDN: I<Service Control Manager>|http://msdn.microsoft.com/fr-fr/library/ms685150>
  814. L<MSDN: I<Service Functions>|http://msdn.microsoft.com/fr-fr/library/ms685942%28v=VS.85%29.aspx>
  815. =head1 AUTHOR
  816. Dave Roth, Roth Consulting, http://www.roth.net/
  817. =head1 CONTRIBUTORS
  818. Haiko Strotbek <haiko@strotbek.com>
  819. Jan Dubois <jand@activestate.com>
  820. Marc Pijnappels <marc.pijnappels@nec-computers.com>
  821. Olivier MenguE<eacute> <dolmen@cpan.org>
  822. =head1 SUPPORT
  823. Dave has retired from active development of this module. It is now
  824. being maintained as part of the libwin32 project <libwin32@perl.org>.
  825. =head1 COPYRIGHT
  826. Copyright E<copy> 1998 - 2011 the Win32::Daemon L</AUTHOR> and L</CONTRIBUTORS>
  827. as listed above.
  828. =head1 LICENSE
  829. This library is free software and may be distributed under the same terms
  830. as perl itself.
  831. =cut