[英]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)以查看程序停止的位置並顯示一些有用的信息:
該計划應該繼續進行。
您正在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;
}
我執行了以下操作:
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.