阻塞,直到进程在微型进程库中结束
Blocking until process ends in Tiny Process Library
我正在编写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(( 等待该过程完成,您的 =* 输出会生成副本。 因此,在第一个版本中,您正在复制一个空字符串(因为该过程尚未完成(,第二个版本在复制之前等待该过程完成。
相关文章:
- 当进程结束时,如何保持由 QProcess 执行的命令?
- kill() 总是返回 0(成功),即使在子进程已经结束之后?
- WaitForSingleObject 不会等待进程结束
- 阻塞,直到进程在微型进程库中结束
- 如何结束在 COM 自动化期间执行的进程
- 使用 VCL 的 C++:关闭辅助表单不会结束进程
- MPI在某个进程找到解决方案时使用广播结束程序
- 当进程结束时,处于Sleep()中间的线程会发生什么
- 当进程无法结束时该怎么办
- 如何等待子进程结束
- 主进程结束后C++内存泄漏
- 结束进程错误代码 -1,如果访问结构的字符串字段
- 侦听进程开始和结束
- 使应用程序/服务,以便在任务管理器中尝试结束/终止其进程将导致"Unable to Terminate Process"
- 检查相邻从进程是否在MPI中结束
- c++代码工作正常,但进程以termination结束,而不是返回0
- 如何在Linux中正确报告另一个进程的突然结束
- 程序结束时进程返回0xC0000005
- Windows服务启动进程结束通知(20032008)
- 如何在c++中结束一个进程