Compile your own windows background process program

Source: Internet
Author: User
There is a powerful service manager in Windows NT, which manages some background processes that implement important functions, such as ftp. HTTP. ras. network Message, etc. These background processes are called services. They can be loaded at system startup and run at a higher priority, it can be said that it is a device driver very close to the core of the system. windows 95 does not provide a service manager, instead it is a simple registration interface, which can be called a service under Windows 95 (but strictly speaking, there is no service under Windows 95). Similarly, through this registration interface, we can make our programs run first when the system starts, stop at the end of the system, and combine with the operating system to implement many unique functions. first, let's take a look at some relevant knowledge.

Introduction to process database (PDB)
In the core data structure of windows, there is an important process management structure called the process database, which is located in the public memory heap of Kernel32. You can use getcurrentprocessid (...) the pointer pointing to this structure is obtained. The following is the composition of some PDB, which is directly related to the service mark byte at the PDB offset of 21 H. Based on the pseudo code analysis, we can clearly see that the service process registered as Windows 95 or Windows 98 is only to set the mark byte in its corresponding PDB to 1.

Offset length description
========================================================== ====
+ 00 h DWORD type // Kernel32 object type
+ 04 h dword creference // reference count
+ 08 h DWORD un1 // unknown
+ 0ch DWORD psomeevent // point to k32obj_event pointer
+ 10 h DWORD terminationstatus // activity flag or return value
+ 14 h DWORD un2 // unknown
...
+ 21 h byte flags1 // service tag,
// "1" is a service process,
// "0" common process
...
+ 24 h dword ppsp // dos PSP pointer
...
========================================================== ====

Implementation Interface
(1) The simple service interface provided in Windows 95 is a 32-bit API: registerserviceprocess. Since you cannot get the exact explanation of this API in online help of VC ++, I have to perform Reverse Analysis on this API. The following is the pseudo code of this API in kernel32.dll of windows95. we can clearly see how window95 is implemented internally. In fact, the processing is very simple.

Bool registerserviceprocess (DWORD dwprocessid, DWORD dwtype)
{
Handle dwpid;
If (dwprocessid = NULL)
Dwpid = dwcurrentprocessid; // get global Kernel32 variable
Else
// Call some kernel functions
If (dwpid = checkpid (dwprocessid) = NULL)
Return false;
If (dwtype = 1)
{
* (Byte *) (dwpid + 0x21) | = 0x01;
Return true;
}
If (dwtype = 0)
{
* (Byte *) (dwpid + 0x21) & = 0xfe;
Return true;
}
Return false;
}
The following shows the original function:
Bool registerserviceprocess (DWORD dwpid, DWORD dwtype)
Parameter: dwpid: process ID. null indicates the current process.
Dwtype: rsp_simple_service is registered
Rsp_unregister_service cancels registration
Return Value: true: the call is successful.
False: Call failed

(2) In addition, in order to enable the service process to start after boot, the registry of Windows 95 provides the loading method: add your own Application Command Line in key "mycomputer/HKEY_LOCAL_MACHINE/software/Microsoft/Windows/CurrentVersion/runservices" to enable automatic loading upon startup. of course, if you do not have this key in the machine, you can create one by yourself.

Routine
---- The following is an implementation routine. All the code has been tested and can be conveniently added to your project file.
---- Header file:

// File: Service. h
// The head file of "service. cpp"
// Note: 1. You must use C ++ Compiler
// 2. The platform is Win32 (winnt & Win95)

# Ifndef _ service_h
# DEFINE _ service_h

//////////////////////////////////////// /// // Used for Win95 Service
// Micros
# Define rsp_simple_service 1
# Define rsp_unregister_service 0

// Function types for getprocaddress
# Define registerserviceprocess_profile (DWORD (_ stdcall *) (DWORD, DWORD ))

// Service fuctions in Win95
Bool w95serviceregister (DWORD dwtype );
Bool w95startservice (DWORD dwtype );

# Endif

CPP file:
// File: Service. cpp --- implement the service

# Include "service. H"
//////////////////////////////////////// /// // Used for Win95 Service
Register as a service Subroutine:
//////////////////////////////////////// ////////////////////////////////////////
/
// Define: bool w95serviceregister (DWORD dwtype)
// Parameters: dwtype --- flag to register or unregister the service
// Rsp_simple_service means register
// Rsp_unregister_service means unregister
// Return: true --- Call success; false --- Call failer

