Browse - Programming Tips - win32: run a command and wait for the result

Date: 2019jun26
OS: Windows
Language: C/C++
Keywords: spawn, CreateProcess

Q.  win32: run a command and wait for the result

A.  Use one of the _spawn() family of functions.

#incude <stdio.h> #incude <process.h> // Example: Run the 'sc' command to get the status of the 'winmgmt' service LPCSTR szExe = "c:/windows/system32/sc.exe"; LPSTR args[] = { "sc", "query", "winmgmt", NULL }; const int result = _spawnv(_P_WAIT, szExe, args); printf("exit code=%d\n", result); // By convention exit code of zero means success but it // will depend on the the command you're running. if (result == 0) { printf("Worked\n"); } else { printf("Didn't work\n"); }
On the command line this is:
sc query winmgmt
Notice we pass in arg[0] as the name of the command that is being run. This is what you expect in main() of a C/C++ program.