在C++中處理CMD命令長時間運行的問題,可以通過創建一個子進程來執行命令,并使用管道(pipe)或共享內存(shared memory)來獲取輸出結果
#include<iostream>
#include<string>
#include <cstring>
#include<thread>
#include<chrono>
#ifdef _WIN32
#include<windows.h>
#else
#include <unistd.h>
#endif
void runCommand(const std::string& cmd, std::string& output) {
output.clear();
#ifdef _WIN32
// Windows平臺
SECURITY_ATTRIBUTES sa = {sizeof(sa), NULL, TRUE};
HANDLE hReadPipe, hWritePipe;
CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
STARTUPINFO si = {sizeof(si)};
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.hStdOutput = hWritePipe;
si.hStdError = hWritePipe;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi;
if (CreateProcess(NULL, const_cast<char*>(cmd.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
CloseHandle(hWritePipe);
char buffer[1024];
DWORD bytesRead;
while (ReadFile(hReadPipe, buffer, sizeof(buffer) - 1, &bytesRead, NULL) && bytesRead) {
buffer[bytesRead] = '\0';
output += buffer;
}
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
CloseHandle(hReadPipe);
#else
// Unix平臺
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid == 0) {
close(pipefd[0]);
dup2(pipefd[1], STDOUT_FILENO);
dup2(pipefd[1], STDERR_FILENO);
execl("/bin/sh", "sh", "-c", cmd.c_str(), NULL);
exit(1);
} else {
close(pipefd[1]);
char buffer[1024];
ssize_t bytesRead;
while ((bytesRead = read(pipefd[0], buffer, sizeof(buffer) - 1)) > 0) {
buffer[bytesRead] = '\0';
output += buffer;
}
waitpid(pid, NULL, 0);
}
close(pipefd[0]);
#endif
}
int main() {
std::string cmd = "ping www.example.com -n 10"; // 這里可以替換為你需要執行的命令
std::string output;
std::cout << "Running command: "<< cmd<< std::endl;
runCommand(cmd, output);
std::cout << "Command output:"<< std::endl<< output<< std::endl;
return 0;
}
這個示例代碼會創建一個子進程來執行指定的CMD命令,并通過管道(pipe)或共享內存(shared memory)來獲取命令的輸出結果。注意,這個示例代碼只適用于Windows和Unix平臺。如果你需要在其他平臺上運行,請根據平臺的特性進行相應的修改。