簡體   English   中英

無法使用read()系統調用從其他終端讀取數據

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

大家好,我在偽終端/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:~$ 

在終端/dev/pts/2我鍵入了“ anirudh”,但是在其上顯示了“ airudh”,並且在終端/dev/pts/1上顯示了丟失的字符n 但是,當我嘗試從終端/dev/pts/1讀取時,我可以正確讀取每個字符。 因此,我無法理解該程序的行為。 請幫幫我。 提前致謝。 :)

首先,您可能有另一個從/ dev / pts / 2讀取的進程,因此將字符發送給它,而不是您的。 然后,該終端可能通過其他過程(這是某些shell所做的)設置為讀取“每個字符一個字符”模式,您只讀取一個字符。

哇。 首先,這是一個普遍的好規則:檢查返回給您的是什么系統調用。 阿拉維斯。

int main(){

    char str[50];

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

其次,讀取可能返回的字節數少於您請求的字節數,請查看man:

如果此數目小於請求的字節數,這不是錯誤; 例如,這可能是因為當前實際可用的字節較少(可能是因為我們接近文件末尾,或者因為我們正在從管道或終端讀取),或者因為read()被a中斷了。信號。

因此,即使讀取也可能返回1個字節。 第三,讀取可能返回-1:

如果出錯,則返回-1,並正確設置errno。

因此,我認為最好寫:

    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