我可以複製輸入檔案描述符並將其用於寫入資料嗎?

我可以複製輸入檔案描述符並將其用於寫入資料嗎?

以下命令複製輸入檔案描述符,並使用複製的檔案描述符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);

相關內容