简体   繁体   中英

Is it legal to read a file descriptor into NULL?

Recently, I've been fixing the timestep for the sake of a library that I am writing. Following some research, suppose that I ended up with this prototype, precise and easy to combine with the generic event system of my library:

#include <stdio.h>
#include <unistd.h>
#include <sys/timerfd.h>
#include <poll.h>

struct pollfd fds[1];
struct itimerspec its;

int main(void) {
    fds[0] = (struct pollfd) {timerfd_create(CLOCK_MONOTONIC, 0), POLLIN, 0}; //long live clarity
    its.it_interval = (struct timespec) {0, 16666667};
    its.it_value = (struct timespec) {0, 16666667};
    timerfd_settime(fds[0].fd, 0, &its, NULL);
    while(1) {
        poll(fds, 1, -1);
        if(fds[0].revents == POLLIN) {
            long long buffer;
            read(fds[0].fd, &buffer, 8);
            printf("ROFL\n");
        } else {
            printf("BOOM\n");
            break;
        }
    }
    close(fds[0].fd);
    return 0;
}

However, it severely hurt me that I've had to pollute my CPU caches with a whole precious 8 bytes of data in order to make the timer's file descriptor reusable. Because of that, I've tried to replace the read() call with lseek() , as follows:

lseek(fds[0].fd, 0, SEEK_END);

Unfortunately, both that and even lseek(fds[0].fd, 8, SEEK_CUR); gave me ESPIPE errors and would not work. But then, I found out that the following actually did its job, despite of giving EFAULT s:

read(fds[0].fd, NULL, 8);

Is it legal, defined behavior to offset the file descriptor like this? If it is not (as the EFAULT s suggested to me, strongly enough to refrain from using that piece of genius), does there exist a function that would discard the read data, without ever writing it down, or otherwise offset my timer's file descriptor?

The POSIX specification of read(2) does not specify the consequences of passing a null pointer as the buffer argument. No specific error code is given, nor does it say whether any data will be read from the descriptor.

The Linux man page has this error, though:

EFAULT buf is outside your accessible address space.

It doesn't say that it will read the 8 bytes and discard them when this happens, though.

So I don't think you can depend on this working as you desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM