繁体   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