windows编程点滴(二)之Windows结束一个进程
Windows中结束进程的方法
(1)主线程的入口函数返回。
(2)进程中一个线程调用了ExitProcess 函数。
(3)此进程中的所有线程都结束了。
(4)其他进程中的一个线程调用了TerminateProcess 函数
结束当前进程调用ExitProcess(UINT uExitcode);
终止其他进程TerminateProcess(HANDLE hProcess , UINT uExitCode);
一旦进程终止,就会有下列事件发生:
(1)所有被这个进程创建或打开的对象句柄就会关闭。
(2)此进程内的所有线程将终止执行。
( 3 ) 进程内核对象变成受信状态, 所有等待在此对象上的线程开始运行, 即
WaitForSingleObject 函数返回(详见3.1 节)。
(4)系统将进程对象中退出代码的值由STILL_ACTIVE 改为指定的退出码。
获取线程句柄
HANDLE OpenProcess(DWORD dwDesiredAccess , BOOL bInheritHandle , DWROD dwProcessId)
dwDesiredAccess
Specifies the access to the process object. For operating systems that support security checking, this access is checked against any security descriptor for the target process. Any combination of the following access flags can be specified in addition to the STANDARD_RIGHTS_REQUIRED access flags:
Access |
Description |
PROCESS_ALL_ACCESS |
Specifies all possible access flags for the process object. |
PROCESS_CREATE_PROCESS |
Used internally. |
PROCESS_CREATE_THREAD |
Enables using the process handle in the CreateRemoteThread function to create a thread in the process. |
PROCESS_DUP_HANDLE |
Enables using the process handle as either the source or target process in the DuplicateHandle function to duplicate a handle. |
PROCESS_QUERY_INFORMATION |
Enables using the process handle in the GetExitCodeProcess and GetPriorityClass functions to read information from the process object. |
PROCESS_SET_INFORMATION |
Enables using the process handle in the SetPriorityClass function to set the priority class of the process. |
PROCESS_TERMINATE |
Enables using the process handle in the TerminateProcess function to terminate the process. |
PROCESS_VM_OPERATION |
Enables using the process handle in the VirtualProtectEx and WriteProcessMemory functions to modify the virtual memory of the process. |
PROCESS_VM_READ |
Enables using the process handle in the ReadProcessMemory function to read from the virtual memory of the process. |
PROCESS_VM_WRITE |
Enables using the process handle in the WriteProcessMemory function to write to the virtual memory of the process. |
SYNCHRONIZE |
Windows NT:Enables using the process handle in any of the wait functions to wait for the process to terminate. |
bInheritHandle
Specifies whether the returned handle can be inherited by a new process created by the current process. If TRUE, the handle is inheritable.
dwProcessId
Specifies the process identifier of the process to open.
#include <windows.h>
#include <stdio.h>
//#include <winbase.h>
BOOL TernimateProcessById(DWORD dwProcessId){
BOOL bRet=FALSE;
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,dwProcessId);
if (hProcess != NULL)
{
bRet = TerminateProcess(hProcess,0);
}
CloseHandle(hProcess);
return bRet;
}
int main(int argc , char *argv[]){
BOOL bRet = TernimateProcessById(3092);
if (!bRet)
{
printf("关闭进程出错\n");
}else{
printf("关闭进程成功\n");
}
return 0;
}