0

using delphi XE I am trying to execute an exe file multiple times with different parameters but i will need to close/restart each one separately for various reasons.

so i thought if i start that example.exe and get its pid
i will be able to kill it later using that unique pid value.

see if i simply execute the example.exe THEN try to get the PID of that process using process name or the process file path it will end up giving me wrong result because there are like 4 processes with that name.

any suggestions or ideas ? my question might seem similar to some others but i need to return the pid value so keep that in mind

Someone
  • 401
  • 3
  • 5
  • 16
  • 1
    Assuming you are launching the EXE with CreateProcess, you could simply keep the handle to the process, that would be more reliable than looking for a PID. – Ken Bourassa May 17 '17 at 14:55

2 Answers2

4

Use the Win32 API CreateProcess() function. It outputs a PROCESS_INFORMATION struct that contains the IDs and handles of the launched process and its main thread. You can use the process handle to wait for the process to exit.

To terminate the process, you can pass the process handle to TerminateProcess().

Or, you can be more civil and:

And/Or:

  • post a WM_QUIT message to the main thread.

If that does not work, then use TerminateProcess() as a last resort.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
3

Look into using CreateProcess. There are multiple examples on StackOverflow including: Hide process window with 'CreateProcess'

If the call is successful, you will have the handle of the Process in the TProcessInformation parameter which you pass into CreateProcess.

Community
  • 1
  • 1
Darian Miller
  • 7,808
  • 3
  • 43
  • 62
  • Use GetProcessId on the handle if you still need a PId. – Sertac Akyuz May 17 '17 at 15:07
  • `GetProcessId` would be over kill. Just remember the PID rather than the handle. `CreateProcess` yields that. – David Heffernan May 17 '17 at 15:11
  • @SertacAkyuz That is not necessary, `CreateProcess()` also returns the PID of the launched process (as well as the ID and handle of the process's main thread). See the [`PROCESS_INFORMATION`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684873.aspx) structure. – Remy Lebeau May 17 '17 at 15:12