biao zhang
biao zhang

Reputation: 5

why non-blocking write to disk doesn't return EAGAIN or EWOULDBLOCK?

I modified a program from APUE, the program first open a file, then mark the fd as non-blocking, then continue write to the fd until write return -1.

I think since disk I/O is slow, when write buffers in OS is nearly full, the write system call will return -1, and the errno should be EAGAIN or EWOULDBLOCK.

But I ran the program for about several minutes and I repeated running the program serveral times, the write system call didn't returned -1 even once! Why? Here's the code:

#include "apue.h"
#include <errno.h>
#include <fcntl.h>

char    buf[4096];

int
main(void)
{
        int nwrite;

        int fd = open("a.txt", O_RDWR);
        if(fd<0){
            printf("fd<0\n");
            return 0;
        }
        int  i;
        for(i = 0; i<sizeof(buf); i++)
            buf[i] = i*2;

        set_fl(fd, O_NONBLOCK); /* set nonblocking */

        while (1) {
                nwrite = write(fd, buf, sizeof(buf));
                if (nwrite < 0) {
                    printf("write returned:%d, errno=%d\n", nwrite, errno);
                    return 0;
                }
        }

        clr_fl(STDOUT_FILENO, O_NONBLOCK);      /* clear nonblocking */

        exit(0);
}

Upvotes: 0

Views: 1314

Answers (1)

user149341
user149341

Reputation:

The O_NONBLOCK flag is primarily meaningful for file descriptors representing streams (e.g, pipes, sockets, and character devices), where it prevents read and write operations from blocking when there is no data waiting to read, or buffers are too full to write anything more at the moment. It has no effect on file descriptors opened to regular files; disk I/O delays are essentially ignored by the system.

If you want to do asynchronous I/O to files, you may want to take a look at the POSIX AIO interface. Be warned that it's rather hairy and infrequently used, though.

Upvotes: 3

Related Questions