HCE project C++ developers source code library  1.1.1
HCE project developer library
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
ShellExec.cpp
Go to the documentation of this file.
1 #include <sstream>
2 #include <string.h>
3 #include <stdio.h>
4 #include <sys/wait.h>
5 #include <Poco/TemporaryFile.h>
6 
7 #include "ShellExec.hpp"
8 
9 //-----------------------------------------------------------------------------
10 ShellExec::ShellExec(const std::string& cmd_)
11 :inherited(cmd_), exitStatus(0)
12 {
13 }
14 //-----------------------------------------------------------------------------
15 bool ShellExec::exec(std::ostream& os, std::ostream& es)
16 {
17  const std::string tmpFile = Poco::TemporaryFile::tempName("");
18 
19  _IsError = false;
20  char buff[SZ]={0};
21  FILE* f = NULL;
22  FILE* err = freopen (tmpFile.c_str(),"w", stderr);
23 
24  f=popen(cmd.c_str(), "r");
25  if(f!=NULL)
26  {
27  while(fgets(buff, sizeof(buff), f))
28  {
29  os << buff;
30  }
31  int ret = pclose(f);
32  exitStatus = ret;
33 
34  if (ret != 0)
35  {
36  _IsError = true;
37  es << strerror(errno) << std::endl;
38  }
39  }
40  else
41  {
42  _IsError = true;
43  es << strerror(errno) << std::endl;
44  }
45 
46  if (err!=NULL)
47  {
48  if (fclose(err)!=0)
49  es << strerror(errno) << std::endl;
50 
51  err = fopen(tmpFile.c_str(), "r");
52  if (err!=NULL)
53  {
54  memset(buff, 0, sizeof(buff));
55  while(fgets(buff, sizeof(buff), err))
56  {
57  es << buff;
58  }
59 
60  if (fclose(err)!=0)
61  es << strerror(errno) << std::endl;
62 
63  if (remove(tmpFile.c_str())!=0)
64  es << strerror(errno) << std::endl;
65  }
66  }
67  return !_IsError;
68 }
69 //-----------------------------------------------------------------------------
70 std::ostream& operator << (std::ostream& os, const ShellExec& shellExec)
71 {
72  const_cast<ShellExec&>(shellExec).exec(os, os);
73  return os;
74 }
75 //-----------------------------------------------------------------------------
76 std::string& operator << (std::string& str, const ShellExec& shellExec)
77 {
78  std::stringstream outMsg;
79  outMsg << shellExec;
80  if (!shellExec.isError())
81  str = outMsg.str();
82  return str;
83 }
84 //-----------------------------------------------------------------------------
85 //-----------------------------------------------------------------------------