The following is the source code of the service programs I understand under Win2000, you can create a service and you can start, stop and remove the service at any time. Use VC6 compilation, below is a introduction method.
You need to install the service, open the DOS window, then enter the program name plus -Install parameter, for example:
#SIMPLE_SERVICE -INSTALL
If you need to delete the service, in the DOS window, enter the program name plus the -emove parameter
#SIMPLE_SERVICE -REMOVE
You can also use tool sc.exe to delete the service, enter sc delete_service_08 in the DOS window.
If you want to start or stop the service, please start in Computer Management -> Services, the service name is _simple_service_08
/
The service program generates debugged log files, you need to include two files in Runtimelog.h and Runtimelog.cpp, http://www.9cbs.net/develop/read_article.asp?id=17477
The following procedure may be useful for the partners who have just gotting, "masters" will save the province, so as not to be stinking again (in the face of the Chinese like this, I have to learn a little).
The following is a complete source program, the file name is: WinMain.cpp, detailed instructions to be attached after I organized.
// ******************************************************** ******************************** *************** FileName : WinMain.cpp **************************************************************************************************************** *********************************************************** ***************** / / Minimum LINK contains: msvcrt.lib kernel32.lib user32.lib advapi32.lib shell32.lib #define Win32_LIAN_and_mean // Say no to mfc !! #define unicode
#include
#include "runtimelog.h" runtimelog log;
LPSTR MSGERR = NULL;
///// define for service
#define serviceName "_SIMPLE_SERVICE_08" #define strinstall text ("install") # Define strremove text ("remote")
Void WinAPI Service_ctrl (DWORD DWCTRLCODE); Void WinApi Service_main (DWORD DWARGC, LPTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTER * DIRE
Void WinMaincleanup (void);
SC_HANDLE SCHSERVICE = NULL, SCHSCMANAGER = NULL; Service_Status ssstatus; service_status_handle sshstatushandle = null; Handle Hservestopevent = NULL; //
// end of define for service
Char Temp [1024] = "TEMP77 IS BAD!";
void WinMainCleanup (void) {if (MsgErr) {LocalFree (MsgErr); MsgErr = NULL;} if (schService) CloseServiceHandle (schService); if (schSCManager) CloseServiceHandle (schSCManager); log.last (true); // log. ShowResult (1500); //log.write ("After ShowResult! "); return;} ///////
// name: WinMain () // ------ --------------------------- Int Winapi WinMain (Hinstance Hinstance, Hinstance Hprevinstance, LPSTR LPCMDLINE, INT NCMDSHOW) {
Log.nobuff = true; log.write (ServiceName "WinMain Start");
// determines whether WinNT OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if (GetVersionEx (& osvi)) {if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) log.write ( "WinNT system available!"); Else {log .write ( "non WinNT system, the clearance exit"); WinMainCleanup (); return 1;}} else {log.write ( "Failed to GetVersionEx."); FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError ( ), NULL, (LPSTR) & msgerr, 0, null; log.write (Msger); WinMaincleanup (); return 1;} // end of if (getversionex (& osvi))
// Filled service entry table service_table_entry dispatchtable [] = {{text (service_mainam), lpservice_main_function (service_main)}, {null, null}};
// obtain command line to observe LPSTR cmdline = getcommandlinea (); log.write ("Commandline By Following."); Log.write (""); log.write (""); // get the current directory to observe GetCurrentDirectorya 1024, TEMP); Log.Write ("CurrentDirectory By Following."); Log.write (temp); log.write ("");
// Get the file name of the module to observe GetModuleFileNamea (NULL, TEMP, SIZEOF (TEMP)); log.write ("Current Module FileName By Following."); Log.write (""); log.write
For (INT I1 = LSTRLENA (TEMP); I1> 0; I1 -) {IF (Temp [I1] == '//') {TEMP [I1] = 0; Break;}} setCurrentDirectorya (TEMP); log .write ("Reset the location of the current directory");
// Reissue the current directory to observe GetCurrentDirectorya (1024, Temp); log.write ("currentdirectory by following."); Log.write (""); log.write ("");
// Separate the parameter group to access int Numargscount = NULL; LPWSTR * LPARGV = CommandLineToargvw (getcommandlinew (), & numargscount); log.numberwrite ("Numargscount =", (DWORD) Numargscount);
INT i = 0; for (i = 0; i // Judgment parameter operation if (NumargScount> 1) // {IF only when the number of parameters is greater than 1, {IF ((lpargv [1] [0] == (Word) '/') || (lpargv [1] [ 0] == (Word) '-')) {log.write); if (! _ Wcsicmp (strinstall, lpargv [1] 1)) {log.write ("Install Specify)); // cmdinstalService (); IF (! getModuleFileNamea (NULL, TEMP, SIZEOF (TEMP))) {log.write ("getMouduleFileName Failed."); WinMaincleanup (); return 0;} // SC_HANDLE schService = NULL, schSCManager = NULL; schSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); if (schSCManager) {log.write ( "OpenSCManager success"); // Open was successfully created schService = CreateServiceA (schSCManager, ServiceName , ServiceName "(Dsp)", SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, temp, NULL, NULL, NULL, NULL, NULL); if (schService) {log.write ( "CreateService" ServiceName "success"); CloseServiceHandle (schService ); schService = NULL;} else {log.write ( "CreateService" ServiceName "failed."); FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), NULL, (LPSTR) & MsgErr, 0, NULL); log .write (msger); winmaincleanup (); return 0;} CloseServiceHandle (SchscManager); Schscmanager = null;} else {log.write; winmaincleanup (); return 0;} Log.Write (""); log.write ("complete the service installation"); log.write ("" "); } Else if (! _ Wcsicmp (strremove, lpargv [1])) {log.write ("Remove Specify."); // cmdremoveService (); // SC_HANDLE schService = NULL, schSCManager = NULL; schSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); if (schSCManager) {log.write ( "OpenSCManager success"); // open succeeded before the next step schService = OpenServiceA (schSCManager , ServiceName, SERVICE_ALL_ACCESS); if (schService) {log.write ( "OpenService" ServiceName "success"); QueryServiceStatus (schService, & ssStatus); if (ssStatus.dwCurrentState == SERVICE_STOPPED) log.write ( "Service already Stopped." ); Else {// Try to Stop The Service Log.write ("try to stop the service"); if (ControlService (schService, SERVICE_CONTROL_STOP, & ssStatus)) {Sleep (50); while (QueryServiceStatus (schService, & ssStatus)) {if (ssStatus.dwCurrentState == SERVICE_STOP_PENDING) {Sleep (500); log.write ( "still stop Service ... ");} else break;} // end of while (QueryServiceStatus (Schservice, & SSstatus)} } // end of if (SSSTATUS.DWCURRENTSTATATE == Service_stopped) ELSE // If Service has been stopped, then delete the service IF (SSSTATUS.DWCURRENTSTATATE == Service_Stopped) {Sleep (1000); if ("successfully deleted" ServiceName "service"); else log .write ("Delete" ServiceName "failed); log.write (" "" "Failed to Stop Service."); CloseServiceHandle (SCHSERVICE); SCHSERVICE = NULL;} else {log.write ("OpenService" service "failed."); FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), NULL, (LPSTR) & MsgErr, 0, NULL); log.write (MsgErr); WinMainCleanup (); return 0;} CloseServiceHandle (schSCManager); schSCManager = NULL; } Else {log.write ("openscmanager failed."); WinMaincleanup (); return 0;} }} WinMaincleanup (); RETURN 0;} // end of if (Numargscount> 1) // When the number of parameters is greater than 1 Log.write ("" "); if (StartServiceCtrlDispatcher (dispatchTable)) log.write ( "StartServiceCtrlDispatcher Complete."); else {log.write ( "StartServiceCtrlDispatcher failed."); FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), NULL, (LPSTR) & Msgerr, 0, null; log.write (msgerr); WinMaincleanup (); // EXITPROCESS (0); log.last (true); Return NULL; } ///////VOID WinAPI Service_ctrl (DWORD DWCTRLCODE) {// Handle The Requested Control Code Log.write ("" "Go INTO Service_Ctrl Function); log.write (" "" ); int i2 = 0; switch (dwCtrlCode) {// Stop the Service case SERVICE_CONTROL_STOP: log.write ( "recive SERVICE_CONTROL_STOP"); ssStatus.dwCheckPoint = ssStatus.dwCheckPoint ; ssStatus.dwWin32ExitCode = NO_ERROR; ssStatus.dwCurrentState = SERVICE_STOP_PENDING; SetServiceStatus (SSHSTATUSHANDLE, & SSSTATUS); SetEvent (HSERVERSTopeVent); log.write ("The service status has been set to Service_Stop_pending, and set the synchronization object to an excitation state."); for (i2 = 0; i2 <12; i2 ) {QueryServiceStatus (schService, & ssStatus); if (ssStatus.dwCurrentState == SERVICE_STOP_PENDING) Sleep (200); else break;} ResetEvent (hServerStopEvent); if (ssStatus.dwCurrentState == SERVICE_STOPPED) {log.write ( "The Service is now stoped"); ssStatus.dwCheckPoint = 0; ssStatus.dwWin32ExitCode = NO_ERROR; ssStatus.dwCurrentState = SERVICE_STOP; SetServiceStatus (sshStatusHandle, & ssStatus);} else log.write ( "stoped Service . Failed "); return; break; case SERVICE_CONTROL_INTERROGATE: log.write (" recive SERVICE_CONTROL_INTERROGATE "); break; default: log.numberwrite (" recive CtrlCode = ", dwCtrlCode); break;} //ssStatus.dwCurrentState = SERVICE_STOP_PENDING; ssStatus.dwCheckPoint = ssStatus.dwCheckPoint ; ssStatus.dwWin32ExitCode = NO_ERROR; SetServiceStatus (sshStatusHandle, & ssStatus); Return;} //////// Void service_maincleanup (void) {log.write (""); log.write ("service_maincleanup!"); log.write ("" "); IF (Hservestopevent) {CloseHandle (HSERVERSTOPEVENT); HserveStopevent = NULL;} ssStatus.dwWin32ExitCode = 0; ssStatus.dwCurrentState = SERVICE_STOPPED; ssStatus.dwWaitHint = 1000; if (SetServiceStatus (sshStatusHandle, & ssStatus)) {log.write ( "SetServiceStatus to SERVICE_STOPPED success!");} else {log.write ( "SetServiceStatus to SERVICE_STOPPED failed ");! FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), NULL, (LPSTR) & MsgErr, 0, NULL); log.write (MsgErr);} //log.showResult(false); return;} void WINAPI service_main (DWORD dwArgc, LPTSTR * lpszArgv) {// Sign up for our Service control handler sshStatusHandle = RegisterServiceCtrlHandlerA (ServiceName, service_ctrl); if (sshStatusHandle!) {FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), NULL, (LPSTR) & msgerr, 0, null; log.write ("Failed to RegisterServiceCtrlhandler); service_maincleanup ();} Log.write ("" "" We now running in service_main); log.write ("Success to RegisterServiceCtrlhandler); HserveStopevent = CreateEvent (NULL, TRUE, FALSE, NULL); if (Hservestopevent) Log.write ("Created Synchronization Object"); Else Log.Write ("Create Synchronization Object Failed"); // The following is the code dword dwweit = null of the test synchronization signal; DWWAIT = WaitForsingleObject (Hservestopevent, 200); {if (dwwait == wait_timeout log.write); if (dwwait == Wait_Object_0) log.write ("Synchronization object is triggered");} // continue to report progress to start now Service ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; ssStatus.dwServiceSpecificExitCode = 0; ssStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; // | SERVICE_ACCEPT_PAUSE_CONTINUE; ssStatus.dwWaitHint = 1000; // set after running ssStatus.dwCheckPoint = 0; ssStatus .dwwin32exitcode = no_error; ssstatus.dwcurrentState = service_start_pend; if (SetServiceStatus (sshStatusHandle, & ssStatus)) {log.write ( "SetServiceStatus success!");} else {log.write ( "SetServiceStatus failed!"); FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), NULL , (LPSTR) & msgerr, 0, null; log.write (msger);} SLEEP (300); // Set SSSTATUS.DWCHECKPOINT ; log.Numberwrite ("progress =", ssstatus.dwcheckpoint; ssstatus.dwwin32exitcode = no_error; ssstatus.dwcurrentState = service_start_pend; SetServiceStatus (SSHSTATUSHANDLE, & SSSTATUS); For (int I1 = 0; I1 <6; i1 ) { Sleep (300); // set after serving //ssStatus.dwCheckPoint ; ssStatus.dwCheckPoint = ssStatus.dwCheckPoint 20; log.numberwrite ( "Progress =", ssStatus.dwCheckPoint); ssStatus.dwWin32ExitCode = NO_ERROR; ssStatus.dwCurrentState = Service_start_pending; setServiceStatus (SSHSTATUSHANDLE, & SSSSTATUS); } Sleep (200); // set after running ssStatus.dwCheckPoint = 0; ssStatus.dwWin32ExitCode = NO_ERROR; ssStatus.dwCurrentState = SERVICE_RUNNING; SetServiceStatus (sshStatusHandle, & ssStatus); log.write ( "SetServiceStatus to SERVICE_RUNNING!"); SLEEP (500); // put into code run service While (True) {dwwait = WaitForsingleObject (HSERVERSTOPEVENT, 1); {// if (dwwait == wait_timeout) log.write ("Waiting for synchronous signal timeout"); if (dwwait == Wait_Object_0) {log.write ("synchronization Objects are triggered "); resetEvent (HSERVERSTOPEVENT); Break;}} // log.write (" Doing Something ... "); SLEEP (100); // Suppose you want to run 100 millisecond operations // } // end of while (true) Service_maincleanup (); Return;}