2013-11-04 32 views
4

我需要打開某個命名管道,以便模糊測試它,但是我的測試代碼無法訪問用於生成命名管道名稱的相同數據。但是,我可以識別管道的名稱,然後使用該名稱打開管道進行模糊處理。如何枚舉進程中所有命名管道的名稱?

我用這個論壇的帖子開始枚舉系統上的把手的名字: http://forum.sysinternals.com/howto-enumerate-handles_topic18892.html

但是似乎不會因爲某些原因命名管道的工作。

TL; DR:我需要使用哪些API列出Windows上當前進程中所有命名管道的名稱?

+0

您是否特別需要僅在當前進程中枚舉管道?我已經有一個用於Windows的命名管道枚舉,但它是系統範圍的。 – Keith4G

+0

我只需要遍歷當前進程中的命名管道,但我完全可以使用枚舉系統上的所有管道。 – mamidon

回答

2

這將枚舉系統中的所有命名管道,或者至少讓您朝正確的方向邁出一步。

在MinGW中使用-fpermissive構建時可以使用。它應該與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; 
} 
+0

我需要一點來驗證這適用於我,但它看起來很合理。我會在大約一兩天內積極解決這個問題。謝謝! – mamidon

+1

我只會注意到這在Windows上運行良好 - 對目標字符串進行了輕微修改。我不知道爲什麼OP使用這樣的宏。 – mamidon

+0

在該點的所有代碼中,「//./pipe/」和L「//./ pipe /」之間的切換很簡單。這並不是說它在樣本中很重要,因爲它很短。 – Keith4G