【问题标题】:run linux command asynchronously with callback in c++在c ++中使用回调异步运行linux命令
【发布时间】:2014-02-15 04:30:21
【问题描述】:

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

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

我已经尝试过 c++ system() 函数。并已尝试运行 boost.process 标头 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++ linux node.js boost asynchronous


    【解决方案1】:

    不清楚你想做什么,但这里有一些我认为可以解决问题的 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 用于期货和异步,您可以使用 Boost.Bind 替换 lambda。

    这至少应该让你开始。

    【讨论】:

    • 粗体中已经很清楚的表明,使用的编译器不支持C++11
    • 是的,但是在一周没有答案之后,我觉得有总比没有好,我确实向 cmets 提供了如何修改 C++98 的代码。
    猜你喜欢
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多