boost.asioライブラリを使用してパイプをエミュレートするコードを以下に書いています。その唯一のデモ・コードとメッセージ・境界チェックはありません、エラーがチェックなど
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include <cctype>
#include <boost/array.hpp>
using boost::asio::local::stream_protocol;
int main()
{
try
{
boost::asio::io_service io_service;
stream_protocol::socket parentSocket(io_service);
stream_protocol::socket childSocket(io_service);
//create socket pair
boost::asio::local::connect_pair(childSocket, parentSocket);
std::string request("Dad I am your child, hello!");
std::string dadRequest("Hello son!");
//Create child process
pid_t pid = fork();
if(pid < 0){
std::cerr << "fork() erred\n";
} else if (pid == 0) { //child process
parentSocket.close(); // no need of parents socket handle, childSocket is bidirectional stream socket unlike pipe that has different handles for read and write
boost::asio::write(childSocket, boost::asio::buffer(request)); //Send data to the parent
std::vector<char> dadResponse(dadRequest.size(),0);
boost::asio::read(childSocket, boost::asio::buffer(dadResponse)); //Wait for parents response
std::cout << "Dads response: ";
std::cout.write(&dadResponse[0], dadResponse.size());
std::cout << std::endl;
} else { //parent
childSocket.close(); //Close childSocket here use one bidirectional socket
std::vector<char> reply(request.size());
boost::asio::read(parentSocket, boost::asio::buffer(reply)); //Wait for child process to send message
std::cout << "Child message: ";
std::cout.write(&reply[0], request.size());
std::cout << std::endl;
sleep(5); //Add 5 seconds delay before sending response to parent
boost::asio::write(parentSocket, boost::asio::buffer(dadRequest)); //Send child process response
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
std::exit(1);
}
}
http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/reference/local__connect_pair.html – user5159806
@ user5159806リンクありがとう – PnotNP