我可以复制输入文件描述符并将其用于写入数据吗?

我可以复制输入文件描述符并将其用于写入数据吗?

以下命令复制输入文件描述符,并使用复制的文件描述符echo将命令中的数据写入终端。

sh-4.2$ 执行 6<&0
sh-4.2$ 回显“你好”>&6
你好

这是否意味着我们可以使用输入文件描述符写入终端?

答案1

这是否意味着我们可以使用输入文件描述符写入终端?

当然。您可以使用任何打开的文件描述符写入终端(实际上是支持和授权写入的任何文件或管道或设备或套接字)。您的代码的更简单版本将是这样的:

echo hello >&0

正如您所期望的,它将“hello\n”发送到 0 指向的任何文件描述符。如果那是您的终端,那就这样吧。

答案2

这是我对一个问题的回答的副本类似的问题去年在 stackoverflow 上。

由于历史习惯,您可以写入终端设备的标准输入。这是发生的事情:

当用户登录类 Unix 系统上的终端,或者在 X11 下打开终端窗口时,文件描述符 0、1、2 会连接到终端设备,并且每个文件描述符都会被打开阅读和写作。情况是这样的尽管通常只从 fd 0 读取并写入 fd 1 和 2

这是来自的代码第 7 版 init.c

open(tty, 2);
dup(0);
dup(0);
...
execl(getty, minus, tty, (char *)0);

这是如何ssh实现的:

ioctl(*ttyfd, TCSETCTTY, NULL);
fd = open("/dev/tty", O_RDWR);
if (fd < 0)
    error("%.100s: %.100s", tty, strerror(errno));
close(*ttyfd);
*ttyfd = fd;
...
/* Redirect stdin/stdout/stderr from the pseudo tty. */
if (dup2(ttyfd, 0) < 0) 
    error("dup2 stdin: %s", strerror(errno));
if (dup2(ttyfd, 1) < 0) 
    error("dup2 stdout: %s", strerror(errno));
if (dup2(ttyfd, 2) < 0) 
    error("dup2 stderr: %s", strerror(errno));

(该dup2函数将 arg1 复制到 arg2 中,如有必要,首先关闭 arg2。)

这是如何xterm实现的:

if ((ttyfd = open(ttydev, O_RDWR)) >= 0) {
    /* make /dev/tty work */
    ioctl(ttyfd, TCSETCTTY, 0);
...
/* this is the time to go and set up stdin, out, and err
 */
{
/* dup the tty */
for (i = 0; i <= 2; i++)
    if (i != ttyfd) {
    IGNORE_RC(close(i));
    IGNORE_RC(dup(ttyfd));
    }
/* and close the tty */
if (ttyfd > 2)
    close_fd(ttyfd);

相关内容