#include #include #include #include #include #include #include namespace { auto error(const int error) { std::cerr << getpid() << "\terror:\t" << error << '\t' << std::strerror(error) << std::endl; return error; } } int main() { const auto name{"/tmp/my_name"}; const auto result = mkfifo(name, 0666); if(result) return error(errno); constexpr auto writers{5}; constexpr auto messages{4}; for(auto idx = 0; idx < writers; ++idx) { const auto pid = fork(); if(pid < 0) return error(errno); if(pid == 0) { std::cout << "child " << getpid() << std::endl; for(auto idx = 0; idx < messages; ++idx) { const auto wfd = open(name, O_WRONLY | O_NONBLOCK); if(wfd < 0) return error(errno); const auto msg{std::to_string(getpid())}; if(write(wfd, msg.data(), msg.size() + 1) < 0) error(errno); close(wfd); } return 0; } } { std::cout << "parent" << std::endl; const auto rfd = open(name, O_RDONLY); const auto wfd = open(name, O_WRONLY); if(rfd < 0) return error(errno); for(auto idx = 0; idx < writers * messages; ++idx) { std::string buffer; buffer.resize(80); if(read(rfd, &buffer[0], buffer.size()) < 0) error(errno); std::cout << buffer << std::endl; } close(wfd); close(rfd); } if(unlink(name) < 0) return error(errno); return 0; }