簡體   English   中英

為什么系統調用“read()”會阻塞我的程序?

[英]Why does the system call "read()" block my program?

我聯系你是因為我的程序有問題。 為了我的學習,我目前正在用 C 語言編寫一個讀取文件的函數,我只能使用以下函數/系統調用: malloc、free、exit、(f)open、(f)close、(f)read , (f)write, getline, ioctl, usleep, sigaction, 信號, stat, lstat, fstat

問題是,當調用我的函數 my_filetostr() 時,它會在 read() 系統調用處阻塞程序,但什么也沒有發生。

這是我的代碼:

char *my_filetostr(const char *filepath)
{
    int fd = 0;
    struct stat s;
    char *buff = NULL;
    if (fd = open(filepath, O_RDONLY) > 0) {
        stat(filepath, &s);
        buff = malloc(sizeof(char) * s.st_size + 1);
        my_printf("fd : %d, size : %d\n", fd, s.st_size);
        if (read(fd, buff, s.st_size) == s.st_size) {
            buff[s.st_size] = '\0';
        }
        close(fd);
    }
    return buff;
}

我指定我的文件存在(我的錯誤處理有效)。

我試圖放置一些 my_printf(我們不得不重新編碼 printf)以查看程序停止的位置並顯示一些有用的信息:

  • 所以我知道問題出在 read()
  • st_size 返回正確的大小並且 filedescriptor 具有正確的值。

該計划應該繼續進行。

您正在if條件內分配給 fd 。

這通常會導致錯誤, 應該避免

您的問題在這里特別是因為>=相比具有更高的優先級,因此fd變為 1 即stdout

我修改了您的代碼以突出顯示問題https://godbolt.org/z/M4PbcPfev

fd:1,尺寸:140728905723182

謝謝@stark、@user3840170、@tejas

我的代碼現在有效:

char *my_filetostr(const char *filepath)
{
    int fd = -1;
    struct stat s;
    char *buff = NULL;
    if ((fd = open(filepath, O_RDONLY)) != -1) {
        fstat(fd, &s);
        buff = malloc(sizeof(char) * s.st_size + 1);
        if (read(fd, buff, s.st_size) == s.st_size) {
            buff[s.st_size] = '\0';
        }
        close(fd);
    }
    return buff;
}

我執行了以下操作:

  • 將 stat 替換為 fstat(但這並沒有解決問題)
  • int fd = 0替換為int fd = -1
  • 替換fd = open(filepath, O_RDONLY) > 0 par (fd = open(filepath, O_RDONLY)) != -1

謝謝您的回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM