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.
piProcessInfo.hProcess
is the handle of the process.After that (
time_in_ms
) the process will be closed.In the struct
pi
you get:The first parameter is the handle to the process.
You can use that handle to end the process:
A handle to the process is returned in the PROCESS_INFORMATION structure,
pi
variable.The TerminateProcess() function can be used to terminate the process. However, you should consider why you need to kill the process and why a graceful shutdown is not possible.
Note you need to set the
cb
member ofsi
before callingCreateProcess()
:EDIT:
To suppress the console window specify
CREATE_NO_WINDOW
, as the creation flag (the sixth argument) in theCreateProcess()
call.EDIT (2):
To suppress the window try setting following members of STARTUPINFO structure prior to calling
CreateProcess()
:This is explained thoroughly in MSDN:
If result is non-zero (which means that it succeeded) you will get the handle and processid in the
pi
structure.In order to kill the process you can use TerminateProcess
Closing the process cleanly
To close the process cleanly, you should send a close signal first:
How To Terminate an Application "Cleanly" in Win32.
See this answer for code.
Terminating the process
If you don't care about clean shutdown, you can use
TerminateProcess()
. However, it is important to note thatTerminateProcess()
is asynchronous; it initiates termination and returns immediately. If you need to be sure the process has terminated, call theWaitForSingleObject()
function with a handle to the process.Not closing, just wait until finished
If the process will finish on its own, instead of terminating you can wait until it has finished.