如何终止由 CreateProcess() 创建的进程?

2022-01-12 00:00:00 winapi visual-c++ c++ mfc createprocess

我使用 CreateProcess() 创建了一个进程.这是代码:

STARTUPINFO si = {0};PROCESS_INFORMATION pi = {0};结果 = CreateProcess("C:\AP\DatabaseBase\dbntsrv.exe", NULL, NULL, NULL, FALSE, 0, NULL, "C:\ADP\SQLBase", &si, &pi)

如何获取这个特定进程的 Handle 和 processId?并最终用它来关闭这个进程?
谢谢.

解决方案

在结构体 pi 中你得到:

typedef struct _PROCESS_INFORMATION {处理 h 进程;处理 hThread;DWORD dwProcessId;DWORD dwThreadId;} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;

第一个参数是进程的句柄.

您可以使用该句柄结束过程:

BOOL WINAPI TerminateProcess(__在 HANDLE hProcess 中,__in UINT uExitCode);

<块引用>

hProcess [in]
要终止的进程的句柄.

句柄必须具有 PROCESS_TERMINATE 访问权限.有关详细信息,请参阅进程安全性和访问权限.

uExitCode [in]
由于此调用,进程和线程要使用的退出代码终止.使用 GetExitCodeProcess 函数检索进程的退出值.使用 GetExitCodeThread 函数检索线程的退出值.

I have created a process using CreateProcess(). This is the code:

STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
result = CreateProcess("C:\AP\DatabaseBase\dbntsrv.exe", NULL, NULL, NULL, FALSE, 0, NULL, "C:\ADP\SQLBase", &si, &pi)

How can I get the Handle and processId of this specific process? And eventually use it to close this process?
Thank You.

解决方案

In the struct pi you get:

typedef struct _PROCESS_INFORMATION {
    HANDLE hProcess;
    HANDLE hThread;
    DWORD  dwProcessId;
    DWORD  dwThreadId;
} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;

The first parameter is the handle to the process.

You can use that handle to end the process:

BOOL WINAPI TerminateProcess(
    __in  HANDLE hProcess,
    __in  UINT uExitCode
);

hProcess [in]
A handle to the process to be terminated.

The handle must have the PROCESS_TERMINATE access right. For more information, see Process Security and Access Rights.

uExitCode [in]
The exit code to be used by the process and threads terminated as a result of this call. Use the GetExitCodeProcess function to retrieve a process's exit value. Use the GetExitCodeThread function to retrieve a thread's exit value.

相关文章