gpt4 book ai didi

c++ - CPP 运行外部程序,等待它完成并返回 retcode

转载 作者:行者123 更新时间:2023-11-28 03:05:48 25 4
gpt4 key购买 nike

好的,作为我的 Lib 的一部分,我需要一个“Worker”应用程序来运行外部程序。通常我会调用:

system("");

但这一次需要的是:

  • 该程序的返回码
  • 应用程序在执行的程序运行时工作

所以伪代码在完美的实现中看起来像这样:

CTask::Run()
{
m_iReturnCode = -1;

ExecuteTask(m_strBinaryName);

while(Task_Executing)
{
HeartBeat();
}

return m_iReturnCode;
}

澄清一下,我在 Unix 平台上运行它。

我在这里有什么选择,popen/fork?任何人都有一个好的解决方案已经在运行并且可以对此有所了解吗?

感谢您对此的任何投入。

最佳答案

我正在使用 linux 系统,用于线程的 boost 和用于执行命令并获取其结果的管道(如果您不知道 boost,您当然应该看看它)。

我在 stackoverflow 上找到了使用管道的提示,但很抱歉,我不再知道确切的问题了。

我不添加外线程代码。只需在它自己的线程中启动方法 execute

std::string execute()
{
std::string result;

// DO NOT INTERRUPT THREAD WHILE READING FROM PIPE
boost::this_thread::disable_interruption di;

// add echo of exit code to command to get the exit code
std::string command = mp_command + "; echo $?";

// open pipe, execute command and read input from pipe
FILE* pipe = popen(command.c_str(), "r");
if (pipe)
{
char buffer[128];
while (!feof(pipe))
{
if (fgets(buffer, 128, pipe) != NULL)
{
std::string currBuffer(buffer);
result += currBuffer;
}
}
}
else
{
mp_isValid = false;
}

// sleeping busy wait for the pipe to close
while (pclose(pipe) == -1)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
}

return result;
}

关于c++ - CPP 运行外部程序,等待它完成并返回 retcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19767429/

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