How to get timestamp at which a file descriptor mo

2019-08-10 15:13发布

My C program uses TCP socket for communication.

I am using an iterative server and select() to listen for monitoring multiple file descriptors; one TCP socket file descriptor for each client.

Is there a method, using which I can figure out when did a file descriptor become ready?

The application is for a linux platform.

The application is like:

I have a set of file descriptors {fd1, fd2, ... fdN}

while (True)
     S <-- select (fd1, fd2, ... fdN)  // Set S contains the ready fds

     S = {fd1, fd2, fd3}.
     /* Say only the file descriptors fd1, fd2 and fd3 are ready.
      * I want to process in FIFO order.
      * Hence, I need timestamp at which a file descriptor became ready.*/

     process (S)   /* It may take 2-3 minutes. Which is not negligible. 
                    * Say t units for generalization.*/

Note that in the since it takes t units to process the file descriptors, the maximum difference between the ready time of two file descriptors in the set S can be t units.

Hence, the time at which a file descriptor became ready becomes important.

And I want to know how to obtain the timestamp at which a file descriptor became ready.

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-10 15:57

The socket became ready nanoseconds before select() returns. It is ready now. select() doesn't wait for a bunch of sockets to become ready.

查看更多
Ridiculous、
3楼-- · 2019-08-10 16:04

The timestamp at which a file descriptor becomes ready is the modification time of the file descriptor. Or in other words, the time at which the file represented by the file descriptor was last modified.

The modification time of a file (represented by a file descriptor) can be obtained using the fstat() method. Read http://pubs.opengroup.org/onlinepubs/009695399/functions/fstat.html for details.

查看更多
够拽才男人
4楼-- · 2019-08-10 16:12

As @EJP already explained, select will return a few nanoseconds after the data arrived. Then it is up to you to call gettimeofday() or something equivalent to get the current time.

If you need to avoid the overhead of calling gettimeofday() for each packet, you may give libevent a go cause it supports a cached gettimeofday() (with a little delta depending on how long your packet-handler is running). See http://www.wangafu.net/~nickm/libevent-book/Ref3_eventloop.html for more information about event_base_gettimeofday_cached().

If you really need the time of the arrival of the frame with highest possible precision you may switch over to libpcap, DPDK or netmap. They offer the timestamp of the frame arrival - by the drawback that you need to handle the whole IP/TCP-stack (you may use lwip or libnids) on your own.

查看更多
登录 后发表回答