libcryfs/process/subprocess.cpp

43 lines
1.1 KiB
C++
Raw Normal View History

#include "subprocess.h"
#include <cstdio>
#include <stdexcept>
using std::string;
namespace cpputils {
2015-11-03 22:11:09 +01:00
//TODO Exception safety
string Subprocess::call(const string &command) {
2015-11-03 22:11:09 +01:00
FILE *subprocessOutput = _call(command);
string result;
char buffer[1024];
while(fgets(buffer, sizeof(buffer), subprocessOutput) != nullptr) {
result += buffer;
}
auto returncode = pclose(subprocessOutput);
if(WEXITSTATUS(returncode) != 0) {
throw std::runtime_error("Subprocess \""+command+"\" exited with code "+std::to_string(WEXITSTATUS(returncode)));
}
return result;
}
2015-11-03 22:11:09 +01:00
int Subprocess::callAndGetReturnCode(const string &command) {
FILE *subprocess = _call(command);
auto returncode = pclose(subprocess);
return WEXITSTATUS(returncode);
}
FILE *Subprocess::_call(const string &command) {
FILE *subprocess = popen(command.c_str(), "r");
if (!subprocess)
{
throw std::runtime_error("Error starting subprocess "+command);
}
return subprocess;
}
}