Select function on procfs file

冷暖自知 提交于 2019-12-13 02:33:44

问题


I'm looking for solution for this kind of problem. I want to monitor changes on a procfs file with select (I want to use select, not i_notify, because I watch another descriptor for a socket).

I've tried with something like this:

fd1 = open("/proc/my_file", O_RDONLY, 0);
FD_ZERO(&rfds);
FD_SET(fd1, &rfds);

tv.tv_sec = 500;
tv.tv_usec = 0;
retval = select(fd1+1,  &rfds, NULL, NULL, &tv);

This is wrong, because file is always ready to read. How can I be notified if there was any change in the file with select?


回答1:


select(2) does not report on "changes", instead "ready to read". From the OpenGroup select() manpage:

File descriptors associated with regular files always select true for ready to read, ready to write, and error conditions.

Kernel-provided files are a little strange -- they're not quite "regular files" -- but select(2) is not the tool to determine changes in these files.

If you want to spot changes, then you must use inotify(7). Though I really wouldn't be surprised if not all files in procfs(5) use this mechanism -- many might not know when their underlying data changes. Consider /proc/loadavg -- it might change every single time you read it, but there's no real point making those changes visible via inotify(7).




回答2:


If you want to know if there is any change in a file descriptor, you could use the library libevent.

libevent is an asynchronous event notification software library. The libevent API provides a mechanism to execute a callback function when a specific event occurs on a file descriptor or after a timeout has been reached. Furthermore, libevent also supports callbacks due to signals or regular timeouts.

Currently, libevent supports /dev/poll, kqueue(2), select(2), poll(2), epoll(4) and Solaris's event ports

Or you could also use epoll.

epoll is a scalable I/O event notification mechanism for Linux, first introduced in Linux 2.5.44 1. It is meant to replace the older POSIX select(2) and poll(2) system calls, to achieve better performance in more demanding applications, where the number of watched file descriptors is large (unlike the older system calls, which operate at O(n), epoll operates in O(1) [2]). epoll is similar to FreeBSD's kqueue, in that it operates on a configurable kernel object, exposed to user space as a file descriptor of its own.

Example of using epoll



来源:https://stackoverflow.com/questions/8527772/select-function-on-procfs-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!