time.texi 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910
  1. @node Date and Time, Resource Usage And Limitation, Arithmetic, Top
  2. @c %MENU% Functions for getting the date and time and formatting them nicely
  3. @chapter Date and Time
  4. This chapter describes functions for manipulating dates and times,
  5. including functions for determining what time it is and conversion
  6. between different time representations.
  7. @menu
  8. * Time Basics:: Concepts and definitions.
  9. * Elapsed Time:: Data types to represent elapsed times
  10. * Processor And CPU Time:: Time a program has spent executing.
  11. * Calendar Time:: Manipulation of ``real'' dates and times.
  12. * Setting an Alarm:: Sending a signal after a specified time.
  13. * Sleeping:: Waiting for a period of time.
  14. @end menu
  15. @node Time Basics
  16. @section Time Basics
  17. @cindex time
  18. Discussing time in a technical manual can be difficult because the word
  19. ``time'' in English refers to lots of different things. In this manual,
  20. we use a rigorous terminology to avoid confusion, and the only thing we
  21. use the simple word ``time'' for is to talk about the abstract concept.
  22. A @dfn{calendar time} is a point in the time continuum, for example
  23. November 4, 1990, at 18:02.5 UTC. Sometimes this is called ``absolute
  24. time''.
  25. @cindex calendar time
  26. We don't speak of a ``date'', because that is inherent in a calendar
  27. time.
  28. @cindex date
  29. An @dfn{interval} is a contiguous part of the time continuum between two
  30. calendar times, for example the hour between 9:00 and 10:00 on July 4,
  31. 1980.
  32. @cindex interval
  33. An @dfn{elapsed time} is the length of an interval, for example, 35
  34. minutes. People sometimes sloppily use the word ``interval'' to refer
  35. to the elapsed time of some interval.
  36. @cindex elapsed time
  37. @cindex time, elapsed
  38. An @dfn{amount of time} is a sum of elapsed times, which need not be of
  39. any specific intervals. For example, the amount of time it takes to
  40. read a book might be 9 hours, independently of when and in how many
  41. sittings it is read.
  42. A @dfn{period} is the elapsed time of an interval between two events,
  43. especially when they are part of a sequence of regularly repeating
  44. events.
  45. @cindex period of time
  46. @dfn{CPU time} is like calendar time, except that it is based on the
  47. subset of the time continuum when a particular process is actively
  48. using a CPU. CPU time is, therefore, relative to a process.
  49. @cindex CPU time
  50. @dfn{Processor time} is an amount of time that a CPU is in use. In
  51. fact, it's a basic system resource, since there's a limit to how much
  52. can exist in any given interval (that limit is the elapsed time of the
  53. interval times the number of CPUs in the processor). People often call
  54. this CPU time, but we reserve the latter term in this manual for the
  55. definition above.
  56. @cindex processor time
  57. @node Elapsed Time
  58. @section Elapsed Time
  59. @cindex elapsed time
  60. One way to represent an elapsed time is with a simple arithmetic data
  61. type, as with the following function to compute the elapsed time between
  62. two calendar times. This function is declared in @file{time.h}.
  63. @deftypefun double difftime (time_t @var{time1}, time_t @var{time0})
  64. @standards{ISO, time.h}
  65. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  66. The @code{difftime} function returns the number of seconds of elapsed
  67. time between calendar time @var{time1} and calendar time @var{time0}, as
  68. a value of type @code{double}. The difference ignores leap seconds
  69. unless leap second support is enabled.
  70. In @theglibc{}, you can simply subtract @code{time_t} values. But on
  71. other systems, the @code{time_t} data type might use some other encoding
  72. where subtraction doesn't work directly.
  73. @end deftypefun
  74. @Theglibc{} provides two data types specifically for representing
  75. an elapsed time. They are used by various @glibcadj{} functions, and
  76. you can use them for your own purposes too. They're exactly the same
  77. except that one has a resolution in microseconds, and the other, newer
  78. one, is in nanoseconds.
  79. @deftp {Data Type} {struct timeval}
  80. @standards{BSD, sys/time.h}
  81. @cindex timeval
  82. The @code{struct timeval} structure represents an elapsed time. It is
  83. declared in @file{sys/time.h} and has the following members:
  84. @table @code
  85. @item time_t tv_sec
  86. This represents the number of whole seconds of elapsed time.
  87. @item long int tv_usec
  88. This is the rest of the elapsed time (a fraction of a second),
  89. represented as the number of microseconds. It is always less than one
  90. million.
  91. @end table
  92. @end deftp
  93. @deftp {Data Type} {struct timespec}
  94. @standards{POSIX.1, sys/time.h}
  95. @cindex timespec
  96. The @code{struct timespec} structure represents an elapsed time. It is
  97. declared in @file{time.h} and has the following members:
  98. @table @code
  99. @item time_t tv_sec
  100. This represents the number of whole seconds of elapsed time.
  101. @item long int tv_nsec
  102. This is the rest of the elapsed time (a fraction of a second),
  103. represented as the number of nanoseconds. It is always less than one
  104. billion.
  105. @end table
  106. @end deftp
  107. It is often necessary to subtract two values of type @w{@code{struct
  108. timeval}} or @w{@code{struct timespec}}. Here is the best way to do
  109. this. It works even on some peculiar operating systems where the
  110. @code{tv_sec} member has an unsigned type.
  111. @smallexample
  112. @include timeval_subtract.c.texi
  113. @end smallexample
  114. Common functions that use @code{struct timeval} are @code{gettimeofday}
  115. and @code{settimeofday}.
  116. There are no @glibcadj{} functions specifically oriented toward
  117. dealing with elapsed times, but the calendar time, processor time, and
  118. alarm and sleeping functions have a lot to do with them.
  119. @node Processor And CPU Time
  120. @section Processor And CPU Time
  121. If you're trying to optimize your program or measure its efficiency,
  122. it's very useful to know how much processor time it uses. For that,
  123. calendar time and elapsed times are useless because a process may spend
  124. time waiting for I/O or for other processes to use the CPU. However,
  125. you can get the information with the functions in this section.
  126. CPU time (@pxref{Time Basics}) is represented by the data type
  127. @code{clock_t}, which is a number of @dfn{clock ticks}. It gives the
  128. total amount of time a process has actively used a CPU since some
  129. arbitrary event. On @gnusystems{}, that event is the creation of the
  130. process. While arbitrary in general, the event is always the same event
  131. for any particular process, so you can always measure how much time on
  132. the CPU a particular computation takes by examining the process' CPU
  133. time before and after the computation.
  134. @cindex CPU time
  135. @cindex clock ticks
  136. @cindex ticks, clock
  137. On @gnulinuxhurdsystems{}, @code{clock_t} is equivalent to @code{long int} and
  138. @code{CLOCKS_PER_SEC} is an integer value. But in other systems, both
  139. @code{clock_t} and the macro @code{CLOCKS_PER_SEC} can be either integer
  140. or floating-point types. Casting CPU time values to @code{double}, as
  141. in the example above, makes sure that operations such as arithmetic and
  142. printing work properly and consistently no matter what the underlying
  143. representation is.
  144. Note that the clock can wrap around. On a 32bit system with
  145. @code{CLOCKS_PER_SEC} set to one million this function will return the
  146. same value approximately every 72 minutes.
  147. For additional functions to examine a process' use of processor time,
  148. and to control it, see @ref{Resource Usage And Limitation}.
  149. @menu
  150. * CPU Time:: The @code{clock} function.
  151. * Processor Time:: The @code{times} function.
  152. @end menu
  153. @node CPU Time
  154. @subsection CPU Time Inquiry
  155. To get a process' CPU time, you can use the @code{clock} function. This
  156. facility is declared in the header file @file{time.h}.
  157. @pindex time.h
  158. In typical usage, you call the @code{clock} function at the beginning
  159. and end of the interval you want to time, subtract the values, and then
  160. divide by @code{CLOCKS_PER_SEC} (the number of clock ticks per second)
  161. to get processor time, like this:
  162. @smallexample
  163. @group
  164. #include <time.h>
  165. clock_t start, end;
  166. double cpu_time_used;
  167. start = clock();
  168. @dots{} /* @r{Do the work.} */
  169. end = clock();
  170. cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
  171. @end group
  172. @end smallexample
  173. Do not use a single CPU time as an amount of time; it doesn't work that
  174. way. Either do a subtraction as shown above or query processor time
  175. directly. @xref{Processor Time}.
  176. Different computers and operating systems vary wildly in how they keep
  177. track of CPU time. It's common for the internal processor clock
  178. to have a resolution somewhere between a hundredth and millionth of a
  179. second.
  180. @deftypevr Macro int CLOCKS_PER_SEC
  181. @standards{ISO, time.h}
  182. The value of this macro is the number of clock ticks per second measured
  183. by the @code{clock} function. POSIX requires that this value be one
  184. million independent of the actual resolution.
  185. @end deftypevr
  186. @deftp {Data Type} clock_t
  187. @standards{ISO, time.h}
  188. This is the type of the value returned by the @code{clock} function.
  189. Values of type @code{clock_t} are numbers of clock ticks.
  190. @end deftp
  191. @deftypefun clock_t clock (void)
  192. @standards{ISO, time.h}
  193. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  194. @c On Hurd, this calls task_info twice and adds user and system time
  195. @c from both basic and thread time info structs. On generic posix,
  196. @c calls times and adds utime and stime. On bsd, calls getrusage and
  197. @c safely converts stime and utime to clock. On linux, calls
  198. @c clock_gettime.
  199. This function returns the calling process' current CPU time. If the CPU
  200. time is not available or cannot be represented, @code{clock} returns the
  201. value @code{(clock_t)(-1)}.
  202. @end deftypefun
  203. @node Processor Time
  204. @subsection Processor Time Inquiry
  205. The @code{times} function returns information about a process'
  206. consumption of processor time in a @w{@code{struct tms}} object, in
  207. addition to the process' CPU time. @xref{Time Basics}. You should
  208. include the header file @file{sys/times.h} to use this facility.
  209. @cindex processor time
  210. @cindex CPU time
  211. @pindex sys/times.h
  212. @deftp {Data Type} {struct tms}
  213. @standards{POSIX.1, sys/times.h}
  214. The @code{tms} structure is used to return information about process
  215. times. It contains at least the following members:
  216. @table @code
  217. @item clock_t tms_utime
  218. This is the total processor time the calling process has used in
  219. executing the instructions of its program.
  220. @item clock_t tms_stime
  221. This is the processor time the system has used on behalf of the calling
  222. process.
  223. @item clock_t tms_cutime
  224. This is the sum of the @code{tms_utime} values and the @code{tms_cutime}
  225. values of all terminated child processes of the calling process, whose
  226. status has been reported to the parent process by @code{wait} or
  227. @code{waitpid}; see @ref{Process Completion}. In other words, it
  228. represents the total processor time used in executing the instructions
  229. of all the terminated child processes of the calling process, excluding
  230. child processes which have not yet been reported by @code{wait} or
  231. @code{waitpid}.
  232. @cindex child process
  233. @item clock_t tms_cstime
  234. This is similar to @code{tms_cutime}, but represents the total processor
  235. time the system has used on behalf of all the terminated child processes
  236. of the calling process.
  237. @end table
  238. All of the times are given in numbers of clock ticks. Unlike CPU time,
  239. these are the actual amounts of time; not relative to any event.
  240. @xref{Creating a Process}.
  241. @end deftp
  242. @deftypevr Macro int CLK_TCK
  243. @standards{POSIX.1, time.h}
  244. This is an obsolete name for the number of clock ticks per second. Use
  245. @code{sysconf (_SC_CLK_TCK)} instead.
  246. @end deftypevr
  247. @deftypefun clock_t times (struct tms *@var{buffer})
  248. @standards{POSIX.1, sys/times.h}
  249. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  250. @c On HURD, this calls task_info twice, for basic and thread times info,
  251. @c adding user and system times into tms, and then gettimeofday, to
  252. @c compute the real time. On BSD, it calls getclktck, getrusage (twice)
  253. @c and time. On Linux, it's a syscall with special handling to account
  254. @c for clock_t counts that look like error values.
  255. The @code{times} function stores the processor time information for
  256. the calling process in @var{buffer}.
  257. The return value is the number of clock ticks since an arbitrary point
  258. in the past, e.g. since system start-up. @code{times} returns
  259. @code{(clock_t)(-1)} to indicate failure.
  260. @end deftypefun
  261. @strong{Portability Note:} The @code{clock} function described in
  262. @ref{CPU Time} is specified by the @w{ISO C} standard. The
  263. @code{times} function is a feature of POSIX.1. On @gnusystems{}, the
  264. CPU time is defined to be equivalent to the sum of the @code{tms_utime}
  265. and @code{tms_stime} fields returned by @code{times}.
  266. @node Calendar Time
  267. @section Calendar Time
  268. This section describes facilities for keeping track of calendar time.
  269. @xref{Time Basics}.
  270. @Theglibc{} represents calendar time three ways:
  271. @itemize @bullet
  272. @item
  273. @dfn{Simple time} (the @code{time_t} data type) is a compact
  274. representation, typically giving the number of seconds of elapsed time
  275. since some implementation-specific base time.
  276. @cindex simple time
  277. @item
  278. There is also a "high-resolution time" representation. Like simple
  279. time, this represents a calendar time as an elapsed time since a base
  280. time, but instead of measuring in whole seconds, it uses a @code{struct
  281. timeval} data type, which includes fractions of a second. Use this time
  282. representation instead of simple time when you need greater precision.
  283. @cindex high-resolution time
  284. @item
  285. @dfn{Local time} or @dfn{broken-down time} (the @code{struct tm} data
  286. type) represents a calendar time as a set of components specifying the
  287. year, month, and so on in the Gregorian calendar, for a specific time
  288. zone. This calendar time representation is usually used only to
  289. communicate with people.
  290. @cindex local time
  291. @cindex broken-down time
  292. @cindex Gregorian calendar
  293. @cindex calendar, Gregorian
  294. @end itemize
  295. @menu
  296. * Simple Calendar Time:: Facilities for manipulating calendar time.
  297. * High-Resolution Calendar:: A time representation with greater precision.
  298. * Broken-down Time:: Facilities for manipulating local time.
  299. * High Accuracy Clock:: Maintaining a high accuracy system clock.
  300. * Formatting Calendar Time:: Converting times to strings.
  301. * Parsing Date and Time:: Convert textual time and date information back
  302. into broken-down time values.
  303. * TZ Variable:: How users specify the time zone.
  304. * Time Zone Functions:: Functions to examine or specify the time zone.
  305. * Time Functions Example:: An example program showing use of some of
  306. the time functions.
  307. @end menu
  308. @node Simple Calendar Time
  309. @subsection Simple Calendar Time
  310. This section describes the @code{time_t} data type for representing calendar
  311. time as simple time, and the functions which operate on simple time objects.
  312. These facilities are declared in the header file @file{time.h}.
  313. @pindex time.h
  314. @cindex epoch
  315. @deftp {Data Type} time_t
  316. @standards{ISO, time.h}
  317. This is the data type used to represent simple time. Sometimes, it also
  318. represents an elapsed time. When interpreted as a calendar time value,
  319. it represents the number of seconds elapsed since 00:00:00 on January 1,
  320. 1970, Coordinated Universal Time. (This calendar time is sometimes
  321. referred to as the @dfn{epoch}.) POSIX requires that this count not
  322. include leap seconds, but on some systems this count includes leap seconds
  323. if you set @code{TZ} to certain values (@pxref{TZ Variable}).
  324. Note that a simple time has no concept of local time zone. Calendar
  325. Time @var{T} is the same instant in time regardless of where on the
  326. globe the computer is.
  327. In @theglibc{}, @code{time_t} is equivalent to @code{long int}.
  328. In other systems, @code{time_t} might be either an integer or
  329. floating-point type.
  330. @end deftp
  331. The function @code{difftime} tells you the elapsed time between two
  332. simple calendar times, which is not always as easy to compute as just
  333. subtracting. @xref{Elapsed Time}.
  334. @deftypefun time_t time (time_t *@var{result})
  335. @standards{ISO, time.h}
  336. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  337. The @code{time} function returns the current calendar time as a value of
  338. type @code{time_t}. If the argument @var{result} is not a null pointer,
  339. the calendar time value is also stored in @code{*@var{result}}. If the
  340. current calendar time is not available, the value
  341. @w{@code{(time_t)(-1)}} is returned.
  342. @end deftypefun
  343. @c The GNU C library implements stime() with a call to settimeofday() on
  344. @c Linux.
  345. @deftypefun int stime (const time_t *@var{newtime})
  346. @standards{SVID, time.h}
  347. @standards{XPG, time.h}
  348. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  349. @c On unix, this is implemented in terms of settimeofday.
  350. @code{stime} sets the system clock, i.e., it tells the system that the
  351. current calendar time is @var{newtime}, where @code{newtime} is
  352. interpreted as described in the above definition of @code{time_t}.
  353. @code{settimeofday} is a newer function which sets the system clock to
  354. better than one second precision. @code{settimeofday} is generally a
  355. better choice than @code{stime}. @xref{High-Resolution Calendar}.
  356. Only the superuser can set the system clock.
  357. If the function succeeds, the return value is zero. Otherwise, it is
  358. @code{-1} and @code{errno} is set accordingly:
  359. @table @code
  360. @item EPERM
  361. The process is not superuser.
  362. @end table
  363. @end deftypefun
  364. @node High-Resolution Calendar
  365. @subsection High-Resolution Calendar
  366. The @code{time_t} data type used to represent simple times has a
  367. resolution of only one second. Some applications need more precision.
  368. So, @theglibc{} also contains functions which are capable of
  369. representing calendar times to a higher resolution than one second. The
  370. functions and the associated data types described in this section are
  371. declared in @file{sys/time.h}.
  372. @pindex sys/time.h
  373. @deftp {Data Type} {struct timezone}
  374. @standards{BSD, sys/time.h}
  375. The @code{struct timezone} structure is used to hold minimal information
  376. about the local time zone. It has the following members:
  377. @table @code
  378. @item int tz_minuteswest
  379. This is the number of minutes west of UTC.
  380. @item int tz_dsttime
  381. If nonzero, Daylight Saving Time applies during some part of the year.
  382. @end table
  383. The @code{struct timezone} type is obsolete and should never be used.
  384. Instead, use the facilities described in @ref{Time Zone Functions}.
  385. @end deftp
  386. @deftypefun int gettimeofday (struct timeval *@var{tp}, struct timezone *@var{tzp})
  387. @standards{BSD, sys/time.h}
  388. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  389. @c On most GNU/Linux systems this is a direct syscall, but the posix/
  390. @c implementation (not used on GNU/Linux or GNU/Hurd) relies on time and
  391. @c localtime_r, saving and restoring tzname in an unsafe manner.
  392. @c On some GNU/Linux variants, ifunc resolvers are used in shared libc
  393. @c for vdso resolution. ifunc-vdso-revisit.
  394. The @code{gettimeofday} function returns the current calendar time as
  395. the elapsed time since the epoch in the @code{struct timeval} structure
  396. indicated by @var{tp}. (@pxref{Elapsed Time} for a description of
  397. @code{struct timeval}). Information about the time zone is returned in
  398. the structure pointed to by @var{tzp}. If the @var{tzp} argument is a null
  399. pointer, time zone information is ignored.
  400. The return value is @code{0} on success and @code{-1} on failure. The
  401. following @code{errno} error condition is defined for this function:
  402. @table @code
  403. @item ENOSYS
  404. The operating system does not support getting time zone information, and
  405. @var{tzp} is not a null pointer. @gnusystems{} do not
  406. support using @w{@code{struct timezone}} to represent time zone
  407. information; that is an obsolete feature of 4.3 BSD.
  408. Instead, use the facilities described in @ref{Time Zone Functions}.
  409. @end table
  410. @end deftypefun
  411. @deftypefun int settimeofday (const struct timeval *@var{tp}, const struct timezone *@var{tzp})
  412. @standards{BSD, sys/time.h}
  413. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  414. @c On HURD, it calls host_set_time with a privileged port. On other
  415. @c unix systems, it's a syscall.
  416. The @code{settimeofday} function sets the current calendar time in the
  417. system clock according to the arguments. As for @code{gettimeofday},
  418. the calendar time is represented as the elapsed time since the epoch.
  419. As for @code{gettimeofday}, time zone information is ignored if
  420. @var{tzp} is a null pointer.
  421. You must be a privileged user in order to use @code{settimeofday}.
  422. Some kernels automatically set the system clock from some source such as
  423. a hardware clock when they start up. Others, including Linux, place the
  424. system clock in an ``invalid'' state (in which attempts to read the clock
  425. fail). A call of @code{stime} removes the system clock from an invalid
  426. state, and system startup scripts typically run a program that calls
  427. @code{stime}.
  428. @code{settimeofday} causes a sudden jump forwards or backwards, which
  429. can cause a variety of problems in a system. Use @code{adjtime} (below)
  430. to make a smooth transition from one time to another by temporarily
  431. speeding up or slowing down the clock.
  432. With a Linux kernel, @code{adjtimex} does the same thing and can also
  433. make permanent changes to the speed of the system clock so it doesn't
  434. need to be corrected as often.
  435. The return value is @code{0} on success and @code{-1} on failure. The
  436. following @code{errno} error conditions are defined for this function:
  437. @table @code
  438. @item EPERM
  439. This process cannot set the clock because it is not privileged.
  440. @item ENOSYS
  441. The operating system does not support setting time zone information, and
  442. @var{tzp} is not a null pointer.
  443. @end table
  444. @end deftypefun
  445. @c On Linux, GNU libc implements adjtime() as a call to adjtimex().
  446. @deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta})
  447. @standards{BSD, sys/time.h}
  448. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  449. @c On hurd and mach, call host_adjust_time with a privileged port. On
  450. @c Linux, it's implemented in terms of adjtimex. On other unixen, it's
  451. @c a syscall.
  452. This function speeds up or slows down the system clock in order to make
  453. a gradual adjustment. This ensures that the calendar time reported by
  454. the system clock is always monotonically increasing, which might not
  455. happen if you simply set the clock.
  456. The @var{delta} argument specifies a relative adjustment to be made to
  457. the clock time. If negative, the system clock is slowed down for a
  458. while until it has lost this much elapsed time. If positive, the system
  459. clock is speeded up for a while.
  460. If the @var{olddelta} argument is not a null pointer, the @code{adjtime}
  461. function returns information about any previous time adjustment that
  462. has not yet completed.
  463. This function is typically used to synchronize the clocks of computers
  464. in a local network. You must be a privileged user to use it.
  465. With a Linux kernel, you can use the @code{adjtimex} function to
  466. permanently change the clock speed.
  467. The return value is @code{0} on success and @code{-1} on failure. The
  468. following @code{errno} error condition is defined for this function:
  469. @table @code
  470. @item EPERM
  471. You do not have privilege to set the time.
  472. @end table
  473. @end deftypefun
  474. @strong{Portability Note:} The @code{gettimeofday}, @code{settimeofday},
  475. and @code{adjtime} functions are derived from BSD.
  476. Symbols for the following function are declared in @file{sys/timex.h}.
  477. @deftypefun int adjtimex (struct timex *@var{timex})
  478. @standards{GNU, sys/timex.h}
  479. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  480. @c It's a syscall, only available on linux.
  481. @code{adjtimex} is functionally identical to @code{ntp_adjtime}.
  482. @xref{High Accuracy Clock}.
  483. This function is present only with a Linux kernel.
  484. @end deftypefun
  485. @node Broken-down Time
  486. @subsection Broken-down Time
  487. @cindex broken-down time
  488. @cindex calendar time and broken-down time
  489. Calendar time is represented by the usual @glibcadj{} functions as an
  490. elapsed time since a fixed base calendar time. This is convenient for
  491. computation, but has no relation to the way people normally think of
  492. calendar time. By contrast, @dfn{broken-down time} is a binary
  493. representation of calendar time separated into year, month, day, and so
  494. on. Broken-down time values are not useful for calculations, but they
  495. are useful for printing human readable time information.
  496. A broken-down time value is always relative to a choice of time
  497. zone, and it also indicates which time zone that is.
  498. The symbols in this section are declared in the header file @file{time.h}.
  499. @deftp {Data Type} {struct tm}
  500. @standards{ISO, time.h}
  501. This is the data type used to represent a broken-down time. The structure
  502. contains at least the following members, which can appear in any order.
  503. @table @code
  504. @item int tm_sec
  505. This is the number of full seconds since the top of the minute (normally
  506. in the range @code{0} through @code{59}, but the actual upper limit is
  507. @code{60}, to allow for leap seconds if leap second support is
  508. available).
  509. @cindex leap second
  510. @item int tm_min
  511. This is the number of full minutes since the top of the hour (in the
  512. range @code{0} through @code{59}).
  513. @item int tm_hour
  514. This is the number of full hours past midnight (in the range @code{0} through
  515. @code{23}).
  516. @item int tm_mday
  517. This is the ordinal day of the month (in the range @code{1} through @code{31}).
  518. Watch out for this one! As the only ordinal number in the structure, it is
  519. inconsistent with the rest of the structure.
  520. @item int tm_mon
  521. This is the number of full calendar months since the beginning of the
  522. year (in the range @code{0} through @code{11}). Watch out for this one!
  523. People usually use ordinal numbers for month-of-year (where January = 1).
  524. @item int tm_year
  525. This is the number of full calendar years since 1900.
  526. @item int tm_wday
  527. This is the number of full days since Sunday (in the range @code{0} through
  528. @code{6}).
  529. @item int tm_yday
  530. This is the number of full days since the beginning of the year (in the
  531. range @code{0} through @code{365}).
  532. @item int tm_isdst
  533. @cindex Daylight Saving Time
  534. @cindex summer time
  535. This is a flag that indicates whether Daylight Saving Time is (or was, or
  536. will be) in effect at the time described. The value is positive if
  537. Daylight Saving Time is in effect, zero if it is not, and negative if the
  538. information is not available.
  539. @item long int tm_gmtoff
  540. This field describes the time zone that was used to compute this
  541. broken-down time value, including any adjustment for daylight saving; it
  542. is the number of seconds that you must add to UTC to get local time.
  543. You can also think of this as the number of seconds east of UTC. For
  544. example, for U.S. Eastern Standard Time, the value is @code{-5*60*60}.
  545. The @code{tm_gmtoff} field is derived from BSD and is a GNU library
  546. extension; it is not visible in a strict @w{ISO C} environment.
  547. @item const char *tm_zone
  548. This field is the name for the time zone that was used to compute this
  549. broken-down time value. Like @code{tm_gmtoff}, this field is a BSD and
  550. GNU extension, and is not visible in a strict @w{ISO C} environment.
  551. @end table
  552. @end deftp
  553. @deftypefun {struct tm *} localtime (const time_t *@var{time})
  554. @standards{ISO, time.h}
  555. @safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  556. @c Calls tz_convert with a static buffer.
  557. @c localtime @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  558. @c tz_convert dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  559. The @code{localtime} function converts the simple time pointed to by
  560. @var{time} to broken-down time representation, expressed relative to the
  561. user's specified time zone.
  562. The return value is a pointer to a static broken-down time structure, which
  563. might be overwritten by subsequent calls to @code{ctime}, @code{gmtime},
  564. or @code{localtime}. (But no other library function overwrites the contents
  565. of this object.)
  566. The return value is the null pointer if @var{time} cannot be represented
  567. as a broken-down time; typically this is because the year cannot fit into
  568. an @code{int}.
  569. Calling @code{localtime} also sets the current time zone as if
  570. @code{tzset} were called. @xref{Time Zone Functions}.
  571. @end deftypefun
  572. Using the @code{localtime} function is a big problem in multi-threaded
  573. programs. The result is returned in a static buffer and this is used in
  574. all threads. POSIX.1c introduced a variant of this function.
  575. @deftypefun {struct tm *} localtime_r (const time_t *@var{time}, struct tm *@var{resultp})
  576. @standards{POSIX.1c, time.h}
  577. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  578. @c localtime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  579. @c tz_convert(use_localtime) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  580. @c libc_lock_lock dup @asulock @aculock
  581. @c tzset_internal @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  582. @c always called with tzset_lock held
  583. @c sets static is_initialized before initialization;
  584. @c reads and sets old_tz; sets tz_rules.
  585. @c some of the issues only apply on the first call.
  586. @c subsequent calls only trigger these when called by localtime;
  587. @c otherwise, they're ok.
  588. @c getenv dup @mtsenv
  589. @c strcmp dup ok
  590. @c strdup @ascuheap
  591. @c tzfile_read @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  592. @c memcmp dup ok
  593. @c strstr dup ok
  594. @c getenv dup @mtsenv
  595. @c asprintf dup @mtslocale @ascuheap @acsmem
  596. @c stat64 dup ok
  597. @c fopen dup @ascuheap @asulock @acsmem @acsfd @aculock
  598. @c fileno dup ok
  599. @c fstat64 dup ok
  600. @c fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
  601. @c free dup @ascuheap @acsmem
  602. @c fsetlocking dup ok [no @mtasurace:stream @asulock, exclusive]
  603. @c fread_unlocked dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
  604. @c memcpy dup ok
  605. @c decode ok
  606. @c bswap_32 dup ok
  607. @c fseek dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
  608. @c ftello dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
  609. @c malloc dup @ascuheap @acsmem
  610. @c decode64 ok
  611. @c bswap_64 dup ok
  612. @c getc_unlocked ok [no @mtasurace:stream @asucorrupt @acucorrupt]
  613. @c tzstring dup @ascuheap @acsmem
  614. @c compute_tzname_max dup ok [guarded by tzset_lock]
  615. @c memset dup ok
  616. @c update_vars ok [guarded by tzset_lock]
  617. @c sets daylight, timezone, tzname and tzname_cur_max;
  618. @c called only with tzset_lock held, unless tzset_parse_tz
  619. @c (internal, but not static) gets called by users; given the its
  620. @c double-underscore-prefixed name, this interface violation could
  621. @c be regarded as undefined behavior.
  622. @c strlen ok
  623. @c tzset_parse_tz @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  624. @c sscanf dup @mtslocale @ascuheap @acsmem
  625. @c isalnum dup @mtsenv
  626. @c tzstring @ascuheap @acsmem
  627. @c reads and changes tzstring_list without synchronization, but
  628. @c only called with tzset_lock held (save for interface violations)
  629. @c strlen dup ok
  630. @c malloc dup @ascuheap @acsmem
  631. @c strcpy dup ok
  632. @c isdigit dup @mtslocale
  633. @c compute_offset ok
  634. @c tzfile_default @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  635. @c sets tzname, timezone, types, zone_names, rule_*off, etc; no guards
  636. @c strlen dup ok
  637. @c tzfile_read dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  638. @c mempcpy dup ok
  639. @c compute_tzname_max ok [if guarded by tzset_lock]
  640. @c iterates over zone_names; no guards
  641. @c free dup @ascuheap @acsmem
  642. @c strtoul dup @mtslocale
  643. @c update_vars dup ok
  644. @c tzfile_compute(use_localtime) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  645. @c sets tzname; no guards. with !use_localtime, as in gmtime, it's ok
  646. @c tzstring dup @acsuheap @acsmem
  647. @c tzset_parse_tz dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  648. @c offtime dup ok
  649. @c tz_compute dup ok
  650. @c strcmp dup ok
  651. @c offtime ok
  652. @c isleap dup ok
  653. @c tz_compute ok
  654. @c compute_change ok
  655. @c isleap ok
  656. @c libc_lock_unlock dup @aculock
  657. The @code{localtime_r} function works just like the @code{localtime}
  658. function. It takes a pointer to a variable containing a simple time
  659. and converts it to the broken-down time format.
  660. But the result is not placed in a static buffer. Instead it is placed
  661. in the object of type @code{struct tm} to which the parameter
  662. @var{resultp} points.
  663. If the conversion is successful the function returns a pointer to the
  664. object the result was written into, i.e., it returns @var{resultp}.
  665. @end deftypefun
  666. @deftypefun {struct tm *} gmtime (const time_t *@var{time})
  667. @standards{ISO, time.h}
  668. @safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  669. @c gmtime @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  670. @c tz_convert dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  671. This function is similar to @code{localtime}, except that the broken-down
  672. time is expressed as Coordinated Universal Time (UTC) (formerly called
  673. Greenwich Mean Time (GMT)) rather than relative to a local time zone.
  674. @end deftypefun
  675. As for the @code{localtime} function we have the problem that the result
  676. is placed in a static variable. POSIX.1c also provides a replacement for
  677. @code{gmtime}.
  678. @deftypefun {struct tm *} gmtime_r (const time_t *@var{time}, struct tm *@var{resultp})
  679. @standards{POSIX.1c, time.h}
  680. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  681. @c You'd think tz_convert could avoid some safety issues with
  682. @c !use_localtime, but no such luck: tzset_internal will always bring
  683. @c about all possible AS and AC problems when it's first called.
  684. @c Calling any of localtime,gmtime_r once would run the initialization
  685. @c and avoid the heap, mem and fd issues in gmtime* in subsequent calls,
  686. @c but the unsafe locking would remain.
  687. @c gmtime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  688. @c tz_convert(gmtime_r) dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  689. This function is similar to @code{localtime_r}, except that it converts
  690. just like @code{gmtime} the given time as Coordinated Universal Time.
  691. If the conversion is successful the function returns a pointer to the
  692. object the result was written into, i.e., it returns @var{resultp}.
  693. @end deftypefun
  694. @deftypefun time_t mktime (struct tm *@var{brokentime})
  695. @standards{ISO, time.h}
  696. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  697. @c mktime @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  698. @c passes a static localtime_offset to mktime_internal; it is read
  699. @c once, used as an initial guess, and updated at the end, but not
  700. @c used except as a guess for subsequent calls, so it should be safe.
  701. @c Even though a compiler might delay the load and perform it multiple
  702. @c times (bug 16346), there are at least two unconditional uses of the
  703. @c auto variable in which the first load is stored, separated by a
  704. @c call to an external function, and a conditional change of the
  705. @c variable before the external call, so refraining from allocating a
  706. @c local variable at the first load would be a very bad optimization.
  707. @c tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  708. @c mktime_internal(localtime_r) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  709. @c ydhms_diff ok
  710. @c ranged_convert(localtime_r) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  711. @c *convert = localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  712. @c time_t_avg dup ok
  713. @c guess_time_tm dup ok
  714. @c ydhms_diff dup ok
  715. @c time_t_add_ok ok
  716. @c time_t_avg ok
  717. @c isdst_differ ok
  718. @c time_t_int_add_ok ok
  719. The @code{mktime} function converts a broken-down time structure to a
  720. simple time representation. It also normalizes the contents of the
  721. broken-down time structure, and fills in some components based on the
  722. values of the others.
  723. The @code{mktime} function ignores the specified contents of the
  724. @code{tm_wday}, @code{tm_yday}, @code{tm_gmtoff}, and @code{tm_zone}
  725. members of the broken-down time
  726. structure. It uses the values of the other components to determine the
  727. calendar time; it's permissible for these components to have
  728. unnormalized values outside their normal ranges. The last thing that
  729. @code{mktime} does is adjust the components of the @var{brokentime}
  730. structure, including the members that were initially ignored.
  731. If the specified broken-down time cannot be represented as a simple time,
  732. @code{mktime} returns a value of @code{(time_t)(-1)} and does not modify
  733. the contents of @var{brokentime}.
  734. Calling @code{mktime} also sets the current time zone as if
  735. @code{tzset} were called; @code{mktime} uses this information instead
  736. of @var{brokentime}'s initial @code{tm_gmtoff} and @code{tm_zone}
  737. members. @xref{Time Zone Functions}.
  738. @end deftypefun
  739. @deftypefun time_t timelocal (struct tm *@var{brokentime})
  740. @standards{???, time.h}
  741. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  742. @c Alias to mktime.
  743. @code{timelocal} is functionally identical to @code{mktime}, but more
  744. mnemonically named. Note that it is the inverse of the @code{localtime}
  745. function.
  746. @strong{Portability note:} @code{mktime} is essentially universally
  747. available. @code{timelocal} is rather rare.
  748. @end deftypefun
  749. @deftypefun time_t timegm (struct tm *@var{brokentime})
  750. @standards{???, time.h}
  751. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  752. @c timegm @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  753. @c gmtime_offset triggers the same caveats as localtime_offset in mktime.
  754. @c although gmtime_r, as called by mktime, might save some issues,
  755. @c tzset calls tzset_internal with always, which forces
  756. @c reinitialization, so all issues may arise.
  757. @c tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  758. @c mktime_internal(gmtime_r) @asulock @aculock
  759. @c ..gmtime_r @asulock @aculock
  760. @c ... dup ok
  761. @c tz_convert(!use_localtime) @asulock @aculock
  762. @c ... dup @asulock @aculock
  763. @c tzfile_compute(!use_localtime) ok
  764. @code{timegm} is functionally identical to @code{mktime} except it
  765. always takes the input values to be Coordinated Universal Time (UTC)
  766. regardless of any local time zone setting.
  767. Note that @code{timegm} is the inverse of @code{gmtime}.
  768. @strong{Portability note:} @code{mktime} is essentially universally
  769. available. @code{timegm} is rather rare. For the most portable
  770. conversion from a UTC broken-down time to a simple time, set
  771. the @code{TZ} environment variable to UTC, call @code{mktime}, then set
  772. @code{TZ} back.
  773. @end deftypefun
  774. @node High Accuracy Clock
  775. @subsection High Accuracy Clock
  776. @cindex time, high precision
  777. @cindex clock, high accuracy
  778. @pindex sys/timex.h
  779. @c On Linux, GNU libc implements ntp_gettime() and npt_adjtime() as calls
  780. @c to adjtimex().
  781. The @code{ntp_gettime} and @code{ntp_adjtime} functions provide an
  782. interface to monitor and manipulate the system clock to maintain high
  783. accuracy time. For example, you can fine tune the speed of the clock
  784. or synchronize it with another time source.
  785. A typical use of these functions is by a server implementing the Network
  786. Time Protocol to synchronize the clocks of multiple systems and high
  787. precision clocks.
  788. These functions are declared in @file{sys/timex.h}.
  789. @tindex struct ntptimeval
  790. @deftp {Data Type} {struct ntptimeval}
  791. This structure is used for information about the system clock. It
  792. contains the following members:
  793. @table @code
  794. @item struct timeval time
  795. This is the current calendar time, expressed as the elapsed time since
  796. the epoch. The @code{struct timeval} data type is described in
  797. @ref{Elapsed Time}.
  798. @item long int maxerror
  799. This is the maximum error, measured in microseconds. Unless updated
  800. via @code{ntp_adjtime} periodically, this value will reach some
  801. platform-specific maximum value.
  802. @item long int esterror
  803. This is the estimated error, measured in microseconds. This value can
  804. be set by @code{ntp_adjtime} to indicate the estimated offset of the
  805. system clock from the true calendar time.
  806. @end table
  807. @end deftp
  808. @deftypefun int ntp_gettime (struct ntptimeval *@var{tptr})
  809. @standards{GNU, sys/timex.h}
  810. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  811. @c Wrapper for adjtimex.
  812. The @code{ntp_gettime} function sets the structure pointed to by
  813. @var{tptr} to current values. The elements of the structure afterwards
  814. contain the values the timer implementation in the kernel assumes. They
  815. might or might not be correct. If they are not, an @code{ntp_adjtime}
  816. call is necessary.
  817. The return value is @code{0} on success and other values on failure. The
  818. following @code{errno} error conditions are defined for this function:
  819. @vtable @code
  820. @item TIME_ERROR
  821. The precision clock model is not properly set up at the moment, thus the
  822. clock must be considered unsynchronized, and the values should be
  823. treated with care.
  824. @end vtable
  825. @end deftypefun
  826. @tindex struct timex
  827. @deftp {Data Type} {struct timex}
  828. This structure is used to control and monitor the system clock. It
  829. contains the following members:
  830. @table @code
  831. @item unsigned int modes
  832. This variable controls whether and which values are set. Several
  833. symbolic constants have to be combined with @emph{binary or} to specify
  834. the effective mode. These constants start with @code{MOD_}.
  835. @item long int offset
  836. This value indicates the current offset of the system clock from the true
  837. calendar time. The value is given in microseconds. If bit
  838. @code{MOD_OFFSET} is set in @code{modes}, the offset (and possibly other
  839. dependent values) can be set. The offset's absolute value must not
  840. exceed @code{MAXPHASE}.
  841. @item long int frequency
  842. This value indicates the difference in frequency between the true
  843. calendar time and the system clock. The value is expressed as scaled
  844. PPM (parts per million, 0.0001%). The scaling is @code{1 <<
  845. SHIFT_USEC}. The value can be set with bit @code{MOD_FREQUENCY}, but
  846. the absolute value must not exceed @code{MAXFREQ}.
  847. @item long int maxerror
  848. This is the maximum error, measured in microseconds. A new value can be
  849. set using bit @code{MOD_MAXERROR}. Unless updated via
  850. @code{ntp_adjtime} periodically, this value will increase steadily
  851. and reach some platform-specific maximum value.
  852. @item long int esterror
  853. This is the estimated error, measured in microseconds. This value can
  854. be set using bit @code{MOD_ESTERROR}.
  855. @item int status
  856. This variable reflects the various states of the clock machinery. There
  857. are symbolic constants for the significant bits, starting with
  858. @code{STA_}. Some of these flags can be updated using the
  859. @code{MOD_STATUS} bit.
  860. @item long int constant
  861. This value represents the bandwidth or stiffness of the PLL (phase
  862. locked loop) implemented in the kernel. The value can be changed using
  863. bit @code{MOD_TIMECONST}.
  864. @item long int precision
  865. This value represents the accuracy or the maximum error when reading the
  866. system clock. The value is expressed in microseconds.
  867. @item long int tolerance
  868. This value represents the maximum frequency error of the system clock in
  869. scaled PPM. This value is used to increase the @code{maxerror} every
  870. second.
  871. @item struct timeval time
  872. The current calendar time.
  873. @item long int tick
  874. The elapsed time between clock ticks in microseconds. A clock tick is a
  875. periodic timer interrupt on which the system clock is based.
  876. @item long int ppsfreq
  877. This is the first of a few optional variables that are present only if
  878. the system clock can use a PPS (pulse per second) signal to discipline
  879. the system clock. The value is expressed in scaled PPM and it denotes
  880. the difference in frequency between the system clock and the PPS signal.
  881. @item long int jitter
  882. This value expresses a median filtered average of the PPS signal's
  883. dispersion in microseconds.
  884. @item int shift
  885. This value is a binary exponent for the duration of the PPS calibration
  886. interval, ranging from @code{PPS_SHIFT} to @code{PPS_SHIFTMAX}.
  887. @item long int stabil
  888. This value represents the median filtered dispersion of the PPS
  889. frequency in scaled PPM.
  890. @item long int jitcnt
  891. This counter represents the number of pulses where the jitter exceeded
  892. the allowed maximum @code{MAXTIME}.
  893. @item long int calcnt
  894. This counter reflects the number of successful calibration intervals.
  895. @item long int errcnt
  896. This counter represents the number of calibration errors (caused by
  897. large offsets or jitter).
  898. @item long int stbcnt
  899. This counter denotes the number of calibrations where the stability
  900. exceeded the threshold.
  901. @end table
  902. @end deftp
  903. @deftypefun int ntp_adjtime (struct timex *@var{tptr})
  904. @standards{GNU, sys/timex.h}
  905. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  906. @c Alias to adjtimex syscall.
  907. The @code{ntp_adjtime} function sets the structure specified by
  908. @var{tptr} to current values.
  909. In addition, @code{ntp_adjtime} updates some settings to match what you
  910. pass to it in *@var{tptr}. Use the @code{modes} element of *@var{tptr}
  911. to select what settings to update. You can set @code{offset},
  912. @code{freq}, @code{maxerror}, @code{esterror}, @code{status},
  913. @code{constant}, and @code{tick}.
  914. @code{modes} = zero means set nothing.
  915. Only the superuser can update settings.
  916. @c On Linux, ntp_adjtime() also does the adjtime() function if you set
  917. @c modes = ADJ_OFFSET_SINGLESHOT (in fact, that is how GNU libc implements
  918. @c adjtime()). But this should be considered an internal function because
  919. @c it's so inconsistent with the rest of what ntp_adjtime() does and is
  920. @c forced in an ugly way into the struct timex. So we don't document it
  921. @c and instead document adjtime() as the way to achieve the function.
  922. The return value is @code{0} on success and other values on failure. The
  923. following @code{errno} error conditions are defined for this function:
  924. @table @code
  925. @item TIME_ERROR
  926. The high accuracy clock model is not properly set up at the moment, thus the
  927. clock must be considered unsynchronized, and the values should be
  928. treated with care. Another reason could be that the specified new values
  929. are not allowed.
  930. @item EPERM
  931. The process specified a settings update, but is not superuser.
  932. @end table
  933. For more details see RFC1305 (Network Time Protocol, Version 3) and
  934. related documents.
  935. @strong{Portability note:} Early versions of @theglibc{} did not
  936. have this function but did have the synonymous @code{adjtimex}.
  937. @end deftypefun
  938. @node Formatting Calendar Time
  939. @subsection Formatting Calendar Time
  940. The functions described in this section format calendar time values as
  941. strings. These functions are declared in the header file @file{time.h}.
  942. @pindex time.h
  943. @deftypefun {char *} asctime (const struct tm *@var{brokentime})
  944. @standards{ISO, time.h}
  945. @safety{@prelim{}@mtunsafe{@mtasurace{:asctime} @mtslocale{}}@asunsafe{}@acsafe{}}
  946. @c asctime @mtasurace:asctime @mtslocale
  947. @c Uses a static buffer.
  948. @c asctime_internal @mtslocale
  949. @c snprintf dup @mtslocale [no @acsuheap @acsmem]
  950. @c ab_day_name @mtslocale
  951. @c ab_month_name @mtslocale
  952. The @code{asctime} function converts the broken-down time value that
  953. @var{brokentime} points to into a string in a standard format:
  954. @smallexample
  955. "Tue May 21 13:46:22 1991\n"
  956. @end smallexample
  957. The abbreviations for the days of week are: @samp{Sun}, @samp{Mon},
  958. @samp{Tue}, @samp{Wed}, @samp{Thu}, @samp{Fri}, and @samp{Sat}.
  959. The abbreviations for the months are: @samp{Jan}, @samp{Feb},
  960. @samp{Mar}, @samp{Apr}, @samp{May}, @samp{Jun}, @samp{Jul}, @samp{Aug},
  961. @samp{Sep}, @samp{Oct}, @samp{Nov}, and @samp{Dec}.
  962. The return value points to a statically allocated string, which might be
  963. overwritten by subsequent calls to @code{asctime} or @code{ctime}.
  964. (But no other library function overwrites the contents of this
  965. string.)
  966. @end deftypefun
  967. @deftypefun {char *} asctime_r (const struct tm *@var{brokentime}, char *@var{buffer})
  968. @standards{POSIX.1c, time.h}
  969. @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
  970. @c asctime_r @mtslocale
  971. @c asctime_internal dup @mtslocale
  972. This function is similar to @code{asctime} but instead of placing the
  973. result in a static buffer it writes the string in the buffer pointed to
  974. by the parameter @var{buffer}. This buffer should have room
  975. for at least 26 bytes, including the terminating null.
  976. If no error occurred the function returns a pointer to the string the
  977. result was written into, i.e., it returns @var{buffer}. Otherwise
  978. it returns @code{NULL}.
  979. @end deftypefun
  980. @deftypefun {char *} ctime (const time_t *@var{time})
  981. @standards{ISO, time.h}
  982. @safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtasurace{:asctime} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  983. @c ctime @mtasurace:tmbuf @mtasurace:asctime @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  984. @c localtime dup @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  985. @c asctime dup @mtasurace:asctime @mtslocale
  986. The @code{ctime} function is similar to @code{asctime}, except that you
  987. specify the calendar time argument as a @code{time_t} simple time value
  988. rather than in broken-down local time format. It is equivalent to
  989. @smallexample
  990. asctime (localtime (@var{time}))
  991. @end smallexample
  992. Calling @code{ctime} also sets the current time zone as if
  993. @code{tzset} were called. @xref{Time Zone Functions}.
  994. @end deftypefun
  995. @deftypefun {char *} ctime_r (const time_t *@var{time}, char *@var{buffer})
  996. @standards{POSIX.1c, time.h}
  997. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  998. @c ctime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  999. @c localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1000. @c asctime_r dup @mtslocale
  1001. This function is similar to @code{ctime}, but places the result in the
  1002. string pointed to by @var{buffer}. It is equivalent to (written using
  1003. gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}):
  1004. @smallexample
  1005. (@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @})
  1006. @end smallexample
  1007. If no error occurred the function returns a pointer to the string the
  1008. result was written into, i.e., it returns @var{buffer}. Otherwise
  1009. it returns @code{NULL}.
  1010. @end deftypefun
  1011. @deftypefun size_t strftime (char *@var{s}, size_t @var{size}, const char *@var{template}, const struct tm *@var{brokentime})
  1012. @standards{ISO, time.h}
  1013. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
  1014. @c strftime @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
  1015. @c strftime_l @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
  1016. @c strftime_internal @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
  1017. @c add ok
  1018. @c memset_zero dup ok
  1019. @c memset_space dup ok
  1020. @c strlen dup ok
  1021. @c mbrlen @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd [no @mtasurace:mbstate/!ps]
  1022. @c mbsinit dup ok
  1023. @c cpy ok
  1024. @c add dup ok
  1025. @c memcpy_lowcase ok
  1026. @c TOLOWER ok
  1027. @c tolower_l ok
  1028. @c memcpy_uppcase ok
  1029. @c TOUPPER ok
  1030. @c toupper_l ok
  1031. @c MEMCPY ok
  1032. @c memcpy dup ok
  1033. @c ISDIGIT ok
  1034. @c STRLEN ok
  1035. @c strlen dup ok
  1036. @c strftime_internal dup @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
  1037. @c TOUPPER dup ok
  1038. @c nl_get_era_entry @ascuheap @asulock @acsmem @aculock
  1039. @c nl_init_era_entries @ascuheap @asulock @acsmem @aculock
  1040. @c libc_rwlock_wrlock dup @asulock @aculock
  1041. @c malloc dup @ascuheap @acsmem
  1042. @c memset dup ok
  1043. @c free dup @ascuheap @acsmem
  1044. @c realloc dup @ascuheap @acsmem
  1045. @c memcpy dup ok
  1046. @c strchr dup ok
  1047. @c wcschr dup ok
  1048. @c libc_rwlock_unlock dup @asulock @aculock
  1049. @c ERA_DATE_CMP ok
  1050. @c DO_NUMBER ok
  1051. @c DO_NUMBER_SPACEPAD ok
  1052. @c nl_get_alt_digit @ascuheap @asulock @acsmem @aculock
  1053. @c libc_rwlock_wrlock dup @asulock @aculock
  1054. @c nl_init_alt_digit @ascuheap @acsmem
  1055. @c malloc dup @ascuheap @acsmem
  1056. @c memset dup ok
  1057. @c strchr dup ok
  1058. @c libc_rwlock_unlock dup @aculock
  1059. @c memset_space ok
  1060. @c memset dup ok
  1061. @c memset_zero ok
  1062. @c memset dup ok
  1063. @c mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1064. @c iso_week_days ok
  1065. @c isleap ok
  1066. @c tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1067. @c localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1068. @c gmtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1069. @c tm_diff ok
  1070. This function is similar to the @code{sprintf} function (@pxref{Formatted
  1071. Input}), but the conversion specifications that can appear in the format
  1072. template @var{template} are specialized for printing components of the date
  1073. and time @var{brokentime} according to the locale currently specified for
  1074. time conversion (@pxref{Locales}) and the current time zone
  1075. (@pxref{Time Zone Functions}).
  1076. Ordinary characters appearing in the @var{template} are copied to the
  1077. output string @var{s}; this can include multibyte character sequences.
  1078. Conversion specifiers are introduced by a @samp{%} character, followed
  1079. by an optional flag which can be one of the following. These flags
  1080. are all GNU extensions. The first three affect only the output of
  1081. numbers:
  1082. @table @code
  1083. @item _
  1084. The number is padded with spaces.
  1085. @item -
  1086. The number is not padded at all.
  1087. @item 0
  1088. The number is padded with zeros even if the format specifies padding
  1089. with spaces.
  1090. @item ^
  1091. The output uses uppercase characters, but only if this is possible
  1092. (@pxref{Case Conversion}).
  1093. @end table
  1094. The default action is to pad the number with zeros to keep it a constant
  1095. width. Numbers that do not have a range indicated below are never
  1096. padded, since there is no natural width for them.
  1097. Following the flag an optional specification of the width is possible.
  1098. This is specified in decimal notation. If the natural size of the
  1099. output of the field has less than the specified number of characters,
  1100. the result is written right adjusted and space padded to the given
  1101. size.
  1102. An optional modifier can follow the optional flag and width
  1103. specification. The modifiers, which were first standardized by
  1104. POSIX.2-1992 and by @w{ISO C99}, are:
  1105. @table @code
  1106. @item E
  1107. Use the locale's alternative representation for date and time. This
  1108. modifier applies to the @code{%c}, @code{%C}, @code{%x}, @code{%X},
  1109. @code{%y} and @code{%Y} format specifiers. In a Japanese locale, for
  1110. example, @code{%Ex} might yield a date format based on the Japanese
  1111. Emperors' reigns.
  1112. @item O
  1113. With all format specifiers that produce numbers: use the locale's
  1114. alternative numeric symbols.
  1115. With @code{%B}, @code{%b}, and @code{%h}: use the grammatical form for
  1116. month names that is appropriate when the month is named by itself,
  1117. rather than the form that is appropriate when the month is used as
  1118. part of a complete date. This is a GNU extension.
  1119. @end table
  1120. If the format supports the modifier but no alternative representation
  1121. is available, it is ignored.
  1122. The conversion specifier ends with a format specifier taken from the
  1123. following list. The whole @samp{%} sequence is replaced in the output
  1124. string as follows:
  1125. @table @code
  1126. @item %a
  1127. The abbreviated weekday name according to the current locale.
  1128. @item %A
  1129. The full weekday name according to the current locale.
  1130. @item %b
  1131. The abbreviated month name according to the current locale, in the
  1132. grammatical form used when the month is part of a complete date.
  1133. As a GNU extension, the @code{O} modifier can be used (@code{%Ob})
  1134. to get the grammatical form used when the month is named by itself.
  1135. @item %B
  1136. The full month name according to the current locale, in the
  1137. grammatical form used when the month is part of a complete date.
  1138. As a GNU extension, the @code{O} modifier can be used (@code{%OB})
  1139. to get the grammatical form used when the month is named by itself.
  1140. Note that not all languages need two different forms of the month
  1141. names, so the text produced by @code{%B} and @code{%OB}, and by
  1142. @code{%b} and @code{%Ob}, may or may not be the same, depending on
  1143. the locale.
  1144. @item %c
  1145. The preferred calendar time representation for the current locale.
  1146. @item %C
  1147. The century of the year. This is equivalent to the greatest integer not
  1148. greater than the year divided by 100.
  1149. If the @code{E} modifier is specified (@code{%EC}), instead produces
  1150. the name of the period for the year (e.g.@: an era name) in the
  1151. locale's alternative calendar.
  1152. This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
  1153. @item %d
  1154. The day of the month as a decimal number (range @code{01} through @code{31}).
  1155. @item %D
  1156. The date using the format @code{%m/%d/%y}.
  1157. This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
  1158. @item %e
  1159. The day of the month like with @code{%d}, but padded with spaces (range
  1160. @code{ 1} through @code{31}).
  1161. This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
  1162. @item %F
  1163. The date using the format @code{%Y-%m-%d}. This is the form specified
  1164. in the @w{ISO 8601} standard and is the preferred form for all uses.
  1165. This format was first standardized by @w{ISO C99} and by POSIX.1-2001.
  1166. @item %g
  1167. The year corresponding to the ISO week number, but without the century
  1168. (range @code{00} through @code{99}). This has the same format and value
  1169. as @code{%y}, except that if the ISO week number (see @code{%V}) belongs
  1170. to the previous or next year, that year is used instead.
  1171. This format was first standardized by @w{ISO C99} and by POSIX.1-2001.
  1172. @item %G
  1173. The year corresponding to the ISO week number. This has the same format
  1174. and value as @code{%Y}, except that if the ISO week number (see
  1175. @code{%V}) belongs to the previous or next year, that year is used
  1176. instead.
  1177. This format was first standardized by @w{ISO C99} and by POSIX.1-2001
  1178. but was previously available as a GNU extension.
  1179. @item %h
  1180. The abbreviated month name according to the current locale. The action
  1181. is the same as for @code{%b}.
  1182. This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
  1183. @item %H
  1184. The hour as a decimal number, using a 24-hour clock (range @code{00} through
  1185. @code{23}).
  1186. @item %I
  1187. The hour as a decimal number, using a 12-hour clock (range @code{01} through
  1188. @code{12}).
  1189. @item %j
  1190. The day of the year as a decimal number (range @code{001} through @code{366}).
  1191. @item %k
  1192. The hour as a decimal number, using a 24-hour clock like @code{%H}, but
  1193. padded with spaces (range @code{ 0} through @code{23}).
  1194. This format is a GNU extension.
  1195. @item %l
  1196. The hour as a decimal number, using a 12-hour clock like @code{%I}, but
  1197. padded with spaces (range @code{ 1} through @code{12}).
  1198. This format is a GNU extension.
  1199. @item %m
  1200. The month as a decimal number (range @code{01} through @code{12}).
  1201. @item %M
  1202. The minute as a decimal number (range @code{00} through @code{59}).
  1203. @item %n
  1204. A single @samp{\n} (newline) character.
  1205. This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
  1206. @item %p
  1207. Either @samp{AM} or @samp{PM}, according to the given time value; or the
  1208. corresponding strings for the current locale. Noon is treated as
  1209. @samp{PM} and midnight as @samp{AM}. In most locales
  1210. @samp{AM}/@samp{PM} format is not supported, in such cases @code{"%p"}
  1211. yields an empty string.
  1212. @ignore
  1213. We currently have a problem with makeinfo. Write @samp{AM} and @samp{am}
  1214. both results in `am'. I.e., the difference in case is not visible anymore.
  1215. @end ignore
  1216. @item %P
  1217. Either @samp{am} or @samp{pm}, according to the given time value; or the
  1218. corresponding strings for the current locale, printed in lowercase
  1219. characters. Noon is treated as @samp{pm} and midnight as @samp{am}. In
  1220. most locales @samp{AM}/@samp{PM} format is not supported, in such cases
  1221. @code{"%P"} yields an empty string.
  1222. This format is a GNU extension.
  1223. @item %r
  1224. The complete calendar time using the AM/PM format of the current locale.
  1225. This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
  1226. In the POSIX locale, this format is equivalent to @code{%I:%M:%S %p}.
  1227. @item %R
  1228. The hour and minute in decimal numbers using the format @code{%H:%M}.
  1229. This format was first standardized by @w{ISO C99} and by POSIX.1-2001
  1230. but was previously available as a GNU extension.
  1231. @item %s
  1232. The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
  1233. Leap seconds are not counted unless leap second support is available.
  1234. This format is a GNU extension.
  1235. @item %S
  1236. The seconds as a decimal number (range @code{00} through @code{60}).
  1237. @item %t
  1238. A single @samp{\t} (tabulator) character.
  1239. This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
  1240. @item %T
  1241. The time of day using decimal numbers using the format @code{%H:%M:%S}.
  1242. This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
  1243. @item %u
  1244. The day of the week as a decimal number (range @code{1} through
  1245. @code{7}), Monday being @code{1}.
  1246. This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
  1247. @item %U
  1248. The week number of the current year as a decimal number (range @code{00}
  1249. through @code{53}), starting with the first Sunday as the first day of
  1250. the first week. Days preceding the first Sunday in the year are
  1251. considered to be in week @code{00}.
  1252. @item %V
  1253. The @w{ISO 8601:1988} week number as a decimal number (range @code{01}
  1254. through @code{53}). ISO weeks start with Monday and end with Sunday.
  1255. Week @code{01} of a year is the first week which has the majority of its
  1256. days in that year; this is equivalent to the week containing the year's
  1257. first Thursday, and it is also equivalent to the week containing January
  1258. 4. Week @code{01} of a year can contain days from the previous year.
  1259. The week before week @code{01} of a year is the last week (@code{52} or
  1260. @code{53}) of the previous year even if it contains days from the new
  1261. year.
  1262. This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
  1263. @item %w
  1264. The day of the week as a decimal number (range @code{0} through
  1265. @code{6}), Sunday being @code{0}.
  1266. @item %W
  1267. The week number of the current year as a decimal number (range @code{00}
  1268. through @code{53}), starting with the first Monday as the first day of
  1269. the first week. All days preceding the first Monday in the year are
  1270. considered to be in week @code{00}.
  1271. @item %x
  1272. The preferred date representation for the current locale.
  1273. @item %X
  1274. The preferred time of day representation for the current locale.
  1275. @item %y
  1276. The year without a century as a decimal number (range @code{00} through
  1277. @code{99}). This is equivalent to the year modulo 100.
  1278. If the @code{E} modifier is specified (@code{%Ey}), instead produces
  1279. the year number according to a locale-specific alternative calendar.
  1280. Unlike @code{%y}, the number is @emph{not} reduced modulo 100.
  1281. However, by default it is zero-padded to a minimum of two digits (this
  1282. can be overridden by an explicit field width or by the @code{_} and
  1283. @code{-} flags).
  1284. @item %Y
  1285. The year as a decimal number, using the Gregorian calendar. Years
  1286. before the year @code{1} are numbered @code{0}, @code{-1}, and so on.
  1287. If the @code{E} modifier is specified (@code{%EY}), instead produces a
  1288. complete representation of the year according to the locale's
  1289. alternative calendar. Generally this will be some combination of the
  1290. information produced by @code{%EC} and @code{Ey}. As a GNU extension,
  1291. the formatting flags @code{_} or @code{-} may be used with this
  1292. conversion specifier; they affect how the year number is printed.
  1293. @item %z
  1294. @w{RFC 822}/@w{ISO 8601:1988} style numeric time zone (e.g.,
  1295. @code{-0600} or @code{+0100}), or nothing if no time zone is
  1296. determinable.
  1297. This format was first standardized by @w{ISO C99} and by POSIX.1-2001
  1298. but was previously available as a GNU extension.
  1299. In the POSIX locale, a full @w{RFC 822} timestamp is generated by the format
  1300. @w{@samp{"%a, %d %b %Y %H:%M:%S %z"}} (or the equivalent
  1301. @w{@samp{"%a, %d %b %Y %T %z"}}).
  1302. @item %Z
  1303. The time zone abbreviation (empty if the time zone can't be determined).
  1304. @item %%
  1305. A literal @samp{%} character.
  1306. @end table
  1307. The @var{size} parameter can be used to specify the maximum number of
  1308. characters to be stored in the array @var{s}, including the terminating
  1309. null character. If the formatted time requires more than @var{size}
  1310. characters, @code{strftime} returns zero and the contents of the array
  1311. @var{s} are undefined. Otherwise the return value indicates the
  1312. number of characters placed in the array @var{s}, not including the
  1313. terminating null character.
  1314. @emph{Warning:} This convention for the return value which is prescribed
  1315. in @w{ISO C} can lead to problems in some situations. For certain
  1316. format strings and certain locales the output really can be the empty
  1317. string and this cannot be discovered by testing the return value only.
  1318. E.g., in most locales the AM/PM time format is not supported (most of
  1319. the world uses the 24 hour time representation). In such locales
  1320. @code{"%p"} will return the empty string, i.e., the return value is
  1321. zero. To detect situations like this something similar to the following
  1322. code should be used:
  1323. @smallexample
  1324. buf[0] = '\1';
  1325. len = strftime (buf, bufsize, format, tp);
  1326. if (len == 0 && buf[0] != '\0')
  1327. @{
  1328. /* Something went wrong in the strftime call. */
  1329. @dots{}
  1330. @}
  1331. @end smallexample
  1332. If @var{s} is a null pointer, @code{strftime} does not actually write
  1333. anything, but instead returns the number of characters it would have written.
  1334. Calling @code{strftime} also sets the current time zone as if
  1335. @code{tzset} were called; @code{strftime} uses this information
  1336. instead of @var{brokentime}'s @code{tm_gmtoff} and @code{tm_zone}
  1337. members. @xref{Time Zone Functions}.
  1338. For an example of @code{strftime}, see @ref{Time Functions Example}.
  1339. @end deftypefun
  1340. @deftypefun size_t wcsftime (wchar_t *@var{s}, size_t @var{size}, const wchar_t *@var{template}, const struct tm *@var{brokentime})
  1341. @standards{ISO/Amend1, time.h}
  1342. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
  1343. @c wcsftime @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
  1344. @c wcsftime_l @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
  1345. @c wcsftime_internal @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
  1346. @c add ok
  1347. @c memset_zero dup ok
  1348. @c memset_space dup ok
  1349. @c wcslen dup ok
  1350. @c cpy ok
  1351. @c add dup ok
  1352. @c memcpy_lowcase ok
  1353. @c TOLOWER ok
  1354. @c towlower_l dup ok
  1355. @c memcpy_uppcase ok
  1356. @c TOUPPER ok
  1357. @c towupper_l dup ok
  1358. @c MEMCPY ok
  1359. @c wmemcpy dup ok
  1360. @c widen @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
  1361. @c memset dup ok
  1362. @c mbsrtowcs_l @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd [no @mtasurace:mbstate/!ps]
  1363. @c ISDIGIT ok
  1364. @c STRLEN ok
  1365. @c wcslen dup ok
  1366. @c wcsftime_internal dup @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
  1367. @c TOUPPER dup ok
  1368. @c nl_get_era_entry dup @ascuheap @asulock @acsmem @aculock
  1369. @c DO_NUMBER ok
  1370. @c DO_NUMBER_SPACEPAD ok
  1371. @c nl_get_walt_digit dup @ascuheap @asulock @acsmem @aculock
  1372. @c libc_rwlock_wrlock dup @asulock @aculock
  1373. @c nl_init_alt_digit dup @ascuheap @acsmem
  1374. @c malloc dup @ascuheap @acsmem
  1375. @c memset dup ok
  1376. @c wcschr dup ok
  1377. @c libc_rwlock_unlock dup @aculock
  1378. @c memset_space ok
  1379. @c wmemset dup ok
  1380. @c memset_zero ok
  1381. @c wmemset dup ok
  1382. @c mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1383. @c iso_week_days ok
  1384. @c isleap ok
  1385. @c tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1386. @c localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1387. @c gmtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1388. @c tm_diff ok
  1389. The @code{wcsftime} function is equivalent to the @code{strftime}
  1390. function with the difference that it operates on wide character
  1391. strings. The buffer where the result is stored, pointed to by @var{s},
  1392. must be an array of wide characters. The parameter @var{size} which
  1393. specifies the size of the output buffer gives the number of wide
  1394. characters, not the number of bytes.
  1395. Also the format string @var{template} is a wide character string. Since
  1396. all characters needed to specify the format string are in the basic
  1397. character set it is portably possible to write format strings in the C
  1398. source code using the @code{L"@dots{}"} notation. The parameter
  1399. @var{brokentime} has the same meaning as in the @code{strftime} call.
  1400. The @code{wcsftime} function supports the same flags, modifiers, and
  1401. format specifiers as the @code{strftime} function.
  1402. The return value of @code{wcsftime} is the number of wide characters
  1403. stored in @code{s}. When more characters would have to be written than
  1404. can be placed in the buffer @var{s} the return value is zero, with the
  1405. same problems indicated in the @code{strftime} documentation.
  1406. @end deftypefun
  1407. @node Parsing Date and Time
  1408. @subsection Convert textual time and date information back
  1409. The @w{ISO C} standard does not specify any functions which can convert
  1410. the output of the @code{strftime} function back into a binary format.
  1411. This led to a variety of more-or-less successful implementations with
  1412. different interfaces over the years. Then the Unix standard was
  1413. extended by the addition of two functions: @code{strptime} and
  1414. @code{getdate}. Both have strange interfaces but at least they are
  1415. widely available.
  1416. @menu
  1417. * Low-Level Time String Parsing:: Interpret string according to given format.
  1418. * General Time String Parsing:: User-friendly function to parse data and
  1419. time strings.
  1420. @end menu
  1421. @node Low-Level Time String Parsing
  1422. @subsubsection Interpret string according to given format
  1423. The first function is rather low-level. It is nevertheless frequently
  1424. used in software since it is better known. Its interface and
  1425. implementation are heavily influenced by the @code{getdate} function,
  1426. which is defined and implemented in terms of calls to @code{strptime}.
  1427. @deftypefun {char *} strptime (const char *@var{s}, const char *@var{fmt}, struct tm *@var{tp})
  1428. @standards{XPG4, time.h}
  1429. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  1430. @c strptime @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1431. @c strptime_internal @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1432. @c memset dup ok
  1433. @c ISSPACE ok
  1434. @c isspace_l dup ok
  1435. @c match_char ok
  1436. @c match_string ok
  1437. @c strlen dup ok
  1438. @c strncasecmp_l dup ok
  1439. @c strcmp dup ok
  1440. @c recursive @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1441. @c strptime_internal dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1442. @c get_number ok
  1443. @c ISSPACE dup ok
  1444. @c localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1445. @c nl_select_era_entry @ascuheap @asulock @acsmem @aculock
  1446. @c nl_init_era_entries dup @ascuheap @asulock @acsmem @aculock
  1447. @c get_alt_number dup @ascuheap @asulock @acsmem @aculock
  1448. @c nl_parse_alt_digit dup @ascuheap @asulock @acsmem @aculock
  1449. @c libc_rwlock_wrlock dup @asulock @aculock
  1450. @c nl_init_alt_digit dup @ascuheap @acsmem
  1451. @c libc_rwlock_unlock dup @aculock
  1452. @c get_number dup ok
  1453. @c day_of_the_week ok
  1454. @c day_of_the_year ok
  1455. The @code{strptime} function parses the input string @var{s} according
  1456. to the format string @var{fmt} and stores its results in the
  1457. structure @var{tp}.
  1458. The input string could be generated by a @code{strftime} call or
  1459. obtained any other way. It does not need to be in a human-recognizable
  1460. format; e.g. a date passed as @code{"02:1999:9"} is acceptable, even
  1461. though it is ambiguous without context. As long as the format string
  1462. @var{fmt} matches the input string the function will succeed.
  1463. The user has to make sure, though, that the input can be parsed in a
  1464. unambiguous way. The string @code{"1999112"} can be parsed using the
  1465. format @code{"%Y%m%d"} as 1999-1-12, 1999-11-2, or even 19991-1-2. It
  1466. is necessary to add appropriate separators to reliably get results.
  1467. The format string consists of the same components as the format string
  1468. of the @code{strftime} function. The only difference is that the flags
  1469. @code{_}, @code{-}, @code{0}, and @code{^} are not allowed.
  1470. @comment Is this really the intention? --drepper
  1471. Several of the distinct formats of @code{strftime} do the same work in
  1472. @code{strptime} since differences like case of the input do not matter.
  1473. For reasons of symmetry all formats are supported, though.
  1474. The modifiers @code{E} and @code{O} are also allowed everywhere the
  1475. @code{strftime} function allows them.
  1476. The formats are:
  1477. @table @code
  1478. @item %a
  1479. @itemx %A
  1480. The weekday name according to the current locale, in abbreviated form or
  1481. the full name.
  1482. @item %b
  1483. @itemx %B
  1484. @itemx %h
  1485. A month name according to the current locale. All three specifiers
  1486. will recognize both abbreviated and full month names. If the
  1487. locale provides two different grammatical forms of month names,
  1488. all three specifiers will recognize both forms.
  1489. As a GNU extension, the @code{O} modifier can be used with these
  1490. specifiers; it has no effect, as both grammatical forms of month
  1491. names are recognized.
  1492. @item %c
  1493. The date and time representation for the current locale.
  1494. @item %Ec
  1495. Like @code{%c} but the locale's alternative date and time format is used.
  1496. @item %C
  1497. The century of the year.
  1498. It makes sense to use this format only if the format string also
  1499. contains the @code{%y} format.
  1500. @item %EC
  1501. The locale's representation of the period.
  1502. Unlike @code{%C} it sometimes makes sense to use this format since some
  1503. cultures represent years relative to the beginning of eras instead of
  1504. using the Gregorian years.
  1505. @item %d
  1506. @item %e
  1507. The day of the month as a decimal number (range @code{1} through @code{31}).
  1508. Leading zeroes are permitted but not required.
  1509. @item %Od
  1510. @itemx %Oe
  1511. Same as @code{%d} but using the locale's alternative numeric symbols.
  1512. Leading zeroes are permitted but not required.
  1513. @item %D
  1514. Equivalent to @code{%m/%d/%y}.
  1515. @item %F
  1516. Equivalent to @code{%Y-%m-%d}, which is the @w{ISO 8601} date
  1517. format.
  1518. This is a GNU extension following an @w{ISO C99} extension to
  1519. @code{strftime}.
  1520. @item %g
  1521. The year corresponding to the ISO week number, but without the century
  1522. (range @code{00} through @code{99}).
  1523. @emph{Note:} Currently, this is not fully implemented. The format is
  1524. recognized, input is consumed but no field in @var{tm} is set.
  1525. This format is a GNU extension following a GNU extension of @code{strftime}.
  1526. @item %G
  1527. The year corresponding to the ISO week number.
  1528. @emph{Note:} Currently, this is not fully implemented. The format is
  1529. recognized, input is consumed but no field in @var{tm} is set.
  1530. This format is a GNU extension following a GNU extension of @code{strftime}.
  1531. @item %H
  1532. @itemx %k
  1533. The hour as a decimal number, using a 24-hour clock (range @code{00} through
  1534. @code{23}).
  1535. @code{%k} is a GNU extension following a GNU extension of @code{strftime}.
  1536. @item %OH
  1537. Same as @code{%H} but using the locale's alternative numeric symbols.
  1538. @item %I
  1539. @itemx %l
  1540. The hour as a decimal number, using a 12-hour clock (range @code{01} through
  1541. @code{12}).
  1542. @code{%l} is a GNU extension following a GNU extension of @code{strftime}.
  1543. @item %OI
  1544. Same as @code{%I} but using the locale's alternative numeric symbols.
  1545. @item %j
  1546. The day of the year as a decimal number (range @code{1} through @code{366}).
  1547. Leading zeroes are permitted but not required.
  1548. @item %m
  1549. The month as a decimal number (range @code{1} through @code{12}).
  1550. Leading zeroes are permitted but not required.
  1551. @item %Om
  1552. Same as @code{%m} but using the locale's alternative numeric symbols.
  1553. @item %M
  1554. The minute as a decimal number (range @code{0} through @code{59}).
  1555. Leading zeroes are permitted but not required.
  1556. @item %OM
  1557. Same as @code{%M} but using the locale's alternative numeric symbols.
  1558. @item %n
  1559. @itemx %t
  1560. Matches any white space.
  1561. @item %p
  1562. @item %P
  1563. The locale-dependent equivalent to @samp{AM} or @samp{PM}.
  1564. This format is not useful unless @code{%I} or @code{%l} is also used.
  1565. Another complication is that the locale might not define these values at
  1566. all and therefore the conversion fails.
  1567. @code{%P} is a GNU extension following a GNU extension to @code{strftime}.
  1568. @item %r
  1569. The complete time using the AM/PM format of the current locale.
  1570. A complication is that the locale might not define this format at all
  1571. and therefore the conversion fails.
  1572. @item %R
  1573. The hour and minute in decimal numbers using the format @code{%H:%M}.
  1574. @code{%R} is a GNU extension following a GNU extension to @code{strftime}.
  1575. @item %s
  1576. The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
  1577. Leap seconds are not counted unless leap second support is available.
  1578. @code{%s} is a GNU extension following a GNU extension to @code{strftime}.
  1579. @item %S
  1580. The seconds as a decimal number (range @code{0} through @code{60}).
  1581. Leading zeroes are permitted but not required.
  1582. @strong{NB:} The Unix specification says the upper bound on this value
  1583. is @code{61}, a result of a decision to allow double leap seconds. You
  1584. will not see the value @code{61} because no minute has more than one
  1585. leap second, but the myth persists.
  1586. @item %OS
  1587. Same as @code{%S} but using the locale's alternative numeric symbols.
  1588. @item %T
  1589. Equivalent to the use of @code{%H:%M:%S} in this place.
  1590. @item %u
  1591. The day of the week as a decimal number (range @code{1} through
  1592. @code{7}), Monday being @code{1}.
  1593. Leading zeroes are permitted but not required.
  1594. @emph{Note:} Currently, this is not fully implemented. The format is
  1595. recognized, input is consumed but no field in @var{tm} is set.
  1596. @item %U
  1597. The week number of the current year as a decimal number (range @code{0}
  1598. through @code{53}).
  1599. Leading zeroes are permitted but not required.
  1600. @item %OU
  1601. Same as @code{%U} but using the locale's alternative numeric symbols.
  1602. @item %V
  1603. The @w{ISO 8601:1988} week number as a decimal number (range @code{1}
  1604. through @code{53}).
  1605. Leading zeroes are permitted but not required.
  1606. @emph{Note:} Currently, this is not fully implemented. The format is
  1607. recognized, input is consumed but no field in @var{tm} is set.
  1608. @item %w
  1609. The day of the week as a decimal number (range @code{0} through
  1610. @code{6}), Sunday being @code{0}.
  1611. Leading zeroes are permitted but not required.
  1612. @emph{Note:} Currently, this is not fully implemented. The format is
  1613. recognized, input is consumed but no field in @var{tm} is set.
  1614. @item %Ow
  1615. Same as @code{%w} but using the locale's alternative numeric symbols.
  1616. @item %W
  1617. The week number of the current year as a decimal number (range @code{0}
  1618. through @code{53}).
  1619. Leading zeroes are permitted but not required.
  1620. @emph{Note:} Currently, this is not fully implemented. The format is
  1621. recognized, input is consumed but no field in @var{tm} is set.
  1622. @item %OW
  1623. Same as @code{%W} but using the locale's alternative numeric symbols.
  1624. @item %x
  1625. The date using the locale's date format.
  1626. @item %Ex
  1627. Like @code{%x} but the locale's alternative data representation is used.
  1628. @item %X
  1629. The time using the locale's time format.
  1630. @item %EX
  1631. Like @code{%X} but the locale's alternative time representation is used.
  1632. @item %y
  1633. The year without a century as a decimal number (range @code{0} through
  1634. @code{99}).
  1635. Leading zeroes are permitted but not required.
  1636. Note that it is questionable to use this format without
  1637. the @code{%C} format. The @code{strptime} function does regard input
  1638. values in the range @math{68} to @math{99} as the years @math{1969} to
  1639. @math{1999} and the values @math{0} to @math{68} as the years
  1640. @math{2000} to @math{2068}. But maybe this heuristic fails for some
  1641. input data.
  1642. Therefore it is best to avoid @code{%y} completely and use @code{%Y}
  1643. instead.
  1644. @item %Ey
  1645. The offset from @code{%EC} in the locale's alternative representation.
  1646. @item %Oy
  1647. The offset of the year (from @code{%C}) using the locale's alternative
  1648. numeric symbols.
  1649. @item %Y
  1650. The year as a decimal number, using the Gregorian calendar.
  1651. @item %EY
  1652. The full alternative year representation.
  1653. @item %z
  1654. The offset from GMT in @w{ISO 8601}/RFC822 format.
  1655. @item %Z
  1656. The timezone name.
  1657. @emph{Note:} Currently, this is not fully implemented. The format is
  1658. recognized, input is consumed but no field in @var{tm} is set.
  1659. @item %%
  1660. A literal @samp{%} character.
  1661. @end table
  1662. All other characters in the format string must have a matching character
  1663. in the input string. Exceptions are white spaces in the input string
  1664. which can match zero or more whitespace characters in the format string.
  1665. @strong{Portability Note:} The XPG standard advises applications to use
  1666. at least one whitespace character (as specified by @code{isspace}) or
  1667. other non-alphanumeric characters between any two conversion
  1668. specifications. @Theglibc{} does not have this limitation but
  1669. other libraries might have trouble parsing formats like
  1670. @code{"%d%m%Y%H%M%S"}.
  1671. The @code{strptime} function processes the input string from right to
  1672. left. Each of the three possible input elements (white space, literal,
  1673. or format) are handled one after the other. If the input cannot be
  1674. matched to the format string the function stops. The remainder of the
  1675. format and input strings are not processed.
  1676. The function returns a pointer to the first character it was unable to
  1677. process. If the input string contains more characters than required by
  1678. the format string the return value points right after the last consumed
  1679. input character. If the whole input string is consumed the return value
  1680. points to the @code{NULL} byte at the end of the string. If an error
  1681. occurs, i.e., @code{strptime} fails to match all of the format string,
  1682. the function returns @code{NULL}.
  1683. @end deftypefun
  1684. The specification of the function in the XPG standard is rather vague,
  1685. leaving out a few important pieces of information. Most importantly, it
  1686. does not specify what happens to those elements of @var{tm} which are
  1687. not directly initialized by the different formats. The
  1688. implementations on different Unix systems vary here.
  1689. The @glibcadj{} implementation does not touch those fields which are not
  1690. directly initialized. Exceptions are the @code{tm_wday} and
  1691. @code{tm_yday} elements, which are recomputed if any of the year, month,
  1692. or date elements changed. This has two implications:
  1693. @itemize @bullet
  1694. @item
  1695. Before calling the @code{strptime} function for a new input string, you
  1696. should prepare the @var{tm} structure you pass. Normally this will mean
  1697. initializing all values to zero. Alternatively, you can set all
  1698. fields to values like @code{INT_MAX}, allowing you to determine which
  1699. elements were set by the function call. Zero does not work here since
  1700. it is a valid value for many of the fields.
  1701. Careful initialization is necessary if you want to find out whether a
  1702. certain field in @var{tm} was initialized by the function call.
  1703. @item
  1704. You can construct a @code{struct tm} value with several consecutive
  1705. @code{strptime} calls. A useful application of this is e.g. the parsing
  1706. of two separate strings, one containing date information and the other
  1707. time information. By parsing one after the other without clearing the
  1708. structure in-between, you can construct a complete broken-down time.
  1709. @end itemize
  1710. The following example shows a function which parses a string which
  1711. contains the date information in either US style or @w{ISO 8601} form:
  1712. @smallexample
  1713. const char *
  1714. parse_date (const char *input, struct tm *tm)
  1715. @{
  1716. const char *cp;
  1717. /* @r{First clear the result structure.} */
  1718. memset (tm, '\0', sizeof (*tm));
  1719. /* @r{Try the ISO format first.} */
  1720. cp = strptime (input, "%F", tm);
  1721. if (cp == NULL)
  1722. @{
  1723. /* @r{Does not match. Try the US form.} */
  1724. cp = strptime (input, "%D", tm);
  1725. @}
  1726. return cp;
  1727. @}
  1728. @end smallexample
  1729. @node General Time String Parsing
  1730. @subsubsection A More User-friendly Way to Parse Times and Dates
  1731. The Unix standard defines another function for parsing date strings.
  1732. The interface is weird, but if the function happens to suit your
  1733. application it is just fine. It is problematic to use this function
  1734. in multi-threaded programs or libraries, since it returns a pointer to
  1735. a static variable, and uses a global variable and global state (an
  1736. environment variable).
  1737. @defvar getdate_err
  1738. @standards{Unix98, time.h}
  1739. This variable of type @code{int} contains the error code of the last
  1740. unsuccessful call to @code{getdate}. Defined values are:
  1741. @table @math
  1742. @item 1
  1743. The environment variable @code{DATEMSK} is not defined or null.
  1744. @item 2
  1745. The template file denoted by the @code{DATEMSK} environment variable
  1746. cannot be opened.
  1747. @item 3
  1748. Information about the template file cannot retrieved.
  1749. @item 4
  1750. The template file is not a regular file.
  1751. @item 5
  1752. An I/O error occurred while reading the template file.
  1753. @item 6
  1754. Not enough memory available to execute the function.
  1755. @item 7
  1756. The template file contains no matching template.
  1757. @item 8
  1758. The input date is invalid, but would match a template otherwise. This
  1759. includes dates like February 31st, and dates which cannot be represented
  1760. in a @code{time_t} variable.
  1761. @end table
  1762. @end defvar
  1763. @deftypefun {struct tm *} getdate (const char *@var{string})
  1764. @standards{Unix98, time.h}
  1765. @safety{@prelim{}@mtunsafe{@mtasurace{:getdate} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  1766. @c getdate @mtasurace:getdate @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1767. @c getdate_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1768. The interface to @code{getdate} is the simplest possible for a function
  1769. to parse a string and return the value. @var{string} is the input
  1770. string and the result is returned in a statically-allocated variable.
  1771. The details about how the string is processed are hidden from the user.
  1772. In fact, they can be outside the control of the program. Which formats
  1773. are recognized is controlled by the file named by the environment
  1774. variable @code{DATEMSK}. This file should contain
  1775. lines of valid format strings which could be passed to @code{strptime}.
  1776. The @code{getdate} function reads these format strings one after the
  1777. other and tries to match the input string. The first line which
  1778. completely matches the input string is used.
  1779. Elements not initialized through the format string retain the values
  1780. present at the time of the @code{getdate} function call.
  1781. The formats recognized by @code{getdate} are the same as for
  1782. @code{strptime}. See above for an explanation. There are only a few
  1783. extensions to the @code{strptime} behavior:
  1784. @itemize @bullet
  1785. @item
  1786. If the @code{%Z} format is given the broken-down time is based on the
  1787. current time of the timezone matched, not of the current timezone of the
  1788. runtime environment.
  1789. @emph{Note}: This is not implemented (currently). The problem is that
  1790. timezone names are not unique. If a fixed timezone is assumed for a
  1791. given string (say @code{EST} meaning US East Coast time), then uses for
  1792. countries other than the USA will fail. So far we have found no good
  1793. solution to this.
  1794. @item
  1795. If only the weekday is specified the selected day depends on the current
  1796. date. If the current weekday is greater than or equal to the @code{tm_wday}
  1797. value the current week's day is chosen, otherwise the day next week is chosen.
  1798. @item
  1799. A similar heuristic is used when only the month is given and not the
  1800. year. If the month is greater than or equal to the current month, then
  1801. the current year is used. Otherwise it wraps to next year. The first
  1802. day of the month is assumed if one is not explicitly specified.
  1803. @item
  1804. The current hour, minute, and second are used if the appropriate value is
  1805. not set through the format.
  1806. @item
  1807. If no date is given tomorrow's date is used if the time is
  1808. smaller than the current time. Otherwise today's date is taken.
  1809. @end itemize
  1810. It should be noted that the format in the template file need not only
  1811. contain format elements. The following is a list of possible format
  1812. strings (taken from the Unix standard):
  1813. @smallexample
  1814. %m
  1815. %A %B %d, %Y %H:%M:%S
  1816. %A
  1817. %B
  1818. %m/%d/%y %I %p
  1819. %d,%m,%Y %H:%M
  1820. at %A the %dst of %B in %Y
  1821. run job at %I %p,%B %dnd
  1822. %A den %d. %B %Y %H.%M Uhr
  1823. @end smallexample
  1824. As you can see, the template list can contain very specific strings like
  1825. @code{run job at %I %p,%B %dnd}. Using the above list of templates and
  1826. assuming the current time is Mon Sep 22 12:19:47 EDT 1986, we can obtain the
  1827. following results for the given input.
  1828. @multitable {xxxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
  1829. @item Input @tab Match @tab Result
  1830. @item Mon @tab %a @tab Mon Sep 22 12:19:47 EDT 1986
  1831. @item Sun @tab %a @tab Sun Sep 28 12:19:47 EDT 1986
  1832. @item Fri @tab %a @tab Fri Sep 26 12:19:47 EDT 1986
  1833. @item September @tab %B @tab Mon Sep 1 12:19:47 EDT 1986
  1834. @item January @tab %B @tab Thu Jan 1 12:19:47 EST 1987
  1835. @item December @tab %B @tab Mon Dec 1 12:19:47 EST 1986
  1836. @item Sep Mon @tab %b %a @tab Mon Sep 1 12:19:47 EDT 1986
  1837. @item Jan Fri @tab %b %a @tab Fri Jan 2 12:19:47 EST 1987
  1838. @item Dec Mon @tab %b %a @tab Mon Dec 1 12:19:47 EST 1986
  1839. @item Jan Wed 1989 @tab %b %a %Y @tab Wed Jan 4 12:19:47 EST 1989
  1840. @item Fri 9 @tab %a %H @tab Fri Sep 26 09:00:00 EDT 1986
  1841. @item Feb 10:30 @tab %b %H:%S @tab Sun Feb 1 10:00:30 EST 1987
  1842. @item 10:30 @tab %H:%M @tab Tue Sep 23 10:30:00 EDT 1986
  1843. @item 13:30 @tab %H:%M @tab Mon Sep 22 13:30:00 EDT 1986
  1844. @end multitable
  1845. The return value of the function is a pointer to a static variable of
  1846. type @w{@code{struct tm}}, or a null pointer if an error occurred. The
  1847. result is only valid until the next @code{getdate} call, making this
  1848. function unusable in multi-threaded applications.
  1849. The @code{errno} variable is @emph{not} changed. Error conditions are
  1850. stored in the global variable @code{getdate_err}. See the
  1851. description above for a list of the possible error values.
  1852. @emph{Warning:} The @code{getdate} function should @emph{never} be
  1853. used in SUID-programs. The reason is obvious: using the
  1854. @code{DATEMSK} environment variable you can get the function to open
  1855. any arbitrary file and chances are high that with some bogus input
  1856. (such as a binary file) the program will crash.
  1857. @end deftypefun
  1858. @deftypefun int getdate_r (const char *@var{string}, struct tm *@var{tp})
  1859. @standards{GNU, time.h}
  1860. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  1861. @c getdate_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1862. @c getenv dup @mtsenv
  1863. @c stat64 dup ok
  1864. @c access dup ok
  1865. @c fopen dup @ascuheap @asulock @acsmem @acsfd @aculock
  1866. @c fsetlocking dup ok [no @mtasurace:stream @asulock, exclusive]
  1867. @c isspace dup @mtslocale
  1868. @c strlen dup ok
  1869. @c malloc dup @ascuheap @acsmem
  1870. @c fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
  1871. @c memcpy dup ok
  1872. @c getline dup @ascuheap @acsmem [no @asucorrupt @aculock @acucorrupt, exclusive]
  1873. @c strptime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1874. @c feof_unlocked dup ok
  1875. @c free dup @ascuheap @acsmem
  1876. @c ferror_unlocked dup dup ok
  1877. @c time dup ok
  1878. @c localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1879. @c first_wday @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1880. @c memset dup ok
  1881. @c mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1882. @c check_mday ok
  1883. @c mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  1884. The @code{getdate_r} function is the reentrant counterpart of
  1885. @code{getdate}. It does not use the global variable @code{getdate_err}
  1886. to signal an error, but instead returns an error code. The same error
  1887. codes as described in the @code{getdate_err} documentation above are
  1888. used, with 0 meaning success.
  1889. Moreover, @code{getdate_r} stores the broken-down time in the variable
  1890. of type @code{struct tm} pointed to by the second argument, rather than
  1891. in a static variable.
  1892. This function is not defined in the Unix standard. Nevertheless it is
  1893. available on some other Unix systems as well.
  1894. The warning against using @code{getdate} in SUID-programs applies to
  1895. @code{getdate_r} as well.
  1896. @end deftypefun
  1897. @node TZ Variable
  1898. @subsection Specifying the Time Zone with @code{TZ}
  1899. In POSIX systems, a user can specify the time zone by means of the
  1900. @code{TZ} environment variable. For information about how to set
  1901. environment variables, see @ref{Environment Variables}. The functions
  1902. for accessing the time zone are declared in @file{time.h}.
  1903. @pindex time.h
  1904. @cindex time zone
  1905. You should not normally need to set @code{TZ}. If the system is
  1906. configured properly, the default time zone will be correct. You might
  1907. set @code{TZ} if you are using a computer over a network from a
  1908. different time zone, and would like times reported to you in the time
  1909. zone local to you, rather than what is local to the computer.
  1910. In POSIX.1 systems the value of the @code{TZ} variable can be in one of
  1911. three formats. With @theglibc{}, the most common format is the
  1912. last one, which can specify a selection from a large database of time
  1913. zone information for many regions of the world. The first two formats
  1914. are used to describe the time zone information directly, which is both
  1915. more cumbersome and less precise. But the POSIX.1 standard only
  1916. specifies the details of the first two formats, so it is good to be
  1917. familiar with them in case you come across a POSIX.1 system that doesn't
  1918. support a time zone information database.
  1919. The first format is used when there is no Daylight Saving Time (or
  1920. summer time) in the local time zone:
  1921. @smallexample
  1922. @r{@var{std} @var{offset}}
  1923. @end smallexample
  1924. The @var{std} string specifies the name of the time zone. It must be
  1925. three or more characters long and must not contain a leading colon,
  1926. embedded digits, commas, nor plus and minus signs. There is no space
  1927. character separating the time zone name from the @var{offset}, so these
  1928. restrictions are necessary to parse the specification correctly.
  1929. The @var{offset} specifies the time value you must add to the local time
  1930. to get a Coordinated Universal Time value. It has syntax like
  1931. [@code{+}|@code{-}]@var{hh}[@code{:}@var{mm}[@code{:}@var{ss}]]. This
  1932. is positive if the local time zone is west of the Prime Meridian and
  1933. negative if it is east. The hour must be between @code{0} and
  1934. @code{24}, and the minute and seconds between @code{0} and @code{59}.
  1935. For example, here is how we would specify Eastern Standard Time, but
  1936. without any Daylight Saving Time alternative:
  1937. @smallexample
  1938. EST+5
  1939. @end smallexample
  1940. The second format is used when there is Daylight Saving Time:
  1941. @smallexample
  1942. @r{@var{std} @var{offset} @var{dst} [@var{offset}]@code{,}@var{start}[@code{/}@var{time}]@code{,}@var{end}[@code{/}@var{time}]}
  1943. @end smallexample
  1944. The initial @var{std} and @var{offset} specify the standard time zone, as
  1945. described above. The @var{dst} string and @var{offset} specify the name
  1946. and offset for the corresponding Daylight Saving Time zone; if the
  1947. @var{offset} is omitted, it defaults to one hour ahead of standard time.
  1948. The remainder of the specification describes when Daylight Saving Time is
  1949. in effect. The @var{start} field is when Daylight Saving Time goes into
  1950. effect and the @var{end} field is when the change is made back to standard
  1951. time. The following formats are recognized for these fields:
  1952. @table @code
  1953. @item J@var{n}
  1954. This specifies the Julian day, with @var{n} between @code{1} and @code{365}.
  1955. February 29 is never counted, even in leap years.
  1956. @item @var{n}
  1957. This specifies the Julian day, with @var{n} between @code{0} and @code{365}.
  1958. February 29 is counted in leap years.
  1959. @item M@var{m}.@var{w}.@var{d}
  1960. This specifies day @var{d} of week @var{w} of month @var{m}. The day
  1961. @var{d} must be between @code{0} (Sunday) and @code{6}. The week
  1962. @var{w} must be between @code{1} and @code{5}; week @code{1} is the
  1963. first week in which day @var{d} occurs, and week @code{5} specifies the
  1964. @emph{last} @var{d} day in the month. The month @var{m} should be
  1965. between @code{1} and @code{12}.
  1966. @end table
  1967. The @var{time} fields specify when, in the local time currently in
  1968. effect, the change to the other time occurs. If omitted, the default is
  1969. @code{02:00:00}. The hours part of the time fields can range from
  1970. @minus{}167 through 167; this is an extension to POSIX.1, which allows
  1971. only the range 0 through 24.
  1972. Here are some example @code{TZ} values, including the appropriate
  1973. Daylight Saving Time and its dates of applicability. In North
  1974. American Eastern Standard Time (EST) and Eastern Daylight Time (EDT),
  1975. the normal offset from UTC is 5 hours; since this is
  1976. west of the prime meridian, the sign is positive. Summer time begins on
  1977. March's second Sunday at 2:00am, and ends on November's first Sunday
  1978. at 2:00am.
  1979. @smallexample
  1980. EST+5EDT,M3.2.0/2,M11.1.0/2
  1981. @end smallexample
  1982. Israel Standard Time (IST) and Israel Daylight Time (IDT) are 2 hours
  1983. ahead of the prime meridian in winter, springing forward an hour on
  1984. March's fourth Thursday at 26:00 (i.e., 02:00 on the first Friday on or
  1985. after March 23), and falling back on October's last Sunday at 02:00.
  1986. @smallexample
  1987. IST-2IDT,M3.4.4/26,M10.5.0
  1988. @end smallexample
  1989. Western Argentina Summer Time (WARST) is 3 hours behind the prime
  1990. meridian all year. There is a dummy fall-back transition on December
  1991. 31 at 25:00 daylight saving time (i.e., 24:00 standard time,
  1992. equivalent to January 1 at 00:00 standard time), and a simultaneous
  1993. spring-forward transition on January 1 at 00:00 standard time, so
  1994. daylight saving time is in effect all year and the initial @code{WART}
  1995. is a placeholder.
  1996. @smallexample
  1997. WART4WARST,J1/0,J365/25
  1998. @end smallexample
  1999. Western Greenland Time (WGT) and Western Greenland Summer Time (WGST)
  2000. are 3 hours behind UTC in the winter. Its clocks follow the European
  2001. Union rules of springing forward by one hour on March's last Sunday at
  2002. 01:00 UTC (@minus{}02:00 local time) and falling back on October's
  2003. last Sunday at 01:00 UTC (@minus{}01:00 local time).
  2004. @smallexample
  2005. WGT3WGST,M3.5.0/-2,M10.5.0/-1
  2006. @end smallexample
  2007. The schedule of Daylight Saving Time in any particular jurisdiction has
  2008. changed over the years. To be strictly correct, the conversion of dates
  2009. and times in the past should be based on the schedule that was in effect
  2010. then. However, this format has no facilities to let you specify how the
  2011. schedule has changed from year to year. The most you can do is specify
  2012. one particular schedule---usually the present day schedule---and this is
  2013. used to convert any date, no matter when. For precise time zone
  2014. specifications, it is best to use the time zone information database
  2015. (see below).
  2016. The third format looks like this:
  2017. @smallexample
  2018. :@var{characters}
  2019. @end smallexample
  2020. Each operating system interprets this format differently; in
  2021. @theglibc{}, @var{characters} is the name of a file which describes the time
  2022. zone.
  2023. @pindex /etc/localtime
  2024. @pindex localtime
  2025. If the @code{TZ} environment variable does not have a value, the
  2026. operation chooses a time zone by default. In @theglibc{}, the
  2027. default time zone is like the specification @samp{TZ=:/etc/localtime}
  2028. (or @samp{TZ=:/usr/local/etc/localtime}, depending on how @theglibc{}
  2029. was configured; @pxref{Installation}). Other C libraries use their own
  2030. rule for choosing the default time zone, so there is little we can say
  2031. about them.
  2032. @cindex time zone database
  2033. @pindex /usr/share/zoneinfo
  2034. @pindex zoneinfo
  2035. If @var{characters} begins with a slash, it is an absolute file name;
  2036. otherwise the library looks for the file
  2037. @w{@file{/usr/share/zoneinfo/@var{characters}}}. The @file{zoneinfo}
  2038. directory contains data files describing local time zones in many
  2039. different parts of the world. The names represent major cities, with
  2040. subdirectories for geographical areas; for example,
  2041. @file{America/New_York}, @file{Europe/London}, @file{Asia/Hong_Kong}.
  2042. These data files are installed by the system administrator, who also
  2043. sets @file{/etc/localtime} to point to the data file for the local time
  2044. zone. The files typically come from the @url{http://www.iana.org/time-zones,
  2045. Time Zone Database} of time zone and daylight saving time
  2046. information for most regions of the world, which is maintained by a
  2047. community of volunteers and put in the public domain.
  2048. @node Time Zone Functions
  2049. @subsection Functions and Variables for Time Zones
  2050. @deftypevar {char *} tzname [2]
  2051. @standards{POSIX.1, time.h}
  2052. The array @code{tzname} contains two strings, which are the standard
  2053. names of the pair of time zones (standard and Daylight
  2054. Saving) that the user has selected. @code{tzname[0]} is the name of
  2055. the standard time zone (for example, @code{"EST"}), and @code{tzname[1]}
  2056. is the name for the time zone when Daylight Saving Time is in use (for
  2057. example, @code{"EDT"}). These correspond to the @var{std} and @var{dst}
  2058. strings (respectively) from the @code{TZ} environment variable. If
  2059. Daylight Saving Time is never used, @code{tzname[1]} is the empty string.
  2060. The @code{tzname} array is initialized from the @code{TZ} environment
  2061. variable whenever @code{tzset}, @code{ctime}, @code{strftime},
  2062. @code{mktime}, or @code{localtime} is called. If multiple abbreviations
  2063. have been used (e.g. @code{"EWT"} and @code{"EDT"} for U.S. Eastern War
  2064. Time and Eastern Daylight Time), the array contains the most recent
  2065. abbreviation.
  2066. The @code{tzname} array is required for POSIX.1 compatibility, but in
  2067. GNU programs it is better to use the @code{tm_zone} member of the
  2068. broken-down time structure, since @code{tm_zone} reports the correct
  2069. abbreviation even when it is not the latest one.
  2070. Though the strings are declared as @code{char *} the user must refrain
  2071. from modifying these strings. Modifying the strings will almost certainly
  2072. lead to trouble.
  2073. @end deftypevar
  2074. @deftypefun void tzset (void)
  2075. @standards{POSIX.1, time.h}
  2076. @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  2077. @c tzset @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  2078. @c libc_lock_lock dup @asulock @aculock
  2079. @c tzset_internal dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
  2080. @c libc_lock_unlock dup @aculock
  2081. The @code{tzset} function initializes the @code{tzname} variable from
  2082. the value of the @code{TZ} environment variable. It is not usually
  2083. necessary for your program to call this function, because it is called
  2084. automatically when you use the other time conversion functions that
  2085. depend on the time zone.
  2086. @end deftypefun
  2087. The following variables are defined for compatibility with System V
  2088. Unix. Like @code{tzname}, these variables are set by calling
  2089. @code{tzset} or the other time conversion functions.
  2090. @deftypevar {long int} timezone
  2091. @standards{SVID, time.h}
  2092. This contains the difference between UTC and the latest local standard
  2093. time, in seconds west of UTC. For example, in the U.S. Eastern time
  2094. zone, the value is @code{5*60*60}. Unlike the @code{tm_gmtoff} member
  2095. of the broken-down time structure, this value is not adjusted for
  2096. daylight saving, and its sign is reversed. In GNU programs it is better
  2097. to use @code{tm_gmtoff}, since it contains the correct offset even when
  2098. it is not the latest one.
  2099. @end deftypevar
  2100. @deftypevar int daylight
  2101. @standards{SVID, time.h}
  2102. This variable has a nonzero value if Daylight Saving Time rules apply.
  2103. A nonzero value does not necessarily mean that Daylight Saving Time is
  2104. now in effect; it means only that Daylight Saving Time is sometimes in
  2105. effect.
  2106. @end deftypevar
  2107. @node Time Functions Example
  2108. @subsection Time Functions Example
  2109. Here is an example program showing the use of some of the calendar time
  2110. functions.
  2111. @smallexample
  2112. @include strftim.c.texi
  2113. @end smallexample
  2114. It produces output like this:
  2115. @smallexample
  2116. Wed Jul 31 13:02:36 1991
  2117. Today is Wednesday, July 31.
  2118. The time is 01:02 PM.
  2119. @end smallexample
  2120. @node Setting an Alarm
  2121. @section Setting an Alarm
  2122. The @code{alarm} and @code{setitimer} functions provide a mechanism for a
  2123. process to interrupt itself in the future. They do this by setting a
  2124. timer; when the timer expires, the process receives a signal.
  2125. @cindex setting an alarm
  2126. @cindex interval timer, setting
  2127. @cindex alarms, setting
  2128. @cindex timers, setting
  2129. Each process has three independent interval timers available:
  2130. @itemize @bullet
  2131. @item
  2132. A real-time timer that counts elapsed time. This timer sends a
  2133. @code{SIGALRM} signal to the process when it expires.
  2134. @cindex real-time timer
  2135. @cindex timer, real-time
  2136. @item
  2137. A virtual timer that counts processor time used by the process. This timer
  2138. sends a @code{SIGVTALRM} signal to the process when it expires.
  2139. @cindex virtual timer
  2140. @cindex timer, virtual
  2141. @item
  2142. A profiling timer that counts both processor time used by the process,
  2143. and processor time spent in system calls on behalf of the process. This
  2144. timer sends a @code{SIGPROF} signal to the process when it expires.
  2145. @cindex profiling timer
  2146. @cindex timer, profiling
  2147. This timer is useful for profiling in interpreters. The interval timer
  2148. mechanism does not have the fine granularity necessary for profiling
  2149. native code.
  2150. @c @xref{profil} !!!
  2151. @end itemize
  2152. You can only have one timer of each kind set at any given time. If you
  2153. set a timer that has not yet expired, that timer is simply reset to the
  2154. new value.
  2155. You should establish a handler for the appropriate alarm signal using
  2156. @code{signal} or @code{sigaction} before issuing a call to
  2157. @code{setitimer} or @code{alarm}. Otherwise, an unusual chain of events
  2158. could cause the timer to expire before your program establishes the
  2159. handler. In this case it would be terminated, since termination is the
  2160. default action for the alarm signals. @xref{Signal Handling}.
  2161. To be able to use the alarm function to interrupt a system call which
  2162. might block otherwise indefinitely it is important to @emph{not} set the
  2163. @code{SA_RESTART} flag when registering the signal handler using
  2164. @code{sigaction}. When not using @code{sigaction} things get even
  2165. uglier: the @code{signal} function has fixed semantics with respect
  2166. to restarts. The BSD semantics for this function is to set the flag.
  2167. Therefore, if @code{sigaction} for whatever reason cannot be used, it is
  2168. necessary to use @code{sysv_signal} and not @code{signal}.
  2169. The @code{setitimer} function is the primary means for setting an alarm.
  2170. This facility is declared in the header file @file{sys/time.h}. The
  2171. @code{alarm} function, declared in @file{unistd.h}, provides a somewhat
  2172. simpler interface for setting the real-time timer.
  2173. @pindex unistd.h
  2174. @pindex sys/time.h
  2175. @deftp {Data Type} {struct itimerval}
  2176. @standards{BSD, sys/time.h}
  2177. This structure is used to specify when a timer should expire. It contains
  2178. the following members:
  2179. @table @code
  2180. @item struct timeval it_interval
  2181. This is the period between successive timer interrupts. If zero, the
  2182. alarm will only be sent once.
  2183. @item struct timeval it_value
  2184. This is the period between now and the first timer interrupt. If zero,
  2185. the alarm is disabled.
  2186. @end table
  2187. The @code{struct timeval} data type is described in @ref{Elapsed Time}.
  2188. @end deftp
  2189. @deftypefun int setitimer (int @var{which}, const struct itimerval *@var{new}, struct itimerval *@var{old})
  2190. @standards{BSD, sys/time.h}
  2191. @safety{@prelim{}@mtsafe{@mtstimer{}}@assafe{}@acsafe{}}
  2192. @c This function is marked with @mtstimer because the same set of timers
  2193. @c is shared by all threads of a process, so calling it in one thread
  2194. @c may interfere with timers set by another thread. This interference
  2195. @c is not regarded as destructive, because the interface specification
  2196. @c makes this overriding while returning the previous value the expected
  2197. @c behavior, and the kernel will serialize concurrent calls so that the
  2198. @c last one prevails, with each call getting the timer information from
  2199. @c the timer installed by the previous call in that serialization.
  2200. The @code{setitimer} function sets the timer specified by @var{which}
  2201. according to @var{new}. The @var{which} argument can have a value of
  2202. @code{ITIMER_REAL}, @code{ITIMER_VIRTUAL}, or @code{ITIMER_PROF}.
  2203. If @var{old} is not a null pointer, @code{setitimer} returns information
  2204. about any previous unexpired timer of the same kind in the structure it
  2205. points to.
  2206. The return value is @code{0} on success and @code{-1} on failure. The
  2207. following @code{errno} error conditions are defined for this function:
  2208. @table @code
  2209. @item EINVAL
  2210. The timer period is too large.
  2211. @end table
  2212. @end deftypefun
  2213. @deftypefun int getitimer (int @var{which}, struct itimerval *@var{old})
  2214. @standards{BSD, sys/time.h}
  2215. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2216. The @code{getitimer} function stores information about the timer specified
  2217. by @var{which} in the structure pointed at by @var{old}.
  2218. The return value and error conditions are the same as for @code{setitimer}.
  2219. @end deftypefun
  2220. @vtable @code
  2221. @item ITIMER_REAL
  2222. @standards{BSD, sys/time.h}
  2223. This constant can be used as the @var{which} argument to the
  2224. @code{setitimer} and @code{getitimer} functions to specify the real-time
  2225. timer.
  2226. @item ITIMER_VIRTUAL
  2227. @standards{BSD, sys/time.h}
  2228. This constant can be used as the @var{which} argument to the
  2229. @code{setitimer} and @code{getitimer} functions to specify the virtual
  2230. timer.
  2231. @item ITIMER_PROF
  2232. @standards{BSD, sys/time.h}
  2233. This constant can be used as the @var{which} argument to the
  2234. @code{setitimer} and @code{getitimer} functions to specify the profiling
  2235. timer.
  2236. @end vtable
  2237. @deftypefun {unsigned int} alarm (unsigned int @var{seconds})
  2238. @standards{POSIX.1, unistd.h}
  2239. @safety{@prelim{}@mtsafe{@mtstimer{}}@assafe{}@acsafe{}}
  2240. @c Wrapper for setitimer.
  2241. The @code{alarm} function sets the real-time timer to expire in
  2242. @var{seconds} seconds. If you want to cancel any existing alarm, you
  2243. can do this by calling @code{alarm} with a @var{seconds} argument of
  2244. zero.
  2245. The return value indicates how many seconds remain before the previous
  2246. alarm would have been sent. If there was no previous alarm, @code{alarm}
  2247. returns zero.
  2248. @end deftypefun
  2249. The @code{alarm} function could be defined in terms of @code{setitimer}
  2250. like this:
  2251. @smallexample
  2252. unsigned int
  2253. alarm (unsigned int seconds)
  2254. @{
  2255. struct itimerval old, new;
  2256. new.it_interval.tv_usec = 0;
  2257. new.it_interval.tv_sec = 0;
  2258. new.it_value.tv_usec = 0;
  2259. new.it_value.tv_sec = (long int) seconds;
  2260. if (setitimer (ITIMER_REAL, &new, &old) < 0)
  2261. return 0;
  2262. else
  2263. return old.it_value.tv_sec;
  2264. @}
  2265. @end smallexample
  2266. There is an example showing the use of the @code{alarm} function in
  2267. @ref{Handler Returns}.
  2268. If you simply want your process to wait for a given number of seconds,
  2269. you should use the @code{sleep} function. @xref{Sleeping}.
  2270. You shouldn't count on the signal arriving precisely when the timer
  2271. expires. In a multiprocessing environment there is typically some
  2272. amount of delay involved.
  2273. @strong{Portability Note:} The @code{setitimer} and @code{getitimer}
  2274. functions are derived from BSD Unix, while the @code{alarm} function is
  2275. specified by the POSIX.1 standard. @code{setitimer} is more powerful than
  2276. @code{alarm}, but @code{alarm} is more widely used.
  2277. @node Sleeping
  2278. @section Sleeping
  2279. The function @code{sleep} gives a simple way to make the program wait
  2280. for a short interval. If your program doesn't use signals (except to
  2281. terminate), then you can expect @code{sleep} to wait reliably throughout
  2282. the specified interval. Otherwise, @code{sleep} can return sooner if a
  2283. signal arrives; if you want to wait for a given interval regardless of
  2284. signals, use @code{select} (@pxref{Waiting for I/O}) and don't specify
  2285. any descriptors to wait for.
  2286. @c !!! select can get EINTR; using SA_RESTART makes sleep win too.
  2287. @deftypefun {unsigned int} sleep (unsigned int @var{seconds})
  2288. @standards{POSIX.1, unistd.h}
  2289. @safety{@prelim{}@mtunsafe{@mtascusig{:SIGCHLD/linux}}@asunsafe{}@acunsafe{}}
  2290. @c On Mach, it uses ports and calls time. On generic posix, it calls
  2291. @c nanosleep. On Linux, it temporarily blocks SIGCHLD, which is MT- and
  2292. @c AS-Unsafe, and in a way that makes it AC-Unsafe (C-unsafe, even!).
  2293. The @code{sleep} function waits for @var{seconds} seconds or until a signal
  2294. is delivered, whichever happens first.
  2295. If @code{sleep} returns because the requested interval is over,
  2296. it returns a value of zero. If it returns because of delivery of a
  2297. signal, its return value is the remaining time in the sleep interval.
  2298. The @code{sleep} function is declared in @file{unistd.h}.
  2299. @end deftypefun
  2300. Resist the temptation to implement a sleep for a fixed amount of time by
  2301. using the return value of @code{sleep}, when nonzero, to call
  2302. @code{sleep} again. This will work with a certain amount of accuracy as
  2303. long as signals arrive infrequently. But each signal can cause the
  2304. eventual wakeup time to be off by an additional second or so. Suppose a
  2305. few signals happen to arrive in rapid succession by bad luck---there is
  2306. no limit on how much this could shorten or lengthen the wait.
  2307. Instead, compute the calendar time at which the program should stop
  2308. waiting, and keep trying to wait until that calendar time. This won't
  2309. be off by more than a second. With just a little more work, you can use
  2310. @code{select} and make the waiting period quite accurate. (Of course,
  2311. heavy system load can cause additional unavoidable delays---unless the
  2312. machine is dedicated to one application, there is no way you can avoid
  2313. this.)
  2314. On some systems, @code{sleep} can do strange things if your program uses
  2315. @code{SIGALRM} explicitly. Even if @code{SIGALRM} signals are being
  2316. ignored or blocked when @code{sleep} is called, @code{sleep} might
  2317. return prematurely on delivery of a @code{SIGALRM} signal. If you have
  2318. established a handler for @code{SIGALRM} signals and a @code{SIGALRM}
  2319. signal is delivered while the process is sleeping, the action taken
  2320. might be just to cause @code{sleep} to return instead of invoking your
  2321. handler. And, if @code{sleep} is interrupted by delivery of a signal
  2322. whose handler requests an alarm or alters the handling of @code{SIGALRM},
  2323. this handler and @code{sleep} will interfere.
  2324. On @gnusystems{}, it is safe to use @code{sleep} and @code{SIGALRM} in
  2325. the same program, because @code{sleep} does not work by means of
  2326. @code{SIGALRM}.
  2327. @deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining})
  2328. @standards{POSIX.1, time.h}
  2329. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2330. @c On Linux, it's a syscall. On Mach, it calls gettimeofday and uses
  2331. @c ports.
  2332. If resolution to seconds is not enough the @code{nanosleep} function can
  2333. be used. As the name suggests the sleep interval can be specified in
  2334. nanoseconds. The actual elapsed time of the sleep interval might be
  2335. longer since the system rounds the elapsed time you request up to the
  2336. next integer multiple of the actual resolution the system can deliver.
  2337. *@code{requested_time} is the elapsed time of the interval you want to
  2338. sleep.
  2339. The function returns as *@code{remaining} the elapsed time left in the
  2340. interval for which you requested to sleep. If the interval completed
  2341. without getting interrupted by a signal, this is zero.
  2342. @code{struct timespec} is described in @xref{Elapsed Time}.
  2343. If the function returns because the interval is over the return value is
  2344. zero. If the function returns @math{-1} the global variable @code{errno}
  2345. is set to the following values:
  2346. @table @code
  2347. @item EINTR
  2348. The call was interrupted because a signal was delivered to the thread.
  2349. If the @var{remaining} parameter is not the null pointer the structure
  2350. pointed to by @var{remaining} is updated to contain the remaining
  2351. elapsed time.
  2352. @item EINVAL
  2353. The nanosecond value in the @var{requested_time} parameter contains an
  2354. illegal value. Either the value is negative or greater than or equal to
  2355. 1000 million.
  2356. @end table
  2357. This function is a cancellation point in multi-threaded programs. This
  2358. is a problem if the thread allocates some resources (like memory, file
  2359. descriptors, semaphores or whatever) at the time @code{nanosleep} is
  2360. called. If the thread gets canceled these resources stay allocated
  2361. until the program ends. To avoid this calls to @code{nanosleep} should
  2362. be protected using cancellation handlers.
  2363. @c ref pthread_cleanup_push / pthread_cleanup_pop
  2364. The @code{nanosleep} function is declared in @file{time.h}.
  2365. @end deftypefun