exec.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2011 Tommi Maekitalo
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * As a special exception, you may use this file as part of a free
10  * software library without restriction. Specifically, if other files
11  * instantiate templates or use macros or inline functions from this
12  * file, or you compile this file and link it with other files to
13  * produce an executable, this file does not by itself cause the
14  * resulting executable to be covered by the GNU General Public
15  * License. This exception does not however invalidate any other
16  * reasons why the executable file might be covered by the GNU Library
17  * General Public License.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27  */
28 
29 #include <cxxtools/noncopyable.h>
30 #include <cxxtools/systemerror.h>
31 #include <stdexcept>
32 #include <string>
33 #include <unistd.h>
34 
35 namespace cxxtools
36 {
37  namespace posix
38  {
50  template <unsigned dataSize, unsigned maxArgs>
52  {
53  char data[dataSize];
54  char* args[maxArgs + 2];
55  unsigned argc;
56 
57  public:
58  typedef const std::string& const_reference;
59  typedef std::string& reference;
60 
61  explicit BasicExec(const std::string& cmd)
62  : argc(0)
63  {
64  if (cmd.size() >= dataSize - 1)
65  throw std::out_of_range("command <" + cmd + "> too large");
66  args[0] = &data[0];
67  cmd.copy(args[0], cmd.size());
68  args[0][cmd.size()] = '\0';
69  args[1] = args[0] + cmd.size() + 1;
70  }
71 
72  BasicExec& push_back(const std::string& arg)
73  {
74  if (static_cast<unsigned>(args[argc + 1] + arg.size() - data) >= dataSize)
75  throw std::out_of_range("argument list too long");
76  if (argc >= maxArgs)
77  throw std::out_of_range("too many arguments");
78 
79  ++argc;
80  arg.copy(args[argc], arg.size());
81  args[argc][arg.size()] = '\0';
82  args[argc + 1] = args[argc] + arg.size() + 1;
83 
84  return *this;
85  }
86 
87  // nice alias of push_back
88  BasicExec& arg(const std::string& arg)
89  { return push_back(arg); }
90 
91  void exec()
92  {
93  args[argc + 1] = 0;
94  ::execvp(args[0], args);
95  throw SystemError("execvp");
96  }
97 
98  };
99 
101  }
102 }