私はついにpty.fork
Pythonで最小限の例を手に入れたと思います.同様の例を見つけるのは非常に難しいことがわかったので、@joniの回答の実例としてここに投稿しています. それは基本的に以下に基づいています。
特に厄介な点master_open()
は、古いドキュメントをまだ参照しているドキュメントを見つけることです。そして、ファイル記述子 ( fork メソッドによって返される) が親プロセスによって読み取られない限り、子プロセスを生成しpty.fork
ないという事実! (そのような要件がないことに注意してください)また、移植性が少し高いようです(一部のプラットフォームでは機能しないことに注意してください)。os.fork
os.fork
pty.fork
とにかく、最初にpyecho.py
、実行可能ファイルとして機能するスクリプト ( ) を示します (標準入力から行を読み取り、大文字で書き戻すだけです)。
#!/usr/bin/env python
# pyecho.py
import sys;
print "pyecho starting..."
while True:
print sys.stdin.readline().upper()
...そして、これが実際のスクリプトです(pyecho.pyが同じディレクトリにある必要があります):
#!/usr/bin/env python
import sys
import os
import time
import pty
def my_pty_fork():
# fork this script
try:
( child_pid, fd ) = pty.fork() # OK
#~ child_pid, fd = os.forkpty() # OK
except OSError as e:
print str(e)
#~ print "%d - %d" % (fd, child_pid)
# NOTE - unlike OS fork; in pty fork we MUST use the fd variable
# somewhere (i.e. in parent process; it does not exist for child)
# ... actually, we must READ from fd in parent process...
# if we don't - child process will never be spawned!
if child_pid == 0:
print "In Child Process: PID# %s" % os.getpid()
# note: fd for child is invalid (-1) for pty fork!
#~ print "%d - %d" % (fd, child_pid)
# the os.exec replaces the child process
sys.stdout.flush()
try:
#Note: "the first of these arguments is passed to the new program as its own name"
# so:: "python": actual executable; "ThePythonProgram": name of executable in process list (`ps axf`); "pyecho.py": first argument to executable..
os.execlp("python","ThePythonProgram","pyecho.py")
except:
print "Cannot spawn execlp..."
else:
print "In Parent Process: PID# %s" % os.getpid()
# MUST read from fd; else no spawn of child!
print os.read(fd, 100) # in fact, this line prints out the "In Child Process..." sentence above!
os.write(fd,"message one\n")
print os.read(fd, 100) # message one
time.sleep(2)
os.write(fd,"message two\n")
print os.read(fd, 10000) # pyecho starting...\n MESSAGE ONE
time.sleep(2)
print os.read(fd, 10000) # message two \n MESSAGE TWO
# uncomment to lock (can exit with Ctrl-C)
#~ while True:
#~ print os.read(fd, 10000)
if __name__ == "__main__":
my_pty_fork()
さて、これが誰かに役立つことを願っています、
乾杯!