Like os.pipe() but with overlapped support and using handles not fds.
(*, duplex=False, overlapped=(True, True), bufsize=BUFSIZE)
| 30 | |
| 31 | |
| 32 | def pipe(*, duplex=False, overlapped=(True, True), bufsize=BUFSIZE): |
| 33 | """Like os.pipe() but with overlapped support and using handles not fds.""" |
| 34 | if duplex: |
| 35 | openmode = _winapi.PIPE_ACCESS_DUPLEX |
| 36 | access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE |
| 37 | obsize, ibsize = bufsize, bufsize |
| 38 | else: |
| 39 | openmode = _winapi.PIPE_ACCESS_INBOUND |
| 40 | access = _winapi.GENERIC_WRITE |
| 41 | obsize, ibsize = 0, bufsize |
| 42 | |
| 43 | openmode |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE |
| 44 | |
| 45 | if overlapped[0]: |
| 46 | openmode |= _winapi.FILE_FLAG_OVERLAPPED |
| 47 | |
| 48 | if overlapped[1]: |
| 49 | flags_and_attribs = _winapi.FILE_FLAG_OVERLAPPED |
| 50 | else: |
| 51 | flags_and_attribs = 0 |
| 52 | |
| 53 | h1 = h2 = None |
| 54 | try: |
| 55 | for attempts in itertools.count(): |
| 56 | address = r'\\.\pipe\python-pipe-{:d}-{:d}-{}'.format( |
| 57 | os.getpid(), next(_mmap_counter), os.urandom(8).hex()) |
| 58 | try: |
| 59 | h1 = _winapi.CreateNamedPipe( |
| 60 | address, openmode, _winapi.PIPE_WAIT, |
| 61 | 1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL) |
| 62 | break |
| 63 | except OSError as e: |
| 64 | if attempts >= _MAX_PIPE_ATTEMPTS: |
| 65 | raise |
| 66 | if e.winerror not in (_winapi.ERROR_PIPE_BUSY, |
| 67 | _winapi.ERROR_ACCESS_DENIED): |
| 68 | raise |
| 69 | |
| 70 | h2 = _winapi.CreateFile( |
| 71 | address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING, |
| 72 | flags_and_attribs, _winapi.NULL) |
| 73 | |
| 74 | ov = _winapi.ConnectNamedPipe(h1, overlapped=True) |
| 75 | ov.GetOverlappedResult(True) |
| 76 | return h1, h2 |
| 77 | except: |
| 78 | if h1 is not None: |
| 79 | _winapi.CloseHandle(h1) |
| 80 | if h2 is not None: |
| 81 | _winapi.CloseHandle(h2) |
| 82 | raise |
| 83 | |
| 84 | |
| 85 | # Wrapper for a pipe handle |