Windows Background Service program example

Source: Internet
Author: User

// Main function of the service program. # Include <stdio. h> // # include "stdafx. H "# include <windows. h> # include <iostream> # define szappname "serversample" // service program name # define szservicename "servicesample" // identifies the internal name of the service/internal variable bool bdebugserver = false; service_status ssstatus; service_status_handle sshstatushandle; DWORD dwerr = 0; tchar szerr [256]; // The following functions are implemented by void winapi service_main (DWORD dwargc, lptstr * lpszargv ); void winapi service_ctrl (DWORD dwctrlcode ); Void installservice (); void removeservice (); void debugservice (INT argc, char ** argv); bool reportstatustoscmgr (DWORD dwcurrentstate, DWORD dwwin32exitcode, DWORD dwwaithint ); void addtomessagelog (lptstr lpszmsg); void servicestop (); void servicepause (); void servicecontinue (); int main (INT argc, char * argv []) {service_table_entry dispatchtable [] = {text (szservicename), (lpservice_main_function) service_mai N },{ null, null }}; if (argc> 1) & (* argv [1] = '-') | (argv [1] = "/") {If (_ stricmp ("Install", argv [1] + 1) = 0) {installservice ();} else if (_ stricmp ("Remove", argv [1] + 1) = 0) {removeservice ();} else if (_ stricmp ("debug", argv [1] + 1) = 0) {bdebugserver = true; debugservice (argc, argv );} else {// If the parameter does not match the above, it may be the Service Control Manager to start the program. Call the // startservicectrldispatcher function immediately. Printf ("% s-install to install the service/N", szappname); printf ("% s-remove to remove the service/N", szappname ); printf ("% s-Debug to debug the service/N", szappname); printf ("/n startservicectrldispatcher being called. /n "); printf (" This may take several seconds. please wait. /n "); If (! Startservicectrldispatcher (dispatchtable) addtomessagelog (text ("startservicectrldispatcher failed. "); else addtomessagelog (text (" startservicectrldispatcher OK. ");} exit (0);} return 0;} // void servicestart (DWORD dwargc, lptstr * lpszargv ); // The initialization entry function void winapi service_main (DWORD dwargc, lptstr * lpszargv) {// register the Service Control Handler function sshstatushandle = registerservicectrlhandler (text (szservicename), Servic E_ctrl); // if the registration fails if (! Sshstatushandle) {goto cleanup; return;} // initialize the ssstatus. dwservicetype = service_win32_own_process; ssstatus. dwservicespecificexitcode = 0; // update the service status if (! Reportstatustoscmgr (service_start_pending, // service status, the service is starting. no_error, // exit code 3000) // wait time goto cleanup; // if the service status fails to be updated, turn to cleanup servicestart (dwargc, lpszargv); return; cleanup: // update the service status to service_stopped and exit. If (sshstatushandle) (void) reportstatustoscmgr (service_stopped, dwerr, 0);} void winapi service_ctrl (DWORD dwctrlcode) {// process control request code switch (dwctrlcode) {// update the service status to servicde_stop_pending before stopping the service. Case service_control_stop: invoke (service_stop_pending, no_error, 500); servicestop (); // return is implemented by a specific service program; // stop the service case service_control_pause: reportstatustoscmgr (service_stop_pending, no_error, 500); servicepause (); // ssstatus is implemented by a specific service program. dwcurrentstate = service_paused; return; // continue service case service_control_continue: reportstatustoscmgr (service_stop_pending, no_error, 500); servicecontinue (); // The ssstatus is implemented by a specific service program. dwcurrentstate = service_running; return; // update the service status case service_control_interrogate: break; // invalid control code default: break;} reportstatustoscmgr (ssstatus. dwcurrentstate, no_error, 0) ;}// install the void installservice () {SC _handle schservice; SC _handle schscmanager; tchar szpath [512]; // obtain the path of the program Disk File // a handle to the loaded module whose path is being requested. if this parameter is null, // get Modulefilename retrieves the path of the executable file of the current process. if (getmodulefilename (null, szpath, 512) = 0) {/* _ tprintf (text ("unable to install % s-% s/n "), text (szappname), getlasterror (); // @ 1 get the last error code returned by the call function */printf ("unable to install % s-% s/n", szappname, getlasterror (); return;} // open the service management database schscmanager = openscmanager (null, // if it is null, it refers to the local computer null, // default database SC _manager_all _ Access // requires all access permissions); If (schscmanager) {// register the service program schservice = createservice (schscmanager, // The service management database handle text (szservicename ), // service name text (szappname), // used to display the service_all_access identifier of the service, // response to all access requests service_win32_own_process, // service_deman_start of the service type, // service_error_normal of the Startup type, // error control type szpath, // service program disk file path null, // service does not belong to any group null, // No tag identifier null, // start the service or service group on which the service depends. Here, it is just an empty string null, // LocalSystem account nu Ll); If (schservice) {/* _ tprintf (text ("% s installed./N"), text (szappname); */printf ("the service created! \ N "); printf (" % s installed. /n ", szappname); closeservicehandle (schservice);} else {/* _ tprintf (text (" createservice failed-% s/n "), getlasterror ()); */printf ("createservice failed-% s/n", getlasterror ();} closeservicehandle (schscmanager);} else printf ("openscmanager failed-% s/n ", getlasterror (); // _ tprintf (text ("openscmanager failed-% s/n"), getlasterror ());} // stop and delete the installed Service Program void removeservice () {SC _handle schservice; SC _handle schscmanager; // open the service management database schscmanager = openscmanager (null, // null on the local computer, // The default database SC _manager_all_access // requires all access permissions); If (schscmanager) {// get the service program handle schservice = openservice (schscmanager, // service management database handle text (szservicename), // service name service_all_access // responds to all access requests); If (schservice) {// try to stop the service send a control code to the service; if (controlservice (schservice, // service program handle (obtained from opening the service above) service_control_stop, // stop Service Request Code & ssstatus // receives the final service status information) {/* _ tprintf (text ("Stopping % S. "), text (szappname); */printf (" Stopping % S. ", szappname); sleep (1000); // wait for the service to stop // while (queryservicestatus (schservice, & ssstatus) {If (service_stop_pending = ssstatus. dwcurrentstate) {// _ tprintf (text (". "); printf (". "); sleep (1000);} else break;} If (service_stopped = ssstatus. dwcurrentstate) printf ("/n % s stopped. /n ", szappname); // _ tprintf (text ("/n % s stopped. /n "), text (szappname); else printf ("/n % s failed to stopp. /n ", szappname); // _ tprintf (text ("/n % s failed to stopp. /n "), text (szappname);} // Delete the installed Service Program install if (deleteservice (schservice) printf (" % s removed. /n ", szappname); // _ tprintf (text (" % s removed. /n "), text (szappname); else // _ tprintf (text (" deleteservice failed-% S. /n "), getlasterror (); printf (" deleteservice failed-% S. /n ", getlasterror (); closeservicehandle (schservice);} else printf (" openservice failed-% s/n ", getlasterror ()); // _ tprintf (text ("openservice failed-% s/n"), getlasterror (); closeservicehandle (schscmanager );} else printf ("openscmanager failed-% s/n", getlasterror (); // _ tprintf (text ("openscmanager failed-% s/n "), getlasterror ();} void servicestop () {} void servicepause () {} void servicecontinue () {} void debugservice (INT argc, char ** argv) {printf ("debuging service... \ n ");} void addtomessagelog (lptstr lpszmsg) {}// void servicestart (DWORD dwargc, lptstr * lpszargv) // The initialization entry function {} bool reportstatustoscmgr (DWORD dwcurrentstate, DWORD dwwin32exitcode, DWORD dwwaithint) {return true ;}

Http://www.vckbase.com/http://www.vckbase.com/document/viewdoc? Http://edu.gamfe.com/tutor/d/12405.htmlhttp://blog.csdn.net/qpl007/article/details/143801 http://www.cnblogs.com/lartely/archive/2011/04/10/2011770.html id = 1474

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.