首页 > 解决方案 > 是什么原因导致 `c` 中的 `read()` 没有从当前的 `tty` 读取其他进程正在输入的内容?

问题描述

我从 openssh 源代码中模仿了 check-password 模块,它用于read()从当前 tty 的文件描述符中获取内容,代码如下:

#include <unistd.h>  
#include <stdio.h> 
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main ()   
{   
    int ttyfd=open("/dev/tty", O_RDWR);
    if(ttyfd>=0)
        printf("good to open\n");

    char * a;
    while(read (ttyfd,a,1)){
        printf("%s", a);
    }

    return 0;  
}  

它在这样的终端中运行:

root@localhost:~/Desktop# tty
/dev/pts/0
root@localhost:~/Desktop# ./a.out 
good to open
11111111111
11111111111
^C
root@localhost:~/Desktop# 

而另一个终端发送的字符串重定向到第一个,例如:

root@localhost:~# echo 11111111111 >> /dev/pts/0
root@localhost:~# echo 11111111111 >> /dev/pts/0

但是read()当有另一个进程要输入时实际上不起作用。那么是什么原因导致read()c从当前读取其他进程正在输入的内容tty呢?

也许我在上一个问题中表达的不是很清楚,但这是我卡住的同一个问题。

标签: clinuxopensshtty

解决方案


推荐阅读