c++ - 在C++中使用回调异步运行linux命令

标签 c++ linux node.js boost asynchronous

我正在尝试编写一个 C++ 程序,该程序将异步运行 linux 命令并注册 linux 命令返回值的回调。我真正想要的是编写一个实用程序函数,我将向其中传递两个参数,一个是linux命令,另一个是回调。

当我们调用这个实用函数时,它不应该阻塞程序并继续程序的执行。但是一旦执行了 linux 命令,它将调用我们作为第二个参数传递的回调。

我尝试过 C++ system() 函数。并尝试使用 boost.process header 来运行 Linux命令。但它们都是从c++调用linux调用的阻塞方式。

我对这种类型的异步+回调寄存器类型的编程很陌生。

该程序应该与我在 Node.js 程序中使用的 Node.js 程序中尝试过的程序完全相同。这对我来说非常有效,我为此关注的链接是 http://www.dzone.com/snippets/execute-unix-command-nodejs

请帮我用 C++ 完成这个工作。我需要在 C++ 系统调用中做哪些改进,这些调用对我来说运行完美但阻塞。或者我们在 C++ 或 boost 库中是否有一些直接可用的工具。

注意:我使用的是 g++ 4.3 编译器。它不是 C++0x 或 C++11。

谢谢, 阿布舍克

最佳答案

目前还不太清楚你想要做什么,但这里有一些我认为可以解决问题的 C++11 代码:

#include <thread>
#include <future>
#include <string>
#include <iostream>
#include <type_traits>

void system(const std::string& s)
{ std::cout << "Executing system with argument '" << s << "'\n"; }


// asynchronously (1) invoke cmd as system command and (2) callback.
// return future for (1) and (2) to caller
template<typename F>                            
std::future<typename std::result_of<F()>::type> 
runCmd(const std::string& cmd, F callback)      
{                                               
  auto cmdLambda = [cmd] { system(cmd); };
  auto fut = std::async(std::launch::async,
                        [cmdLambda, callback] { cmdLambda(); return callback(); });
  return fut;  
}

int main()
{
  auto fut = runCmd("ls", []{ std::cout << "Executing callback\n"; });
  fut.get();
}

对于 C++98,您可以使用 Boost.Threads 进行 future 和异步,并且可以使用 Boost.Bind 来替换 lambda。

这至少应该让您开始。

关于c++ - 在C++中使用回调异步运行linux命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21793417/

相关文章:

C++ 错误 "redefinition of ' 字符串“作为不同种类的符号”

c++ - 没有绝对路径无法访问数据库

c++ - SWIG 包装库中 __cxa_allocate_exception 期间的段错误

python - 显示动态平面

node.js - 如何使用 Node Puppeteer 设置 select 的值

c++ - 用于保存不同值的数据类型 C++

c++ - 如何将 vector 的一个元素作为 C++ 中的引用传递给函数?

linux - 如何停止读取剥离空间

javascript - 仅从 gcloud 数据存储区的对象数组中获取选定的对象

node.js - 想要猴子补丁表达 res.json - 有更好的方法吗?