Boost C++ 函式庫

...世界上最受推崇且設計精良的 C++ 函式庫專案之一。 Herb SutterAndrei Alexandrescu,《C++ 程式碼規範

PrevUpHomeNext

全域 std_out

boost::process::v1::std_out

概要

// In header: <boost/process/v1/io.hpp>

unspecified std_out;

說明

此屬性允許設定子行程的輸出串流。

[Note] 注意事項

語義與 std_err 相同

[Note] 注意事項

std_errstd_out 可以使用 operator & 合併成一個串流,例如 std_out & std_err

詳細資訊

檔案輸入

檔案 I/O 簡單地將串流重新導向至檔案,可能的類型如下:

  • boost::process::v1::filesystem::path

  • std::basic_string<char_type>

  • const char_type*

  • FILE*

其中 char_type 可以是 charwchar_t

明確地加入 FILE*,以便行程可以輕鬆地將子行程的輸出串流重新導向至行程的另一個輸出串流。也就是說

system("ls", std_out < stdin);
[Warning] 警告

如果啟動行程和子行程使用相同的輸入,將導致未定義的行為。

由於 C++ 實作不提供對控制代碼的存取權,因此像 system("ls", std_out > std::cerr) 這樣的語法是不可能的。

此屬性的有效表達式如下:

std_out < file;
std_out = file;

管道輸出

如相關章節所述,boost.process 函式庫提供了一個 async_pipe 類別,可用於與子行程通訊。

[Note] 注意事項

技術上,由於函式庫在此處未使用任何 asio 實作,async_pipe 的運作方式類似於同步管道。然而,如果行程已完成,非同步操作將不會結束,因為管道仍然保持開啟狀態。您可以使用 async_close 函數搭配 on_exit 來解決此問題。

使用管道的有效表達式如下:

std_out > pipe;
std_out = pipe;

其中 pipe 的有效類型如下:

請注意,管道也可以在多個行程之間使用,如下所示:

pipe p;
child c1("nm", "a.out", std_out>p);
child c2("c++filt", std_in<p);

非同步管道輸出

非同步管道 I/O 將通訊分類為由行程函式庫自動處理非同步操作。這表示將會建構一個管道,自動啟動 async_read/-write,並且子行程結束時也會關閉管道。

管道 I/O 的有效類型如下:

  • boost::asio::mutable_buffer [31]

  • boost::asio::streambuf

  • std::future<std::vector<char>>

  • std::future<std::string>

使用管道的有效表達式如下:

std_out > buffer;
std_out = buffer;
std_err > buffer;
std_err = buffer;
(std_out & std_err) > buffer;
(std_out & std_err) = buffer;
[Note] 注意事項

boost::asio::buffer 也可在 boost::process 命名空間中使用。

[Warning] 警告

此功能需要包含 boost/process/async.hpp 並將 boost::asio::io_context 的參考傳遞給啟動函數。

關閉

可以關閉輸出串流,使其無法寫入。嘗試寫入將導致錯誤。

這可以透過以下語法實現。

std_out > close;
std_out = close;
std_out.close();

空值

輸出串流可以被重新導向至寫入空裝置,這表示所有輸出都會被捨棄。

達成此目的的語法有以下幾種變體:

std_out > null;
std_out = null;
std_out.null();



[31] 使用 boost::asio::buffer 構建


PrevUpHomeNext