管道重定向符“|”

来源:互联网 发布:数据透视表汇总 编辑:程序博客网 时间:2024/04/28 18:17

在 cmd.exe 的命令行模式下,管道重定向符“|”用于把一个命令的输出传递给另一个程序,比如,在查看一个比较长的文件时,需要把 type 命令的结果分页显示,这时候就需要把它重定向到 more 命令,如:

    type somefile.txt | more

    管道重定向符“|”的实质作用是把 type 的输出结果发送给 more 进程的标准输入句柄(STD_INPUT_HANDLE),more 进程则不断读取这个句柄的内容,并将读出的内容计算后分页输出。

    下面的示例代码 DbgPrint 示范了如何使用 STD_INPUT_HANDLE。

    // DbgPrint.cpp

    #include 〈Windows.h〉
    #include 〈tchar.h〉

    int main(void)
    {
        HANDLE hPipe = GetStdHandle(STD_INPUT_HANDLE);

        CHAR str[1024];
        DWORD dwRead;
        BOOL b;

        do
        {
            ZeroMemory(str, sizeof(str));
            b = ReadFile(hPipe, str, sizeof(str), &dwRead, NULL);

            if (b && dwRead 〉 0)
                OutputDebugStringA(str);
        } while (b && dwRead 〉 0);

        return 0;
    }

    代码编译完成后,可以在命令行中输入:

    dir | DbgPrint

    这样将会使 dir 的结果重定向到 DbgPrint 的标准输入句柄中,也就是由 OutputDebugStringA 来输出。

    最后说一句,最初我尝试在 do-while 中使用 ReadConsoleA 来获取管道输出,但是什么也得不到,而 ReadFile 则工作正常。查了一下 MSDN ,其中对 GetStdHandle 的解释有这么一句:

    These handles can be used by the ReadFile and WriteFile functions, or by any of the console functions that access the console input buffer or a screen buffer (for example, the ReadConsoleInput, WriteConsole, or GetConsoleScreenBufferInfo functions).

    如此看来,由 GetStdHandle 返回的句柄应该是不支持 ReadConsole 的。不过,我并没有再测试 ReadConsoleInput ,有兴趣的朋友们可以自己测试一下。

原创粉丝点击