Reputation: 2065
I am writing C++ code that accepts a command line argument, passes it to a system command like echo
and prints the response. To communicate with external process, I am using tiny-process-library. The problem with my current code is that it has to wait for a configured delay of 5 seconds
.
When I tried moving my code into the Process
object, I get below compilation error.
Test.cpp: In lambda function:
Test.cpp:29:3: error: ‘p_Request’ is not captured
Could somebody please help me to remove the delay and populate the Result
object once the external command completes its execution?
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";
}
}
Compilation Command
g++ -std=c++11 -pthread process.cpp process_unix.cpp Test.cpp -o Test
Result with Delay
./Test "Hello Stack Overflow"
Hello Stack Overflow
Result without Delay
./Test "Hello Stack Overflow"
[[EMPTY_LINE]]
Upvotes: 2
Views: 424
Reputation: 6993
this_thread::sleep_for(chrono::seconds(5));
p_Request->s_Response=*output;
auto exit_status=process.get_exit_status();
Edit to
auto exit_status=process.get_exit_status();
p_Request->s_Response=*output;
The .get_exit_status() waits for the process to complete, and your =*output makes a copy. So in the first version you're copying an empty string (as the process hasn't finished) and the second, it's awaiting the process to complete before making the copy.
Upvotes: 4