阻塞,直到进程在微型进程库中结束

Blocking until process ends in Tiny Process Library

本文关键字:进程 结束 微型 阻塞      更新时间:2023-10-16

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

当我尝试将代码移动到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(( 等待该过程完成,您的 =* 输出会生成副本。 因此,在第一个版本中,您正在复制一个空字符串(因为该过程尚未完成(,第二个版本在复制之前等待该过程完成。