Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading