温馨提示×

如何在c++中处理cmd命令的长时间运行问题

c++
小樊
83
2024-09-15 18:45:35
栏目: 编程语言

在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平台。如果你需要在其他平台上运行,请根据平台的特性进行相应的修改。

0