0

I wrote a class to listen for process events via a PF_NETLINK socket connection.

The recv() function is given a message which includes a timestamp representing the number of nanoseconds since the last boot of the kernel.

What is the function to convert such a timestamp to real time?

The only thing I can think of is to use the clock_gettime() function to read both values and generate an offset. But I want to make sure that there isn't already a library that does that for us.

struct timespec realtime;
struct timespec boottime;

clock_gettime(CLOCK_REALTIME, &realtime);
clock_gettime(CLOCK_BOOTTIME, &boottime);

// the following is pseudo code since timespec is a struct
struct timespec offset = realtime - boottime;

struct timespec event_timestamp = ...; // value from PF_NETLINK event

struct timespec event_realtime = event_timesamp + offset;

This looks ugly and that's why I'm hoping there is a C library function that does all of that for us. Is there? If so, what is it?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
  • 1
    AFAIK, there is no std function for this. Depends on what you think is "ugly". Is it using an offset? Or, that the times come as structs? Here is an answer of mine: [Calculate average time between timespec](https://stackoverflow.com/a/72873001/5382650) that has examples of functions that I personally use all the time [in production code] – Craig Estey Apr 30 '23 at 17:38

1 Answers1

2

There is no function and it can't exist - CLOCK_REALTIME is arbitrary, can be set by user and nonmonotonic. The history of realtime clock settings is not stored in any database. If you don't know what the real time was at some point you have no way of knowing.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Good point. It would probably make more sense to do a `clock_gettime(CLOCK_REALTIME)` at the time I receive the event! – Alexis Wilke Apr 30 '23 at 21:11