/** * Call another command and get stdout as a result. */ inline std::string call(const std::string& cmd, const std::vector<std::string> &args) { cybozu::FileStat stat = cybozu::FilePath(cmd).stat(); if (!stat.exists()) { throw std::runtime_error("command not found:" + cmd); } if (!stat.isExecutable()) { throw std::runtime_error("command not executable:" + cmd); } Pipe pipe0, pipe1; pid_t cpid; cpid = ::fork(); if (cpid < 0) { throw std::runtime_error("fork() failed."); } if (cpid == 0) { /* child process */ /* bind pipe and stdout. */ pipe0.closeR(); pipe0.dupW(1); pipe1.closeR(); pipe1.dupW(2); try { redirectToNullDev(0); } catch (...) { ::exit(1); } closeAllFileDescriptors(); std::vector<char *> argv = prepareArgv(cmd, args); ::execv(cmd.c_str(), &argv[0]); } /* parent process. */ /* Read the stdout/stderr of the child process. */ pipe0.closeW(); pipe1.closeW(); std::string stdOutStr, stdErrStr; std::exception_ptr epOut, epErr; std::thread th0(streamToStr, pipe0.fdR(), std::ref(stdOutStr), std::ref(epOut)); std::thread th1(streamToStr, pipe1.fdR(), std::ref(stdErrStr), std::ref(epErr)); th0.join(); th1.join(); /* wait for done */ int status; ::waitpid(cpid, &status, 0); /* handle errors */ if (status != 0) { std::string msg("child process has returned non-zero:"); msg += cybozu::util::formatString("%d\n", status); msg += "cmd:" + cmd + "\n"; msg += "args:"; for (const std::string &arg : args) msg += arg + " "; msg += "\nstderr:" + stdErrStr; throw std::runtime_error(msg); } if (epOut) std::rethrow_exception(epOut); if (epErr) std::rethrow_exception(epErr); return stdOutStr; }
int main() { HDC1000 hdc1000_1; MPL115A2 mpl115a2_1; MS5607 ms5607_1; DISPLAY d; LOG l; DB db; hdc1000_1.Init(); mpl115a2_1.Init(); ms5607_1.Init(); std::cout << "Hello\nWorld!\n"; db.Connect(); if( signal(SIGINT, sig_handler) == SIG_ERR) { std::cerr << "sig_handler fail."<<std::endl; } while(1) { std::thread th0(governor); // std::thread th1([&]{hdc1000_1.Get();}); std::thread th2([&]{mpl115a2_1.Get();}); std::thread th3([&]{ms5607_1.Get();}); // l.GetTime();//現在時刻の取得 // th1.join(); th2.join(); th3.join(); // l.Write( hdc1000_1.Read(0),//Temp hdc1000_1.Read(1),//Humi mpl115a2_1.Read(1), mpl115a2_1.Read(0), ms5607_1.Read(1),// ms5607_1.Read(0) //Temp ); // 表示 d.Disp(l); // DBインサート db.Insert(l); // Wait th0.join(); // Terminate if(sig) { std::cout <<"Recieve SIGINT\n"; db.Disconnect(); std::cout <<std::flush; break; } } }