将匿名管道手柄传递给子进程

问题描述 投票:1回答:1

我想将一个匿名的Pipe HANDLE传递给Child Process。 This答案似乎很好地解释了C ++,但是我想在C中做到这一点。

我将句柄转换为整数吗?或者我将HANDLE的内存地址传递给子进程,然后再指向另一个HANDLE?

例如:

家长:

    BOOL bCreatePipe, bReadFile;
    HANDLE hRead = NULL;
    HANDLE hWrite = NULL;
    SECURITY_ATTRIBUTES lpPipeAttributes;
    lpPipeAttributes.nLength = sizeof(lpPipeAttributes);
    lpPipeAttributes.lpSecurityDescriptor = NULL;
    lpPipeAttributes.bInheritHandle = TRUE;

    // Create pipe file descriptors for parent and child
    bCreatePipe = CreatePipe(&hRead, &hWrite, &lpPipeAttributes, (DWORD)BUFFER_SIZE);
    if (bCreatePipe == FALSE) {
        printf("[-]Error creating IPC pipe : %d", GetLastError());
        exit(-1);
    }

    // Create command line arguments for child process
    snprintf(child_cmd, CMD_LINE_SIZE, "%d", &hWrite);

    // Create child process to handle request
    if ( !CreateProcess(
         "C:\\Users\\Child.exe",        // No module name (use command line)
         child_cmd,      // Command line
         NULL,           // Process handle not inheritable
         NULL,           // Thread handle not inheritable
         TRUE,           // Set handle inheritance to TRUE (for pipe)
         0,              // No creation flags
         NULL,           // Use parent's environment block
         NULL,           // Use parent's starting directory
         &si,            // Pointer to STARTUPINFO structure
         &pi)            // Pointer to PROCESS_INFORMATION structure
         )
    {
        printf("[-]CreateProcess failed : %d\n", GetLastError());
        exit(-1);
    }

儿童:

// Set variables to arguements passed by parent 
HANDLE hWrite = atoi(argv[0]);
c windows
1个回答
1
投票

是的,这可以通过值传递HANDLE。在实践中,目前您的代码将正常工作。但是需要记住,HANDLE在64位系统上是64位大小 - 所以不适合32位大小的int(现在用户模式处理值实际上适合32位)。所以需要使用说%I64x格式来编码句柄值和_atoi64_wcstoi64来解码。

例如在父母:

WCHAR child_cmd[32];
swprintf(child_cmd, L"<%I64x>", (ULONG64)(ULONG_PTR)hWrite);

在孩子:

HANDLE hWrite = 0;
if (PWSTR sz = wcschr(GetCommandLineW(), '<'))
{
    hWrite = (HANDLE)(ULONG_PTR)_wcstoi64(sz + 1, &sz, 16);
    if (*sz != '>')
    {
        hWrite = 0;
    }
}

作为单独的注释 - 使用CreatePipe不是最好的选择 - 这个api非常糟糕的设计,比如一个句柄只用于写入,另一个只用于读取,不能选择异步I / O,不能使一个句柄继承而另一个不能(因为需要)这种情况) - 更好地使用CreateNamedPipeW + CreateFileW来创建管道对。或this方式,如果你不想管道上的名字(从win7工作)

© www.soinside.com 2019 - 2024. All rights reserved.