zoukankan      html  css  js  c++  java
  • C++ 执行cmd命令 并读取输出

    出处:https://blog.csdn.net/weixin_43903378/article/details/105297406

    头文件

    #ifndef _PIPE_CMD_H_
    #define _PIPE_CMD_H_
    
    
    #include <Windows.h>
    
    
    // 执行 cmd 命令, 并获取执行结果数据
    BOOL PipeCmd(char *pszCmd, char *pszResultBuffer, DWORD dwResultBufferSize);
    
    
    #endif

    源文件

    #include "stdafx.h"
    #include "PipeCmd.h"
    
    
    void ShowError(char *pszText)
    {
        char szErr[MAX_PATH] = {0};
        ::wsprintf(szErr, "%s Error[%d]
    ", pszText, ::GetLastError());
        ::MessageBox(NULL, szErr, "ERROR", MB_OK);
    }
    
    
    // 执行 cmd 命令, 并获取执行结果数据
    BOOL PipeCmd(char *pszCmd, char *pszResultBuffer, DWORD dwResultBufferSize)
    {
        HANDLE hReadPipe = NULL;
        HANDLE hWritePipe = NULL;
        SECURITY_ATTRIBUTES securityAttributes = {0};
        BOOL bRet = FALSE;
        STARTUPINFO si = {0};
        PROCESS_INFORMATION pi = {0};
    
        // 设定管道的安全属性
        securityAttributes.bInheritHandle = TRUE;
        securityAttributes.nLength = sizeof(securityAttributes);
        securityAttributes.lpSecurityDescriptor = NULL;
        // 创建匿名管道
        bRet = ::CreatePipe(&hReadPipe, &hWritePipe, &securityAttributes, 0);
        if (FALSE == bRet)
        {
            ShowError("CreatePipe");
            return FALSE;
        }
        // 设置新进程参数
        si.cb = sizeof(si);
        si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
        si.wShowWindow = SW_HIDE;
        si.hStdError = hWritePipe;
        si.hStdOutput = hWritePipe;
        // 创建新进程执行命令, 将执行结果写入匿名管道中
        bRet = ::CreateProcess(NULL, pszCmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
        if (FALSE == bRet)
        {
            ShowError("CreateProcess");
        }
        // 等待命令执行结束
        ::WaitForSingleObject(pi.hThread, INFINITE);
        ::WaitForSingleObject(pi.hProcess, INFINITE);
        // 从匿名管道中读取结果到输出缓冲区
        ::RtlZeroMemory(pszResultBuffer, dwResultBufferSize);
        ::ReadFile(hReadPipe, pszResultBuffer, dwResultBufferSize, NULL, NULL);
        // 关闭句柄, 释放内存
        ::CloseHandle(pi.hThread);
        ::CloseHandle(pi.hProcess);
        ::CloseHandle(hWritePipe);
        ::CloseHandle(hReadPipe);
    
        return TRUE;
    }
  • 相关阅读:
    SQL Server 2016,2014 “无法找到数据库引擎启动句柄”
    SCCM Collection 集合获取计算机最后启动时间
    在Office 365 添加就地保留用户邮箱
    SQL Server数据库log shipping 灾备(Part2 )
    SQL Server数据库log shipping 灾备(Part1 )
    领域驱动设计案例之实现业务3
    领域驱动设计案例之业务实现2
    领域驱动设计案例之业务实现1
    领域驱动设计案例之仓储顶层实现
    领域驱动设计案例之领域层实体与聚合根实现
  • 原文地址:https://www.cnblogs.com/liujx2019/p/14325584.html
Copyright © 2011-2022 走看看