close_fds_if.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 
17 #include <boost/iterator/counting_iterator.hpp>
19 #include <boost/range/adaptor/filtered.hpp>
20 #include <boost/range/algorithm/for_each.hpp>
21 #include <boost/range/counting_range.hpp>
22 
23 #ifndef BOOST_PROCESS_POSIX_MAX_FD
24 #define BOOST_PROCESS_POSIX_MAX_FD 32
25 #endif
26 
28 {
29 
30  template <class Predicate>
32  {
33  private:
34  static void
35  close(int fd)
36  {
37  ::fcntl(fd, F_SETFD, FD_CLOEXEC);
38  }
39 
40  public:
41  explicit close_fds_if_(const Predicate& pred) : pred_(pred)
42  {
43  }
44 
45  template <class PosixExecutor>
46  void
47  on_exec_setup(PosixExecutor&) const
48  {
49  boost::for_each(boost::adaptors::filter(boost::counting_range(0, upper_bound()), pred_),
50  close);
51  }
52 
53  private:
54  static int
55  upper_bound()
56  {
57  int up;
58 #if defined(F_MAXFD)
59  do
60  {
61  up = ::fcntl(0, F_MAXFD);
62  } while (up == -1 && errno == EINTR);
63  if (up == -1)
64 #endif
65  up = ::sysconf(_SC_OPEN_MAX);
66  if (up == -1)
67  {
69  }
70  return up;
71  }
72 
73  Predicate pred_;
74  };
75 
76  template <class Predicate>
77  close_fds_if_<Predicate>
78  close_fds_if(const Predicate& pred)
79  {
80  return close_fds_if_<Predicate>(pred);
81  }
82 
83 } // namespace boost::process::posix::initializers
boost::process::posix::initializers::close_fds_if_::close_fds_if_
close_fds_if_(const Predicate &pred)
Definition: close_fds_if.hpp:41
initializer_base.hpp
BOOST_PROCESS_POSIX_MAX_FD
#define BOOST_PROCESS_POSIX_MAX_FD
Definition: close_fds_if.hpp:24
boost::process::posix::initializers
Definition: bind_fd.hpp:16
boost::process::posix::initializers::close_fds_if_::on_exec_setup
void on_exec_setup(PosixExecutor &) const
Definition: close_fds_if.hpp:47
boost::process::posix::initializers::close_fds_if_
Definition: close_fds_if.hpp:31
boost::process::posix::initializers::initializer_base
Definition: initializer_base.hpp:15
boost::process::posix::initializers::close_fds_if
close_fds_if_< Predicate > close_fds_if(const Predicate &pred)
Definition: close_fds_if.hpp:78