您的位置:首页 > 其它

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

2010-12-12 20:10 316 查看
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cmd null delete