C CreateProcess exec system command

  • 8 months ago
Comment

ChatGPT
1 / 1

In C, you can use the CreateProcess function to execute an external system command. This function is available in the Windows API. Here's how you can use it:

c
#include <stdio.h>
#include <windows.h>

int main() {
// Command to execute
const char* command = "notepad.exe"; // Replace with your command

// CreateProcess 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 to specify the command)
(LPSTR)command, // Command to execute
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 finish (optional)
WaitForSingleObject(pi.hProcess, INFINITE);

// Close process and thread handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else {
printf("CreateProcess failed (%d).\n", GetLastError());
return 1;
}

return 0;
}

Replace "notepad.exe" with the full path to the executable you want to run or the command you want to execute. The CreateProcess function creates a new process and waits for it to finish before proceeding. If you don't want to wait, you can remove the WaitForSingleObject line.

Make sure to include the appropriate header files (stdio.h and windows.h) and compile the code using a C compiler compatible with the Windows API (like MinGW or Visual Studio).

Keep in mind that using CreateProcess directly requires careful handling of arguments and paths, especially if your command contains spaces or special characters. If you need to pass arguments to the command, you might want to wrap them properly and adjust the command string accordingly.