What causes `read()` in `c` does not read content that being input by other processes from the current `tty`?

淺唱寂寞╮ 提交于 2019-12-11 15:17:54

问题


I imitated the check-password module from openssh source code and it uses read() to get the content from the current tty's file descriptor, here is the code:

#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;  
}  

It runs in a terminal like this:

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

While the other terminal sending strings redirecting to the first one like:

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

But read() does not actually works when there is another process wants to input. So what causes read() in c does not read content that being input by other processes from the current tty?

Perhaps I expressed not very clear in my previous question, but it is the same question I get stuck.

来源:https://stackoverflow.com/questions/55415122/what-causes-read-in-c-does-not-read-content-that-being-input-by-other-proc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!