阻止直到流程在Tiny Process Library中结束

时间:2017-08-03 14:06:19

标签: c++ delay external-process

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

当我尝试将代码移到Process对象中时,我遇到了编译错误。

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

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

Test.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]]

1 个答案:

答案 0 :(得分:4)

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()等待进程完成,你的= *输出进行复制。因此,在第一个版本中,您复制一个空字符串(因为该过程尚未完成),而第二个版本正在等待该过程在复制之前完成。