set_on_error.hpp
Go to the documentation of this file.
1// Copyright (c) 2006, 2007 Julio M. Merino Vidal
2// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
3// Copyright (c) 2009 Boris Schaeling
4// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
5// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
6//
7// Distributed under the Boost Software License, Version 1.0. (See accompanying
8// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9
10#pragma once
11
12#include <errno.h>
13
14#include <fcntl.h>
15#include <unistd.h>
16
19#include <boost/system/error_code.hpp>
20
22{
23
25 {
26 public:
27 explicit set_on_error(boost::system::error_code& ec) : ec_(ec)
28 {
29 }
30
31 template <class PosixExecutor>
32 void
33 on_fork_setup(PosixExecutor&) const
34 {
35 if (::pipe(fds_) == -1)
36 {
37 BOOST_PROCESS_RETURN_LAST_SYSTEM_ERROR(ec_);
38 }
39 if (::fcntl(fds_[1], F_SETFD, FD_CLOEXEC) == -1)
40 {
41 BOOST_PROCESS_RETURN_LAST_SYSTEM_ERROR(ec_);
42 ::close(fds_[0]);
43 ::close(fds_[1]);
44 }
45 }
46
47 template <class PosixExecutor>
48 void
49 on_fork_error(PosixExecutor&) const
50 {
51 if (!ec_)
52 {
53 BOOST_PROCESS_RETURN_LAST_SYSTEM_ERROR(ec_);
54 ::close(fds_[0]);
55 ::close(fds_[1]);
56 }
57 }
58
59 template <class PosixExecutor>
60 void
61 on_fork_success(PosixExecutor&) const
62 {
63 if (!ec_)
64 {
65 ::close(fds_[1]);
66 int code;
67 if (::read(fds_[0], &code, sizeof(int)) > 0)
68 {
69 ec_ = boost::system::error_code(code, boost::system::system_category());
70 }
71 ::close(fds_[0]);
72 }
73 }
74
75 template <class PosixExecutor>
76 void
77 on_exec_setup(PosixExecutor&) const
78 {
79 if (!ec_)
80 {
81 ::close(fds_[0]);
82 }
83 }
84
85 template <class PosixExecutor>
86 void
87 on_exec_error(PosixExecutor&) const
88 {
89 if (!ec_)
90 {
91 int e = errno;
92 while (::write(fds_[1], &e, sizeof(int)) == -1 && errno == EINTR)
93 ;
94 ::close(fds_[1]);
95 }
96 }
97
98 private:
99 boost::system::error_code& ec_;
100 mutable int fds_[2];
101 };
102
103} // namespace boost::process::posix::initializers
Defines various macros.