匿名管道读取CMD回显信息

之前用了很坑爹的做法去读取了cmd命令的回显信息,现在发现了用匿名管道的实现方法,由于楼主没有学过Windows核心编程,找了一个代码来凑数

存下来以后研究

#include <windows.h>
#include <stdio.h>
#define EXE_NAME    NULL//TEXT("Cmd.exe")
#define EXE_CMD     TEXT("Cmd.exe /C ipconfig/all")
int main()
{

        char Buffer[4096];
        STARTUPINFO sInfo;//新进程的主窗口特性
        PROCESS_INFORMATION pInfo;
        SECURITY_ATTRIBUTES sa;
        HANDLE hRead, hWrite;
        DWORD bytesRead;    //读取代码的长度
        sa.nLength = sizeof(SECURITY_ATTRIBUTES);/ /结构体的大小,可用SIZEOF取得
        sa.lpSecurityDescriptor = NULL;//安全描述符
        sa.bInheritHandle = TRUE;;/ /安全描述的对象能否被新创建ÆÆ的进程继承

        if (!CreatePipe(&hRead, &hWrite, &sa, 0)) //创建匿名管道
        {
            return GetLastError();//返回最近的一个错误,0表示正常
        }

        GetStartupInfo(&sInfo);
        sInfo.cb = sizeof(sInfo);
        sInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
        sInfo.wShowWindow = SW_HIDE;
        sInfo.hStdError = hWrite;   //将管道的写端交给子进程
        sInfo.hStdOutput = hWrite;
        memset(&pInfo, 0, sizeof(pInfo));

        if (!CreateProcess(EXE_NAME, EXE_CMD, NULL, NULL, TRUE, 0, NULL, NULL, &sInfo, &pInfo)) //创建子进程
        {
            CloseHandle(hWrite);
            CloseHandle(hRead);
            return GetLastError();
        }
        CloseHandle(hWrite); //关闭父进程的写端

        
        for (int i = 0;; ++i)
        {
            if (!ReadFile(hRead, Buffer, sizeof(Buffer) - 1, &bytesRead, NULL)) //读取内容
            {
                break;
            }
            Buffer[bytesRead] = 0;
            printf("%s\n", Buffer);

        }

        WaitForSingleObject(pInfo.hProcess, INFINITE);//当等待仍在挂起状态时,句柄被关闭,那么函数行为是未定义的。该句柄必须具有 SYNCHRONIZE 访问权限;
    CloseHandle(hRead);
    system("pause");
    return 0;
}

 

posted @ 2016-04-01 21:32  Breeze0806  阅读(1058)  评论(0编辑  收藏  举报