CASM  1.1.0
A Clusters Approach to Statistical Mechanics
Popen.cc
Go to the documentation of this file.
1 #include "casm/system/Popen.hh"
2 
3 #include <stdexcept>
4 
5 namespace CASM {
6 
8 Popen::Popen(std::function<void(FILE *)> _popen_handler,
9  std::function<void(int)> _pclose_handler,
10  bool _combine_stdout_stderr)
11  : m_popen_handler(_popen_handler),
12  m_pclose_handler(_pclose_handler),
13  m_combine_stdout_stderr(_combine_stdout_stderr) {}
14 
19 void Popen::popen(std::string _command) {
20  m_command = _command;
21 
23  m_command += " 2>&1";
24  }
25 
26  FILE *fp;
27  char path[PATH_MAX];
28 
29  fp = ::popen(m_command.c_str(), "r");
30  m_popen_handler(fp);
31 
32  m_stdout = "";
33  while (fgets(path, PATH_MAX, fp) != nullptr) {
34  m_stdout += path;
35  }
36 
37  m_pclose_result = pclose(fp);
38 
40 }
41 
43 std::string Popen::gets() const { return m_stdout; }
44 
46 void Popen::print(std::ostream &sout) const {
47  sout << m_command << "\n";
48  sout << m_stdout;
49 }
50 
52 int Popen::exit_code() const { return m_pclose_result / 256; }
53 
56  if (fp == nullptr) {
57  throw std::runtime_error("Error: popen failed.");
58  }
59 }
60 
64  if (status == -1) {
65  throw std::runtime_error("Error: pclose failed.");
66  }
67 }
68 
69 } // namespace CASM
std::string gets() const
Returns the stdout resulting from the last popen call.
Definition: Popen.cc:43
int m_pclose_result
Definition: Popen.hh:44
Popen(std::function< void(FILE *)> _popen_handler=Popen::default_popen_handler, std::function< void(int)> _pclose_handler=Popen::default_pclose_handler, bool _combine_stdout_stderr=true)
Construct a Popen object.
Definition: Popen.cc:8
static void default_pclose_handler(int status)
Default pclose error handler throws std::runtime_error if pclose failed.
Definition: Popen.cc:63
void popen(std::string _command)
Execute popen for a given command.
Definition: Popen.cc:19
void print(std::ostream &sout) const
Print the last command executed and the resulting stdout.
Definition: Popen.cc:46
std::function< void(int)> m_pclose_handler
Definition: Popen.hh:46
std::string m_command
Definition: Popen.hh:42
int exit_code() const
Returns pclose(fp)/256.
Definition: Popen.cc:52
static void default_popen_handler(FILE *fp)
Default popen error handler throws std::runtime_error if popen failed.
Definition: Popen.cc:55
std::function< void(FILE *)> m_popen_handler
Definition: Popen.hh:45
std::string m_stdout
Definition: Popen.hh:43
bool m_combine_stdout_stderr
Definition: Popen.hh:47
Main CASM namespace.
Definition: APICommand.hh:8