Skip to content

Instantly share code, notes, and snippets.

@tokibito
Last active October 20, 2016 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokibito/5be1a5d71124b376f4fa62edd7a88cae to your computer and use it in GitHub Desktop.
Save tokibito/5be1a5d71124b376f4fa62edd7a88cae to your computer and use it in GitHub Desktop.
forkとpipeとepollのサンプルコード
import os
import sys
import time
import select
READ_ONLY = select.EPOLLIN
def main():
read_fd, write_fd = os.pipe2(os.O_NONBLOCK)
pid = os.fork()
if pid:
print("子PID: {}".format(pid))
# 親
os.close(read_fd)
write_pipe = os.fdopen(write_fd, 'wb')
for bit in b"hello":
time.sleep(2)
write_pipe.write(bytes([bit]))
write_pipe.flush()
write_pipe.close()
print("--end parent--")
else:
# 子
os.close(write_fd)
read_pipe = os.fdopen(read_fd, 'rb')
poller = select.epoll()
poller.register(read_fd, READ_ONLY)
bytes_read = 0
content = b""
done = False
while True:
events = poller.poll()
print(events)
for fd, event in events:
if fd != read_fd:
continue
read_data = read_pipe.read()
if read_data:
bytes_read += len(read_data)
print("読めた: {}".format(bytes_read))
content += read_data
if bytes_read >= 5:
done = True
break
if done:
break
read_pipe.close()
print(content)
print("--end child--")
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment