time.texi 130 KB

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