在这个分叉的过程中,为什么不能从stdin中读取内容? [英] Why can I not read from stdin in this forked process?

查看:74
本文介绍了在这个分叉的过程中,为什么不能从stdin中读取内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码不打印任何内容,但应重复打印出"a".分叉的进程在os.read(0,1)上阻塞.父进程确实正在向stdin_master写入,但是stdin_slave什么也没收到.有什么想法吗?

The following code prints nothing, but it should print out "a" repeatedly. The forked process blocks on the os.read(0, 1). The parent process is indeed writing to the stdin_master, but stdin_slave receives nothing. Any ideas?

import os
import pty
import resource
import select
import signal
import time


stdin_master, stdin_slave = pty.openpty()
stdout_master, stdout_slave = pty.openpty()
stderr_master, stderr_slave = pty.openpty()

pid = os.fork()

# child process
if pid == 0:
    os.setsid()
    os.close(stdin_master)
    os.close(stdout_master)
    os.close(stderr_master)

    os.dup2(stdin_slave, 0)
    os.dup2(stdout_slave, 1)
    os.dup2(stderr_slave, 2)

    max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
    os.closerange(3, max_fd)


    while True:
        char = os.read(0, 1)
        os.write(1, char)

    os._exit(255)

# parent process
else:
    os.close(stdin_slave)
    os.close(stdout_slave)
    os.close(stderr_slave)

    try:
        while True:
            read, write, err = select.select([stdout_master], [stdin_master], [], 0)
            for to_read in read:
                print os.read(to_read, 1)

            for to_write in write:
                os.write(to_write, "a")

            time.sleep(0.1)

    finally:
        os.kill(pid, signal.SIGKILL)

推荐答案

Thomas Wouters很友善地提供了答案:

Thomas Wouters was kind enough to furnish the answer:

只能从主文件fd中读取PTY.因此,孩子的os.read(0,1)无法正常工作.如果我们更改

PTYs can only be read from the master fd. So the child's os.read(0, 1) was not working because of this. If we change

stdin_master, stdin_slave = pty.openpty()

stdin_slave, stdin_master = pty.openpty()

现在,chlid将从主机读取数据,而我们将从父级写入从机.这行得通.

Now the chlid will be reading from the master, and we'll be writing to the slave from the parent. This works.

这篇关于在这个分叉的过程中,为什么不能从stdin中读取内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