Browse Source

Util: Add class Shell for executing more basic OS shell commands

master
Riyyi 3 years ago
parent
commit
9926849640
  1. 53
      src/util/shell.cpp
  2. 30
      src/util/shell.h
  3. 8
      src/util/system.cpp

53
src/util/shell.cpp

@ -0,0 +1,53 @@
#include <cstdio> // pclose, perror, popen
#include <string>
#include <string_view>
#include "util/shell.h"
namespace Util {
Shell::Shell()
{
}
Shell::Shell(std::string output, int status)
: m_output(output)
, m_status(status)
{
}
Shell Shell::operator()(const char* command)
{
FILE* shell = popen(command, "r");
if (!shell) {
perror("\033[31;1mError:\033[0m popen");
return { "", -1 };
}
std::string output;
constexpr int bufferSize = 4096;
char buffer[bufferSize];
while (fgets(buffer, sizeof(buffer), shell)) {
output.append(buffer);
}
int status = pclose(shell);
if (status < 0) {
perror("\033[31;1mError:\033[0m pclose");
}
return { output, status };
}
Shell Shell::operator()(std::string command)
{
return operator()(command.c_str());
}
Shell Shell::operator()(std::string_view command)
{
return operator()(command.data());
}
} // namespace Util

30
src/util/shell.h

@ -0,0 +1,30 @@
#ifndef SHELL_H
#define SHELL_H
#include <string>
#include <string_view>
namespace Util {
class Shell {
public:
Shell();
virtual ~Shell() {}
Shell operator()(const char* command);
Shell operator()(std::string command);
Shell operator()(std::string_view command);
std::string output() const { return m_output; }
int status() const { return m_status; }
private:
Shell(std::string output, int status);
std::string m_output;
int m_status { 0 };
};
} // namespace Util
#endif // SHELL_H

8
src/util/system.cpp

@ -160,20 +160,20 @@ System System::exec(std::string input)
int stdoutFd[2]; int stdoutFd[2];
int stderrFd[2]; int stderrFd[2];
if (pipe(stdinFd) < 0) { if (pipe(stdinFd) < 0) {
perror("\033[31;1mError\033[0m"); perror("\033[31;1mError:\033[0m pipe");
} }
if (pipe(stdoutFd) < 0) { if (pipe(stdoutFd) < 0) {
perror("\033[31;1mError\033[0m"); perror("\033[31;1mError:\033[0m pipe");
} }
if (pipe(stderrFd) < 0) { if (pipe(stderrFd) < 0) {
perror("\033[31;1mError\033[0m"); perror("\033[31;1mError:\033[0m pipe");
} }
pid_t pid = fork(); pid_t pid = fork();
switch (pid) { switch (pid) {
// Failed // Failed
case -1: case -1:
perror("\033[31;1mError\033[0m"); perror("\033[31;1mError:\033[0m fork");
break; break;
// Child // Child
case 0: { case 0: {

Loading…
Cancel
Save