Boost.Processを試す

ふと新たなアプリのネタを思いついたのですが、それで子プロセスと通信する必要があったので、Boost.Processを試してみました。
以下のコードは、Boost Vaultにアップされているバージョンではなく、SoCのSVNリポジトリの最新trunkバージョンです。

#include <boost/process.hpp>
#include <iostream>

namespace bp = ::boost::process;

int main()
{
    try
    {
        // 標準入出力はパイプで補足
        // 標準エラー出力は標準出力にリダイレクト
        bp::context ctx;
        ctx.m_stdin_behavior = bp::capture_stream();
        ctx.m_stdout_behavior = bp::capture_stream();
        ctx.m_stderr_behavior = bp::redirect_stream_to_stdout();

        std::string exe = bp::find_executable_in_path("sort");
        bp::child c = bp::launch_shell(exe, ctx);

        bp::postream& os = c.get_stdin();
        os <<
            "one\n"
            "two\n"
            "three\n"
            ;
        os.flush(); // 必須
        os.close(); // 必須

        bp::pistream& is = c.get_stdout();
        std::string line;
        while (std::getline(is, line))
            std::cout << line << '\n';

        c.wait(); // 終了待ち

        // ここでも子プロセスとそのメインスレッドのハンドルが有効(バグ)
    }
    catch (const std::exception& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
    }
}

とりあえず動いていますし、便利ではあるんですが、いろいろ不満があります。

  • windows.hなどのシステムヘッダがインクルードされる
  • m_stdin_behaviorみたいな変数にアクセスするインタフェース
  • Windows版の実装はまだバグが多い
  • Windows版はセキュアAPIを使っているのでVC++8.0以外では使えない

まだ開発中のようなので、Vaultバージョンも参考にしつつ、Boost.Coroutineのときのように独自に実装することにします。
Windows版のバグはそのうち作者に報告しときます。