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

How to Launch and Manage Windows Executables with ::CreateProcess in C ?

Mary-Kate Olsen
Release: 2024-11-02 13:02:29
Original
379 people have browsed it

How to Launch and Manage Windows Executables with ::CreateProcess in C  ?

Calling ::CreateProcess to Launch and Manage Windows Executables in C

This article will demonstrate how to utilize the ::CreateProcess function in C to launch Windows executables, wait for their completion, and correctly handle their termination.

Launching an Executable

The ::CreateProcess function accepts several parameters, including the executable path and command line arguments. To launch an EXE, specify the path to the executable in the path parameter:

<code class="cpp">STARTUPINFO info = { sizeof(info) };
PROCESS_INFORMATION processInfo;

if (CreateProcess("C:\path\to\my.exe", NULL, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo)) {
  // Executable successfully launched
} else {
  // Handle launch failure
}</code>
Copy after login

Waiting for Completion

To wait for the executable to finish, call the WaitForSingleObject function with processInfo.hProcess as the handle to wait for:

<code class="cpp">WaitForSingleObject(processInfo.hProcess, INFINITE);</code>
Copy after login

This will block the current thread until the process exits.

Handling Process Termination

After the executable has finished, close the process and thread handles to properly release system resources:

<code class="cpp">CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);</code>
Copy after login

Sample Code

Putting it all together, the following code demonstrates how to launch an EXE, wait for its completion, and handle process termination:

<code class="cpp">STARTUPINFO info = { sizeof(info) };
PROCESS_INFORMATION processInfo;

if (CreateProcess("C:\path\to\my.exe", NULL, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo)) {
  WaitForSingleObject(processInfo.hProcess, INFINITE);
  CloseHandle(processInfo.hProcess);
  CloseHandle(processInfo.hThread);
}</code>
Copy after login

This code will launch the specified EXE, wait for it to finish, and then properly close all handles, ensuring proper cleanup and resource deallocation.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template