Created
October 19, 2016 16:43
-
-
Save tokibito/ce7a936da6c3e64307d2b45fa9f33247 to your computer and use it in GitHub Desktop.
selectorsモジュールのサンプルコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import time | |
import fcntl | |
import selectors | |
read_fd, write_fd = os.pipe() | |
pid = os.fork() | |
if pid: | |
# 親プロセス | |
write_pipe = os.fdopen(write_fd, 'wb') | |
for b in b'hello': | |
time.sleep(2) | |
write_pipe.write(bytes([b])) | |
write_pipe.flush() | |
write_pipe.close() | |
else: | |
# 子プロセス | |
fcntl.fcntl(read_fd, fcntl.F_SETFL, os.O_NONBLOCK) | |
read_pipe = os.fdopen(read_fd, 'rb') | |
content = b'' | |
sel = selectors.DefaultSelector() | |
sel.register(read_fd, selectors.EVENT_READ) | |
while True: | |
events = sel.select() | |
for selector_key, mask in events: | |
if selector_key.fd != read_fd: | |
continue | |
data = read_pipe.read(5) | |
if data: | |
print(data) | |
content += data | |
if len(content) >= 5: | |
break | |
read_pipe.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment