從這里我得到了給我命令列輸出和退出代碼的代碼。不幸的是,我不太了解該運算子多載,如果我嘗試將其重寫為我知道的簡單代碼(使用全域變數,即),我總是得到錯誤的退出代碼狀態 0。
那么如何修改以下代碼,以便存盤輸出和退出代碼狀態以供將來使用?
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
struct CommandResult {
std::string output;
int exitstatus;
friend std::ostream &operator<<(std::ostream &os, const CommandResult &result) {
os << "command exitstatus: " << result.exitstatus << " output: " << result.output;
return os;
}
bool operator==(const CommandResult &rhs) const {
return output == rhs.output &&
exitstatus == rhs.exitstatus;
}
bool operator!=(const CommandResult &rhs) const {
return !(rhs == *this);
}
};
class Command {
public:
/**
* Execute system command and get STDOUT result.
* Like system() but gives back exit status and stdout.
* @param command system command to execute
* @return CommandResult containing STDOUT (not stderr) output & exitstatus
* of command. Empty if command failed (or has no output). If you want stderr,
* use shell redirection (2&>1).
*/
static CommandResult exec(const std::string &command) {
int exitcode = 255;
std::array<char, 1048576> buffer {};
std::string result;
#ifdef _WIN32
#define popen _popen
#define pclose _pclose
#define WEXITSTATUS
#endif
FILE *pipe = popen(command.c_str(), "r");
if (pipe == nullptr) {
throw std::runtime_error("popen() failed!");
}
try {
std::size_t bytesread;
while ((bytesread = fread(buffer.data(), sizeof(buffer.at(0)), sizeof(buffer), pipe)) != 0) {
result = std::string(buffer.data(), bytesread);
}
} catch (...) {
pclose(pipe);
throw;
}
exitcode = WEXITSTATUS(pclose(pipe));
return CommandResult{result, exitcode};
}
};
int main ()
{
std::cout << Command::exec("echo blablub") << std::endl;
}
這是我的代碼,函式中的全域變數是正確的,但之后會被覆寫。
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
int exitcode = 555;
std::string exec(const std::string cmd) {
int exitcode = 255;
std::array<char, 128> buffer {};
std::string result;
#ifdef _WIN32
#define popen _popen
#define pclose _pclose
#define WEXITSTATUS
#endif
FILE *pipe = popen(cmd.c_str(), "r");
if (pipe == nullptr) {
throw std::runtime_error("popen() failed!");
}
try {
std::size_t bytesread;
while ((bytesread = fread(buffer.data(), sizeof(buffer.at(0)), sizeof(buffer), pipe)) != 0) {
result = std::string(buffer.data(), bytesread);
}
} catch (...) {
pclose(pipe);
throw;
}
exitcode = WEXITSTATUS(pclose(pipe));
std::cout<<exitcode<<'\n';
return result;
}
int main (){
exec("echo bla");
std::cout<<exitcode<<'\n';
}
uj5u.com熱心網友回復:
假設文章中提供的代碼是正確的并且做了它應該做的,它已經做了你需要的一切。退出代碼和輸出從exec函式回傳。
您只需使用回傳的CommandResult并訪問其成員:
int main() {
auto result = Command::exec("echo blablub");
std::cout << result.output << "\n":
std::cout << result.exitstatus << "\n";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/493789.html
上一篇:關于std::istream&運算子實作的問題>>(std::istream&is,icmp_header&header)
