Linux — namespaces: Time namespace (Part 3)

Shlomi Boutnaru, Ph.D.
2 min readDec 12, 2022

--

In the first part of the series we have talked generally about what are namespace and what we can do with them — in case you want to go over it you can use the following link https://medium.com/@boutnaru/linux-namespaces-part-1-dcee9c40fb68. Now we are going to deep dive into the time namespaces.

By using time namespaces we can separate/isolate/segregate and thus “virtual” the values of two system clocks (https://man7.org/linux/man-pages/man7/time_namespaces.7.html). We are talking about “CLOCK_MONOTONIC” and “CLOCK_BOOTTIME”.

“CLOCK_MONOTONIC” goal is to represent an absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It is important to understand that it isn’t affected by changes in the system time-of-day clock. As opposed to “CLOCK_REALTIME” which can change based on configurations/NTP (Network Time Protocol) data (https://stackoverflow.com/questions/3523442/difference-between-clock-realtime-and-clock-monotonic). Moreover, “CLOCK_MONOTONIC” does not measure time spent during suspend. If we want a monotonic clock that is running during suspend we need to use “CLOCK_BOOTTIME” (https://linux.die.net/man/2/clock_gettime).

Thus, all the processes in the same time namespace share the same values of the clocks explained above. Due to that, it affect the results of the following syscalls: timer_settime (“man 2 timer_settime”, clock_gettime (“man 2 clock_gettime”), clock_nanosleep (“man 2 clock_nanosleep”), timerfd_settime (“man 2 timerfd_settime”). Also, the content returned from “/proc/uptime” is affected.

In order to create a new time namespace we have to use the unshare syscall (“man 2 unshare”) and pass the “CLONE_NEWTIME” flag. You can see an example of that using the “unshare” cli tool (“man 1 unshare”) in the screenshot below. In order to see the difference between the initial time namespace and the process’ time namespace we can use “/proc/[PID]/timens_offsets” also shown in the screenshot below.

You can follow me on twitter — @boutnaru (https://twitter.com/boutnaru).

--

--