xref: /PHP-5.5/sapi/fpm/fpm/fpm_clock.c (revision 306d08a0)
1 
2 	/* $Id: fpm_clock.c,v 1.4 2008/09/18 23:19:59 anight Exp $ */
3 	/* (c) 2007,2008 Andrei Nigmatulin */
4 
5 #include "fpm_config.h"
6 
7 #if defined(HAVE_CLOCK_GETTIME)
8 #include <time.h> /* for CLOCK_MONOTONIC */
9 #endif
10 
11 #include "fpm_clock.h"
12 #include "zlog.h"
13 
14 
15 /* posix monotonic clock - preferred source of time */
16 #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
17 
18 static int monotonic_works;
19 
fpm_clock_init()20 int fpm_clock_init() /* {{{ */
21 {
22 	struct timespec ts;
23 
24 	monotonic_works = 0;
25 
26 	if (0 == clock_gettime(CLOCK_MONOTONIC, &ts)) {
27 		monotonic_works = 1;
28 	}
29 
30 	return 0;
31 }
32 /* }}} */
33 
fpm_clock_get(struct timeval * tv)34 int fpm_clock_get(struct timeval *tv) /* {{{ */
35 {
36 	if (monotonic_works) {
37 		struct timespec ts;
38 
39 		if (0 > clock_gettime(CLOCK_MONOTONIC, &ts)) {
40 			zlog(ZLOG_SYSERROR, "clock_gettime() failed");
41 			return -1;
42 		}
43 
44 		tv->tv_sec = ts.tv_sec;
45 		tv->tv_usec = ts.tv_nsec / 1000;
46 		return 0;
47 	}
48 
49 	return gettimeofday(tv, 0);
50 }
51 /* }}} */
52 
53 /* macosx clock */
54 #elif defined(HAVE_CLOCK_GET_TIME)
55 
56 #include <mach/mach.h>
57 #include <mach/clock.h>
58 #include <mach/mach_error.h>
59 
60 static clock_serv_t mach_clock;
61 
62 /* this code borrowed from here: http://lists.apple.com/archives/Darwin-development/2002/Mar/msg00746.html */
63 /* mach_clock also should be re-initialized in child process after fork */
fpm_clock_init()64 int fpm_clock_init() /* {{{ */
65 {
66 	kern_return_t ret;
67 	mach_timespec_t aTime;
68 
69 	ret = host_get_clock_service(mach_host_self(), REALTIME_CLOCK, &mach_clock);
70 
71 	if (ret != KERN_SUCCESS) {
72 		zlog(ZLOG_ERROR, "host_get_clock_service() failed: %s", mach_error_string(ret));
73 		return -1;
74 	}
75 
76 	/* test if it works */
77 	ret = clock_get_time(mach_clock, &aTime);
78 
79 	if (ret != KERN_SUCCESS) {
80 		zlog(ZLOG_ERROR, "clock_get_time() failed: %s", mach_error_string(ret));
81 		return -1;
82 	}
83 
84 	return 0;
85 }
86 /* }}} */
87 
fpm_clock_get(struct timeval * tv)88 int fpm_clock_get(struct timeval *tv) /* {{{ */
89 {
90 	kern_return_t ret;
91 	mach_timespec_t aTime;
92 
93 	ret = clock_get_time(mach_clock, &aTime);
94 
95 	if (ret != KERN_SUCCESS) {
96 		zlog(ZLOG_ERROR, "clock_get_time() failed: %s", mach_error_string(ret));
97 		return -1;
98 	}
99 
100 	tv->tv_sec = aTime.tv_sec;
101 	tv->tv_usec = aTime.tv_nsec / 1000;
102 
103 	return 0;
104 }
105 /* }}} */
106 
107 #else /* no clock */
108 
fpm_clock_init()109 int fpm_clock_init() /* {{{ */
110 {
111 	return 0;
112 }
113 /* }}} */
114 
fpm_clock_get(struct timeval * tv)115 int fpm_clock_get(struct timeval *tv) /* {{{ */
116 {
117 	return gettimeofday(tv, 0);
118 }
119 /* }}} */
120 
121 #endif
122