简体   繁体   English

无法使用read()系统调用从其他终端读取数据

[英]Not able to read data from other terminal using read() system call

Hi everyone I am running the following code on pseudo terminal /dev/pts/1 and I am tryin to read the contents from the terminal /dev/pts/2 . 大家好,我在伪终端/dev/pts/1上运行以下代码,并且尝试从终端/dev/pts/2读取内容。

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>

int main(){

char str[50];

int fd = open("/dev/pts/2",O_RDONLY);
str[read(fd,str,20)] = '\0';

printf("%s\n",str);


return 0;

} }

anirudh@anirudh-Aspire-5920:~$ gcc test.c
anirudh@anirudh-Aspire-5920:~$ ./a.out
n
anirudh@anirudh-Aspire-5920:~$ 

On the terminal /dev/pts/2 I had typed "anirudh" however it showed "airudh" on that and the missing character n was displayed on the terminal /dev/pts/1 . 在终端/dev/pts/2我键入了“ anirudh”,但是在其上显示了“ airudh”,并且在终端/dev/pts/1上显示了丢失的字符n However when I try to read from the terminal /dev/pts/1 I can read every character properly. 但是,当我尝试从终端/dev/pts/1读取时,我可以正确读取每个字符。 So I am not able to understand the behavior of this program. 因此,我无法理解该程序的行为。 Please help me out. 请帮帮我。 Thanks in advance. 提前致谢。 :) :)

First, you probably have another process reading from /dev/pts/2 and thus characters are send to it and not yours. 首先,您可能有另一个从/ dev / pts / 2读取的进程,因此将字符发送给它,而不是您的。 Then the terminal is probably set in read "char per char" mode by that other process (that's what some shell do), you are reading just one character. 然后,该终端可能通过其他过程(这是某些shell所做的)设置为读取“每个字符一个字符”模式,您只读取一个字符。

Wow. 哇。 First, it is a general good rule: check what syscalls are returned to you. 首先,这是一个普遍的好规则:检查返回给您的是什么系统调用。 Alaways. 阿拉维斯。

int main(){

    char str[50];

    int fd = open("/dev/pts/2",O_RDONLY);
    if (fd == -1) {
        perror("open");
        ...
    }

Second, read may return fewer bytes than you request, look at the man: 其次,读取可能返回的字节数少于您请求的字节数,请查看man:

It is not an error if this number is smaller than the number of bytes requested; 如果此数目小于请求的字节数,这不是错误; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. 例如,这可能是因为当前实际可用的字节较少(可能是因为我们接近文件末尾,或者因为我们正在从管道或终端读取),或者因为read()被a中断了。信号。

So even 1 byte may be returned from read. 因此,即使读取也可能返回1个字节。 Third, read may return -1: 第三,读取可能返回-1:

On error, -1 is returned, and errno is set appropriately. 如果出错,则返回-1,并正确设置errno。

So I guess it's better to write: 因此,我认为最好写:

    ssize_t nread;
    if ((nread = read(fd, str, 20) > 0)) {
       str[nread] = '\0';
    } else if (nread == -1) {
       perror("read");
       ...
    }

    printf("%s\n",str);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM