What causes `read()` in `c` does not read content

2019-08-27 23:11发布

问题:

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.