ctimeruntime-errorclockinvalid-argument

Unable to set time of process clock, do I need some privileges?


In my C program, I am trying to set the time of the process clock by using the command clock_settime(CLOCK_PROCESS_CPUTIME_ID,...) but I am getting the invalid argument error EINVAL.

#include<time.h>
#include<stdio.h>
int main(void)
{
        struct timespec a;
        clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&a);
        fprintf(stdout,"Current process time: %d %d\n",a.tv_sec,a.tv_nsec);
        
        a.tv_sec=0; 
        a.tv_nsec=0;
        
        fprintf(stdout,"Resetting process time status: %d\n",clock_settime(CLOCK_PROCESS_CPUTIME_ID,&a));
        clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&a);
        fprintf(stdout,"Current process time: %d %d\n",a.tv_sec,a.tv_nsec);
        return 0;
}
 

Strace output:

clock_settime(CLOCK_PROCESS_CPUTIME_ID, {0, 0}) = -1 EINVAL (Invalid argument)
write(1, "Resetting process time status: -"..., 34Resetting process time status: -1

This is my first time playing around with clocks. Do I need some privilege to be able to set the time of this clock, or is there some logical error?


Solution

  • On Linux, the CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID clocks are not settable. This is noted in various places in the man 2 clock_getres manpage, including the NOTES section linked to above:

    According to POSIX.1-2001, a process with "appropriate privileges" may set the CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID clocks using clock_settime(). On Linux, these clocks are not settable (i.e., no process has "appropriate privileges").

    (That text was moved from BUGS to NOTES about a year ago, so if you haven't updated your manpages recently, you'll find it in BUGS, close to the end. About the same time that it was moved to NOTES, it was also noted in the individual descriptions of the two clocks.)

    Recent versions of the manpage also list that as a possible reason for the EINVAL return code (it was always a possible reason, but only recently documented).