#include <iostream>
#include <array>
#include <memory>
#include <string>
#ifdef _WIN32
#include <windows.h>
std::string executeCommand(const std::string& cmd)
{
SECURITY_ATTRIBUTES sa = { sizeof(sa), nullptr, TRUE };
HANDLE hRead, hWrite;
CreatePipe(&hRead, &hWrite, &sa, 0);
SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);
STARTUPINFOA si = { sizeof(si) };
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hWrite;
si.hStdError = hWrite;
PROCESS_INFORMATION pi;
std::string cmdLine = "cmd /c " + cmd;
if (CreateProcessA(nullptr, const_cast<char*>(cmdLine.c_str()),
nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi))
{
CloseHandle(hWrite);
std::string result;
char buffer[4096];
DWORD bytesRead;
while (ReadFile(hRead, buffer, sizeof(buffer), &bytesRead, nullptr) && bytesRead > 0)
{
result.append(buffer, bytesRead);
}
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(hRead);
return result;
}
CloseHandle(hRead);
CloseHandle(hWrite);
return "";
}
#else
std::string executeCommand(const std::string& cmd)
{
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(
popen(cmd.c_str(), "r"), pclose);
if (!pipe)
return "";
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr)
{
result += buffer.data();
}
return result;
}
#endif
int main()
{
// 获取系统信息
#ifdef _WIN32
std::cout << executeCommand("systeminfo") << std::endl;
#else
std::cout << executeCommand("uname -a") << std::endl;
#endif
return 0;
}