- 1 year ago
How to use exec() on Windows with MSVC++?
To use the exec()
function on Windows with MSVC++ (Microsoft Visual C++), you can utilize the CreateProcess()
function, which is a Windows API for creating a new process. Here's an example of how you can achieve this:
cpp#include <Windows.h>
#include <iostream>
int main() {
const char* command = "notepad.exe"; // Command to be executed
// Create process parameters
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// Create the process
if (CreateProcess(NULL, // Module name (use NULL for the current executable)
const_cast<LPSTR>(command), // Command to be executed
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi)) // Pointer to PROCESS_INFORMATION structure
{
// Wait for the process to complete (optional)
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else {
std::cerr << "Failed to execute command: " << command << std::endl;
return 1;
}
return 0;
}
In this example, we execute the notepad.exe
command using CreateProcess()
. You can replace "notepad.exe"
with the desired command or the path to an executable file.
Make sure to include the necessary header files, <Windows.h>
and <iostream>
. Also, handle any error conditions appropriately, such as when CreateProcess()
fails.
Please note that the exec()
function is not a standard C++ function and is commonly found in Unix-like systems. On Windows, you typically use the Windows API functions like CreateProcess()
for similar functionality.