Bonus: clock_gettime and time¶
Tools: GCC, Make, strace
Goal¶
Implement clock_gettime(2) and build a libc-style time() on top of it, this time spread across a proper header and implementation file rather than a single main.c.
Background¶
Same three-layer pattern as the previous exercises:
clock_gettime reads a high-resolution clock into a timespec (see man 2 clock_gettime):
clkid— which clock to read.CLOCK_REALTIMEis wall-clock time since the Unix Epoch;CLOCK_MONOTONIConly ever increases and is the right choice for measuring durations.tp— an output parameter: the kernel fills it in.
time(2) is the coarser call, returning only whole seconds of CLOCK_REALTIME:
It also has the unusual habit of returning its result and optionally storing it through a pointer.
Your Task¶
-
my_time.h— add declarations formy_clock_gettime()andmy_time()where the TODO comments are. Note that this file is included by bothmain.candmy_time.c, so the declarations must match the definitions exactly. -
my_time.c— complete the three TODOs:SYS_clock_gettime— define the correct x86-64 syscall number.my_clock_gettime()— the syscall wrapper:clkidfirst,tpsecond,0for the rest.my_time()— readCLOCK_REALTIME, store the seconds throughtlocif it is notNULL, and return them.
Build & Run¶
Check Your Work¶
- The two values printed should agree, or differ by at most 1 if the second ticked over between the calls.
-
Sanity-check the absolute value against the system clock:
Your seconds should match to within a second or two. A value near zero means the kernel never filled the structure; a small negative value is an error code being returned rather than a time.
-
Confirm the calls reach the kernel:
You may see fewer
clock_gettimelines than you expect, or none at all — that is not necessarily a bug in your code. Compare with a program that calls libc'sclock_gettime()and discuss the difference with the teaching assistant. -
Passing
NULLfortlocmust work and must not crash. Try a non-NULLpointer too, and check both paths give the same value.