Bool w95serviceregister (DWORD dwtype)
{
// Function address defination
DWORD (_ stdcall * hookregisterserviceprocess)
(DWORD dwprocessid, DWORD dwtype );

// Get address of Function
Hookregisterserviceprocess = registerserviceprocess_profile
Getprocaddress
(Getmodulehandle ("Kernel32 "),
Text ("registerserviceprocess "));

// Register the Win95 Service
If (hookregisterserviceprocess (null, dwtype) = 0)
Return false;
Return true;
}

Add the Registry Program:

# Define SERVICE_NAME text ("service ")
// Define: bool w95startservice (DWORD dwtype)
// Parameters: dwtype --- flag to register or unregister the service
// Rsp_simple_service means register
// Rsp_unregister_service means unregister
// Return: true --- Call success; false --- Call failer

Bool w95startservice (DWORD dwtype)
{
// Local variables
Tchar lpszbuff [256];
Lptstr lpszstr = lpszbuff + 128;
Lptstr lpszname = lpszbuff;
Handle hkey = NULL;
DWORD dwstrcb = 0;
DWORD dwvaluetype = 0;

// Get service name currently
Lpszname = getcommandline ();
For (INT I = _ tcslen (lpszname)-1; I> = 0; I --)
{
If (lpszname [I]! = '"') & (Lpszname [I]! = ''))
Break;
Else if (lpszname [I] = '"')
Lpszname [I] = '/0 ';
}
If (lpszname [0] = '"')
Lpszname = lpszname + 1;

// Registe as start up service
If (regopenkeyex (HKEY_LOCAL_MACHINE,
Text ("software // Microsoft // windows // CurrentVersion // runservices "),
0,
Key_query_value | key_set_value,
& Hkey )! = Error_success)
{
If (regcreatekey (HKEY_LOCAL_MACHINE,
Text ("software // Microsoft // windows // CurrentVersion // runservices "),
& Hkey )! = Error_success)
{
// Debugout ("regcreatekey () error! ");
Return false;
}
}

Dwvaluetype = REG_SZ;
Dwstrcb = 128;

// Take value
If (regqueryvalueex (hkey,
SERVICE_NAME,
0,
& Dwvaluetype,
(Lpbyte) lpszstr,
& Dwstrcb) = error_success)

{
// Find this key value
If (_ tcscmp (lpszstr, lpszname) = 0)
{
// Remove the service
If (dwtype = rsp_unregister_service)
{
If (regdeletevalue (hkey, SERVICE_NAME) = error_success)
{
Regclosekey (hkey );
Return true;
}
Regclosekey (hkey );
Return false;
}
// Already exist service
If (dwtype = rsp_simple_service)
{
// Debugout ("already registed! ");
Regclosekey (hkey );
Return true;
}
}
// Not find it
} // No this value

// Unregiste return
If (dwtype = rsp_unregister_service)
{
Regclosekey (hkey );
Return true;
}

// No this value then create it
If (dwtype = rsp_simple_service)
{
Dwstrcb = 128;

// Set Value
If (regsetvalueex (hkey,
SERVICE_NAME,
0,
REG_SZ,
(Const byte *) lpszname,
Dwstrcb )! = Error_success)
{
// Debugout ("regsetvalueex () error! ");
Regclosekey (hkey );

Return false;
}
Regclosekey (hkey );
Return true;
}

// Unknow type
Regclosekey (hkey );
Return false;
}

Main Program:
// Winmain function is the entry of the this program
Int apientry winmain (hinstance,
Hinstance hprevinstance,
Lpstr lpcmdline,
Int ncmdshow)
{
If (w95serviceregister (rsp_simple_service ))
{
W95startservice (rsp_simple_service );
}

MessageBox (null, "Sample Service", "service", mb_ OK );
Unreferenced_parameter (hinstance );
Unreferenced_parameter (lpcmdline );
Unreferenced_parameter (ncmdshow );
Unreferenced_parameter (hprevinstance );
Return 0;
}

Run this program. After MessageBox pops up, It exits from windows to log on. You will see that MessageBox remains open until it is responded or the system shuts down.

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.