how to terminate a process created by CreateProcess()?

digvijay picture digvijay · Feb 24, 2012 · Viewed 27.4k times · Source

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.

Answer

HardCoder picture HardCoder · Feb 24, 2012

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.