1

在 C++ 中,是否可以调用/运行另一个可执行文件并从该可执行文件接收返回值(例如 1 或 0 表示其他 exe 是否成功执行其操作)?

为简单起见,举个例子,如果我有一个名为 filelist.exe 的外部控制台 .exe,它列出了目录中的所有文件并将这些文件名写入文件。如果 filelist.exe 成功运行,则 main 返回 1,否则返回 0。

如果我要使用以下代码运行 filelist.exe,有​​没有办法从 filelist.exe 获取返回值?

int res = system("filelist.exe dirPath");

// Maybe the windows function CreateProcess() allows filelist.exe to return
// a value to the currently running application?
CreateProcess();

注意我不打算创建一个简单的控制台应用程序来列出目录中的文件我正在尝试创建一个控制台应用程序来检查用户是否有一个有效版本的第 3 方程序,如果他们有一个有效的版本和返回 1如果没有,则为 0。

4

2 回答 2

3

一个示例如下所示:

    res = CreateProcess(
        NULL,                //  pointer to name of executable module  
        commandLine,         //  pointer to command line string  
        NULL,                //  pointer to process security attributes  
        NULL,                //  pointer to thread security attributes  
        TRUE,                //  handle inheritance flag  
        0,                   //  creation flags  
        NULL,                //  pointer to new environment block  
        NULL,                //  pointer to current directory name  
        &StartupInfo,        //  pointer to STARTUPINFO  
        &ProcessInfo         //  pointer to PROCESS_INFORMATION  
      );

    if (!res)
      //  process creation failed!
      {
        showError(commandLine);
        retVal = 1;
      }
    else if (waitForCompletion)
      {
        res = WaitForSingleObject(
                ProcessInfo.hProcess,  
                INFINITE      // time-out interval in milliseconds  
                );  
        GetExitCodeProcess(ProcessInfo.hProcess, &exitCode);

        retVal = (int)exitCode;
      }

Process使用 . 从对象中检索外部进程的返回码GetExitProcess()。这假设您的代码在启动该过程后正在等待完成。

于 2013-01-13T20:39:24.263 回答
2

是的,您将启动另一个进程并运行可执行文件。您要问的是所谓的进程间通信,通常通过像您这样的场景中的信号管道来实现。

于 2013-01-12T04:41:31.660 回答