1 /* Tests for POSIX timer implementation using thread CPU clock.  */
2 
3 #include <unistd.h>
4 
5 #if _POSIX_THREADS && defined _POSIX_CPUTIME
6 
7 #include <errno.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <fcntl.h>
12 #include <time.h>
13 #include <pthread.h>
14 
15 static clockid_t worker_thread_clock;
16 
17 #define TEST_CLOCK worker_thread_clock
18 #define TEST_CLOCK_MISSING(clock) \
19   (setup_test () ? "thread CPU clock timer support" : NULL)
20 
21 /* This function is intended to rack up both user and system time.  */
22 static void *
chew_cpu(void * arg)23 chew_cpu (void *arg)
24 {
25   while (1)
26     {
27       static volatile char buf[4096];
28       for (int i = 0; i < 100; ++i)
29 	for (size_t j = 0; j < sizeof buf; ++j)
30 	  buf[j] = 0xaa;
31       int nullfd = open ("/dev/null", O_WRONLY);
32       for (int i = 0; i < 100; ++i)
33 	for (size_t j = 0; j < sizeof buf; ++j)
34 	  buf[j] = 0xbb;
35       write (nullfd, (char *) buf, sizeof buf);
36       close (nullfd);
37     }
38 
39   return NULL;
40 }
41 
42 static int
setup_test(void)43 setup_test (void)
44 {
45   /* Test timers on a thread CPU clock by having a worker thread eating
46      CPU.  First make sure we can make such timers at all.  */
47 
48   pthread_t th;
49   int e = pthread_create (&th, NULL, chew_cpu, NULL);
50   if (e != 0)
51     {
52       printf ("pthread_create: %s\n", strerror (e));
53       exit (1);
54     }
55 
56   e = pthread_getcpuclockid (th, &worker_thread_clock);
57   if (e == EPERM || e == ENOENT || e == ENOTSUP)
58     {
59       puts ("pthread_getcpuclockid does not support other threads");
60       return 1;
61     }
62   if (e != 0)
63     {
64       printf ("pthread_getcpuclockid: %s\n", strerror (e));
65       exit (1);
66     }
67 
68   timer_t t;
69   if (timer_create (TEST_CLOCK, NULL, &t) != 0)
70     {
71       printf ("timer_create: %m\n");
72       return 1;
73     }
74   timer_delete (t);
75 
76   return 0;
77 }
78 
79 #else
80 # define TEST_CLOCK_MISSING(clock) "process clocks"
81 #endif
82 
83 #include "tst-timer4.c"
84