gpt4 book ai didi

python pty.fork - 它是如何工作的

转载 作者:太空狗 更新时间:2023-10-29 20:38:22 25 4
gpt4 key购买 nike

http://docs.python.org/library/pty.html说——

pty.fork()¶ Fork. Connect the child’s controlling terminal to a pseudo-terminal. Return value is (pid, fd). Note that the child gets pid 0, and the fd is invalid. The parent’s return value is the pid of the child, and fd is a file descriptor connected to the child’s controlling terminal (and also to the child’s standard input and output).

这是什么意思?每个进程都有 3 个 fd(stdin、stdout、stderr)。现在这会影响这些 fds 吗?子进程不会有任何这些 fds 吗?我很困惑。--完全。

最佳答案

我想我终于在 Python 中得到了 pty.fork 的最小示例 - 因为我发现很难找到类似的示例,所以我将它张贴在这里作为 @joni 的示例回答。它主要基于:

特别令人讨厌的是发现仍然引用过时的 master_open() 的文档; pty.fork 不会生成子进程的事实,除非文件描述符(由 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()

好吧,希望这对某人有帮助,
干杯!

关于python pty.fork - 它是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4022600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com