Windows Process Control

Source: Internet
Author: User

In Windows systems, applications are present in memory as processes. When running a program, the operating system loads the program into memory and allocates the resources required to run the program, creating the main thread for the process.

The system also provides a task manager that we can use. The interface for the management process is as follows:


There is no need to explain what is included in the content at a glance. Go directly to the common API.

1. creation of processes

UINT WinExec (  LPCSTR lpcmdline,//points to an executable file  UINT ucmdshow//The window state after the program runs/*sw_show: Indicates that the window is displayed after the program is run Sw_hide: Indicates that the window is hidden after the program is run */);

BOOL CreateProcess (  lpctstr lpapplicationname,//Specifies the name of the executable file  LPTSTR lpcommandline,//Specifies the command-line arguments  to pass to the new process Lpsecurity_attributes lpprocessattributes,//Process Security property, typically null, represents the default security attribute  lpsecurity_attributes lpthreadattributes ,///thread-safe property, typically null, indicates that the default security attribute  BOOL binherithandles,//Specifies whether an inheritable handle in the current process is inherited by a new process  DWORD dwcreationflags,// Specifies the priority of the new process and other creation flags  LPVOID lpenvironment,//Specifies the new process environment variable, typically specified as a null value  LPCTSTR lpcurrentdirectory,//Specifies the current directory used by the new process  Lpstartupinfo lpstartupinfo,//points to the struct  that specifies the startup information for the new process Lpprocess_information lpprocessinformation//points to the struct that is used to return information about the new process and the main thread. );


2. the end of the process

BOOL terminateprocess (  HANDLE hprocess,//with the process handle of the end process  , the exit code of the UINT uexitcode//process, usually 0);

3. Enumeration of processes

Handlewinapi createtoolhelp32snapshot (  DWORD dwflags,//indicates the type of system snapshot to be established. /*th32cs_snapmodule: Specifying th32cs_snapprocess when enumerating DLLs in the process: specifying Th32cs_snapthread when enumerating processes in the system: specifying the */DWORD when enumerating threads in the system  th32processid//This parameter differs depending on the dwflags parameter. Null if the process or thread in the system is enumerated, or if the DLL loaded in the process is enumerated, the parameter is the process ID. );

BOOL WINAPI Process32First (  HANDLE hsnapshot,//This parameter is the snapshot handle returned by the above function  LPPROCESSENTRY32 lppe//Pointer to the struct, when using the struct body, The variable dwsize of the struct needs to be assigned. );

BOOL WINAPI process32next (  HANDLE hsnapshot,//as above, is the snapshot handle  LPPROCESSENTRY32 lppe//is still the same as above);

Returns True if the function takes the next process, otherwise returns error_no_more_files.


4. Suspension of the process

DWORD SuspendThread (  HANDLE hthread//to pause the handle of the thread);

The so-called pause process is the suspension of all threads in the process.

Get the thread handle:

HANDLE openthread (  DWORD dwdesiredaccess,//Open line Cheng gain access, for convenience can be set to thread_all_access  BOOL binherithandle,// Specifies whether the obtained handle can be inherited, typically set to False  DWORD dwthreadid//thread id);

Sometimes you have to leave the process in a paused state. For example, the virus has two running processes, which constantly detect each other, and when a virus process discovers that another virus process is over, it will start again with that end of the virus process. Because the virus process detects a high frequency of each other, it is difficult to end the two virus processes, and you need to pause both processes before ending them.


5. Recovery of processes

The DWORD resumethread (  HANDLE hthread//is the same as the parameter usage of the SuspendThread function);

With the previous API, we can do something about it. You can design a process management software yourself, implement the enumeration of processes in the system, enumerate the DLLs in the process, pause, resume and end of the process, etc. Yes, according to international practice, I have prepared my implementation code for the reference of the small partners.

The interface is roughly as follows:

Enumeration process void Cprocessmanagerdlg::showprocess () {//Empties list Box contents M_listprocess.deleteallitems ();//create process snapshot handle hsnap = CreateToolhelp32Snapshot (th32cs_snapprocess, 0), if (Hsnap = = Invalid_handle_value) {AfxMessageBox (_T ("Create TOOLHELP32 Snapshot Error ")); return;} PROCESSENTRY32 Pe32 = {0}; pe32.dwsize = sizeof (PROCESSENTRY32); BOOL BRet = Process32First (Hsnap, &pe32); int i = 0; CString str;//Loop gets each item in the process snapshot while (BRet) {M_listprocess.insertitem (I, pe32.szexefile); Str. Format (_t ("%d"), Pe32.th32processid), M_listprocess.setitemtext (i, 1, str); ++i;bret = Process32Next (Hsnap, &PE32) ;} CloseHandle (HSNAP);}

Gets the pidint of the selected process Cprocessmanagerdlg::getselectpid () {//selects the index of the process position Pos = m_ Listprocess.getfirstselecteditemposition (); int nselect = -1;while (Pos) {nselect = M_listprocess.getnextselecteditem ( Pos);} if ( -1 = = nselect) {AfxMessageBox ("Select the process to enumerate DLLs") (_t); return 0;} Gets the selected process Idchar Szprocessid[maxbyte] = {0};m_listprocess.getitemtext (nselect, 1, (LPTSTR) Szprocessid, maxbyte); CString Str;str. Format (_t ("%s"), Szprocessid);//afxmessagebox (str); int iRet = _ttoi (str); return iRet;}

Displays the Dllvoid cprocessmanagerdlg::onbnclickedshowmodule () {//Empty list Box Contents M_listmodule.deleteallitems () loaded in the corresponding process;         Gets the selected process ID number intnpid = getselectpid ();         CString s;         S.format (_t ("%d"), npid);          AfxMessageBox (s);         If the process ID is 0, return if (Npid = = 0) {return;         } MODULEENTRY32 Me32 = {0};          me32.dwsize = sizeof (MODULEENTRY32);         Create Module Snapshot Handlehsnap = CreateToolhelp32Snapshot (Th32cs_snapmodule, npid);                   if (Hsnap = = Invalid_handle_value) {AfxMessageBox (_t ("Create toolhelp32snapshot Error"));         Return         } Boolbret = Module32first (Hsnap, &me32);         inti = 0;          CSTRINGSTR;                   Loop gets each item in the module snapshot while (BRet) {M_listmodule.insertitem (I, me32.szmodule);                   M_listmodule.setitemtext (i, 1, me32.szexepath);                   ++i;BRet = Module32next (Hsnap, &me32); } closehandle (HSNAP);}

Ends the corresponding process void cprocessmanagerdlg::onbnclickedendprocess () {int npid = Getselectpid (); HANDLE hprocess = OpenProcess (process_all_access, FALSE, npid); if (hprocess = = NULL) {return;} BOOL BRet = terminateprocess (hprocess, 0), if (BRet = = TRUE) {AfxMessageBox (_t ("process ended successfully"));} CloseHandle (hprocess); return;}

Pauses the corresponding process void cprocessmanagerdlg::onbnclickedstopprocess () {int npid = -1;npid = Getselectpid (); if (npid = = 0) {return;} Create thread snapshot HANDLE hsnap = CreateToolhelp32Snapshot (Th32cs_snapthread, npid); if (Hsnap = = Invalid_handle_value) { AfxMessageBox (_t ("Create Toolhelp32 Snapshot Error"); return;} THREADENTRY32 Te32 = {0}; te32.dwsize = sizeof (THREADENTRY32); BOOL BRet = Thread32first (Hsnap, &te32);//loop to get each item in the thread snapshot while (BRet) {//Get the thread that belongs to the selection process if (Te32.th32ownerprocessid = = NPID) {//open thread handle hthread = Openthread (Thread_all_access,false, Te32.th32threadid);//Suspend thread SuspendThread (hthread); CloseHandle (hthread);} BRet = Thread32next (Hsnap, &te32);} CloseHandle (HSNAP);}

Recover the corresponding process void Cprocessmanagerdlg::onbnclickedresume () {int npid = -1;npid = Getselectpid (); if (npid = = 0) {return;} Create thread snapshot HANDLE hsnap = CreateToolhelp32Snapshot (Th32cs_snapthread, npid); if (Hsnap = = Invalid_handle_value) { AfxMessageBox (_t ("Create Toolhelp32 Snapshot Error"); return;} THREADENTRY32 Te32 = {0}; te32.dwsize = sizeof (THREADENTRY32); BOOL BRet = Thread32first (Hsnap, &te32);//loop to get each item in the thread snapshot while (BRet) {//Get the thread that belongs to the selection process if (Te32.th32ownerprocessid = = NPID) {//open thread handle hthread = Openthread (Thread_all_access,false, Te32.th32threadid);//Resume Thread resumethread (hthread); CloseHandle (hthread);} BRet = Thread32next (Hsnap, &te32);} CloseHandle (HSNAP);}

Open process void Cprocessmanagerdlg::onbnclickedopen () {addprocess process;process. DoModal (); AfxMessageBox (process.m_codelocation); AfxMessageBox (process.m_codename);//Determine if the input is complete if (process.m_CodeLocation.GetLength () > 0 &&process.m_ Codename.getlength () > 0) {process_information pi = {0}; Startupinfo si = {0};si.cb = sizeof (STARTUPINFO); CString file = process.m_codelocation + "\" + process.m_codename; BOOL BRet = CreateProcess (file, NULL, NULL, NULL, false,null, NULL, NULL, &SI, &PI); if (BRet = = FALSE) {Afxmessageb Ox (_t ("Create Process Error"); return;} Showprocess (); CloseHandle (Pi.hthread); CloseHandle (pi.hprocess); return;} Else{afxmessagebox (_t ("Please enter full content!")); return;}

Warm tip: Some operations may attempt to increase the system permissions of the process if it is not successful, possibly because the current process has insufficient permissions.



Windows Process Control

Related Article

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.