gpt4 book ai didi

c++ - 运行外部 .exe 并从中接收返回值

转载 作者:行者123 更新时间:2023-11-27 23:19:32 26 4
gpt4 key购买 nike

在 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();

请注意,我不打算创建一个简单的控制台应用程序来列出目录中的文件有效版本,否则为 0。

最佳答案

示例如下:

    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;
}

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

关于c++ - 运行外部 .exe 并从中接收返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14290291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com