Home > Software engineering >  Why does the system call "read()" block my program?
Why does the system call "read()" block my program?

Time:12-25

I am contacting you because I have a problem with my program. For my studies, I am currently programming in C a function to read a file, I am only allowed to use the following functions/system calls: malloc, free, exit, (f)open, (f)close, (f)read, (f)write, getline, ioctl, usleep, sigaction, signal, stat, lstat, fstat

The problem is that when calling my function my_filetostr(), it blocks the program at the read() system call and nothing happens.

here's my code:

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;
}

I specify that my file exists (my error handling works).

I tried to put some my_printf (we had to recode printf) in order to see where the program stops and to display some useful information:

  • So I know that the problem comes from read()
  • st_size returns the right size and filedescriptor has a correct value.

The program is just supposed to move on.

CodePudding user response:

You are assigning to fd inside the if condition.

This usually causes bugs and should be avoided

Your issue here is specifically because > has higher precedence compared to =, so fd becomes 1 which is stdout.

I have modified your code to highlight the issue https://godbolt.org/z/M4PbcPfev

fd : 1, size : 140728905723182

CodePudding user response:

Thanks you @stark , @user3840170 , @tejas

My code now works :

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;
}

I have performed the following actions:

  • Replace stat with fstat (but that didn't solve the problem)
  • Replace int fd = 0 by int fd = -1
  • Replace fd = open(filepath, O_RDONLY) > 0 par (fd = open(filepath, O_RDONLY)) != -1

Thank you for your answers.

  • Related