문제

익명 파이프에 중첩된 I/O를 사용할 수 있습니까?CreatePipe()에는 FILE_FLAG_OVERLAPPED를 지정할 방법이 없으므로 OVERLAPPED 구조를 제공하더라도 ReadFile()이 차단될 것이라고 가정합니다.

도움이 되었습니까?

해결책

다음은 FILE_FLAG_OVERLAPPED를 지정할 수 있는 익명 파이프 함수의 구현입니다.

/******************************************************************************\
*       This is a part of the Microsoft Source Code Samples. 
*       Copyright 1995 - 1997 Microsoft Corporation.
*       All rights reserved. 
*       This source code is only intended as a supplement to 
*       Microsoft Development Tools and/or WinHelp documentation.
*       See these sources for detailed information regarding the 
*       Microsoft samples programs.
\******************************************************************************/

/*++
Copyright (c) 1997  Microsoft Corporation
Module Name:
    pipeex.c
Abstract:
    CreatePipe-like function that lets one or both handles be overlapped
Author:
    Dave Hart  Summer 1997
Revision History:
--*/

#include <windows.h>
#include <stdio.h>

ULONG PipeSerialNumber;

BOOL
APIENTRY
MyCreatePipeEx(
    OUT LPHANDLE lpReadPipe,
    OUT LPHANDLE lpWritePipe,
    IN LPSECURITY_ATTRIBUTES lpPipeAttributes,
    IN DWORD nSize,
    DWORD dwReadMode,
    DWORD dwWriteMode
    )

/*++
Routine Description:
    The CreatePipeEx API is used to create an anonymous pipe I/O device.
    Unlike CreatePipe FILE_FLAG_OVERLAPPED may be specified for one or
    both handles.
    Two handles to the device are created.  One handle is opened for
    reading and the other is opened for writing.  These handles may be
    used in subsequent calls to ReadFile and WriteFile to transmit data
    through the pipe.
Arguments:
    lpReadPipe - Returns a handle to the read side of the pipe.  Data
        may be read from the pipe by specifying this handle value in a
        subsequent call to ReadFile.
    lpWritePipe - Returns a handle to the write side of the pipe.  Data
        may be written to the pipe by specifying this handle value in a
        subsequent call to WriteFile.
    lpPipeAttributes - An optional parameter that may be used to specify
        the attributes of the new pipe.  If the parameter is not
        specified, then the pipe is created without a security
        descriptor, and the resulting handles are not inherited on
        process creation.  Otherwise, the optional security attributes
        are used on the pipe, and the inherit handles flag effects both
        pipe handles.
    nSize - Supplies the requested buffer size for the pipe.  This is
        only a suggestion and is used by the operating system to
        calculate an appropriate buffering mechanism.  A value of zero
        indicates that the system is to choose the default buffering
        scheme.
Return Value:
    TRUE - The operation was successful.
    FALSE/NULL - The operation failed. Extended error status is available
        using GetLastError.
--*/

{
  HANDLE ReadPipeHandle, WritePipeHandle;
  DWORD dwError;
  UCHAR PipeNameBuffer[ MAX_PATH ];

  //
  // Only one valid OpenMode flag - FILE_FLAG_OVERLAPPED
  //

  if ((dwReadMode | dwWriteMode) & (~FILE_FLAG_OVERLAPPED)) {
    SetLastError(ERROR_INVALID_PARAMETER);
    return FALSE;
  }

  //
  //  Set the default timeout to 120 seconds
  //

  if (nSize == 0) {
    nSize = 4096;
  }

  sprintf( PipeNameBuffer,
           "\\\\.\\Pipe\\RemoteExeAnon.%08x.%08x",
           GetCurrentProcessId(),
           PipeSerialNumber++
         );

  ReadPipeHandle = CreateNamedPipeA(
                       PipeNameBuffer,
                       PIPE_ACCESS_INBOUND | dwReadMode,
                       PIPE_TYPE_BYTE | PIPE_WAIT,
                       1,             // Number of pipes
                       nSize,         // Out buffer size
                       nSize,         // In buffer size
                       120 * 1000,    // Timeout in ms
                       lpPipeAttributes
                       );

  if (! ReadPipeHandle) {
    return FALSE;
  }

  WritePipeHandle = CreateFileA(
                      PipeNameBuffer,
                      GENERIC_WRITE,
                      0,                         // No sharing
                      lpPipeAttributes,
                      OPEN_EXISTING,
                      FILE_ATTRIBUTE_NORMAL | dwWriteMode,
                      NULL                       // Template file
                    );

  if (INVALID_HANDLE_VALUE == WritePipeHandle) {
    dwError = GetLastError();
    CloseHandle( ReadPipeHandle );
    SetLastError(dwError);
    return FALSE;
  }

  *lpReadPipe = ReadPipeHandle;
  *lpWritePipe = WritePipeHandle;
  return( TRUE );
}

다른 팁

아니요.설명대로 여기, 익명 파이프는 비동기 I/O를 지원하지 않습니다.명명된 파이프를 사용해야 합니다.MSDN에는 이를 수행하는 예제 코드가 있습니다. 여기 그리고 여기.

우선 이해가 필요합니다 - 무엇입니까 익명 파이프 그리고 익명과 익명의 차이점은 무엇입니까? 명명된 파이프 조금도.

정말로 존재하는 것만 단일 파이프 유형 (구현된 npfs.sys).명명된 파이프와 익명 파이프 사이에는 이름을 제외하고는 아무런 차이가 없습니다.둘 다 파이프일 뿐이다.

