将CMD的输入输出重定向到自己的进程

简介: void CreateMyPipe(){    //创建管道    CreatePipe(&hReadPipe, &hWritePipe, NULL, NULL);    CreatePipe...
void CreateMyPipe()
{
    //创建管道
    CreatePipe(&hReadPipe, &hWritePipe, NULL, NULL);
    CreatePipe(&hChildReadPipe, &hChildWritePipe, NULL, NULL);


    SetHandleInformation(hWritePipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
    SetHandleInformation(hChildReadPipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);


    DWORD dwWord = PIPE_NOWAIT;
    SetNamedPipeHandleState(hReadPipe, &dwWord, NULL, NULL);


    //创建CMD进程
    PROCESS_INFORMATION stProcessInfo;
    STARTUPINFO stStartInfo;
    ::ZeroMemory(&stStartInfo,sizeof(stStartInfo));


    stStartInfo.cb = sizeof(stStartInfo);
    stStartInfo.dwFlags = STARTF_USESTDHANDLES;//STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
    stStartInfo.hStdError = hWritePipe;
    stStartInfo.hStdOutput = hWritePipe;
    stStartInfo.hStdInput = hChildReadPipe;


    if(!CreateProcessA(NULL, "cmd.exe/0", NULL, NULL, true, DETACHED_PROCESS, NULL, NULL, &stStartInfo, &stProcessInfo))
    {
        MessageBox("启动进程失败!");
        return;
    }else{
        CloseHandle(stProcessInfo.hThread);
        CloseHandle(stProcessInfo.hProcess);
    }


    //从管道中读出数据, 该数据通常为CMD的版本及版权信息
    ReadFromChildPipe();
}


void ReadFromChildPipe()
{
    //读取管道中所有可读取的数据并写入到txtMessage中
    DWORD nRead;
    char* strBuffer = new char[65536];
    long nBufferLen;


    nRead = -1;
    while(nRead != 0)
    {
        nBufferLen = 65536;
        memset(strBuffer, 0, 65536);
        Sleep(30);


        ReadFile(hReadPipe, strBuffer, nBufferLen, &nRead, NULL);
        if(nRead != 0)
        {
            GetDlgItem(IDC_EDIT_MSG)->SetWindowTextA(strBuffer);
        }
    }


    delete[] strBuffer;
}


void WriteMyPipe()
{
    //将命令写入管道
    DWORD nWrite;
    char* strBuffer = new char[300];
    memset(strBuffer, 0, 300);
    memcpy(strBuffer, "dir/r/n", 5);


    if (WriteFile(hChildWritePipe, strBuffer, 5, &nWrite, NULL))
    {
        ReadFromChildPipe();
    }else{
        MessageBox("写入失败");
    }


    delete[] strBuffer;
}


HANDLE hReadPipe;
HANDLE hWritePipe;
HANDLE hChildReadPipe;
HANDLE hChildWritePipe;


CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
CloseHandle(hChildReadPipe);
CloseHandle(hChildWritePipe);
目录
相关文章
|
10月前
|
Windows
|
Windows
Windows 技术篇-cmd强制关闭端口、解除端口占用方法,cmd查询端口相关的进程pid并杀死进程实例演示
Windows 技术篇-cmd强制关闭端口、解除端口占用方法,cmd查询端口相关的进程pid并杀死进程实例演示
742 0
Windows 技术篇-cmd强制关闭端口、解除端口占用方法,cmd查询端口相关的进程pid并杀死进程实例演示
|
5天前
|
存储 Linux Shell
Linux:进程等待 & 进程替换
Linux:进程等待 & 进程替换
29 9
|
5天前
|
存储 Linux C语言
Linux:进程创建 & 进程终止
Linux:进程创建 & 进程终止
24 6
|
3天前
|
Unix Linux 调度
linux线程与进程的区别及线程的优势
linux线程与进程的区别及线程的优势
|
4天前
|
存储 安全 Linux
【Linux】详解进程通信中信号量的本质&&同步和互斥的概念&&临界资源和临界区的概念
【Linux】详解进程通信中信号量的本质&&同步和互斥的概念&&临界资源和临界区的概念