Well, this is windows-specific, but here's the code I use when I need to do something similar. It spawns a process, waits for the process to terminate, and then returns the error code.
Note: this will cause your program to pause (indefinitely) until the child process returns. That is by design, but this may not be applicable for your needs. In my case it was fine; this was only called once, on program startup, the program's only GUI was a taskbar icon, and the process it spawned would always return within a few seconds, success or fail.
Code:
long SpawnProcess(std::wstring commandLine){
// Because the command line can't be a const string, make a copy of the string:
wchar_t * cmdLine = new wchar_t[commandLine.length()+1];
wcscpy(cmdLine,commandLine.c_str());
// Startup options for the new process
STARTUPINFOW si;
::ZeroMemory(&si,sizeof(si)); // Zero it all
si.cb = sizeof(si); // Let it know its size
// We don't really need to use any of the rest of the structure (which is things like
// window size, position, and other crap) so we can leave it all zeroed.
PROCESS_INFORMATION pi; // This will be filled in by CreateProcess
if (!::CreateProcessW(
NULL, // Application name (we put it in the command line so this can be NULL)
cmdLine,
NULL, // Security attributes if we want the process handle inheritable
NULL, // Security attributes if we want the thread handle inheritable
FALSE, // Our child process doesn't need any of our handles.
CREATE_NO_WINDOW, // Flags
NULL, // Environment Variables
NULL, // Current directory (NULL = the current directory of our program)
&si, // That startup info struct.
&pi // Process information
)){
delete[] cmdLine;
throw std::runtime_error("SpawnProcess: Create process failed.");
}
delete[] cmdLine;
// OK we made the program run. Let's wait for it to stop.
::WaitForSingleObject(pi.hProcess,INFINITE); // You may want a timeout here...
// Let's check the error code
long exitCode;
if (!::GetExitCodeProcess(pi.hProcess,(unsigned long *)&exitCode))
throw std::runtime_error("SpawnProcess: Retrieving process exit code failed.");
// Close the handles after we get the exit code
::CloseHandle(pi.hThread);
::CloseHandle(pi.hProcess);
return exitCode;
}