Skip to content

Instantly share code, notes, and snippets.

@tokibito
Created October 20, 2016 15:16
Show Gist options
  • Save tokibito/6b726e99995504826da88c15e01ddca9 to your computer and use it in GitHub Desktop.
Save tokibito/6b726e99995504826da88c15e01ddca9 to your computer and use it in GitHub Desktop.
forkとpipeモジュールのサンプル(fd閉じるようにしたやつ)
import os
import time
import fcntl
import select
read_fd, write_fd = os.pipe()
pid = os.fork()
if pid:
# 親プロセス
# 読み込み側のfdは使わないのでclose
os.close(read_fd)
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:
# 子プロセス
# 書き込み側のfdは使わないのでclose
os.close(write_fd)
fcntl.fcntl(read_fd, fcntl.F_SETFL, os.O_NONBLOCK)
read_pipe = os.fdopen(read_fd, 'rb')
content = b''
poller = select.poll()
poller.register(read_fd, select.POLLIN)
while True:
events = poller.poll()
for fd, event in events:
if fd != read_fd:
continue
data = read_pipe.read()
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