Home >Backend Development >C++ >How to Launch and Control External Executables with ::CreateProcess in C ?

How to Launch and Control External Executables with ::CreateProcess in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 08:17:03951browse

How to Launch and Control External Executables with ::CreateProcess in C  ?

Launching Windows Executables with ::CreateProcess in C

When working with Windows in C , it's necessary to understand how to effectively launch and control external executables. One crucial function for this purpose is ::CreateProcess.

Example: Launching and Interacting with Executables

Let's explore an example that covers the key requirements:

  • Launching an EXE file
  • Monitoring its execution
  • Properly closing handles after completion

Consider the following code snippet:

<code class="c++">STARTUPINFO info = { sizeof(info) };
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
    WaitForSingleObject(processInfo.hProcess, INFINITE);
    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);
}</code>

This code demonstrates how to:

  1. Launch an executable defined by path and potential command line arguments in cmd.
  2. Obtain information about the created process and its main thread using processInfo.
  3. Wait indefinitely for the process to complete using WaitForSingleObject.
  4. Close the process and thread handles using CloseHandle to ensure proper cleanup.

By following this approach, you can effectively create and manage subprocesses in your C applications.

The above is the detailed content of How to Launch and Control External Executables with ::CreateProcess in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn