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