12

How do you run an executable with parameters passed on it from a C++ program and how do you get the return value from it?

Something like this: c:\myprogram.exe -v

3 Answers3

15

Portable way:

 int retCode = system("prog.exe arg1 arg2 arg3");

With embedded quotes/spaces:

 int retCode = system("prog.exe \"arg 1\" arg2 arg3");
Chris K
  • 11,996
  • 7
  • 37
  • 65
5

On Windows, if you want a bit more control over the process, you can use CreateProcess to spawn the process, WaitForSingleObject to wait for it to exit, and GetExitCodeProcess to get the return code.

This technique allows you to control the child process's input and output, its environment, and a few other bits and pieces about how it runs.

Martin
  • 3,703
  • 2
  • 21
  • 43
0

Issue
How do you run an executable with parameters passed on it from a C++ program?
Solution
Use ShellExecuteEx and SHELLEXECUTEINFO

Issue
How do you get the return value from it?
Solution
Use GetExitCodeProcess and exitCode

Essential things to know
If you want to wait until process ,which is handling by external exe, is finished then need to use WaitForSingleObject

bool ClassName::ExecuteExternalExeFileNGetReturnValue(Parameter ...)
{
    DWORD exitCode = 0;
    SHELLEXECUTEINFO ShExecInfo = {0};
    ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
    ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
    ShExecInfo.hwnd = NULL;
    ShExecInfo.lpVerb = _T("open");
    ShExecInfo.lpFile = _T("XXX.exe");        
    ShExecInfo.lpParameters = strParameter.c_str();   
    ShExecInfo.lpDirectory = strEXEPath.c_str();
    ShExecInfo.nShow = SW_SHOW;
    ShExecInfo.hInstApp = NULL; 
    ShellExecuteEx(&ShExecInfo);

    if(WaitForSingleObject(ShExecInfo.hProcess,INFINITE) == 0){             
        GetExitCodeProcess(ShExecInfo.hProcess, &exitCode);
        if(exitCode != 0){
            return false;
        }else{
            return true;
        }
    }else{
        return false;
    }
}

Reference to know more detail

Community
  • 1
  • 1
Frank Myat Thu
  • 4,448
  • 9
  • 67
  • 113