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

0

3 Answers 3

15

Portable way:

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

With embedded quotes/spaces:

 int retCode = system("prog.exe \"arg 1\" arg2 arg3");
Sign up to request clarification or add additional context in comments.

1 Comment

how do you handle parameters with spaces in them? (e.g. "arg 1", "arg 2")
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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.