在没有关闭pty的情况下指示不再输入

时间:2013-08-14 07:38:47

标签: linux io pty

当使用PTY主/从对控制进程时,我想向相关进程指出stdin已关闭,我没有更多内容要发送,但我仍然希望从进程接收输出。

问题是我只有一个文件描述符(PTY“master”),它处理来自子进程的输入和输出到子进程。因此关闭描述符会关闭两者。

python中的示例:

import subprocess, pty, os
master,slave = pty.openpty()
proc = subprocess.Popen(["/bin/cat"], stdin=slave, stdout=slave)
os.close(slave)  # now belongs to child process
os.write(master,"foo")
magic_close_fn(master)  # <--- THIS is what I want
while True:
    out = os.read(master,4096)
    if out: 
        print out
    else: 
        break
proc.wait()

2 个答案:

答案 0 :(得分:0)

您需要获得单独的读写文件描述符。这样做的简单方法是使用管道和PTY。所以现在你的代码看起来像这样:

import subprocess, pty, os
master, slave = pty.openpty()
child_stdin, parent_stdin = os.pipe()
proc = subprocess.Popen(["/bin/cat"], stdin=child_stdin, stdout=slave)
os.close(child_stdin)  # now belongs to child process
os.close(slave)
os.write(parent_stdin,"foo") #Write to the write end (our end) of the child's stdin
#Here's the "magic" close function
os.close(parent_stdin)
while True:
    out = os.read(master,4096)
    if out: 
        print out
    else: 
        break
proc.wait()

答案 1 :(得分:0)

我认为你想要的是发送CTRL-D(EOT - End Of Transmission)字符,不是吗?这将在某些应用程序中关闭输入,但其他应用程序将退出。

perl -e 'print qq,\cD,'

或纯粹的shell:

echo -e '\x04' | nc localhost 8080

两者都只是例子。 BTW CTRL-D特征是六进制\x04