2
我正在編寫接受命令行參數的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]]
我建議仔細看一下你沒有發佈的「Process.h」文件;那裏應該有些東西可以讓你等待整個過程。 – UKMonkey
_error:'p_Request'沒有被捕獲_ - 你試圖捕獲它嗎? – 2017-08-03 14:11:03
@UKMonkey - 以下是process.hpp的源代碼https://github.com/eidheim/tiny-process-library/blob/master/process.hpp – Beginner