我想不出任何明显的方法来做到这一点。这里的原因...
壳牌从接收其输入,而其输出发送到,一些终端设备 :
+-----------+
| |
| bash |
| |
+-----------+
^|
| |
| v
+----------------------+
| some terminal device |
+----------------------+
当write
写到终端,它发送的数据直接到同一个终端设备。它不会去任何地方你的shell附近:
+-----------+ +-----------+
| | | |
| bash | | write |
| | | |
+-----------+ +-----------+
^| |
| | |
| v v
+----------------------+
| some terminal device |
+----------------------+
因此,为了让您能够捕捉到什么是write
发送,你需要通过终端设备本身提供了一些钩子,和我不没想到有什么可以用来做到这一点。
那么script
如何工作,为什么不捕获write
输出?
script
也无法挂入终端设备。它真的想在你的shell和你的终端之间进行自我介入,但是没有一个好的方法可以直接做到这一点。
因此,它创建了一个新的终端设备(一个伪终端,也被称为“pty”)并在其中运行一个新的shell。一个pty包含两个方面:“主”,它只是一个字节流,和一个“奴隶”,它看起来就像任何其他交互式终端设备。
新的外壳连接到从属端,而script
控制主端 - 这意味着它可以将字节流保存到文件中,并在新外壳和原始端子之间转发它们:
+-----------+
| |
| bash |
| |
+-----------+
^|
| |
| v
+-----------------+ <=== slave side of pty -- presents the interface of
| pseudo-terminal | an interactive terminal
+-----------------+ <=== master side of pty -- just a stream of bytes
^|
| v
+-----------+
| |
| script |
| |
+-----------+
^|
| |
| v
+----------------------+
| some terminal device |
+----------------------+
现在你可以看到一个write
到原来的终端设备绕过一切,就像它在上面的简单的情况下所做的:
+-----------+
| |
| bash |
| |
+-----------+
^|
| |
| v
+-----------------+ <=== slave side of pty -- presents the interface of
| pseudo-terminal | an interactive terminal
+-----------------+ <=== master side of pty -- just a stream of bytes
^|
| v
+-----------+ +-----------+
| | | |
| script | | write |
| | | |
+-----------+ +-----------+
^| |
| | |
| v v
+----------------------+
| some terminal device |
+----------------------+
如果你将数据写入到的从属面新的终端在这里,你的会看到输出显示出来,因为它会出现在主控端的数据流中,即script
看到的。您可以从script
内的shell中找到命令的新pty的名称。
不幸的是,这并不write
帮助,因为你可能会无法write
它:您的登录会话与原来的终端,而不是新的关联,并write
可能会抱怨你”没有登录。但是,如果你例如echo hello >/dev/pts/NNN
,您会看到它确实显示在script
输出中。
感谢您长时间详细的解释,我没有意识到'脚本'通过辅助伪终端工作,所以很有趣。我想我会尝试投入一些时间来查看是否让我的脚本检测到新的pty,并将其用于原来的目的,尽管将不得不尝试将'write'的功能复制到不关心ID的东西。 – 2011-06-01 06:14:17