소위 익명 파이프 - 이것은 win7 이전의 특수/임의 명명된 파이프이고 실제 명명되지 않은 파이프는 win7부터 시작됩니다.

msdn이 그걸 쓸 때 "익명 파이프는 단방향 파이프입니다" - 이것은 거짓말하다.모든 파이프는 단방향 또는 이중일 수 있습니다.msdn이 그걸 쓸 때 "비동기(중복) 읽기 및 쓰기 작업은 익명 파이프에서 지원되지 않습니다." - 이것은 거짓말하다.물론 파이프는 비동기식 io를 지원합니다.파이프 이름은 이에 영향을 미치지 않습니다.

win7 이전에는 실제로 이름이 지정되지 않은 파이프가 전혀 존재하지도 않았습니다. CreatePipe 기능 사용 Win32Pipes.%08x.%08x "Anonymous Pipe"라는 이름을 만들기 위한 형식입니다.

    static LONG PipeSerialNumber;
    WCHAR name[64];
    swprintf(name, L"\\Device\\NamedPipe\\Win32Pipes.%08x.%08x", 
        GetCurrentProcessId(), InterlockedIncrement(&PipeSerialNumber));

win7부터 시작하세요 CreatePipe 파이프 쌍을 생성하려면 다른 기술(상대 파일 열기)을 사용하십시오. 이제는 실제로 익명입니다.

예를 들어 코드 마녀는 하나의 파이프가 비동기적이고 상속할 수 없는 파이프 쌍을 만듭니다.또 다른 파이프는 동기적이고 상속 가능합니다.두 파이프 모두 이중입니다(읽기 및 쓰기 모두 지원).

ULONG CreatePipeAnonymousPair7(PHANDLE phServerPipe, PHANDLE phClientPipe)
{
    HANDLE hNamedPipe;

    IO_STATUS_BLOCK iosb;

    static UNICODE_STRING NamedPipe = RTL_CONSTANT_STRING(L"\\Device\\NamedPipe\\");

    OBJECT_ATTRIBUTES oa = { sizeof(oa), 0, const_cast<PUNICODE_STRING>(&NamedPipe), OBJ_CASE_INSENSITIVE };

    NTSTATUS status;

    if (0 <= (status = NtOpenFile(&hNamedPipe, SYNCHRONIZE, &oa, &iosb, FILE_SHARE_VALID_FLAGS, 0)))
    {
        oa.RootDirectory = hNamedPipe;

        static LARGE_INTEGER timeout = { 0, MINLONG };
        static UNICODE_STRING empty = {};

        oa.ObjectName = &empty;

        if (0 <= (status = ZwCreateNamedPipeFile(phServerPipe,
            FILE_READ_ATTRIBUTES|FILE_READ_DATA|
            FILE_WRITE_ATTRIBUTES|FILE_WRITE_DATA|
            FILE_CREATE_PIPE_INSTANCE, 
            &oa, &iosb, FILE_SHARE_READ|FILE_SHARE_WRITE,
            FILE_CREATE, 0, FILE_PIPE_BYTE_STREAM_TYPE, FILE_PIPE_BYTE_STREAM_MODE,
            FILE_PIPE_QUEUE_OPERATION, 1, 0, 0, &timeout)))
        {
            oa.RootDirectory = *phServerPipe;
            oa.Attributes = OBJ_CASE_INSENSITIVE|OBJ_INHERIT;

            if (0 > (status = NtOpenFile(phClientPipe, SYNCHRONIZE|FILE_READ_ATTRIBUTES|FILE_READ_DATA|
                FILE_WRITE_ATTRIBUTES|FILE_WRITE_DATA, &oa, &iosb, 
                FILE_SHARE_VALID_FLAGS, FILE_SYNCHRONOUS_IO_NONALERT)))
            {
                NtClose(oa.RootDirectory);
            }
        }

        NtClose(hNamedPipe);
    }

    return RtlNtStatusToDosError(status);
}

ULONG CreatePipeAnonymousPair(PHANDLE phServerPipe, PHANDLE phClientPipe)
{
    static char flag_supported = -1;

    if (flag_supported < 0)
    {
        ULONG dwMajorVersion, dwMinorVersion;
        RtlGetNtVersionNumbers(&dwMajorVersion, &dwMinorVersion, 0);
        flag_supported = _WIN32_WINNT_WIN7 <= ((dwMajorVersion << 8)| dwMinorVersion);
    }

    if (flag_supported)
    {
        return CreatePipeAnonymousPair7(phServerPipe, phClientPipe);
    }

    static LONG PipeSerialNumber;

    WCHAR name[64];

    swprintf(name, L"\\\\?\\pipe\\Win32Pipes.%08x.%08x", GetCurrentProcessId(), InterlockedIncrement(&PipeSerialNumber));

    HANDLE hClient, hServer = CreateNamedPipeW(name, 
        PIPE_ACCESS_DUPLEX|FILE_READ_DATA|FILE_WRITE_DATA|FILE_FLAG_OVERLAPPED, 
        PIPE_TYPE_BYTE|PIPE_READMODE_BYTE, 1, 0, 0, 0, 0);

    if (hServer != INVALID_HANDLE_VALUE)
    {
        static SECURITY_ATTRIBUTES sa = { sizeof(sa), 0, TRUE };

        hClient = CreateFileW(name, FILE_GENERIC_READ|FILE_GENERIC_WRITE, 
            FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, 0);

        if (hClient != INVALID_HANDLE_VALUE)
        {
            *phServerPipe = hServer, *phClientPipe = hClient;
            return NOERROR;
        }

        CloseHandle(hServer);
    }

    return GetLastError();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top