FairMQ  1.2.1
C++ Message Passing Framework
Process.h
1 /********************************************************************************
2  * Copyright (C) 2017 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH *
3  * *
4  * This software is distributed under the terms of the *
5  * GNU Lesser General Public Licence (LGPL) version 3, *
6  * copied verbatim in the file "LICENSE" *
7  ********************************************************************************/
8 
9 #ifndef FAIR_MQ_TOOLS_PROCESS_H
10 #define FAIR_MQ_TOOLS_PROCESS_H
11 
12 #include <boost/process.hpp>
13 
14 #include <string>
15 
16 namespace fair
17 {
18 namespace mq
19 {
20 namespace tools
21 {
22 
27 {
28  std::string console_out;
29  int exit_code;
30 };
31 
40 inline execute_result execute(std::string cmd, std::string prefix = "")
41 {
42  execute_result result;
43  std::stringstream out;
44 
45  // print full line thread-safe
46  std::stringstream printCmd;
47  printCmd << prefix << cmd << "\n";
48  std::cout << printCmd.str() << std::flush;
49 
50  out << prefix << cmd << std::endl;
51 
52  // Execute command and capture stdout, add prefix line by line
53  boost::process::ipstream stdout;
54  boost::process::child c(cmd, boost::process::std_out > stdout);
55  std::string line;
56  while (getline(stdout, line))
57  {
58  // print full line thread-safe
59  std::stringstream printLine;
60  printLine << prefix << line << "\n";
61  std::cout << printLine.str() << std::flush;
62 
63  out << prefix << line << "\n";
64  }
65 
66  c.wait();
67 
68  // Capture exit code
69  result.exit_code = c.exit_code();
70  out << prefix << " Exit code: " << result.exit_code << std::endl;
71 
72  result.console_out = out.str();
73 
74  // Return result
75  return result;
76 }
77 
78 } /* namespace tools */
79 } /* namespace mq */
80 } /* namespace fair */
81 
82 #endif /* FAIR_MQ_TOOLS_PROCESS_H */
Definition: Process.h:26
Definition: DeviceRunner.h:23