c++ - 在 Tiny Process Library 中阻塞直到进程结束

标签 c++ delay external-process

我正在编写接受命令行参数的 C++ 代码,将其传递给 echo 等系统命令并打印响应。为了与外部进程通信,我使用 tiny-process-library 。我当前代码的问题是它必须等待配置的 5 秒 延迟。

当我尝试将代码移动到 Process 对象中时,出现以下编译错误。

Test.cpp: In lambda function:
Test.cpp:29:3: error: ‘p_Request’ is not captured

有人可以帮我消除延迟并在外部命令完成执行后填充 Result 对象吗?

测试.cpp

#include "process.hpp"
#include <iostream>
#include <string>

using namespace TinyProcessLib;
using namespace std;

class Request{

    public:

        string s_Request;

        bool b_requestProcessed = false;

        bool b_error = false;

        string s_Response = "No response yet";

};

void processCommand( Request* );

int main(int argc, char *argv[]){

    Request *p_Request = new Request();
    p_Request->s_Request = argv[1];
    processCommand( p_Request );
    while(!p_Request->b_requestProcessed){
    }
    cout << p_Request->s_Response << endl;
}


void processCommand( Request* p_Request ){

    if(!p_Request){
        p_Request->b_error = true;
        return;
    }
    auto output=make_shared<string>();
    Process process(string("echo ") + string(p_Request->s_Request), "", [output](const char *bytes, size_t n){
         *output+=string(bytes, n);
    });
    // Help me to remove this delay
    this_thread::sleep_for(chrono::seconds(5));
    p_Request->s_Response=*output;
    auto exit_status=process.get_exit_status();
    if(exit_status == 0){
        p_Request->b_requestProcessed = true;
        p_Request->b_error = false;
    }else{

        p_Request->b_error = true;
        p_Request->s_Response="Command Execution Failed";
    }

}

编译命令

g++ -std=c++11 -pthread process.cpp process_unix.cpp Test.cpp -o Test

延迟结果

./Test  "Hello Stack Overflow"
Hello Stack Overflow

结果毫不延迟

./Test  "Hello Stack Overflow"
[[EMPTY_LINE]]

最佳答案

this_thread::sleep_for(chrono::seconds(5));
p_Request->s_Response=*output;
auto exit_status=process.get_exit_status();

编辑为

auto exit_status=process.get_exit_status();
p_Request->s_Response=*output;

.get_exit_status() 等待该过程完成,并且您的=*输出会生成一个拷贝。因此,在第一个版本中,您将复制一个空字符串(因为该过程尚未完成),而在第二个版本中,它会在进行复制之前等待该过程完成。

关于c++ - 在 Tiny Process Library 中阻塞直到进程结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45486602/

相关文章:

jquery - 在单独启动的动画之间添加延迟

java - 在 Java 应用程序中嵌入外部应用程序(或伪造它)

c++ - 导出命名空间之后的所有内容都没有导出吗?

c++ - 查找句柄打开的位置

jquery - 为什么在 jquery 中添加第二个函数后我的对象没有出现?

JavaScript 代码在失去焦点时停止

c++ - Eclipse for C++ 中的 "string could not resolved"错误(Eclipse 无法解析标准库)

内部类的 C++ vector

java - 使用自定义参数运行外部程序

java - 从 Java 代码中运行程序