如何枚举进程中所有命名管道的名称

How to Enumerate Names of All Named Pipes in a Process?

本文关键字:管道 枚举进程      更新时间:2023-10-16

我需要打开某个命名管道,以便我可以模糊测试它,但是我的测试代码无法访问用于生成命名管道名称的相同数据。 但是,我可以识别管道的名称,然后使用该名称打开管道进行模糊测试。

我使用这个论坛帖子开始枚举系统上句柄的名称:http://forum.sysinternals.com/howto-enumerate-handles_topic18892.html

但是,由于某种原因,这似乎不适用于命名管道。

TL;DR:我需要使用什么 API 来列出 Windows 上当前进程中所有命名管道的名称?

这将枚举系统中的所有命名管道,或者至少使您朝着正确的方向迈出一步。

当使用 -permissive 构建时,这在 MinGW 中有效。它应该适用于 MSVC 中的类似设置。

#ifndef _WIN32_WINNT
// Windows XP
#define _WIN32_WINNT 0x0501
#endif
#include <Windows.h>
#include <Psapi.h>

// mycreatepipeex.c is at http://www.davehart.net/remote/PipeEx.c
// I created a simple header based on that.    
#include "mycreatepipeex.h"
#include <iostream>
#include <cstdio>
#include <errno.h>
void EnumeratePipes()
{
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind;
#define TARGET_PREFIX "//./pipe/"
    const char *target = TARGET_PREFIX "*";
    memset(&FindFileData, 0, sizeof(FindFileData));
    hFind = FindFirstFileA(target, &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE) 
    {
        std::cerr << "FindFirstFileA() failed: " << GetLastError() << std::endl;
        return;
    }
    else 
    {
        do
        {
            std::cout << "Pipe: " << TARGET_PREFIX << FindFileData.cFileName << std::endl;
        }
        while (FindNextFile(hFind, &FindFileData));
        FindClose(hFind);
    }
#undef TARGET_PREFIX
    return;
}
int main(int argc, char**argv)
{
    HANDLE read = INVALID_HANDLE_VALUE;
    HANDLE write = INVALID_HANDLE_VALUE;
    unsigned char pipe_name[MAX_PATH+1];
    BOOL success = MyCreatePipeEx(&read, &write, NULL, 0, 0, 0, pipe_name);
    EnumeratePipes();
    if ( success == FALSE )
    {
        std::cerr << "MyCreatePipeEx() failed: " << GetLastError() << std::endl;
        return 1;
    }
    FILE *f = fopen((const char*)pipe_name, "rwb");
    if ( f == NULL )
    {
        std::cerr << "fopen("" << pipe_name << "") failed: " << (int)errno << std::endl;
    }
    CloseHandle(read);
    CloseHandle(write);
    return 0;
}