This isThe GNU C Library Reference Manual, for version2.42.
Copyright © 1993–2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version1.3 or any later version published by the FreeSoftware Foundation; with the Invariant Sections being “Free SoftwareNeeds Free Documentation” and “GNU Lesser General Public License”,the Front-Cover texts being “A GNU Manual”, and with the Back-CoverTexts as in (a) below. A copy of the license is included in thesection entitled "GNU Free Documentation License".
(a) The FSF’s Back-Cover Text is: “You have the freedom tocopy and modify this GNU manual. Buying copies from the FSFsupports it in developing GNU and promoting software freedom.”
Next:Introduction, Previous:(dir), Up:(dir) [Contents][Index]
malloc
malloc
malloc
malloc
-Related Functionsmalloc
printf
inetd
Daemongetopt
argp_parse
Functionargp_parse
argp_help
Functionargp_help
Functionsysconf
pathconf
Next:Error Reporting, Previous:Main Menu, Up:Main Menu [Contents][Index]
The C language provides no built-in facilities for performing suchcommon operations as input/output, memory management, stringmanipulation, and the like. Instead, these facilities are definedin a standardlibrary, which you compile and link with yourprograms.
The GNU C Library, described in this document, defines all of thelibrary functions that are specified by the ISO C standard, as well asadditional features specific to POSIX and other derivatives of the Unixoperating system, and extensions specific to GNU systems.
The purpose of this manual is to tell you how to use the facilitiesof the GNU C Library. We have mentioned which features belong to whichstandards to help you identify things that are potentially non-portableto other systems. But the emphasis in this manual is not on strictportability.
Next:Standards and Portability, Up:Introduction [Contents][Index]
This manual is written with the assumption that you are at leastsomewhat familiar with the C programming language and basic programmingconcepts. Specifically, familiarity with ISO standard C(seeISO C), rather than “traditional” pre-ISO C dialects, isassumed.
The GNU C Library includes severalheader files, each of whichprovides definitions and declarations for a group of related facilities;this information is used by the C compiler when processing your program.For example, the header filestdio.h declares facilities forperforming input and output, and the header filestring.hdeclares string processing utilities. The organization of this manualgenerally follows the same division as the header files.
If you are reading this manual for the first time, you should read allof the introductory material and skim the remaining chapters. There arealot of functions in the GNU C Library and it’s not realistic toexpect that you will be able to remember exactlyhow to use eachand every one of them. It’s more important to become generally familiarwith the kinds of facilities that the library provides, so that when youare writing your programs you can recognizewhen to make use oflibrary functions, andwhere in this manual you can find morespecific information about them.
Next:Using the Library, Previous:Getting Started, Up:Introduction [Contents][Index]
This section discusses the various standards and other sources that the GNU C Libraryis based upon. These sources include the ISO C andPOSIX standards, and the System V and Berkeley Unix implementations.
The primary focus of this manual is to tell you how to make effectiveuse of the GNU C Library facilities. But if you are concerned aboutmaking your programs compatible with these standards, or portable tooperating systems other than GNU, this can affect how you use thelibrary. This section gives you an overview of these standards, so thatyou will know what they are when they are mentioned in other parts ofthe manual.
SeeSummary of Library Facilities, for an alphabetical list of the functions andother symbols provided by the library. This list also states whichstandards each function or symbol comes from.
Next:POSIX (The Portable Operating System Interface), Up:Standards and Portability [Contents][Index]
The GNU C Library is compatible with the C standard adopted by theAmerican National Standards Institute (ANSI):American National Standard X3.159-1989—“ANSI C” and laterby the International Standardization Organization (ISO):ISO/IEC 9899:1990, “Programming languages—C”.We here refer to the standard as ISO C since this is the moregeneral standard in respect of ratification.The header files and library facilities that make up the GNU C Library area superset of those specified by the ISO C standard.
If you are concerned about strict adherence to the ISO C standard, youshould use the ‘-ansi’ option when you compile your programs withthe GNU C compiler. This tells the compiler to defineonly ISOstandard features from the library header files, unless you explicitlyask for additional features. SeeFeature Test Macros, forinformation on how to do this.
Being able to restrict the library to include only ISO C features isimportant because ISO C puts limitations on what names can be definedby the library implementation, and the GNU extensions don’t fit theselimitations. SeeReserved Names, for more information about theserestrictions.
This manual does not attempt to give you complete details on thedifferences between ISO C and older dialects. It gives advice on howto write programs to work portably under multiple C dialects, but doesnot aim for completeness.
Next:Berkeley Unix, Previous:ISO C, Up:Standards and Portability [Contents][Index]
The GNU C Library is also compatible with the ISOPOSIX family ofstandards, known more formally as thePortable Operating SystemInterface for Computer Environments (ISO/IEC 9945). They were alsopublished as ANSI/IEEE Std 1003. POSIX is derived mostly from variousversions of the Unix operating system.
The library facilities specified by the POSIX standards are a supersetof those required by ISO C; POSIX specifies additional features forISO C functions, as well as specifying new additional functions. Ingeneral, the additional requirements and functionality defined by thePOSIX standards are aimed at providing lower-level support for aparticular kind of operating system environment, rather than generalprogramming language support which can run in many diverse operatingsystem environments.
The GNU C Library implements all of the functions specified inISO/IEC 9945-1:1996, the POSIX System Application ProgramInterface, commonly referred to as POSIX.1. The primary extensions tothe ISO C facilities specified by this standard include file systeminterface primitives (seeFile System Interface), device-specificterminal control functions (seeLow-Level Terminal Interface), andprocess control functions (seeProcesses).
Some facilities fromISO/IEC 9945-2:1993, the POSIX Shell andUtilities standard (POSIX.2) are also implemented in the GNU C Library.These include utilities for dealing with regular expressions and otherpattern matching facilities (seePattern Matching).
This manual documents various safety properties of GNU C Libraryfunctions, in lines that follow their prototypes and look like:
Preliminary:| MT-Safe | AS-Safe | AC-Safe |
The properties are assessed according to the criteria set forth in thePOSIX standard for such safety contexts as Thread-, Async-Signal- andAsync-Cancel- -Safety. Intuitive definitions of these properties,attempting to capture the meaning of the standard definitions, follow.
MT-Safe
or Thread-Safe functions are safe to call in the presenceof other threads. MT, in MT-Safe, stands for Multi Thread.Being MT-Safe does not imply a function is atomic, nor that it uses anyof the memory synchronization mechanisms POSIX exposes to users. It iseven possible that calling MT-Safe functions in sequence does not yieldan MT-Safe combination. For example, having a thread call two MT-Safefunctions one right after the other does not guarantee behaviorequivalent to atomic execution of a combination of both functions, sinceconcurrent calls in other threads may interfere in a destructive way.
Whole-program optimizations that could inline functions across libraryinterfaces may expose unsafe reordering, and so performing inliningacross the GNU C Library interface is not recommended. The documentedMT-Safety status is not guaranteed under whole-program optimization.However, functions defined in user-visible headers are designed to besafe for inlining.
AS-Safe
or Async-Signal-Safe functions are safe to call fromasynchronous signal handlers. AS, in AS-Safe, stands for AsynchronousSignal.Many functions that are AS-Safe may seterrno
, or modify thefloating-point environment, because their doing so does not make themunsuitable for use in signal handlers. However, programs couldmisbehave should asynchronous signal handlers modify this thread-localstate, and the signal handling machinery cannot be counted on topreserve it. Therefore, signal handlers that call functions that mayseterrno
or modify the floating-point environmentmustsave their original values, and restore them before returning.
AC-Safe
or Async-Cancel-Safe functions are safe to call whenasynchronous cancellation is enabled. AC in AC-Safe stands forAsynchronous Cancellation.The POSIX standard defines only three functions to be AC-Safe, namelypthread_cancel
,pthread_setcancelstate
, andpthread_setcanceltype
. At present the GNU C Library provides noguarantees beyond these three functions, but does document whichfunctions are presently AC-Safe. This documentation is provided for useby the GNU C Library developers.
Just like signal handlers, cancellation cleanup routines must configurethe floating point environment they require. The routines cannot assumea floating point environment, particularly when asynchronouscancellation is enabled. If the configuration of the floating pointenvironment cannot be performed atomically then it is also possible thatthe environment encountered is internally inconsistent.
MT-Unsafe
,AS-Unsafe
,AC-Unsafe
functions are notsafe to call within the safety contexts described above. Calling themwithin such contexts invokes undefined behavior.Functions not explicitly documented as safe in a safety context shouldbe regarded as Unsafe.
Preliminary
safety properties are documented, indicating theseproperties maynot be counted on in future releases ofthe GNU C Library.Such preliminary properties are the result of an assessment of theproperties of our current implementation, rather than of what ismandated and permitted by current and future standards.
Although we strive to abide by the standards, in some cases ourimplementation is safe even when the standard does not demand safety,and in other cases our implementation does not meet the standard safetyrequirements. The latter are most likely bugs; the former, when markedasPreliminary
, should not be counted on: future standards mayrequire changes that are not compatible with the additional safetyproperties afforded by the current implementation.
Furthermore, the POSIX standard does not offer a detailed definition ofsafety. We assume that, by “safe to call”, POSIX means that, as longas the program does not invoke undefined behavior, the “safe to call”function behaves as specified, and does not cause other functions todeviate from their specified behavior. We have chosen to use its loosedefinitions of safety, not because they are the best definitions to use,but because choosing them harmonizes this manual with POSIX.
Please keep in mind that these are preliminary definitions andannotations, and certain aspects of the definitions are still underdiscussion and might be subject to clarification or change.
Over time, we envision evolving the preliminary safety notes into stablecommitments, as stable as those of our interfaces. As we do, we willremove thePreliminary
keyword from safety notes. As long as thekeyword remains, however, they are not to be regarded as a promise offuture behavior.
Other keywords that appear in safety notes are defined in subsequentsections.
Next:Conditionally Safe Features, Previous:POSIX Safety Concepts, Up:POSIX (The Portable Operating System Interface) [Contents][Index]
Functions that are unsafe to call in certain contexts are annotated withkeywords that document their features that make them unsafe to call.AS-Unsafe features in this section indicate the functions are never safeto call when asynchronous signals are enabled. AC-Unsafe featuresindicate they are never safe to call when asynchronous cancellation isenabled. There are no MT-Unsafe marks in this section.
lock
Functions marked withlock
as an AS-Unsafe feature may beinterrupted by a signal while holding a non-recursive lock. If thesignal handler calls another such function that takes the same lock, theresult is a deadlock.
Functions annotated withlock
as an AC-Unsafe feature may, ifcancelled asynchronously, fail to release a lock that would have beenreleased if their execution had not been interrupted by asynchronousthread cancellation. Once a lock is left taken, attempts to take thatlock will block indefinitely.
corrupt
Functions marked withcorrupt
as an AS-Unsafe feature may corruptdata structures and misbehave when they interrupt, or are interruptedby, another such function. Unlike functions marked withlock
,these take recursive locks to avoid MT-Safety problems, but this is notenough to stop a signal handler from observing a partially-updated datastructure. Further corruption may arise from the interrupted function’sfailure to notice updates made by signal handlers.
Functions marked withcorrupt
as an AC-Unsafe feature may leavedata structures in a corrupt, partially updated state. Subsequent usesof the data structure may misbehave.
heap
Functions marked withheap
may call heap memory managementfunctions from themalloc
/free
family of functions and areonly as safe as those functions. This note is thus equivalent to:
| AS-Unsafe lock| AC-Unsafe lock fd mem|
dlopen
Functions marked withdlopen
use the dynamic loader to loadshared libraries into the current execution image. This involvesopening files, mapping them into memory, allocating additional memory,resolving symbols, applying relocations and more, all of this whileholding internal dynamic loader locks.
The locks are enough for these functions to be AS- and AC-Unsafe, butother issues may arise. At present this is a placeholder for allpotential safety issues raised bydlopen
.
plugin
Functions annotated withplugin
may run code from plugins thatmay be external to the GNU C Library. Such plugin functions are assumed to beMT-Safe, AS-Unsafe and AC-Unsafe. Examples of such plugins are stackunwinding libraries, name service switch (NSS) and character setconversion (iconv) back-ends.
Although the plugins mentioned as examples are all brought in by meansof dlopen, theplugin
keyword does not imply any directinvolvement of the dynamic loader or thelibdl
interfaces, thoseare covered bydlopen
. For example, if one function loads amodule and finds the addresses of some of its functions, while anotherjust calls those already-resolved functions, the former will be markedwithdlopen
, whereas the latter will get theplugin
. Whena single function takes all of these actions, then it gets both marks.
i18n
Functions marked withi18n
may call internationalizationfunctions of thegettext
family and will be only as safe as thosefunctions. This note is thus equivalent to:
| MT-Safe env| AS-Unsafe corrupt heap dlopen| AC-Unsafe corrupt|
timer
Functions marked withtimer
use thealarm
function orsimilar to set a time-out for a system call or a long-running operation.In a multi-threaded program, there is a risk that the time-out signalwill be delivered to a different thread, thus failing to interrupt theintended thread. Besides being MT-Unsafe, such functions are alwaysAS-Unsafe, because calling them in signal handlers may interfere withtimers set in the interrupted code, and AC-Unsafe, because there is nosafe way to guarantee an earlier timer will be reset in case ofasynchronous cancellation.
Next:Other Safety Remarks, Previous:Unsafe Features, Up:POSIX (The Portable Operating System Interface) [Contents][Index]
For some features that make functions unsafe to call in certaincontexts, there are known ways to avoid the safety problem other thanrefraining from calling the function altogether. The keywords thatfollow refer to such features, and each of their definitions indicatehow the whole program needs to be constrained in order to remove thesafety problem indicated by the keyword. Only when all the reasons thatmake a function unsafe are observed and addressed, by applying thedocumented constraints, does the function become safe to call in acontext.
init
Functions marked withinit
as an MT-Unsafe feature performMT-Unsafe initialization when they are first called.
Calling such a function at least once in single-threaded mode removesthis specific cause for the function to be regarded as MT-Unsafe. If noother cause for that remains, the function can then be safely calledafter other threads are started.
Functions marked withinit
as an AS- or AC-Unsafe feature use theinternallibc_once
machinery or similar to initialize internaldata structures.
If a signal handler interrupts such an initializer, and calls anyfunction that also performslibc_once
initialization, it willdeadlock if the thread library has been loaded.
Furthermore, if an initializer is partially complete before it iscanceled or interrupted by a signal whose handler requires the sameinitialization, some or all of the initialization may be performed morethan once, leaking resources or even resulting in corrupt internal data.
Applications that need to call functions marked withinit
as anAS- or AC-Unsafe feature should ensure the initialization is performedbefore configuring signal handlers or enabling cancellation, so that theAS- and AC-Safety issues related withlibc_once
do not arise.
race
Functions annotated withrace
as an MT-Safety issue operate onobjects in ways that may cause data races or similar forms ofdestructive interference out of concurrent execution. In some cases,the objects are passed to the functions by users; in others, they areused by the functions to return values to users; in others, they are noteven exposed to users.
We consider access to objects passed as (indirect) arguments tofunctions to be data race free. The assurance of data race free objectsis the caller’s responsibility. We will not mark a function asMT-Unsafe or AS-Unsafe if it misbehaves when users fail to take themeasures required by POSIX to avoid data races when dealing with suchobjects. As a general rule, if a function is documented as reading froman object passed (by reference) to it, or modifying it, users ought touse memory synchronization primitives to avoid data races just as theywould should they perform the accesses themselves rather than by callingthe library function.FILE
streams are the exception to thegeneral rule, in that POSIX mandates the library to guard against dataraces in many functions that manipulate objects of this specific opaquetype. We regard this as a convenience provided to users, rather than asa general requirement whose expectations should extend to other types.
In order to remind users that guarding certain arguments is theirresponsibility, we will annotate functions that take objects of certaintypes as arguments. We draw the line for objects passed by users asfollows: objects whose types are exposed to users, and that users areexpected to access directly, such as memory buffers, strings, andvarious user-visiblestruct
types, donot give reason forfunctions to be annotated withrace
. It would be noisy andredundant with the general requirement, and not many would be surprisedby the library’s lack of internal guards when accessing objects that canbe accessed directly by users.
As for objects that are opaque or opaque-like, in that they are to bemanipulated only by passing them to library functions (e.g.,FILE
,DIR
,obstack
,iconv_t
), there might beadditional expectations as to internal coordination of access by thelibrary. We will annotate, withrace
followed by a colon and theargument name, functions that take such objects but that do not takecare of synchronizing access to them by default. For example,FILE
streamunlocked
functions will be annotated, butthose that perform implicit locking onFILE
streams by defaultwill not, even though the implicit locking may be disabled on aper-stream basis.
In either case, we will not regard as MT-Unsafe functions that mayaccess user-supplied objects in unsafe ways should users fail to ensurethe accesses are well defined. The notion prevails that users areexpected to safeguard against data races any user-supplied objects thatthe library accesses on their behalf.
This user responsibility does not apply, however, to objects controlledby the library itself, such as internal objects and static buffers usedto return values from certain calls. When the library doesn’t guardthem against concurrent uses, these cases are regarded as MT-Unsafe andAS-Unsafe (although therace
mark under AS-Unsafe will be omittedas redundant with the one under MT-Unsafe). As in the case ofuser-exposed objects, the mark may be followed by a colon and anidentifier. The identifier groups all functions that operate on acertain unguarded object; users may avoid the MT-Safety issues relatedwith unguarded concurrent access to such internal objects by creating anon-recursive mutex related with the identifier, and always holding themutex when calling any function marked as racy on that identifier, asthey would have to should the identifier be an object under usercontrol. The non-recursive mutex avoids the MT-Safety issue, but ittrades one AS-Safety issue for another, so use in asynchronous signalsremains undefined.
When the identifier relates to a static buffer used to hold returnvalues, the mutex must be held for as long as the buffer remains in useby the caller. Many functions that return pointers to static buffersoffer reentrant variants that store return values in caller-suppliedbuffers instead. In some cases, such astmpname
, the variant ischosen not by calling an alternate entry point, but by passing anon-NULL
pointer to the buffer in which the returned values areto be stored. These variants are generally preferable in multi-threadedprograms, although some of them are not MT-Safe because of otherinternal buffers, also documented withrace
notes.
const
Functions marked withconst
as an MT-Safety issue non-atomicallymodify internal objects that are better regarded as constant, because asubstantial portion of the GNU C Library accesses them withoutsynchronization. Unlikerace
, that causes both readers andwriters of internal objects to be regarded as MT-Unsafe and AS-Unsafe,this mark is applied to writers only. Writers remain equally MT- andAS-Unsafe to call, but the then-mandatory constness of objects theymodify enables readers to be regarded as MT-Safe and AS-Safe (as long asno other reasons for them to be unsafe remain), since the lack ofsynchronization is not a problem when the objects are effectivelyconstant.
The identifier that follows theconst
mark will appear by itselfas a safety note in readers. Programs that wish to work around thissafety issue, so as to call writers, may use a non-recursverwlock
associated with the identifier, and guardall callsto functions marked withconst
followed by the identifier with awrite lock, andall calls to functions marked with the identifierby itself with a read lock. The non-recursive locking removes theMT-Safety problem, but it trades one AS-Safety problem for another, souse in asynchronous signals remains undefined.
sig
Functions marked withsig
as a MT-Safety issue (that implies anidentical AS-Safety issue, omitted for brevity) may temporarily installa signal handler for internal purposes, which may interfere with otheruses of the signal, identified after a colon.
This safety problem can be worked around by ensuring that no other usesof the signal will take place for the duration of the call. Holding anon-recursive mutex while calling all functions that use the sametemporary signal; blocking that signal before the call and resetting itshandler afterwards is recommended.
There is no safe way to guarantee the original signal handler isrestored in case of asynchronous cancellation, therefore so-markedfunctions are also AC-Unsafe.
Besides the measures recommended to work around the MT- and AS-Safetyproblem, in order to avert the cancellation problem, disablingasynchronous cancellationand installing a cleanup handler torestore the signal to the desired state and to release the mutex arerecommended.
term
Functions marked withterm
as an MT-Safety issue may change theterminal settings in the recommended way, namely: calltcgetattr
,modify some flags, and then calltcsetattr
; this creates a windowin which changes made by other threads are lost. Thus, functions markedwithterm
are MT-Unsafe. The same window enables changes made byasynchronous signals to be lost. These functions are also AS-Unsafe,but the corresponding mark is omitted as redundant.
It is thus advisable for applications using the terminal to avoidconcurrent and reentrant interactions with it, by not using it in signalhandlers or blocking signals that might use it, and holding a lock whilecalling these functions and interacting with the terminal. This lockshould also be used for mutual exclusion with functions marked withrace:tcattr(fd)
, wherefd is a file descriptor forthe controlling terminal. The caller may use a single mutex forsimplicity, or use one mutex per terminal, even if referenced bydifferent file descriptors.
Functions marked withterm
as an AC-Safety issue are supposed torestore terminal settings to their original state, after temporarilychanging them, but they may fail to do so if cancelled.
Besides the measures recommended to work around the MT- and AS-Safetyproblem, in order to avert the cancellation problem, disablingasynchronous cancellationand installing a cleanup handler torestore the terminal settings to the original state and to release themutex are recommended.
Previous:Conditionally Safe Features, Up:POSIX (The Portable Operating System Interface) [Contents][Index]
Additional keywords may be attached to functions, indicating featuresthat do not make a function unsafe to call, but that may need to betaken into account in certain classes of programs:
locale
Functions annotated withlocale
as an MT-Safety issue read fromthe locale object without any form of synchronization. Functionsannotated withlocale
called concurrently with locale changes maybehave in ways that do not correspond to any of the locales activeduring their execution, but an unpredictable mix thereof.
We do not mark these functions as MT- or AS-Unsafe, however, becausefunctions that modify the locale object are marked withconst:locale
and regarded as unsafe. Being unsafe, the latterare not to be called when multiple threads are running or asynchronoussignals are enabled, and so the locale can be considered effectivelyconstant in these contexts, which makes the former safe.
env
Functions marked withenv
as an MT-Safety issue access theenvironment withgetenv
or similar, without any guards to ensuresafety in the presence of concurrent modifications.
We do not mark these functions as MT- or AS-Unsafe, however, becausefunctions that modify the environment are all marked withconst:env
and regarded as unsafe. Being unsafe, the latter arenot to be called when multiple threads are running or asynchronoussignals are enabled, and so the environment can be consideredeffectively constant in these contexts, which makes the former safe.
hostid
The function marked withhostid
as an MT-Safety issue reads fromthe system-wide data structures that hold the “host ID” of themachine. These data structures cannot generally be modified atomically.Since it is expected that the “host ID” will not normally change, thefunction that reads from it (gethostid
) is regarded as safe,whereas the function that modifies it (sethostid
) is marked withconst:hostid
, indicating it may require specialcare if it is to be called. In this specific case, the special careamounts to system-wide (not merely intra-process) coordination.
sigintr
Functions marked withsigintr
as an MT-Safety issue access the_sigintr
internal data structure without any guards to ensuresafety in the presence of concurrent modifications.
We do not mark these functions as MT- or AS-Unsafe, however, becausefunctions that modify the this data structure are all marked withconst:sigintr
and regarded as unsafe. Being unsafe, the latterare not to be called when multiple threads are running or asynchronoussignals are enabled, and so the data structure can be consideredeffectively constant in these contexts, which makes the former safe.
fd
Functions annotated withfd
as an AC-Safety issue may leak filedescriptors if asynchronous thread cancellation interrupts theirexecution.
Functions that allocate or deallocate file descriptors will generally bemarked as such. Even if they attempted to protect the file descriptorallocation and deallocation with cleanup regions, allocating a newdescriptor and storing its number where the cleanup region could releaseit cannot be performed as a single atomic operation. Similarly,releasing the descriptor and taking it out of the data structurenormally responsible for releasing it cannot be performed atomically.There will always be a window in which the descriptor cannot be releasedbecause it was not stored in the cleanup handler argument yet, or it wasalready taken out before releasing it. It cannot be taken out afterrelease: an open descriptor could mean either that the descriptor stillhas to be closed, or that it already did so but the descriptor wasreallocated by another thread or signal handler.
Such leaks could be internally avoided, with some performance penalty,by temporarily disabling asynchronous thread cancellation. However,since callers of allocation or deallocation functions would have to dothis themselves, to avoid the same sort of leak in their own layer, itmakes more sense for the library to assume they are taking care of itthan to impose a performance penalty that is redundant when the problemis solved in upper layers, and insufficient when it is not.
This remark by itself does not cause a function to be regarded asAC-Unsafe. However, cumulative effects of such leaks may pose aproblem for some programs. If this is the case, suspending asynchronouscancellation for the duration of calls to such functions is recommended.
mem
Functions annotated withmem
as an AC-Safety issue may leakmemory if asynchronous thread cancellation interrupts their execution.
The problem is similar to that of file descriptors: there is no atomicinterface to allocate memory and store its address in the argument to acleanup handler, or to release it and remove its address from thatargument, without at least temporarily disabling asynchronouscancellation, which these functions do not do.
This remark does not by itself cause a function to be regarded asgenerally AC-Unsafe. However, cumulative effects of such leaks may besevere enough for some programs that disabling asynchronous cancellationfor the duration of calls to such functions may be required.
cwd
Functions marked withcwd
as an MT-Safety issue may temporarilychange the current working directory during their execution, which maycause relative pathnames to be resolved in unexpected ways in otherthreads or within asynchronous signal or cancellation handlers.
This is not enough of a reason to mark so-marked functions as MT- orAS-Unsafe, but when this behavior is optional (e.g.,nftw
withFTW_CHDIR
), avoiding the option may be a good alternative tousing full pathnames or file descriptor-relative (e.g.openat
)system calls.
!posix
This remark, as an MT-, AS- or AC-Safety note to a function, indicatesthe safety status of the function is known to differ from the specifiedstatus in the POSIX standard. For example, POSIX does not require afunction to be Safe, but our implementation is, or vice-versa.
For the time being, the absence of this remark does not imply the safetyproperties we documented are identical to those mandated by POSIX forthe corresponding functions.
:identifier
Annotations may sometimes be followed by identifiers, intended to groupseveral functions that e.g. access the data structures in an unsafe way,as inrace
andconst
, or to provide more specificinformation, such as naming a signal in a function marked withsig
. It is envisioned that it may be applied tolock
andcorrupt
as well in the future.
In most cases, the identifier will name a set of functions, but it mayname global objects or function arguments, or identifiable properties orlogical components associated with them, with a notation such ase.g.:buf(arg)
to denote a buffer associated with the argumentarg, or:tcattr(fd)
to denote the terminal attributes of afile descriptorfd.
The most common use for identifiers is to provide logical groups offunctions and arguments that need to be protected by the samesynchronization primitive in order to ensure safe operation in a givencontext.
/condition
Some safety annotations may be conditional, in that they only apply if aboolean expression involving arguments, global variables or even theunderlying kernel evaluates to true. Such conditions as/hurd
or/!linux!bsd
indicate the preceding marker onlyapplies when the underlying kernel is the HURD, or when it is neitherLinux nor a BSD kernel, respectively./!ps
and/one_per_line
indicate the preceding marker only applies whenargumentps is NULL, or global variableone_per_line isnonzero.
When all marks that render a function unsafe are adorned with suchconditions, and none of the named conditions hold, then the function canbe regarded as safe.
Next:SVID (The System V Interface Description), Previous:POSIX (The Portable Operating System Interface), Up:Standards and Portability [Contents][Index]
The GNU C Library defines facilities from some versions of Unix whichare not formally standardized, specifically from the 4.2 BSD, 4.3 BSD,and 4.4 BSD Unix systems (also known asBerkeley Unix) and fromSunOS (a popular 4.2 BSD derivative that includes some Unix SystemV functionality). These systems support most of the ISO C and POSIXfacilities, and 4.4 BSD and newer releases of SunOS in fact support them all.
The BSD facilities include symbolic links (seeSymbolic Links), theselect
function (seeWaiting for Input or Output), the BSD signalfunctions (seeBSD Signal Handling), and sockets (seeSockets).
Next:XPG (The X/Open Portability Guide), Previous:Berkeley Unix, Up:Standards and Portability [Contents][Index]
TheSystem V Interface Description (SVID) is a document describingthe AT&T Unix System V operating system. It is to some extent asuperset of the POSIX standard (seePOSIX (The Portable Operating System Interface)).
The GNU C Library defines most of the facilities required by the SVIDthat are not also required by the ISO C or POSIX standards, forcompatibility with System V Unix and other Unix systems (such asSunOS) which include these facilities. However, many of the moreobscure and less generally useful facilities required by the SVID arenot included. (In fact, Unix System V itself does not provide them all.)
The supported facilities from System V include the methods forinter-process communication and shared memory, thehsearch
anddrand48
families of functions,fmtmsg
and several of themathematical functions.
Next:Linux (The Linux Kernel), Previous:SVID (The System V Interface Description), Up:Standards and Portability [Contents][Index]
The X/Open Portability Guide, published by the X/Open Company, Ltd., isa more general standard than POSIX. X/Open owns the Unix copyright andthe XPG specifies the requirements for systems which are intended to bea Unix system.
The GNU C Library complies to the X/Open Portability Guide, Issue 4.2,with all extensions common to XSI (X/Open System Interface)compliant systems and also all X/Open UNIX extensions.
The additions on top of POSIX are mainly derived from functionalityavailable in System V and BSD systems. Some of the really badmistakes in System V systems were corrected, though. Sincefulfilling the XPG standard with the Unix extensions is aprecondition for getting the Unix brand chances are good that thefunctionality is available on commercial systems.
Previous:XPG (The X/Open Portability Guide), Up:Standards and Portability [Contents][Index]
The GNU C Library includes by reference the Linux man-pages6.9.1 documentation to document the listedsyscalls for the Linux kernel. For reference purposes only, the latestLinux man-pages Projectdocumentation can be accessed from theLinux kernel website. Where the syscallhas more specific documentation in this manual that more specificdocumentation is considered authoritative.
Throughout this manual, when we refer to a man page, for example:
we are referring primarily to the specific version noted above (the“normative” version), typically accessed by running (for example)man 2 sendmsg
on a system with that version installed. Forconvenience, we will also link to the online latest copy of the manpages, but keep in mind that version will almost always be newer than,and thus different than, the normative version noted above.
Additional details on the Linux system call interface can be found inSeeSystem Calls.
Next:Roadmap to the Manual, Previous:Standards and Portability, Up:Introduction [Contents][Index]
This section describes some of the practical issues involved in usingthe GNU C Library.
Next:Macro Definitions of Functions, Up:Using the Library [Contents][Index]
Libraries for use by C programs really consist of two parts:headerfiles that define types and macros and declare variables andfunctions; and the actual library orarchive that contains thedefinitions of the variables and functions.
(Recall that in C, adeclaration merely provides information thata function or variable exists and gives its type. For a functiondeclaration, information about the types of its arguments might beprovided as well. The purpose of declarations is to allow the compilerto correctly process references to the declared variables and functions.Adefinition, on the other hand, actually allocates storage for avariable or says what a function does.)
In order to use the facilities in the GNU C Library, you should be surethat your program source files include the appropriate header files.This is so that the compiler has declarations of these facilitiesavailable and can correctly process references to them. Once yourprogram has been compiled, the linker resolves these references tothe actual definitions provided in the archive file.
Header files are included into a program source file by the‘#include’ preprocessor directive. The C language supports twoforms of this directive; the first,
#include "header"
is typically used to include a header fileheader that you writeyourself; this would contain definitions and declarations describing theinterfaces between the different parts of your particular application.By contrast,
#include <file.h>
is typically used to include a header filefile.h that containsdefinitions and declarations for a standard library. This file wouldnormally be installed in a standard place by your system administrator.You should use this second form for the C library header files.
Typically, ‘#include’ directives are placed at the top of the Csource file, before any other code. If you begin your source files withsome comments explaining what the code in the file does (a good idea),put the ‘#include’ directives immediately afterwards, following thefeature test macro definition (seeFeature Test Macros).
For more information about the use of header files and ‘#include’directives, seeHeader Files inThe GNU C Preprocessor Manual.
The GNU C Library provides several header files, each of which containsthe type and macro definitions and variable and function declarationsfor a group of related facilities. This means that your programs mayneed to include several header files, depending on exactly whichfacilities you are using.
Some library header files include other library header filesautomatically. However, as a matter of programming style, you shouldnot rely on this; it is better to explicitly include all the headerfiles required for the library facilities you are using. The GNU C Libraryheader files have been written in such a way that it doesn’tmatter if a header file is accidentally included more than once;including a header file a second time has no effect. Likewise, if yourprogram needs to include multiple header files, the order in which theyare included doesn’t matter.
Compatibility Note: Inclusion of standard header files in anyorder and any number of times works in any ISO C implementation.However, this has traditionally not been the case in many older Cimplementations.
Strictly speaking, you don’thave to include a header file to usea function it declares; you could declare the function explicitlyyourself, according to the specifications in this manual. But it isusually better to include the header file because it may define typesand macros that are not otherwise available and because it may definemore efficient macro replacements for some functions. It is also a sureway to have the correct declaration.
Next:Reserved Names, Previous:Header Files, Up:Using the Library [Contents][Index]
If we describe something as a function in this manual, it may have amacro definition as well. This normally has no effect on how yourprogram runs—the macro definition does the same thing as the functionwould. In particular, macro equivalents for library functions evaluatearguments exactly once, in the same way that a function call would. Themain reason for these macro definitions is that sometimes they canproduce an inline expansion that is considerably faster than an actualfunction call.
Taking the address of a library function works even if it is alsodefined as a macro. This is because, in this context, the name of thefunction isn’t followed by the left parenthesis that is syntacticallynecessary to recognize a macro call.
You might occasionally want to avoid using the macro definition of afunction—perhaps to make your program easier to debug. There aretwo ways you can do this:
For example, suppose the header filestdlib.h declares a functionnamedabs
with
extern int abs (int);
and also provides a macro definition forabs
. Then, in:
#include <stdlib.h>int f (int *i) { return abs (++*i); }
the reference toabs
might refer to either a macro or a function.On the other hand, in each of the following examples the reference isto a function and not a macro.
#include <stdlib.h>int g (int *i) { return (abs) (++*i); }#undef absint h (int *i) { return abs (++*i); }
Since macro definitions that double for a function behave inexactly the same way as the actual function version, there is usually noneed for any of these methods. In fact, removing macro definitions usuallyjust makes your program slower.
Next:Feature Test Macros, Previous:Macro Definitions of Functions, Up:Using the Library [Contents][Index]
The names of all library types, macros, variables and functions thatcome from the ISO C standard are reserved unconditionally; your programmay not redefine these names. All other library names arereserved if your program explicitly includes the header file thatdefines or declares them. There are several reasons for theserestrictions:
exit
to do something completely different fromwhat the standardexit
function does, for example. Preventingthis situation helps to make your programs easier to understand andcontributes to modularity and maintainability.In addition to the names documented in this manual, reserved namesinclude all external identifiers (global functions and variables) thatbegin with an underscore (‘_’) and all identifiers regardless ofuse that begin with either two underscores or an underscore followed bya capital letter are reserved names. This is so that the library andheader files can define functions, variables, and macros for internalpurposes without risk of conflict with names in user programs.
Some additional classes of identifier names are reserved for futureextensions to the C language or the POSIX.1 environment. While using thesenames for your own purposes right now might not cause a problem, they doraise the possibility of conflict with future versions of the Cor POSIX standards, so you should avoid these names.
float
andlong double
arguments,respectively.In addition, some individual header files reserve names beyondthose that they actually define. You only need to worry about theserestrictions if your program includes that particular header file.
Previous:Reserved Names, Up:Using the Library [Contents][Index]
The exact set of features available when you compile a source fileis controlled by whichfeature test macros you define.
If you compile your programs using ‘gcc -ansi’, you get only theISO C library features, unless you explicitly request additionalfeatures by defining one or more of the feature macros.SeeGNU CC Command Options inThe GNU CC Manual,for more information about GCC options.
You should define these macros by using ‘#define’ preprocessordirectives at the top of your source code files. These directivesmust come before any#include
of a system header file. Itis best to make them the very first thing in the file, preceded only bycomments. You could also use the ‘-D’ option to GCC, but it’sbetter if you make the source files indicate their own meaning in aself-contained way.
This system exists to allow the library to conform to multiple standards.Although the different standards are often described as supersets of eachother, they are usually incompatible because larger standards requirefunctions with names that smaller ones reserve to the user program. Thisis not mere pedantry — it has been a problem in practice. For instance,some non-GNU programs define functions namedgetline
that havenothing to do with this library’sgetline
. They would not becompilable if all features were enabled indiscriminately.
This should not be used to verify that a program conforms to a limitedstandard. It is insufficient for this purpose, as it will not protect youfrom including header files outside the standard, or relying on semanticsundefined within the standard.
If you define this macro, then the functionality from the POSIX.1standard (IEEE Standard 1003.1) is available, as well as all of theISO C facilities.
The state of_POSIX_SOURCE
is irrelevant if you define themacro_POSIX_C_SOURCE
to a positive integer.
Define this macro to a positive integer to control which POSIXfunctionality is made available. The greater the value of this macro,the more functionality is made available.
If you define this macro to a value greater than or equal to1
,then the functionality from the 1990 edition of the POSIX.1 standard(IEEE Standard 1003.1-1990) is made available.
If you define this macro to a value greater than or equal to2
,then the functionality from the 1992 edition of the POSIX.2 standard(IEEE Standard 1003.2-1992) is made available.
If you define this macro to a value greater than or equal to199309L
,then the functionality from the 1993 edition of the POSIX.1b standard(IEEE Standard 1003.1b-1993) is made available.
If you define this macro to a value greater than or equal to199506L
, then the functionality from the 1995 edition of thePOSIX.1c standard (IEEE Standard 1003.1c-1995) is made available.
If you define this macro to a value greater than or equal to200112L
, then the functionality from the 2001 edition of thePOSIX standard (IEEE Standard 1003.1-2001) is made available.
If you define this macro to a value greater than or equal to200809L
, then the functionality from the 2008 edition of thePOSIX standard (IEEE Standard 1003.1-2008) is made available.
Greater values for_POSIX_C_SOURCE
will enable future extensions.The POSIX standards process will define these values as necessary, andthe GNU C Library should support them some time after they become standardized.The 1996 edition of POSIX.1 (ISO/IEC 9945-1: 1996) states thatif you define_POSIX_C_SOURCE
to a value greater thanor equal to199506L
, then the functionality from the 1996edition is made available. In general, in the GNU C Library, bugfixes tothe standards are included when specifying the base version; e.g.,POSIX.1-2004 will always be included with a value of200112L
.
If you define this macro, functionality described in the X/OpenPortability Guide is included. This is a superset of the POSIX.1 andPOSIX.2 functionality and in fact_POSIX_SOURCE
and_POSIX_C_SOURCE
are automatically defined.
As the unification of all Unices, functionality only available inBSD and SVID is also included.
If the macro_XOPEN_SOURCE_EXTENDED
is also defined, even morefunctionality is available. The extra functions will make all functionsavailable which are necessary for the X/Open Unix brand.
If the macro_XOPEN_SOURCE
has the value500 this includesall functionality described so far plus some new definitions from theSingle Unix Specification, version 2. The value600(corresponding to the sixth revision) includes definitions from SUSv3,and using700 (the seventh revision) includes definitions fromSUSv4.
If this macro is defined some extra functions are available whichrectify a few shortcomings in all previous standards. Specifically,the functionsfseeko
andftello
are available. Withoutthese functions the difference between the ISO C interface(fseek
,ftell
) and the low-level POSIX interface(lseek
) would lead to problems.
This macro was introduced as part of the Large File Support extension (LFS).
If you define this macro an additional set of functions is made availablewhich enables 32 bit systems to use files of sizes beyondthe usual limit of 2GB. This interface is not available if the systemdoes not support files that large. On systems where the natural filesize limit is greater than 2GB (i.e., on 64 bit systems) the newfunctions are identical to the replaced functions.
The new functionality is made available by a new set of types andfunctions which replace the existing ones. The names of these new objectscontain64
to indicate the intention, e.g.,off_t
vs.off64_t
andfseeko
vs.fseeko64
.
This macro was introduced as part of the Large File Support extension(LFS). It is a transition interface for the period when 64 bitoffsets are not generally used (see_FILE_OFFSET_BITS
).
This macro determines which file system interface shall be used, onereplacing the other. Whereas_LARGEFILE64_SOURCE
makes the 64 bit interface available as an additional interface,_FILE_OFFSET_BITS
allows the 64 bit interface toreplace the old interface.
If_FILE_OFFSET_BITS
is defined to thevalue32
, the 32 bit interface is used andtypes likeoff_t
have a size of 32 bits on 32 bitsystems.
If the macro is defined to the value64
, the large file interfacereplaces the old interface. I.e., the functions are not made availableunder different names (as they are with_LARGEFILE64_SOURCE
).Instead the old function names now reference the new functions, e.g., acall tofseeko
now indeed callsfseeko64
.
If the macro is not defined it currently defaults to32
, butthis default is planned to change due to a need to updatetime_t
for Y2038 safety, and applications should not rely onthe default.
This macro should only be selected if the system provides mechanisms forhandling large files. On 64 bit systems this macro has no effectsince the*64
functions are identical to the normal functions.
This macro was introduced as part of the Large File Support extension(LFS).
Define this macro to control the bit size oftime_t
, and thereforethe bit size of alltime_t
-derived types and the prototypes of allrelated functions.
_TIME_BITS
is undefined, the bit size oftime_t
isarchitecture dependent. Currently it defaults to 64 bits on mostarchitectures. Although it defaults to 32 bits on some traditionalarchitectures (i686, ARM), this is planned to change and applicationsshould not rely on this._TIME_BITS
is defined to be 64,time_t
is definedto be a 64-bit integer. On platforms wheretime_t
wastraditionally 32 bits, calls to proper syscalls depend on theLinux kernel version on which the system is running. For Linux kernelversion above5.1 syscalls supporting 64-bit time are used. Otherwise,a fallback code is used with legacy (i.e. 32-bit) syscalls.On such platforms, the GNU C Library will also define__USE_TIME64_REDIRECTS
to indicate whether the declarations are expanded to different ones(either by redefining the symbol name or using a symbol alias).For instance, if the symbolclock_gettime
expands to__clock_gettime64
.
_TIME_BITS
is defined to be 32,time_t
is defined tobe a 32-bit integer where that is supported. This is not recommended,as 32-bittime_t
stops working in the year 2038._TIME_BITS=64
can be defined only when_FILE_OFFSET_BITS=64
is also defined.
By using this macro certain ports gain support for 64-bit time and asa result become immune to the Y2038 problem.
If this macro is defined, features from ISO C99 are included. Sincethese features are included by default, this macro is mostly relevantwhen the compiler uses an earlier language version.
If this macro is defined, ISO C11 extensions to ISO C99 are included.
If this macro is defined, ISO C23 extensions to ISO C11 are included.Only some features from this draft standard are supported bythe GNU C Library. The older name_ISOC2X_SOURCE
is also supported.
If this macro is defined, ISO C2Y extensions to ISO C23 are included.Only some features from this draft standard are supported bythe GNU C Library.
If you define this macro to the value1
, features from ISO/IECTR 24731-2:2010 (Dynamic Allocation Functions) are enabled. Only someof the features from this TR are supported by the GNU C Library.
If you define this macro, features from ISO/IEC TS 18661-1:2014(Floating-point extensions for C: Binary floating-point arithmetic)are enabled. Only some of the features from this TS are supported bythe GNU C Library.
If you define this macro, features from ISO/IEC TS 18661-4:2015(Floating-point extensions for C: Supplementary functions) areenabled. Only some of the features from this TS are supported bythe GNU C Library.
If you define this macro, features from ISO/IEC TS 18661-3:2015(Floating-point extensions for C: Interchange and extended types) areenabled. Only some of the features from this TS are supported bythe GNU C Library.
If you define this macro, ISO C23 features defined in Annex F of thatstandard are enabled. This affects declarations of thetotalorder
functions and functions related to NaN payloads.
If you define this macro, everything is included: ISO C89, ISO C99, POSIX.1, POSIX.2, BSD, SVID, X/Open, LFS, and GNU extensions. Inthe cases where POSIX.1 conflicts with BSD, the POSIX definitions takeprecedence.
If you define this macro, most features are included apart fromX/Open, LFS and GNU extensions: the effect is to enable features fromthe 2008 edition of POSIX, as well as certain BSD and SVID featureswithout a separate feature test macro to control them.
Be aware that compiler options also affect included features:
If this macro is defined, additional*at
interfaces areincluded.
If this macro is defined to1, security hardening is added tovarious library functions. If defined to2, even stricterchecks are applied. If defined to3, the GNU C Library may also usechecks that may have an additional performance overhead.SeeFortification of function calls.
If this macro is defined, correct (but non compile-time constant)MINSIGSTKSZ, SIGSTKSZ and PTHREAD_STACK_MIN are defined.
These macros are obsolete. They have the same effect as defining_POSIX_C_SOURCE
with the value199506L
.
Some very old C libraries required one of these macros to be definedfor basic functionality (e.g.getchar
) to be thread-safe.
We recommend you use_GNU_SOURCE
in new programs. If you don’tspecify the ‘-ansi’ option to GCC, or other conformance optionssuch as-std=c99, and don’t define any of these macrosexplicitly, the effect is the same as defining_DEFAULT_SOURCE
to 1.
When you define a feature test macro to request a larger class of features,it is harmless to define in addition a feature test macro for a subset ofthose features. For example, if you define_POSIX_C_SOURCE
, thendefining_POSIX_SOURCE
as well has no effect. Likewise, if youdefine_GNU_SOURCE
, then defining either_POSIX_SOURCE
or_POSIX_C_SOURCE
as well has no effect.
Previous:Using the Library, Up:Introduction [Contents][Index]
Here is an overview of the contents of the remaining chapters ofthis manual.
isspace
) and functions forperforming case conversion.char
data type.FILE *
objects). These are the normal C library functionsfromstdio.h.setjmp
andlongjmp
functions. These functions provide a facility forgoto
-like jumps which can jump from one function to another.sizeof
operator and the symbolic constantNULL
, how to write functionsaccepting variable numbers of arguments, and constants describing theranges and other properties of the numerical types. There is also a simpledebugging mechanism which allows you to put assertions in your code, andhave diagnostic messages printed if the tests fail.If you already know the name of the facility you are interested in, youcan look it up inSummary of Library Facilities. This gives you a summary ofits syntax and a pointer to where you can find a more detaileddescription. This appendix is particularly useful if you just want toverify the order and type of arguments to a function, for example. Italso tells you what standard or system each function, variable, or macrois derived from.
Next:Virtual Memory Allocation And Paging, Previous:Introduction, Up:Main Menu [Contents][Index]
Many functions in the GNU C Library detect and report error conditions,and sometimes your programs need to check for these error conditions.For example, when you open an input file, you should verify that thefile was actually opened correctly, and print an error message or takeother appropriate action if the call to the library function failed.
This chapter describes how the error reporting facility works. Yourprogram should include the header fileerrno.h to use thisfacility.
Next:Error Codes, Up:Error Reporting [Contents][Index]
Most library functions return a special value to indicate that they havefailed. The special value is typically-1
, a null pointer, or aconstant such asEOF
that is defined for that purpose. But thisreturn value tells you only that an error has occurred. To find outwhat kind of error it was, you need to look at the error code stored in thevariableerrno
. This variable is declared in the header fileerrno.h.
volatile int
errno ¶The variableerrno
contains the system error number. You canchange the value oferrno
.
Sinceerrno
is declaredvolatile
, it might be changedasynchronously by a signal handler; seeDefining Signal Handlers.However, a properly written signal handler saves and restores the valueoferrno
, so you generally do not need to worry about thispossibility except when writing signal handlers.
The initial value oferrno
at program startup is zero. In manycases, when a library function encounters an error, it will seterrno
to a non-zero value to indicate what specific errorcondition occurred. The documentation for each function lists theerror conditions that are possible for that function. Not all libraryfunctions use this mechanism; some return an error code directly,instead.
Warning: Many library functions may seterrno
to somemeaningless non-zero value even if they did not encounter any errors,and even if they return error codes directly. Therefore, it isusually incorrect to checkwhether an error occurred byinspecting the value oferrno
. The proper way to check forerror is documented for each function.
Portability Note: ISO C specifieserrno
as a“modifiable lvalue” rather than as a variable, permitting it to beimplemented as a macro. For example, its expansion might involve afunction call, like*__errno_location ()
. In fact, that iswhat it ison GNU/Linux and GNU/Hurd systems. The GNU C Library, on each system, doeswhatever is right for the particular system.
There are a few library functions, likesqrt
andatan
,that return a perfectly legitimate value in case of an error, but alsoseterrno
. For these functions, if you want to check to seewhether an error occurred, the recommended method is to seterrno
to zero before calling the function, and then check its value afterward.
All the error codes have symbolic names; they are macros defined inerrno.h. The names start with ‘E’ and an upper-caseletter or digit; you should consider names of this form to bereserved names. SeeReserved Names.
The error code values are all positive integers and are all distinct,with one exception:EWOULDBLOCK
andEAGAIN
are the same.Since the values are distinct, you can use them as labels in aswitch
statement; just don’t use bothEWOULDBLOCK
andEAGAIN
. Your program should not make any other assumptions aboutthe specific values of these symbolic constants.
The value oferrno
doesn’t necessarily have to correspond to anyof these macros, since some library functions might return other errorcodes of their own for other situations. The only values that areguaranteed to be meaningful for a particular library function are theones that this manual lists for that function.
Except on GNU/Hurd systems, almost any system call can returnEFAULT
ifit is given an invalid pointer as an argument. Since this could onlyhappen as a result of a bug in your program, and since it will nothappen on GNU/Hurd systems, we have saved space by not mentioningEFAULT
in the descriptions of individual functions.
In some Unix systems, many system calls can also returnEFAULT
ifgiven as an argument a pointer into the stack, and the kernel for someobscure reason fails in its attempt to extend the stack. If this everhappens, you should probably try using statically or dynamicallyallocated memory instead of stack memory on that system.
Next:Error Messages, Previous:Checking for Errors, Up:Error Reporting [Contents][Index]
The error code macros are defined in the header fileerrno.h.All of them expand into integer constant values. Some of these errorcodes can’t occur on GNU systems, but they can occur using the GNU C Libraryon other systems.
int
EPERM ¶“Operation not permitted.”Only the owner of the file (or other resource)or processes with special privileges can perform the operation.
int
ENOENT ¶“No such file or directory.”This is a “file doesn’t exist” errorfor ordinary files that are referenced in contexts where they areexpected to already exist.
int
ESRCH ¶“No such process.”No process matches the specified process ID.
int
EINTR ¶“Interrupted system call.”An asynchronous signal occurred and preventedcompletion of the call. When this happens, you should try the callagain.
You can choose to have functions resume after a signal that is handled,rather than failing withEINTR
; seePrimitives Interrupted by Signals.
int
EIO ¶“Input/output error.”Usually used for physical read or write errors.
int
ENXIO ¶“No such device or address.”The system tried to use the devicerepresented by a file you specified, and it couldn’t find the device.This can mean that the device file was installed incorrectly, or thatthe physical device is missing or not correctly attached to thecomputer.
int
E2BIG ¶“Argument list too long.”Used when the arguments passed to a new programbeing executed with one of theexec
functions (seeExecuting a File) occupy too much memory space. This condition never arises onGNU/Hurd systems.
int
ENOEXEC ¶“Exec format error.”Invalid executable file format. This condition is detected by theexec
functions; seeExecuting a File.
int
EBADF ¶“Bad file descriptor.”For example, I/O on a descriptor that has beenclosed or reading from a descriptor open only for writing (or viceversa).
int
ECHILD ¶“No child processes.”This error happens on operations that aresupposed to manipulate child processes, when there aren’t any processesto manipulate.
int
EDEADLK ¶“Resource deadlock avoided.”Allocating a system resource would have resulted in adeadlock situation. The system does not guarantee that it will noticeall such situations. This error means you got lucky and the systemnoticed; it might just hang. SeeFile Locks, for an example.
int
ENOMEM ¶“Cannot allocate memory.”The system cannot allocate more virtual memorybecause its capacity is full.
int
EACCES ¶“Permission denied.”The file permissions do not allow the attempted operation.
int
EFAULT ¶“Bad address.”An invalid pointer was detected.On GNU/Hurd systems, this error never happens; you get a signal instead.
int
ENOTBLK ¶“Block device required.”A file that isn’t a block special file was given in a situation thatrequires one. For example, trying to mount an ordinary file as a filesystem in Unix gives this error.
int
EBUSY ¶“Device or resource busy.”A system resource that can’t be shared is already in use.For example, if you try to delete a file that is the root of a currentlymounted filesystem, you get this error.
int
EEXIST ¶“File exists.”An existing file was specified in a context where it onlymakes sense to specify a new file.
int
EXDEV ¶“Invalid cross-device link.”An attempt to make an improper link across file systems was detected.This happens not only when you uselink
(seeHard Links) butalso when you rename a file withrename
(seeRenaming Files).
int
ENODEV ¶“No such device.”The wrong type of device was given to a function that expects aparticular sort of device.
int
ENOTDIR ¶“Not a directory.”A file that isn’t a directory was specified when a directory is required.
int
EISDIR ¶“Is a directory.”You cannot open a directory for writing,or create or remove hard links to it.
int
EINVAL ¶“Invalid argument.”This is used to indicate various kinds of problemswith passing the wrong argument to a library function.
int
EMFILE ¶“Too many open files.”The current process has too many files open and can’t open any more.Duplicate descriptors do count toward this limit.
In BSD and GNU, the number of open files is controlled by a resourcelimit that can usually be increased. If you get this error, you mightwant to increase theRLIMIT_NOFILE
limit or make it unlimited;seeLimiting Resource Usage.
int
ENFILE ¶“Too many open files in system.”There are too many distinct file openings in the entire system. Notethat any number of linked channels count as just one file opening; seeLinked Channels. This error never occurs on GNU/Hurd systems.
int
ENOTTY ¶“Inappropriate ioctl for device.”Inappropriate I/O control operation, such as trying to set terminalmodes on an ordinary file.
int
ETXTBSY ¶“Text file busy.”An attempt to execute a file that is currently open for writing, orwrite to a file that is currently being executed. Often using adebugger to run a program is considered having it open for writing andwill cause this error. (The name stands for “text file busy”.) Thisis not an error on GNU/Hurd systems; the text is copied as necessary.
int
EFBIG ¶“File too large.”The size of a file would be larger than allowed by the system.
int
ENOSPC ¶“No space left on device.”Write operation on a file failed because thedisk is full.
int
ESPIPE ¶“Illegal seek.”Invalid seek operation (such as on a pipe).
int
EROFS ¶“Read-only file system.”An attempt was made to modify something on a read-only file system.
int
EMLINK ¶“Too many links.”The link count of a single file would become too large.rename
can cause this error if the file being renamed already hasas many links as it can take (seeRenaming Files).
int
EPIPE ¶“Broken pipe.”There is no process reading from the other end of a pipe.Every library function that returns this error code also generates aSIGPIPE
signal; this signal terminates the program if not handledor blocked. Thus, your program will never actually seeEPIPE
unless it has handled or blockedSIGPIPE
.
int
EDOM ¶“Numerical argument out of domain.”Used by mathematical functions when an argument value doesnot fall into the domain over which the function is defined.
int
ERANGE ¶“Numerical result out of range.”Used by mathematical functions when the result value isnot representable because of overflow or underflow.
int
EAGAIN ¶“Resource temporarily unavailable.”The call might work if you try againlater. The macroEWOULDBLOCK
is another name forEAGAIN
;they are always the same in the GNU C Library.
This error can happen in a few different situations:
select
to find outwhen the operation will be possible; seeWaiting for Input or Output.Portability Note: In many older Unix systems, this conditionwas indicated byEWOULDBLOCK
, which was a distinct error codedifferent fromEAGAIN
. To make your program portable, you shouldcheck for both codes and treat them the same.
fork
can return this error. It indicates that the shortage is expected topass, so your program can try the call again later and it may succeed.It is probably a good idea to delay for a few seconds before trying itagain, to allow time for other processes to release scarce resources.Such shortages are usually fairly serious and affect the whole system,so usually an interactive program should report the error to the userand return to its command loop.int
EWOULDBLOCK ¶“Operation would block.”In the GNU C Library, this is another name forEAGAIN
(above).The values are always the same, on every operating system.
C libraries in many older Unix systems haveEWOULDBLOCK
as aseparate error code.
int
EINPROGRESS ¶“Operation now in progress.”An operation that cannot complete immediately was initiated on an objectthat has non-blocking mode selected. Some functions that must alwaysblock (such asconnect
; seeMaking a Connection) never returnEAGAIN
. Instead, they returnEINPROGRESS
to indicate thatthe operation has begun and will take some time. Attempts to manipulatethe object before the call completes returnEALREADY
. You canuse theselect
function to find out when the pending operationhas completed; seeWaiting for Input or Output.
int
EALREADY ¶“Operation already in progress.”An operation is already in progress on an object that has non-blockingmode selected.
int
ENOTSOCK ¶“Socket operation on non-socket.”A file that isn’t a socket was specified when a socket is required.
int
EMSGSIZE ¶“Message too long.”The size of a message sent on a socket was larger than the supportedmaximum size.
int
EPROTOTYPE ¶“Protocol wrong type for socket.”The socket type does not support the requested communications protocol.
int
ENOPROTOOPT ¶“Protocol not available.”You specified a socket option that doesn’t make sense for theparticular protocol being used by the socket. SeeSocket Options.
int
EPROTONOSUPPORT ¶“Protocol not supported.”The socket domain does not support the requested communications protocol(perhaps because the requested protocol is completely invalid).SeeCreating a Socket.
int
ESOCKTNOSUPPORT ¶“Socket type not supported.”The socket type is not supported.
int
EOPNOTSUPP ¶“Operation not supported.”The operation you requested is not supported. Some socket functionsdon’t make sense for all types of sockets, and others may not beimplemented for all communications protocols. On GNU/Hurd systems, thiserror can happen for many calls when the object does not support theparticular operation; it is a generic indication that the server knowsnothing to do for that call.
int
EPFNOSUPPORT ¶“Protocol family not supported.”The socket communications protocol family you requested is not supported.
int
EAFNOSUPPORT ¶“Address family not supported by protocol.”The address family specified for a socket is not supported; it isinconsistent with the protocol being used on the socket. SeeSockets.
int
EADDRINUSE ¶“Address already in use.”The requested socket address is already in use. SeeSocket Addresses.
int
EADDRNOTAVAIL ¶“Cannot assign requested address.”The requested socket address is not available; for example, you triedto give a socket a name that doesn’t match the local host name.SeeSocket Addresses.
int
ENETDOWN ¶“Network is down.”A socket operation failed because the network was down.
int
ENETUNREACH ¶“Network is unreachable.”A socket operation failed because the subnet containing the remote hostwas unreachable.
int
ENETRESET ¶“Network dropped connection on reset.”A network connection was reset because the remote host crashed.
int
ECONNABORTED ¶“Software caused connection abort.”A network connection was aborted locally.
int
ECONNRESET ¶“Connection reset by peer.”A network connection was closed for reasons outside the control of thelocal host, such as by the remote machine rebooting or an unrecoverableprotocol violation.
int
ENOBUFS ¶“No buffer space available.”The kernel’s buffers for I/O operations are all in use. In GNU, thiserror is always synonymous withENOMEM
; you may get one or theother from network operations.
int
EISCONN ¶“Transport endpoint is already connected.”You tried to connect a socket that is already connected.SeeMaking a Connection.
int
ENOTCONN ¶“Transport endpoint is not connected.”The socket is not connected to anything. You get this error when youtry to transmit data over a socket, without first specifying adestination for the data. For a connectionless socket (for datagramprotocols, such as UDP), you getEDESTADDRREQ
instead.
int
EDESTADDRREQ ¶“Destination address required.”No default destination address was set for the socket. You get thiserror when you try to transmit data over a connectionless socket,without first specifying a destination for the data withconnect
.
int
ESHUTDOWN ¶“Cannot send after transport endpoint shutdown.”The socket has already been shut down.
int
ETOOMANYREFS ¶“Too many references: cannot splice.”
int
ETIMEDOUT ¶“Connection timed out.”A socket operation with a specified timeout received no response duringthe timeout period.
int
ECONNREFUSED ¶“Connection refused.”A remote host refused to allow the network connection (typically becauseit is not running the requested service).
int
ELOOP ¶“Too many levels of symbolic links.”Too many levels of symbolic links were encountered in looking up a file name.This often indicates a cycle of symbolic links.
int
ENAMETOOLONG ¶“File name too long.”Filename too long (longer thanPATH_MAX
; seeLimits on File System Capacity) or host name too long (ingethostname
orsethostname
; seeHost Identification).
int
EHOSTDOWN ¶“Host is down.”The remote host for a requested network connection is down.
int
EHOSTUNREACH ¶“No route to host.”The remote host for a requested network connection is not reachable.
int
ENOTEMPTY ¶“Directory not empty.”Directory not empty, where an empty directory was expected. Typically,this error occurs when you are trying to delete a directory.
int
EPROCLIM ¶“Too many processes.”This means that the per-user limit on new process would be exceeded byan attemptedfork
. SeeLimiting Resource Usage, for details ontheRLIMIT_NPROC
limit.
int
EUSERS ¶“Too many users.”The file quota system is confused because there are too many users.
int
EDQUOT ¶“Disk quota exceeded.”The user’s disk quota was exceeded.
int
ESTALE ¶“Stale file handle.”This indicates an internal confusion in thefile system which is due to file system rearrangements on the server hostfor NFS file systems or corruption in other file systems.Repairing this condition usually requires unmounting, possibly repairingand remounting the file system.
int
EREMOTE ¶“Object is remote.”An attempt was made to NFS-mount a remote file system with a file name thatalready specifies an NFS-mounted file.(This is an error on some operating systems, but we expect it to workproperly on GNU/Hurd systems, making this error code impossible.)
int
EBADRPC ¶“RPC struct is bad.”
int
ERPCMISMATCH ¶“RPC version wrong.”
int
EPROGUNAVAIL ¶“RPC program not available.”
int
EPROGMISMATCH ¶“RPC program version wrong.”
int
EPROCUNAVAIL ¶“RPC bad procedure for program.”
int
ENOLCK ¶“No locks available.”This is used by the file locking facilities; seeFile Locks. This error is never generated by GNU/Hurd systems, butit can result from an operation to an NFS server running anotheroperating system.
int
EFTYPE ¶“Inappropriate file type or format.”The file was the wrong type for theoperation, or a data file had the wrong format.
On some systemschmod
returns this error if you try to set thesticky bit on a non-directory file; seeAssigning File Permissions.
int
EAUTH ¶“Authentication error.”
int
ENEEDAUTH ¶“Need authenticator.”
int
ENOSYS ¶“Function not implemented.”This indicates that the function called isnot implemented at all, either in the C library itself or in theoperating system. When you get this error, you can be sure that thisparticular function will always fail withENOSYS
unless youinstall a new version of the C library or the operating system.
int
ELIBEXEC ¶“Cannot exec a shared library directly.”
int
ENOTSUP ¶“Not supported.”A function returns this error when certain parametervalues are valid, but the functionality they request is not available.This can mean that the function does not implement a particular commandor option value or flag bit at all. For functions that operate on someobject given in a parameter, such as a file descriptor or a port, itmight instead mean that onlythat specific object (filedescriptor, port, etc.) is unable to support the other parameters given;different file descriptors might support different ranges of parametervalues.
If the entire function is not available at all in the implementation,it returnsENOSYS
instead.
int
EILSEQ ¶“Invalid or incomplete multibyte or wide character.”While decoding a multibyte character the function came along an invalidor an incomplete sequence of bytes or the given wide character is invalid.
int
EBACKGROUND ¶“Inappropriate operation for background process.”On GNU/Hurd systems, servers supporting theterm
protocol returnthis error for certain operations when the caller is not in theforeground process group of the terminal. Users do not usually see thiserror because functions such asread
andwrite
translateit into aSIGTTIN
orSIGTTOU
signal. SeeJob Control,for information on process groups and these signals.
int
EDIED ¶“Translator died.”On GNU/Hurd systems, opening a file returns this error when the file istranslated by a program and the translator program dies while startingup, before it has connected to the file.
int
ED ¶“?.”The experienced user will know what is wrong.
int
EGREGIOUS ¶“You really blew it this time.”You didwhat?
int
EIEIO ¶“Computer bought the farm.”Go home and have a glass of warm, dairy-fresh milk.
int
EGRATUITOUS ¶“Gratuitous error.”This error code has no purpose.
int
EBADMSG ¶“Bad message.”
int
EIDRM ¶“Identifier removed.”
int
EMULTIHOP ¶“Multihop attempted.”
int
ENODATA ¶“No data available.”
int
ENOLINK ¶“Link has been severed.”
int
ENOMSG ¶“No message of desired type.”
int
ENOSR ¶“Out of streams resources.”
int
ENOSTR ¶“Device not a stream.”
int
EOVERFLOW ¶“Value too large for defined data type.”
int
EPROTO ¶“Protocol error.”
int
ETIME ¶“Timer expired.”
int
ECANCELED ¶“Operation canceled.”An asynchronous operation was canceled before itcompleted. SeePerform I/O Operations in Parallel. When you callaio_cancel
,the normal result is for the operations affected to complete with thiserror; seeCancellation of AIO Operations.
int
EOWNERDEAD ¶“Owner died.”
int
ENOTRECOVERABLE ¶“State not recoverable.”
The following error codes are defined by the Linux/i386 kernel.They are not yet documented.
int
ERESTART ¶“Interrupted system call should be restarted.”
int
ECHRNG ¶“Channel number out of range.”
int
EL2NSYNC ¶“Level 2 not synchronized.”
int
EL3HLT ¶“Level 3 halted.”
int
EL3RST ¶“Level 3 reset.”
int
ELNRNG ¶“Link number out of range.”
int
EUNATCH ¶“Protocol driver not attached.”
int
ENOCSI ¶“No CSI structure available.”
int
EL2HLT ¶“Level 2 halted.”
int
EBADE ¶“Invalid exchange.”
int
EBADR ¶“Invalid request descriptor.”
int
EXFULL ¶“Exchange full.”
int
ENOANO ¶“No anode.”
int
EBADRQC ¶“Invalid request code.”
int
EBADSLT ¶“Invalid slot.”
int
EDEADLOCK ¶“File locking deadlock error.”
int
EBFONT ¶“Bad font file format.”
int
ENONET ¶“Machine is not on the network.”
int
ENOPKG ¶“Package not installed.”
int
EADV ¶“Advertise error.”
int
ESRMNT ¶“Srmount error.”
int
ECOMM ¶“Communication error on send.”
int
EDOTDOT ¶“RFS specific error.”
int
ENOTUNIQ ¶“Name not unique on network.”
int
EBADFD ¶“File descriptor in bad state.”
int
EREMCHG ¶“Remote address changed.”
int
ELIBACC ¶“Can not access a needed shared library.”
int
ELIBBAD ¶“Accessing a corrupted shared library.”
int
ELIBSCN ¶“.lib section in a.out corrupted.”
int
ELIBMAX ¶“Attempting to link in too many shared libraries.”
int
ESTRPIPE ¶“Streams pipe error.”
int
EUCLEAN ¶“Structure needs cleaning.”
int
ENOTNAM ¶“Not a XENIX named type file.”
int
ENAVAIL ¶“No XENIX semaphores available.”
int
EISNAM ¶“Is a named type file.”
int
EREMOTEIO ¶“Remote I/O error.”
int
ENOMEDIUM ¶“No medium found.”
int
EMEDIUMTYPE ¶“Wrong medium type.”
int
ENOKEY ¶“Required key not available.”
int
EKEYEXPIRED ¶“Key has expired.”
int
EKEYREVOKED ¶“Key has been revoked.”
int
EKEYREJECTED ¶“Key was rejected by service.”
int
ERFKILL ¶“Operation not possible due to RF-kill.”
int
EHWPOISON ¶“Memory page has hardware error.”
Previous:Error Codes, Up:Error Reporting [Contents][Index]
The library has functions and variables designed to make it easy foryour program to report informative error messages in the customaryformat about the failure of a library call. The functionsstrerror
andperror
give you the standard error messagefor a given error code; the variableprogram_invocation_short_name
gives you convenient access to thename of the program that encountered the error.
char *
strerror(interrnum)
¶Preliminary:| MT-Safe | AS-Unsafe heap i18n| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thestrerror
function maps the error code (seeChecking for Errors) specified by theerrnum argument to a descriptive errormessage string. The string is translated according to the currentlocale. The return value is a pointer to this string.
The valueerrnum normally comes from the variableerrno
.
You should not modify the string returned bystrerror
. Also, ifyou make subsequent calls tostrerror
orstrerror_l
, orthe thread that obtained the string exits, the returned pointer will beinvalidated.
As there is no way to restore the previous state after callingstrerror
, library code should not call this function because itmay interfere with application use ofstrerror
, invalidating thestring pointer before the application is done using it. Instead,strerror_r
,snprintf
with the ‘%m’ or ‘%#m’specifiers,strerrorname_np
, orstrerrordesc_np
can beused instead.
Thestrerror
function preserves the value oferrno
andcannot fail.
The functionstrerror
is declared instring.h.
char *
strerror_l(interrnum, locale_tlocale)
¶Preliminary:| MT-Safe | AS-Unsafe heap i18n| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function is likestrerror
, except that the returned stringis translated according tolocale (instead of the current localeused bystrerror
). Note that callingstrerror_l
invalidates the pointer returned bystrerror
and vice versa.
The functionstrerror_l
is defined by POSIX and is declared instring.h.
char *
strerror_r(interrnum, char *buf, size_tn)
¶Preliminary:| MT-Safe | AS-Unsafe i18n| AC-Unsafe | SeePOSIX Safety Concepts.
The following description is for the GNU variant of the function,used if_GNU_SOURCE
is defined. SeeFeature Test Macros.
Thestrerror_r
function works likestrerror
but instead ofreturning a pointer to a string that is managed by the GNU C Library, it canuse the user supplied buffer starting atbuf for storing thestring.
At mostn characters are written (including the NUL byte) tobuf, so it is up to the user to select a buffer large enough.Whether returned pointer points to thebuf array or not depends ontheerrnum argument. If the result string is not stored inbuf, the string will not change for the remaining executionof the program.
The functionstrerror_r
as described above is a GNU extension andit is declared instring.h. There is a POSIX variant of thisfunction, described next.
int
strerror_r(interrnum, char *buf, size_tn)
¶Preliminary:| MT-Safe | AS-Unsafe i18n| AC-Unsafe | SeePOSIX Safety Concepts.
This variant of thestrerror_r
function is used if a standard isselected that includesstrerror_r
, but_GNU_SOURCE
is notdefined. This POSIX variant of the function always writes the errormessage to the specified bufferbuf of sizen bytes.
Upon success,strerror_r
returns 0. Two more return values areused to indicate failure.
EINVAL
¶Theerrnum argument does not correspond to a known error constant.
ERANGE
¶The buffer sizen is not large enough to store the entire error message.
Even if an error is reported,strerror_r
still writes as much ofthe error message to the output buffer as possible. After a call tostrerror_r
, the value oferrno
is unspecified.
If you want to use the always-copying POSIX semantics ofstrerror_r
in a program that is potentially compiled with_GNU_SOURCE
defined, you can usesnprintf
with the‘%m’ conversion specifier, like this:
int saved_errno = errno;errno = errnum;int ret = snprintf (buf, n, "%m");errno = saved_errno;if (strerrorname_np (errnum) == NULL) return EINVAL;if (ret >= n) return ERANGE:return 0;
This function is declared instring.h if it is declared at all.It is a POSIX extension.
void
perror(const char *message)
¶Preliminary:| MT-Unsafe race:stderr| AS-Unsafe corrupt i18n heap lock| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
This function prints an error message to the streamstderr
;seeStandard Streams. The orientation ofstderr
is notchanged.
If you callperror
with amessage that is either a nullpointer or an empty string,perror
just prints the error messagecorresponding toerrno
, adding a trailing newline.
If you supply a non-nullmessage argument, thenperror
prefixes its output with this string. It adds a colon and a spacecharacter to separate themessage from the error string correspondingtoerrno
.
The functionperror
is declared instdio.h.
const char *
strerrorname_np(interrnum)
¶| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the name describing the errorerrnum orNULL
if there is no known constant with this value (e.g "EINVAL"forEINVAL
). The returned string does not change for theremaining execution of the program.
This function is a GNU extension, declared in the header filestring.h.
const char *
strerrordesc_np(interrnum)
¶| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the message describing the errorerrnum orNULL
if there is no known constant with this value (e.g "Invalidargument" forEINVAL
). Different thanstrerror
thereturned description is not translated, and the returned string does notchange for the remaining execution of the program.
This function is a GNU extension, declared in the header filestring.h.
strerror
andperror
produce the exact same message for anygiven error code under the same locale; the precise text varies fromsystem to system. With the GNU C Library, the messages are fairly short;there are no multi-line messages or embedded newlines. Each errormessage begins with a capital letter and does not include anyterminating punctuation.
Many programs that don’t read input from the terminal are designed toexit if any system call fails. By convention, the error message fromsuch a program should start with the program’s name, sans directories.You can find that name in the variableprogram_invocation_short_name
; the full file name is stored thevariableprogram_invocation_name
.
char *
program_invocation_name ¶This variable’s value is the name that was used to invoke the programrunning in the current process. It is the same asargv[0]
. Notethat this is not necessarily a useful file name; often it contains nodirectory names. SeeProgram Arguments.
This variable is a GNU extension and is declared inerrno.h.
char *
program_invocation_short_name ¶This variable’s value is the name that was used to invoke the programrunning in the current process, with directory names removed. (That isto say, it is the same asprogram_invocation_name
minuseverything up to the last slash, if any.)
This variable is a GNU extension and is declared inerrno.h.
The library initialization code sets up both of these variables beforecallingmain
.
Portability Note: If you want your program to work withnon-GNU libraries, you must save the value ofargv[0]
inmain
, and then strip off the directory names yourself. Weadded these extensions to make it possible to write self-containederror-reporting subroutines that require no explicit cooperation frommain
.
Here is an example showing how to handle failure to open a filecorrectly. The functionopen_sesame
tries to open the named filefor reading and returns a stream if successful. Thefopen
library function returns a null pointer if it couldn’t open the file forsome reason. In that situation,open_sesame
constructs anappropriate error message using thestrerror
function, andterminates the program. If we were going to make some other librarycalls before passing the error code tostrerror
, we’d have tosave it in a local variable instead, because those other libraryfunctions might overwriteerrno
in the meantime.
#define _GNU_SOURCE#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <string.h>FILE *open_sesame (char *name){ FILE *stream; errno = 0; stream = fopen (name, "r"); if (stream == NULL) { fprintf (stderr, "%s: Couldn't open file %s; %s\n", program_invocation_short_name, name, strerror (errno)); exit (EXIT_FAILURE); } else return stream;}
Usingperror
has the advantage that the function is portable andavailable on all systems implementing ISO C. But often the textperror
generates is not what is wanted and there is no way toextend or change whatperror
does. The GNU coding standard, forinstance, requires error messages to be preceded by the program name andprograms which read some input files should provide informationabout the input file name and the line number in case an error isencountered while reading the file. For these occasions there are twofunctions available which are widely used throughout the GNU project.These functions are declared inerror.h.
void
error(intstatus, interrnum, const char *format, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap i18n| AC-Safe | SeePOSIX Safety Concepts.
Theerror
function can be used to report general problems duringprogram execution. Theformat argument is a format string justlike those given to theprintf
family of functions. Thearguments required for the format can follow theformat parameter.Just likeperror
,error
also can report an error code intextual form. But unlikeperror
the error value is explicitlypassed to the function in theerrnum parameter. This eliminatesthe problem mentioned above that the error reporting function must becalled immediately after the function causing the error since otherwiseerrno
might have a different value.
error
prints first the program name. If the applicationdefined a global variableerror_print_progname
and points it to afunction this function will be called to print the program name.Otherwise the string from the global variableprogram_name
isused. The program name is followed by a colon and a space which in turnis followed by the output produced by the format string. If theerrnum parameter is non-zero the format string output is followedby a colon and a space, followed by the error message for the error codeerrnum. In any case is the output terminated with a newline.
The output is directed to thestderr
stream. If thestderr
wasn’t oriented before the call it will be narrow-orientedafterwards.
The function will return unless thestatus parameter has anon-zero value. In this case the function will callexit
withthestatus value for its parameter and therefore never return. Iferror
returns, the global variableerror_message_count
isincremented by one to keep track of the number of errors reported.
void
error_at_line(intstatus, interrnum, const char *fname, unsigned intlineno, const char *format, …)
¶Preliminary:| MT-Unsafe race:error_at_line/error_one_per_line locale| AS-Unsafe corrupt heap i18n| AC-Unsafe corrupt/error_one_per_line| SeePOSIX Safety Concepts.
Theerror_at_line
function is very similar to theerror
function. The only differences are the additional parametersfnameandlineno. The handling of the other parameters is identical tothat oferror
except that between the program name and the stringgenerated by the format string additional text is inserted.
Directly following the program name a colon, followed by the file namepointed to byfname, another colon, and the value oflineno isprinted.
This additional output of course is meant to be used to locate an errorin an input file (like a programming language source code file etc).
If the global variableerror_one_per_line
is set to a non-zerovalueerror_at_line
will avoid printing consecutive messages forthe same file and line. Repetition which are not directly followingeach other are not caught.
Just likeerror
this function only returns ifstatus iszero. Otherwiseexit
is called with the non-zero value. Iferror
returns, the global variableerror_message_count
isincremented by one to keep track of the number of errors reported.
As mentioned above, theerror
anderror_at_line
functionscan be customized by defining a variable namederror_print_progname
.
void (*error_print_progname)
(void) ¶If theerror_print_progname
variable is defined to a non-zerovalue the function pointed to is called byerror
orerror_at_line
. It is expected to print the program name or dosomething similarly useful.
The function is expected to print to thestderr
stream andmust be able to handle whatever orientation the stream has.
The variable is global and shared by all threads.
unsigned int
error_message_count ¶Theerror_message_count
variable is incremented whenever one ofthe functionserror
orerror_at_line
returns. Thevariable is global and shared by all threads.
int
error_one_per_line ¶Theerror_one_per_line
variable influences onlyerror_at_line
. Normally theerror_at_line
functioncreates output for every invocation. Iferror_one_per_line
isset to a non-zero valueerror_at_line
keeps track of the lastfile name and line number for which an error was reported and avoidsdirectly following messages for the same file and line. This variableis global and shared by all threads.
A program which read some input file and reports errors in it could looklike this:
{ char *line = NULL; size_t len = 0; unsigned int lineno = 0; error_message_count = 0; while (! feof_unlocked (fp)) { ssize_t n = getline (&line, &len, fp); if (n <= 0) /*End of file or error. */ break; ++lineno; /*Process the line. */ ... if (Detect error in line) error_at_line (0, errval, filename, lineno, "some error text %s", some_variable); } if (error_message_count != 0) error (EXIT_FAILURE, 0, "%u errors found", error_message_count);}
error
anderror_at_line
are clearly the functions ofchoice and enable the programmer to write applications which follow theGNU coding standard. The GNU C Library additionally contains functions whichare used in BSD for the same purpose. These functions are declared inerr.h. It is generally advised to not use these functions. Theyare included only for compatibility.
void
warn(const char *format, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap i18n| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Thewarn
function is roughly equivalent to a call like
error (0, errno, format,the parameters)
except that the global variableserror
respects and modifiesare not used.
void
vwarn(const char *format, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap i18n| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Thevwarn
function is just likewarn
except that theparameters for the handling of the format stringformat are passedin as a value of typeva_list
.
void
warnx(const char *format, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Thewarnx
function is roughly equivalent to a call like
error (0, 0, format,the parameters)
except that the global variableserror
respects and modifiesare not used. The difference towarn
is that no error numberstring is printed.
void
vwarnx(const char *format, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Thevwarnx
function is just likewarnx
except that theparameters for the handling of the format stringformat are passedin as a value of typeva_list
.
void
err(intstatus, const char *format, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap i18n| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Theerr
function is roughly equivalent to a call like
error (status, errno, format,the parameters)
except that the global variableserror
respects and modifiesare not used and that the program is exited even ifstatus is zero.
void
verr(intstatus, const char *format, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap i18n| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Theverr
function is just likeerr
except that theparameters for the handling of the format stringformat are passedin as a value of typeva_list
.
void
errx(intstatus, const char *format, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Theerrx
function is roughly equivalent to a call like
error (status, 0, format,the parameters)
except that the global variableserror
respects and modifiesare not used and that the program is exited even ifstatusis zero. The difference toerr
is that no error numberstring is printed.
void
verrx(intstatus, const char *format, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Theverrx
function is just likeerrx
except that theparameters for the handling of the format stringformat are passedin as a value of typeva_list
.
Next:Character Handling, Previous:Error Reporting, Up:Main Menu [Contents][Index]
This chapter describes how processes manage and use memory in a systemthat uses the GNU C Library.
The GNU C Library has several functions for dynamically allocatingvirtual memory in various ways. They vary in generality and inefficiency. The library also provides functions for controlling pagingand allocation of real memory.
Memory mapped I/O is not discussed in this chapter. SeeMemory-mapped I/O.
One of the most basic resources a process has available to it is memory.There are a lot of different ways systems organize memory, but in atypical one, each process has one linear virtual address space, withaddresses running from zero to some huge maximum. It need not becontiguous; i.e., not all of these addresses actually can be used tostore data.
The virtual memory is divided into pages (4 kilobytes is typical).Backing each page of virtual memory is a page of real memory (called aframe) or some secondary storage, usually disk space. The diskspace might be swap space or just some ordinary disk file. Actually, apage of all zeroes sometimes has nothing at all backing it – there’sjust a flag saying it is all zeroes.
The same frame of real memory or backing store can back multiple virtualpages belonging to multiple processes. This is normally the case, forexample, with virtual memory occupied by GNU C Library code. The samereal memory frame containing theprintf
function backs a virtualmemory page in each of the existing processes that has aprintf
call in its program.
In order for a program to access any part of a virtual page, the pagemust at that moment be backed by (“connected to”) a real frame. Butbecause there is usually a lot more virtual memory than real memory, thepages must move back and forth between real memory and backing storeregularly, coming into real memory when a process needs to access themand then retreating to backing store when not needed anymore. Thismovement is calledpaging.
When a program attempts to access a page which is not at that momentbacked by real memory, this is known as apage fault. When a pagefault occurs, the kernel suspends the process, places the page into areal page frame (this is called “paging in” or “faulting in”), thenresumes the process so that from the process’ point of view, the pagewas in real memory all along. In fact, to the process, all pages alwaysseem to be in real memory. Except for one thing: the elapsed executiontime of an instruction that would normally be a few nanoseconds issuddenly much, much, longer (because the kernel normally has to do I/Oto complete the page-in). For programs sensitive to that, the functionsdescribed inLocking Pages can control it.
Within each virtual address space, a process has to keep track of whatis at which addresses, and that process is called memory allocation.Allocation usually brings to mind meting out scarce resources, but inthe case of virtual memory, that’s not a major goal, because there isgenerally much more of it than anyone needs. Memory allocation within aprocess is mainly just a matter of making sure that the same byte ofmemory isn’t used to store two different things.
Processes allocate memory in two major ways: by exec andprogrammatically. Actually, forking is a third way, but it’s not veryinteresting. SeeCreating a Process.
Exec is the operation of creating a virtual address space for a process,loading its basic program into it, and executing the program. It isdone by the “exec” family of functions (e.g.execl
). Theoperation takes a program file (an executable), it allocates space toload all the data in the executable, loads it, and transfers control toit. That data is most notably the instructions of the program (thetext), but also literals and constants in the program and evensome variables: C variables with the static storage class (seeMemory Allocation in C Programs).
Once that program begins to execute, it uses programmatic allocation togain additional memory. In a C program with the GNU C Library, thereare two kinds of programmatic allocation: automatic and dynamic.SeeMemory Allocation in C Programs.
Memory-mapped I/O is another form of dynamic virtual memory allocation.Mapping memory to a file means declaring that the contents of certainrange of a process’ addresses shall be identical to the contents of aspecified regular file. The system makes the virtual memory initiallycontain the contents of the file, and if you modify the memory, thesystem writes the same modification to the file. Note that due to themagic of virtual memory and page faults, there is no reason for thesystem to do I/O to read the file, or allocate real memory for itscontents, until the program accesses the virtual memory.SeeMemory-mapped I/O.
Just as it programmatically allocates memory, the program canprogrammatically deallocate (free) it. You can’t free the memorythat was allocated by exec. When the program exits or execs, you mightsay that all its memory gets freed, but since in both cases the addressspace ceases to exist, the point is really moot. SeeProgram Termination.
A process’ virtual address space is divided into segments. A segment isa contiguous range of virtual addresses. Three important segments are:
Next:Resizing the Data Segment, Previous:Process Memory Concepts, Up:Virtual Memory Allocation And Paging [Contents][Index]
This section covers how ordinary programs manage storage for their data,including the famousmalloc
function and some fancier facilitiesspecial to the GNU C Library and GNU Compiler.
malloc
The C language supports two kinds of memory allocation through thevariables in C programs:
In GNU C, the size of the automatic storage can be an expressionthat varies. In other C implementations, it must be a constant.
A third important kind of memory allocation,dynamic allocation,is not supported by C variables but is available via GNU C Libraryfunctions.
Dynamic memory allocation is a technique in which programsdetermine as they are running where to store some information. You needdynamic allocation when the amount of memory you need, or how long youcontinue to need it, depends on factors that are not known before theprogram runs.
For example, you may need a block to store a line read from an inputfile; since there is no limit to how long a line can be, you mustallocate the memory dynamically and make it dynamically larger as youread more of the line.
Or, you may need a block for each record or each definition in the inputdata; since you can’t know in advance how many there will be, you mustallocate a new block for each record or definition as you read it.
When you use dynamic allocation, the allocation of a block of memory isan action that the program requests explicitly. You call a function ormacro when you want to allocate space, and specify the size with anargument. If you want to free the space, you do so by calling anotherfunction or macro. You can do these things whenever you want, as oftenas you want.
Dynamic allocation is not supported by C variables; there is no storageclass “dynamic”, and there can never be a C variable whose value isstored in dynamically allocated space. The only way to get dynamicallyallocated memory is via a system call (which is generally via a GNU C Libraryfunction call), and the only way to refer to dynamicallyallocated space is through a pointer. Because it is less convenient,and because the actual process of dynamic allocation requires morecomputation time, programmers generally use dynamic allocation only whenneither static nor automatic allocation will serve.
For example, if you want to allocate dynamically some space to hold astruct foobar
, you cannot declare a variable of typestructfoobar
whose contents are the dynamically allocated space. But you candeclare a variable of pointer typestruct foobar *
and assign it theaddress of the space. Then you can use the operators ‘*’ and‘->’ on this pointer variable to refer to the contents of the space:
{ struct foobar *ptr = malloc (sizeof *ptr); ptr->name = x; ptr->next = current_foobar; current_foobar = ptr;}
Next:Unconstrained Allocation, Previous:Memory Allocation in C Programs, Up:Allocating Storage For Program Data [Contents][Index]
Themalloc
implementation in the GNU C Library is derived from ptmalloc(pthreads malloc), which in turn is derived from dlmalloc (Doug Lea malloc).Thismalloc
may allocate memoryin two different ways depending on their sizeand certain parameters that may be controlled by users. The most common way isto allocate portions of memory (called chunks) from a large contiguous area ofmemory and manage these areas to optimize their use and reduce wastage in theform of unusable chunks. Traditionally the system heap was set up to be the onelarge memory area but the GNU C Librarymalloc
implementation maintainsmultiple such areas to optimize their use in multi-threaded applications. Eachsuch area is internally referred to as anarena.
As opposed to other versions, themalloc
in the GNU C Library does not roundup chunk sizes to powers of two, neither for large nor for small sizes.Neighboring chunks can be coalesced on afree
no matter what their sizeis. This makes the implementation suitable for all kinds of allocationpatterns without generally incurring high memory waste through fragmentation.The presence of multiple arenas allows multiple threads to allocatememory simultaneously in separate arenas, thus improving performance.
The other way of memory allocation is for very large blocks, i.e. much largerthan a page. These requests are allocated withmmap
(anonymous or via/dev/zero; seeMemory-mapped I/O)). This has the great advantagethat these chunks are returned to the system immediately when they are freed.Therefore, it cannot happen that a large chunk becomes “locked” in betweensmaller ones and even after callingfree
wastes memory. The sizethreshold formmap
to be used is dynamic and gets adjusted according toallocation patterns of the program.mallopt
can be used to staticallyadjust the threshold usingM_MMAP_THRESHOLD
and the use ofmmap
can be disabled completely withM_MMAP_MAX
;seeMalloc Tunable Parameters.
A more detailed technical description of the GNU Allocator is maintained inthe GNU C Library wiki. Seehttps://sourceware.org/glibc/wiki/MallocInternals.
It is possible to use your own custommalloc
instead of thebuilt-in allocator provided by the GNU C Library. SeeReplacingmalloc
.
Next:Allocation Debugging, Previous:The GNU Allocator, Up:Allocating Storage For Program Data [Contents][Index]
The most general dynamic allocation facility ismalloc
. Itallows you to allocate blocks of memory of any size at any time, makethem bigger or smaller at any time, and free the blocks individually atany time (or never).
malloc
malloc
malloc
malloc
-Related FunctionsNext:Examples ofmalloc
, Up:Unconstrained Allocation [Contents][Index]
To allocate a block of memory, callmalloc
. The prototype forthis function is instdlib.h.
void *
malloc(size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
This function returns a pointer to a newly allocated blocksizebytes long, or a null pointer (settingerrno
)if the block could not be allocated.
The contents of the block are undefined; you must initialize it yourself(or usecalloc
instead; seeAllocating Cleared Space).Normally you would convert the value to a pointer to the kind of objectthat you want to store in the block. Here we show an example of doingso, and of initializing the space with zeros using the library functionmemset
(seeCopying Strings and Arrays):
struct foo *ptr = malloc (sizeof *ptr);if (ptr == 0) abort ();memset (ptr, 0, sizeof (struct foo));
You can store the result ofmalloc
into any pointer variablewithout a cast, because ISO C automatically converts the typevoid *
to another type of pointer when necessary. However, a castis necessary if the type is needed but not specified by context.
Remember that when allocating space for a string, the argument tomalloc
must be one plus the length of the string. This isbecause a string is terminated with a null character that doesn’t countin the “length” of the string but does need space. For example:
char *ptr = malloc (length + 1);
SeeRepresentation of Strings, for more information about this.
Next:Freeing Memory Allocated withmalloc
, Previous:Basic Memory Allocation, Up:Unconstrained Allocation [Contents][Index]
malloc
¶If no more space is available,malloc
returns a null pointer.You should check the value ofevery call tomalloc
. It isuseful to write a subroutine that callsmalloc
and reports anerror if the value is a null pointer, returning only if the value isnonzero. This function is conventionally calledxmalloc
. Hereit is:
void *xmalloc (size_t size){ void *value = malloc (size); if (value == 0) fatal ("virtual memory exhausted"); return value;}
Here is a real example of usingmalloc
(by way ofxmalloc
).The functionsavestring
will copy a sequence of characters intoa newly allocated null-terminated string:
char *savestring (const char *ptr, size_t len){ char *value = xmalloc (len + 1); value[len] = '\0'; return memcpy (value, ptr, len);}
The block thatmalloc
gives you is guaranteed to be aligned sothat it can hold any type of data. On GNU systems, the address isalways a multiple of eight on 32-bit systems, and a multiple of 16 on64-bit systems. Only rarely is any higher boundary (such as a pageboundary) necessary; for those cases, usealigned_alloc
orposix_memalign
(seeAllocating Aligned Memory Blocks).
Note that the memory located after the end of the block is likely to bein use for something else; perhaps a block already allocated by anothercall tomalloc
. If you attempt to treat the block as longer thanyou asked for it to be, you are liable to destroy the data thatmalloc
uses to keep track of its blocks, or you may destroy thecontents of another block. If you have already allocated a block anddiscover you want it to be bigger, userealloc
(seeChanging the Size of a Block).
Portability Notes:
malloc (0)
returns a non-null pointer to a newly allocated size-zero block;other implementations may returnNULL
instead.POSIX and the ISO C standard allow both behaviors.malloc
call setserrno
,but ISO C does not require this and non-POSIX implementationsneed not seterrno
when failing.malloc
always fails whensize exceedsPTRDIFF_MAX
, to avoid problems with programs that subtractpointers or use signed indexes. Other implementations may succeed inthis case, leading to undefined behavior later.Next:Changing the Size of a Block, Previous:Examples ofmalloc
, Up:Unconstrained Allocation [Contents][Index]
malloc
¶When you no longer need a block that you got withmalloc
, use thefunctionfree
to make the block available to be allocated again.The prototype for this function is instdlib.h.
void
free(void *ptr)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Thefree
function deallocates the block of memory pointed atbyptr.
Freeing a block alters the contents of the block.Do not expect tofind any data (such as a pointer to the next block in a chain of blocks) inthe block after freeing it. Copy whatever you need out of the block beforefreeing it! Here is an example of the proper way to free all the blocks ina chain, and the strings that they point to:
struct chain { struct chain *next; char *name; }voidfree_chain (struct chain *chain){ while (chain != 0) { struct chain *next = chain->next; free (chain->name); free (chain); chain = next; }}
Occasionally,free
can actually return memory to the operatingsystem and make the process smaller. Usually, all it can do is allow alater call tomalloc
to reuse the space. In the meantime, thespace remains in your program as part of a free-list used internally bymalloc
.
Thefree
function preserves the value oferrno
, so thatcleanup code need not worry about saving and restoringerrno
around a call tofree
. Although neither ISO C norPOSIX.1-2017 requiresfree
to preserveerrno
, a futureversion of POSIX is planned to require it.
There is no point in freeing blocks at the end of a program, because allof the program’s space is given back to the system when the processterminates.
Next:Allocating Cleared Space, Previous:Freeing Memory Allocated withmalloc
, Up:Unconstrained Allocation [Contents][Index]
Often you do not know for certain how big a block you will ultimately needat the time you must begin to use the block. For example, the block mightbe a buffer that you use to hold a line being read from a file; no matterhow long you make the buffer initially, you may encounter a line that islonger.
You can make the block longer by callingrealloc
orreallocarray
. These functions are declared instdlib.h.
void *
realloc(void *ptr, size_tnewsize)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Therealloc
function changes the size of the block whose address isptr to benewsize.
Since the space after the end of the block may be in use,realloc
may find it necessary to copy the block to a new address where more freespace is available. The value ofrealloc
is the new address of theblock. If the block needs to be moved,realloc
copies the oldcontents.
If you pass a null pointer forptr,realloc
behaves justlike ‘malloc (newsize)’.Otherwise, ifnewsize is zerorealloc
frees the block and returnsNULL
.Otherwise, ifrealloc
cannot reallocate the requested sizeit returnsNULL
and setserrno
; the original blockis left undisturbed.
void *
reallocarray(void *ptr, size_tnmemb, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Thereallocarray
function changes the size of the block whose addressisptr to be long enough to contain a vector ofnmemb elements,each of sizesize. It is equivalent to ‘realloc (ptr,nmemb *size)’, except thatreallocarray
fails safely ifthe multiplication overflows, by settingerrno
toENOMEM
,returning a null pointer, and leaving the original block unchanged.
reallocarray
should be used instead ofrealloc
when the new sizeof the allocated block is the result of a multiplication that might overflow.
This function was originally derived from OpenBSD 5.6, but was added inPOSIX.1-2024.
Likemalloc
,realloc
andreallocarray
may return a nullpointer if no memory space is available to make the block bigger. When thishappens, the original block is untouched; it has not been modified orrelocated.
In most cases it makes no difference what happens to the original blockwhenrealloc
fails, because the application program cannot continuewhen it is out of memory, and the only thing to do is to give a fatal errormessage. Often it is convenient to write and use subroutines,conventionally calledxrealloc
andxreallocarray
,that take care of the error messageasxmalloc
does formalloc
:
void *xreallocarray (void *ptr, size_t nmemb, size_t size){ void *value = reallocarray (ptr, nmemb, size); if (value == 0) fatal ("Virtual memory exhausted"); return value;}void *xrealloc (void *ptr, size_t size){ return xreallocarray (ptr, 1, size);}
You can also userealloc
orreallocarray
to make a blocksmaller. The reason you would do this is to avoid tying up a lot of memoryspace when only a little is needed.In several allocation implementations, making a block smaller sometimesnecessitates copying it, so it can fail if no other space is available.
Portability Notes:
realloc (ptr, 0)
might free the block and return a non-null pointer to a size-zeroobject, or it might fail and returnNULL
without freeing the block.The ISO C17 standard allows these variations.PTRDIFF_MAX
in size, to avoid problems with programsthat subtract pointers or use signed indexes. Other implementations maysucceed, leading to undefined behavior later.realloc
andreallocarray
are guaranteed to change nothing and return the sameaddress that you gave. However, POSIX and ISO C allow the functionsto relocate the object or fail in this situation.Next:Allocating Aligned Memory Blocks, Previous:Changing the Size of a Block, Up:Unconstrained Allocation [Contents][Index]
The functioncalloc
allocates memory and clears it to zero. Itis declared instdlib.h.
void *
calloc(size_tcount, size_teltsize)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
This function allocates a block long enough to contain a vector ofcount elements, each of sizeeltsize. Its contents arecleared to zero beforecalloc
returns.
You could definecalloc
as follows:
void *calloc (size_t count, size_t eltsize){ void *value = reallocarray (0, count, eltsize); if (value != 0) memset (value, 0, count * eltsize); return value;}
But in general, it is not guaranteed thatcalloc
callsreallocarray
andmemset
internally. For example, if thecalloc
implementation knows for other reasons that the newmemory block is zero, it need not zero out the block again withmemset
. Also, if an application provides its ownreallocarray
outside the C library,calloc
might not usethat redefinition. SeeReplacingmalloc
.
Next:Malloc Tunable Parameters, Previous:Allocating Cleared Space, Up:Unconstrained Allocation [Contents][Index]
The address of a block returned bymalloc
orrealloc
inGNU systems is always a multiple of eight (or sixteen on 64-bitsystems). If you need a block whose address is a multiple of a higherpower of two than that, usealigned_alloc
orposix_memalign
.aligned_alloc
andposix_memalign
are declared instdlib.h.
void *
aligned_alloc(size_talignment, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Thealigned_alloc
function allocates a block ofsize bytes whoseaddress is a multiple ofalignment. Thealignment must be apower of two.
Thealigned_alloc
function returns a null pointer on error and setserrno
to one of the following values:
ENOMEM
There was insufficient memory available to satisfy the request.
EINVAL
alignment is not a power of two.
This function was introduced in ISO C11 and hence may have betterportability to modern non-POSIX systems thanposix_memalign
.
void *
memalign(size_tboundary, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Thememalign
function allocates a block ofsize bytes whoseaddress is a multiple ofboundary. Theboundary must be apower of two! The functionmemalign
works by allocating asomewhat larger block, and then returning an address within the blockthat is on the specified boundary.
Thememalign
function returns a null pointer on error and setserrno
to one of the following values:
ENOMEM
There was insufficient memory available to satisfy the request.
EINVAL
boundary is not a power of two.
Thememalign
function is obsolete andaligned_alloc
orposix_memalign
should be used instead.
int
posix_memalign(void **memptr, size_talignment, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Theposix_memalign
function is similar to thememalign
function in that it returns a buffer ofsize bytes aligned to amultiple ofalignment. But it adds one requirement to theparameteralignment: the value must be a power of two multiple ofsizeof (void *)
.
If the function succeeds in allocation memory a pointer to the allocatedmemory is returned in*memptr
and the return value is zero.Otherwise the function returns an error value indicating the problem.The possible error values returned are:
ENOMEM
There was insufficient memory available to satisfy the request.
EINVAL
alignment is not a power of two multiple ofsizeof (void *)
.
This function was introduced in POSIX 1003.1d. Although this function issuperseded byaligned_alloc
, it is more portable to older POSIXsystems that do not support ISO C11.
void *
valloc(size_tsize)
¶Preliminary:| MT-Unsafe init| AS-Unsafe init lock| AC-Unsafe init lock fd mem| SeePOSIX Safety Concepts.
Usingvalloc
is like usingmemalign
and passing the page sizeas the value of the first argument. It is implemented like this:
void *valloc (size_t size){ return memalign (getpagesize (), size);}
How to get information about the memory subsystem? for more information about the memorysubsystem.
Thevalloc
function is obsolete andaligned_alloc
orposix_memalign
should be used instead.
Next:Heap Consistency Checking, Previous:Allocating Aligned Memory Blocks, Up:Unconstrained Allocation [Contents][Index]
You can adjust some parameters for dynamic memory allocation with themallopt
function. This function is the general SVID/XPGinterface, defined inmalloc.h.
int
mallopt(intparam, intvalue)
¶Preliminary:| MT-Unsafe init const:mallopt| AS-Unsafe init lock| AC-Unsafe init lock| SeePOSIX Safety Concepts.
When callingmallopt
, theparam argument specifies theparameter to be set, andvalue the new value to be set. Possiblechoices forparam, as defined inmalloc.h, are:
M_MMAP_MAX
¶The maximum number of chunks to allocate withmmap
. Setting thisto zero disables all use ofmmap
.
The default value of this parameter is65536
.
This parameter can also be set for the process at startup by setting theenvironment variableMALLOC_MMAP_MAX_
to the desired value.
M_MMAP_THRESHOLD
¶All chunks larger than this value are allocated outside the normalheap, using themmap
system call. This way it is guaranteedthat the memory for these chunks can be returned to the system onfree
. Note that requests smaller than this threshold might stillbe allocated viammap
.
If this parameter is not set, the default value is set as 128 KiB and thethreshold is adjusted dynamically to suit the allocation patterns of theprogram. If the parameter is set, the dynamic adjustment is disabled and thevalue is set statically to the input value.
This parameter can also be set for the process at startup by setting theenvironment variableMALLOC_MMAP_THRESHOLD_
to the desired value.
M_PERTURB
¶If non-zero, memory blocks are filled with values depending on somelow order bits of this parameter when they are allocated (except whenallocated bycalloc
) and freed. This can be used to debug theuse of uninitialized or freed heap memory. Note that this option does notguarantee that the freed block will have any specific values. It onlyguarantees that the content the block had before it was freed will beoverwritten.
The default value of this parameter is0
.
This parameter can also be set for the process at startup by setting theenvironment variableMALLOC_PERTURB_
to the desired value.
M_TOP_PAD
¶This parameter determines the amount of extra memory to obtain from the systemwhen an arena needs to be extended. It also specifies the number of bytes toretain when shrinking an arena. This provides the necessary hysteresis in heapsize such that excessive amounts of system calls can be avoided.
The default value of this parameter is0
.
This parameter can also be set for the process at startup by setting theenvironment variableMALLOC_TOP_PAD_
to the desired value.
M_TRIM_THRESHOLD
¶This is the minimum size (in bytes) of the top-most, releasable chunkthat will trigger a system call in order to return memory to the system.
If this parameter is not set, the default value is set as 128 KiB and thethreshold is adjusted dynamically to suit the allocation patterns of theprogram. If the parameter is set, the dynamic adjustment is disabled and thevalue is set statically to the provided input.
This parameter can also be set for the process at startup by setting theenvironment variableMALLOC_TRIM_THRESHOLD_
to the desired value.
M_ARENA_TEST
¶This parameter specifies the number of arenas that can be created before thetest on the limit to the number of arenas is conducted. The value is ignored ifM_ARENA_MAX
is set.
The default value of this parameter is 2 on 32-bit systems and 8 on 64-bitsystems.
This parameter can also be set for the process at startup by setting theenvironment variableMALLOC_ARENA_TEST
to the desired value.
M_ARENA_MAX
¶This parameter sets the number of arenas to use regardless of the number ofcores in the system.
The default value of this tunable is0
, meaning that the limit on thenumber of arenas is determined by the number of CPU cores online. For 32-bitsystems the limit is twice the number of cores online and on 64-bit systems, itis eight times the number of cores online. Note that the default value is notderived from the default value of M_ARENA_TEST and is computed independently.
This parameter can also be set for the process at startup by setting theenvironment variableMALLOC_ARENA_MAX
to the desired value.
Next:Statistics for Memory Allocation withmalloc
, Previous:Malloc Tunable Parameters, Up:Unconstrained Allocation [Contents][Index]
You can askmalloc
to check the consistency of dynamic memory byusing themcheck
function and preloading the malloc debug librarylibc_malloc_debug using theLD_PRELOAD environment variable.This function is a GNU extension, declared inmcheck.h.
int
mcheck(void (*abortfn) (enum mcheck_statusstatus))
¶Preliminary:| MT-Unsafe race:mcheck const:malloc_hooks| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Callingmcheck
tellsmalloc
to perform occasionalconsistency checks. These will catch things such as writingpast the end of a block that was allocated withmalloc
.
Theabortfn argument is the function to call when an inconsistencyis found. If you supply a null pointer, thenmcheck
uses adefault function which prints a message and callsabort
(seeAborting a Program). The function you supply is called withone argument, which says what sort of inconsistency was detected; itstype is described below.
It is too late to begin allocation checking once you have allocatedanything withmalloc
. Somcheck
does nothing in thatcase. The function returns-1
if you call it too late, and0
otherwise (when it is successful).
The easiest way to arrange to callmcheck
early enough is to usethe option ‘-lmcheck’ when you link your program; then you don’tneed to modify your program source at all. Alternatively you might usea debugger to insert a call tomcheck
whenever the program isstarted, for example these gdb commands will automatically callmcheck
whenever the program starts:
(gdb) break mainBreakpoint 1, main (argc=2, argv=0xbffff964) at whatever.c:10(gdb) command 1Type commands for when breakpoint 1 is hit, one per line.End with a line saying just "end".>call mcheck(0)>continue>end(gdb) ...
This will however only work if no initialization function of any objectinvolved calls any of themalloc
functions sincemcheck
must be called before the first such function.
enum mcheck_status
mprobe(void *pointer)
¶Preliminary:| MT-Unsafe race:mcheck const:malloc_hooks| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Themprobe
function lets you explicitly check for inconsistenciesin a particular allocated block. You must have already calledmcheck
at the beginning of the program, to do its occasionalchecks; callingmprobe
requests an additional consistency checkto be done at the time of the call.
The argumentpointer must be a pointer returned bymalloc
orrealloc
.mprobe
returns a value that says whatinconsistency, if any, was found. The values are described below.
This enumerated type describes what kind of inconsistency was detectedin an allocated block, if any. Here are the possible values:
MCHECK_DISABLED
mcheck
was not called before the first allocation.No consistency checking can be done.
MCHECK_OK
No inconsistency detected.
MCHECK_HEAD
The data immediately before the block was modified.This commonly happens when an array index or pointeris decremented too far.
MCHECK_TAIL
The data immediately after the block was modified.This commonly happens when an array index or pointeris incremented too far.
MCHECK_FREE
The block was already freed.
Another possibility to check for and guard against bugs in the use ofmalloc
,realloc
andfree
is to set the environmentvariableMALLOC_CHECK_
. WhenMALLOC_CHECK_
is set to anon-zero value less than 4, a special (less efficient) implementation isused which is designed to be tolerant against simple errors, such asdouble calls offree
with the same argument, or overruns of asingle byte (off-by-one bugs). Not all such errors can be protectedagainst, however, and memory leaks can result. Like in the case ofmcheck
, one would need to preload thelibc_malloc_debuglibrary to enableMALLOC_CHECK_
functionality. Without thispreloaded library, settingMALLOC_CHECK_
will have no effect.
Any detected heap corruption results in immediate termination of theprocess.
There is one problem withMALLOC_CHECK_
: in SUID or SGID binariesit could possibly be exploited since diverging from the normal programsbehavior it now writes something to the standard error descriptor.Therefore the use ofMALLOC_CHECK_
is disabled by default forSUID and SGID binaries.
So, what’s the difference between usingMALLOC_CHECK_
and linkingwith ‘-lmcheck’?MALLOC_CHECK_
is orthogonal with respect to‘-lmcheck’. ‘-lmcheck’ has been added for backwardcompatibility. BothMALLOC_CHECK_
and ‘-lmcheck’ shoulduncover the same bugs - but usingMALLOC_CHECK_
you don’t need torecompile your application.
Next:Summary ofmalloc
-Related Functions, Previous:Heap Consistency Checking, Up:Unconstrained Allocation [Contents][Index]
malloc
¶You can get information about dynamic memory allocation by calling themallinfo2
function. This function and its associated data typeare declared inmalloc.h; they are an extension of the standardSVID/XPG version.
This structure type is used to return information about the dynamicmemory allocator. It contains the following members:
size_t arena
This is the total size of memory allocated withsbrk
bymalloc
, in bytes.
size_t ordblks
This is the number of chunks not in use. (The memory allocatorinternally gets chunks of memory from the operating system, and thencarves them up to satisfy individualmalloc
requests;seeThe GNU Allocator.)
size_t smblks
This field is unused.
size_t hblks
This is the total number of chunks allocated withmmap
.
size_t hblkhd
This is the total size of memory allocated withmmap
, in bytes.
size_t usmblks
This field is unused and always 0.
size_t fsmblks
This field is unused.
size_t uordblks
This is the total size of memory occupied by chunks handed out bymalloc
.
size_t fordblks
This is the total size of memory occupied by free (not in use) chunks.
size_t keepcost
This is the size of the top-most releasable chunk that normallyborders the end of the heap (i.e., the high end of the virtual addressspace’s data segment).
struct mallinfo2
mallinfo2(void)
¶Preliminary:| MT-Unsafe init const:mallopt| AS-Unsafe init lock| AC-Unsafe init lock| SeePOSIX Safety Concepts.
This function returns information about the current dynamic memory usagein a structure of typestruct mallinfo2
.
malloc
-Related Functions ¶Here is a summary of the functions that work withmalloc
:
void *malloc (size_tsize)
Allocate a block ofsize bytes. SeeBasic Memory Allocation.
void free (void *addr)
Free a block previously allocated bymalloc
. SeeFreeing Memory Allocated withmalloc
.
void *realloc (void *addr, size_tsize)
Make a block previously allocated bymalloc
larger or smaller,possibly by copying it to a new location. SeeChanging the Size of a Block.
void *reallocarray (void *ptr, size_tnmemb, size_tsize)
Change the size of a block previously allocated bymalloc
tonmemb *size
bytes as withrealloc
. SeeChanging the Size of a Block.
void *calloc (size_tcount, size_teltsize)
Allocate a block ofcount *eltsize bytes usingmalloc
, and set its contents to zero. SeeAllocating Cleared Space.
void *valloc (size_tsize)
Allocate a block ofsize bytes, starting on a page boundary.SeeAllocating Aligned Memory Blocks.
void *aligned_alloc (size_talignment, size_tsize)
Allocate a block ofsize bytes, starting on an address that is amultiple ofalignment. SeeAllocating Aligned Memory Blocks.
int posix_memalign (void **memptr, size_talignment, size_tsize)
Allocate a block ofsize bytes, starting on an address that is amultiple ofalignment. SeeAllocating Aligned Memory Blocks.
void *memalign (size_tboundary, size_tsize)
Allocate a block ofsize bytes, starting on an address that is amultiple ofboundary. SeeAllocating Aligned Memory Blocks.
int mallopt (intparam, intvalue)
Adjust a tunable parameter. SeeMalloc Tunable Parameters.
int mcheck (void (*abortfn) (void))
Tellmalloc
to perform occasional consistency checks ondynamically allocated memory, and to callabortfn when aninconsistency is found. SeeHeap Consistency Checking.
struct mallinfo2 mallinfo2 (void)
Return information about the current dynamic memory usage.SeeStatistics for Memory Allocation withmalloc
.
Next:Replacingmalloc
, Previous:Unconstrained Allocation, Up:Allocating Storage For Program Data [Contents][Index]
A complicated task when programming with languages which do not usegarbage collected dynamic memory allocation is to find memory leaks.Long running programs must ensure that dynamically allocated objects arefreed at the end of their lifetime. If this does not happen the systemruns out of memory, sooner or later.
Themalloc
implementation in the GNU C Library provides somesimple means to detect such leaks and obtain some information to findthe location. To do this the application must be started in a specialmode which is enabled by an environment variable. There are no speedpenalties for the program if the debugging mode is not enabled.
Next:Example program excerpts, Up:Allocation Debugging [Contents][Index]
void
mtrace(void)
¶Preliminary:| MT-Unsafe env race:mtrace init| AS-Unsafe init heap corrupt lock| AC-Unsafe init corrupt lock fd mem| SeePOSIX Safety Concepts.
Themtrace
function provides a way to trace memory allocationevents in the program that calls it. It is disabled by default in thelibrary and can be enabled by preloading the debugging librarylibc_malloc_debug using theLD_PRELOAD
environmentvariable.
When themtrace
function is called it looks for an environmentvariable namedMALLOC_TRACE
. This variable is supposed tocontain a valid file name. The user must have write access. If thefile already exists it is truncated. If the environment variable is notset or it does not name a valid file which can be opened for writingnothing is done. The behavior ofmalloc
etc. is not changed.For obvious reasons this also happens if the application is installedwith the SUID or SGID bit set.
If the named file is successfully opened,mtrace
installs specialhandlers for the functionsmalloc
,realloc
, andfree
. From then on, all uses of these functions are traced andprotocolled into the file. There is now of course a speed penalty for allcalls to the traced functions so tracing should not be enabled during normaluse.
This function is a GNU extension and generally not available on othersystems. The prototype can be found inmcheck.h.
void
muntrace(void)
¶Preliminary:| MT-Unsafe race:mtrace locale| AS-Unsafe corrupt heap| AC-Unsafe corrupt mem lock fd| SeePOSIX Safety Concepts.
Themuntrace
function can be called aftermtrace
was usedto enable tracing themalloc
calls. If no (successful) call ofmtrace
was mademuntrace
does nothing.
Otherwise it deinstalls the handlers formalloc
,realloc
,andfree
and then closes the protocol file. No calls areprotocolled anymore and the program runs again at full speed.
This function is a GNU extension and generally not available on othersystems. The prototype can be found inmcheck.h.
Next:Some more or less clever ideas, Previous:How to install the tracing functionality, Up:Allocation Debugging [Contents][Index]
Even though the tracing functionality does not influence the runtimebehavior of the program it is not a good idea to callmtrace
inall programs. Just imagine that you debug a program usingmtrace
and all other programs used in the debugging session also trace theirmalloc
calls. The output file would be the same for all programsand thus is unusable. Therefore one should callmtrace
only ifcompiled for debugging. A program could therefore start like this:
#include <mcheck.h>intmain (int argc, char *argv[]){#ifdef DEBUGGING mtrace ();#endif ...}
This is all that is needed if you want to trace the calls during thewhole runtime of the program. Alternatively you can stop the tracing atany time with a call tomuntrace
. It is even possible to restartthe tracing again with a new call tomtrace
. But this can causeunreliable results since there may be calls of the functions which arenot called. Please note that not only the application uses the tracedfunctions, also libraries (including the C library itself) use thesefunctions.
This last point is also why it is not a good idea to callmuntrace
before the program terminates. The libraries are informed about thetermination of the program only after the program returns frommain
or callsexit
and so cannot free the memory they usebefore this time.
So the best thing one can do is to callmtrace
as the very firstfunction in the program and never callmuntrace
. So the programtraces almost all uses of themalloc
functions (except thosecalls which are executed by constructors of the program or usedlibraries).
Next:Interpreting the traces, Previous:Example program excerpts, Up:Allocation Debugging [Contents][Index]
You know the situation. The program is prepared for debugging and inall debugging sessions it runs well. But once it is started withoutdebugging the error shows up. A typical example is a memory leak thatbecomes visible only when we turn off the debugging. If you foreseesuch situations you can still win. Simply use something equivalent tothe following little program:
#include <mcheck.h>#include <signal.h>static voidenable (int sig){ mtrace (); signal (SIGUSR1, enable);}static voiddisable (int sig){ muntrace (); signal (SIGUSR2, disable);}intmain (int argc, char *argv[]){ ... signal (SIGUSR1, enable); signal (SIGUSR2, disable); ...}
I.e., the user can start the memory debugger any time s/he wants if theprogram was started withMALLOC_TRACE
set in the environment.The output will of course not show the allocations which happened beforethe first signal but if there is a memory leak this will show upnevertheless.
Previous:Some more or less clever ideas, Up:Allocation Debugging [Contents][Index]
If you take a look at the output it will look similar to this:
= Start [0x8048209] - 0x8064cc8 [0x8048209] - 0x8064ce0 [0x8048209] - 0x8064cf8 [0x80481eb] + 0x8064c48 0x14 [0x80481eb] + 0x8064c60 0x14 [0x80481eb] + 0x8064c78 0x14 [0x80481eb] + 0x8064c90 0x14= End
What this all means is not really important since the trace file is notmeant to be read by a human. Therefore no attention is given toreadability. Instead there is a program which comes with the GNU C Librarywhich interprets the traces and outputs a summary in anuser-friendly way. The program is calledmtrace
(it is in fact aPerl script) and it takes one or two arguments. In any case the name ofthe file with the trace output must be specified. If an optionalargument precedes the name of the trace file this must be the name ofthe program which generated the trace.
drepper$ mtrace tst-mtrace logNo memory leaks.
In this case the programtst-mtrace
was run and it produced atrace filelog. The message printed bymtrace
shows thereare no problems with the code, all allocated memory was freedafterwards.
If we callmtrace
on the example trace given above we would get adifferent output:
drepper$ mtrace errlog- 0x08064cc8 Free 2 was never alloc'd 0x8048209- 0x08064ce0 Free 3 was never alloc'd 0x8048209- 0x08064cf8 Free 4 was never alloc'd 0x8048209Memory not freed:----------------- Address Size Caller0x08064c48 0x14 at 0x80481eb0x08064c60 0x14 at 0x80481eb0x08064c78 0x14 at 0x80481eb0x08064c90 0x14 at 0x80481eb
We have calledmtrace
with only one argument and so the scripthas no chance to find out what is meant with the addresses given in thetrace. We can do better:
drepper$ mtrace tst errlog- 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst.c:39- 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst.c:39- 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst.c:39Memory not freed:----------------- Address Size Caller0x08064c48 0x14 at /home/drepper/tst.c:330x08064c60 0x14 at /home/drepper/tst.c:330x08064c78 0x14 at /home/drepper/tst.c:330x08064c90 0x14 at /home/drepper/tst.c:33
Suddenly the output makes much more sense and the user can seeimmediately where the function calls causing the trouble can be found.
Interpreting this output is not complicated. There are at most twodifferent situations being detected. First,free
was called forpointers which were never returned by one of the allocation functions.This is usually a very bad problem and what this looks like is shown inthe first three lines of the output. Situations like this are quiterare and if they appear they show up very drastically: the programnormally crashes.
The other situation which is much harder to detect are memory leaks. Asyou can see in the output themtrace
function collects all thisinformation and so can say that the program calls an allocation functionfrom line 33 in the source file/home/drepper/tst-mtrace.c fourtimes without freeing this memory before the program terminates.Whether this is a real problem remains to be investigated.
Next:Obstacks, Previous:Allocation Debugging, Up:Allocating Storage For Program Data [Contents][Index]
malloc
¶The GNU C Library supports replacing the built-inmalloc
implementationwith a different allocator with the same interface. For dynamicallylinked programs, this happens through ELF symbol interposition, eitherusing shared object dependencies orLD_PRELOAD
. For staticlinking, themalloc
replacement library must be linked in beforelinking againstlibc.a
(explicitly or implicitly).
Care must be taken not to use functionality from the GNU C Library that usesmalloc
internally. For example, thefopen
,opendir
,dlopen
, andpthread_setspecific
functionscurrently use themalloc
subsystem internally. If thereplacementmalloc
or its dependencies use thread-local storage(TLS), it must use the initial-exec TLS model, and not one of thedynamic TLS variants.
Note: Failure to provide a complete set of replacementfunctions (that is, all the functions used by the application,the GNU C Library, and other linked-in libraries) can lead to static linkingfailures, and, at run time, to heap corruption and application crashes.Replacement functions should implement the behavior documented fortheir counterparts in the GNU C Library; for example, the replacementfree
should also preserveerrno
.
The minimum set of functions which has to be provided by a custommalloc
is given in the table below.
malloc
free
calloc
realloc
Thesemalloc
-related functions are required for the GNU C Library towork.1
Themalloc
implementation in the GNU C Library provides additionalfunctionality not used by the library itself, but which is often used byother system libraries and applications. A general-purpose replacementmalloc
implementation should provide definitions of thesefunctions, too. Their names are listed in the following table.
aligned_alloc
malloc_usable_size
memalign
posix_memalign
pvalloc
valloc
In addition, very old applications may use the obsoletecfree
function.
Furthermalloc
-related functions such asmallopt
ormallinfo2
will not have any effect or return incorrect statisticswhen a replacementmalloc
is in use. However, failure to replacethese functions typically does not result in crashes or other incorrectapplication behavior, but may result in static linking failures.
There are other functions (reallocarray
,strdup
, etc.) inthe GNU C Library that are not listed above but return newly allocated memory tocallers. Replacement of these functions is not supported and may produceincorrect results. The GNU C Library implementations of these functions callthe replacement allocator functions whenever available, so they will workcorrectly withmalloc
replacement.
Next:Automatic Storage with Variable Size, Previous:Replacingmalloc
, Up:Allocating Storage For Program Data [Contents][Index]
Anobstack is a pool of memory containing a stack of objects. Youcan create any number of separate obstacks, and then allocate objects inspecified obstacks. Within each obstack, the last object allocated mustalways be the first one freed, but distinct obstacks are independent ofeach other.
Aside from this one constraint of order of freeing, obstacks are totallygeneral: an obstack can contain any number of objects of any size. Theyare implemented with macros, so allocation is usually very fast as long asthe objects are usually small. And the only space overhead per object isthe padding needed to start each object on a suitable boundary.
Next:Preparing for Using Obstacks, Up:Obstacks [Contents][Index]
The utilities for manipulating obstacks are declared in the headerfileobstack.h.
An obstack is represented by a data structure of typestructobstack
. This structure has a small fixed size; it records the statusof the obstack and how to find the space in which objects are allocated.It does not contain any of the objects themselves. You should not tryto access the contents of the structure directly; use only the functionsdescribed in this chapter.
You can declare variables of typestruct obstack
and use them asobstacks, or you can allocate obstacks dynamically like any other kindof object. Dynamic allocation of obstacks allows your program to have avariable number of different stacks. (You can even allocate anobstack structure in another obstack, but this is rarely useful.)
All the functions that work with obstacks require you to specify whichobstack to use. You do this with a pointer of typestruct obstack*
. In the following, we often say “an obstack” when strictlyspeaking the object at hand is such a pointer.
The objects in the obstack are packed into large blocks calledchunks. Thestruct obstack
structure points to a chain ofthe chunks currently in use.
The obstack library obtains a new chunk whenever you allocate an objectthat won’t fit in the previous chunk. Since the obstack library manageschunks automatically, you don’t need to pay much attention to them, butyou do need to supply a function which the obstack library should use toget a chunk. Usually you supply a function which usesmalloc
directly or indirectly. You must also supply a function to free a chunk.These matters are described in the following section.
Next:Allocation in an Obstack, Previous:Creating Obstacks, Up:Obstacks [Contents][Index]
Each source file in which you plan to use the obstack functionsmust include the header fileobstack.h, like this:
#include <obstack.h>
Also, if the source file uses the macroobstack_init
, it mustdeclare or define two functions or macros that will be called by theobstack library. One,obstack_chunk_alloc
, is used to allocatethe chunks of memory into which objects are packed. The other,obstack_chunk_free
, is used to return chunks when the objects inthem are freed. These macros should appear before any use of obstacksin the source file.
Usually these are defined to usemalloc
via the intermediaryxmalloc
(seeUnconstrained Allocation). This is done withthe following pair of macro definitions:
#define obstack_chunk_alloc xmalloc#define obstack_chunk_free free
Though the memory you get using obstacks really comes frommalloc
,using obstacks is faster becausemalloc
is called less often, forlarger blocks of memory. SeeObstack Chunks, for full details.
At run time, before the program can use astruct obstack
objectas an obstack, it must initialize the obstack by callingobstack_init
.
int
obstack_init(struct obstack *obstack-ptr)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Safe mem| SeePOSIX Safety Concepts.
Initialize obstackobstack-ptr for allocation of objects. Thisfunction calls the obstack’sobstack_chunk_alloc
function. Ifallocation of memory fails, the function pointed to byobstack_alloc_failed_handler
is called. Theobstack_init
function always returns 1 (Compatibility notice: Former versions ofobstack returned 0 if allocation failed).
Here are two examples of how to allocate the space for an obstack andinitialize it. First, an obstack that is a static variable:
static struct obstack myobstack;...obstack_init (&myobstack);
Second, an obstack that is itself dynamically allocated:
struct obstack *myobstack_ptr = (struct obstack *) xmalloc (sizeof (struct obstack));obstack_init (myobstack_ptr);
The value of this variable is a pointer to a function thatobstack
uses whenobstack_chunk_alloc
fails to allocatememory. The default action is to print a message and abort.You should supply a function that either callsexit
(seeProgram Termination) orlongjmp
(seeNon-Local Exits) and doesn’t return.
void my_obstack_alloc_failed (void)...obstack_alloc_failed_handler = &my_obstack_alloc_failed;
Next:Freeing Objects in an Obstack, Previous:Preparing for Using Obstacks, Up:Obstacks [Contents][Index]
The most direct way to allocate an object in an obstack is withobstack_alloc
, which is invoked almost likemalloc
.
void *
obstack_alloc(struct obstack *obstack-ptr, intsize)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
This allocates an uninitialized block ofsize bytes in an obstackand returns its address. Hereobstack-ptr specifies which obstackto allocate the block in; it is the address of thestruct obstack
object which represents the obstack. Each obstack function or macrorequires you to specify anobstack-ptr as the first argument.
This function calls the obstack’sobstack_chunk_alloc
function ifit needs to allocate a new chunk of memory; it callsobstack_alloc_failed_handler
if allocation of memory byobstack_chunk_alloc
failed.
For example, here is a function that allocates a copy of a stringstrin a specific obstack, which is in the variablestring_obstack
:
struct obstack string_obstack;char *copystring (char *string){ size_t len = strlen (string) + 1; char *s = (char *) obstack_alloc (&string_obstack, len); memcpy (s, string, len); return s;}
To allocate a block with specified contents, use the functionobstack_copy
, declared like this:
void *
obstack_copy(struct obstack *obstack-ptr, void *address, intsize)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
This allocates a block and initializes it by copyingsizebytes of data starting ataddress. It callsobstack_alloc_failed_handler
if allocation of memory byobstack_chunk_alloc
failed.
void *
obstack_copy0(struct obstack *obstack-ptr, void *address, intsize)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Likeobstack_copy
, but appends an extra byte containing a nullcharacter. This extra byte is not counted in the argumentsize.
Theobstack_copy0
function is convenient for copying a sequenceof characters into an obstack as a null-terminated string. Here is anexample of its use:
char *obstack_savestring (char *addr, int size){ return obstack_copy0 (&myobstack, addr, size);}
Contrast this with the previous example ofsavestring
usingmalloc
(seeBasic Memory Allocation).
Next:Obstack Functions and Macros, Previous:Allocation in an Obstack, Up:Obstacks [Contents][Index]
To free an object allocated in an obstack, use the functionobstack_free
. Since the obstack is a stack of objects, freeingone object automatically frees all other objects allocated more recentlyin the same obstack.
void
obstack_free(struct obstack *obstack-ptr, void *object)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Ifobject is a null pointer, everything allocated in the obstackis freed. Otherwise,object must be the address of an objectallocated in the obstack. Thenobject is freed, along witheverything allocated inobstack-ptr sinceobject.
Note that ifobject is a null pointer, the result is anuninitialized obstack. To free all memory in an obstack but leave itvalid for further allocation, callobstack_free
with the addressof the first object allocated on the obstack:
obstack_free (obstack_ptr, first_object_allocated_ptr);
Recall that the objects in an obstack are grouped into chunks. When allthe objects in a chunk become free, the obstack library automaticallyfrees the chunk (seePreparing for Using Obstacks). Then otherobstacks, or non-obstack allocation, can reuse the space of the chunk.
Next:Growing Objects, Previous:Freeing Objects in an Obstack, Up:Obstacks [Contents][Index]
The interfaces for using obstacks may be defined either as functions oras macros, depending on the compiler. The obstack facility works withall C compilers, including both ISO C and traditional C, but there areprecautions you must take if you plan to use compilers other than GNU C.
If you are using an old-fashioned non-ISO C compiler, all the obstack“functions” are actually defined only as macros. You can call thesemacros like functions, but you cannot use them in any other way (forexample, you cannot take their address).
Calling the macros requires a special precaution: namely, the firstoperand (the obstack pointer) may not contain any side effects, becauseit may be computed more than once. For example, if you write this:
obstack_alloc (get_obstack (), 4);
you will find thatget_obstack
may be called several times.If you use*obstack_list_ptr++
as the obstack pointer argument,you will get very strange results since the incrementation may occurseveral times.
In ISO C, each function has both a macro definition and a functiondefinition. The function definition is used if you take the address of thefunction without calling it. An ordinary call uses the macro definition bydefault, but you can request the function definition instead by writing thefunction name in parentheses, as shown here:
char *x;void *(*funcp) ();/*Use the macro. */x = (char *) obstack_alloc (obptr, size);/*Call the function. */x = (char *) (obstack_alloc) (obptr, size);/*Take the address of the function. */funcp = obstack_alloc;
This is the same situation that exists in ISO C for the standard libraryfunctions. SeeMacro Definitions of Functions.
Warning: When you do use the macros, you must observe theprecaution of avoiding side effects in the first operand, even in ISO C.
If you use the GNU C compiler, this precaution is not necessary, becausevarious language extensions in GNU C permit defining the macros so as tocompute each argument only once.
Next:Extra Fast Growing Objects, Previous:Obstack Functions and Macros, Up:Obstacks [Contents][Index]
Because memory in obstack chunks is used sequentially, it is possible tobuild up an object step by step, adding one or more bytes at a time to theend of the object. With this technique, you do not need to know how muchdata you will put in the object until you come to the end of it. We callthis the technique ofgrowing objects. The special functionsfor adding data to the growing object are described in this section.
You don’t need to do anything special when you start to grow an object.Using one of the functions to add data to the object automaticallystarts it. However, it is necessary to say explicitly when the object isfinished. This is done with the functionobstack_finish
.
The actual address of the object thus built up is not known until theobject is finished. Until then, it always remains possible that you willadd so much data that the object must be copied into a new chunk.
While the obstack is in use for a growing object, you cannot use it forordinary allocation of another object. If you try to do so, the spacealready added to the growing object will become part of the other object.
void
obstack_blank(struct obstack *obstack-ptr, intsize)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
The most basic function for adding to a growing object isobstack_blank
, which adds space without initializing it.
void
obstack_grow(struct obstack *obstack-ptr, void *data, intsize)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
To add a block of initialized space, useobstack_grow
, which isthe growing-object analogue ofobstack_copy
. It addssizebytes of data to the growing object, copying the contents fromdata.
void
obstack_grow0(struct obstack *obstack-ptr, void *data, intsize)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
This is the growing-object analogue ofobstack_copy0
. It addssize bytes copied fromdata, followed by an additional nullcharacter.
void
obstack_1grow(struct obstack *obstack-ptr, charc)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
To add one character at a time, use the functionobstack_1grow
.It adds a single byte containingc to the growing object.
void
obstack_ptr_grow(struct obstack *obstack-ptr, void *data)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Adding the value of a pointer one can use the functionobstack_ptr_grow
. It addssizeof (void *)
bytescontaining the value ofdata.
void
obstack_int_grow(struct obstack *obstack-ptr, intdata)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
A single value of typeint
can be added by using theobstack_int_grow
function. It addssizeof (int)
bytes tothe growing object and initializes them with the value ofdata.
void *
obstack_finish(struct obstack *obstack-ptr)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
When you are finished growing the object, use the functionobstack_finish
to close it off and return its final address.
Once you have finished the object, the obstack is available for ordinaryallocation or for growing another object.
This function can return a null pointer under the same conditions asobstack_alloc
(seeAllocation in an Obstack).
When you build an object by growing it, you will probably need to knowafterward how long it became. You need not keep track of this as you growthe object, because you can find out the length from the obstack justbefore finishing the object with the functionobstack_object_size
,declared as follows:
int
obstack_object_size(struct obstack *obstack-ptr)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the current size of the growing object, in bytes.Remember to call this functionbefore finishing the object.After it is finished,obstack_object_size
will return zero.
If you have started growing an object and wish to cancel it, you shouldfinish it and then free it, like this:
obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
This has no effect if no object was growing.
You can useobstack_blank
with a negative size argument to makethe current object smaller. Just don’t try to shrink it beyond zerolength—there’s no telling what will happen if you do that.
Next:Status of an Obstack, Previous:Growing Objects, Up:Obstacks [Contents][Index]
The usual functions for growing objects incur overhead for checkingwhether there is room for the new growth in the current chunk. If youare frequently constructing objects in small steps of growth, thisoverhead can be significant.
You can reduce the overhead by using special “fast growth”functions that grow the object without checking. In order to have arobust program, you must do the checking yourself. If you do this checkingin the simplest way each time you are about to add data to the object, youhave not saved anything, because that is what the ordinary growthfunctions do. But if you can arrange to check less often, or checkmore efficiently, then you make the program faster.
The functionobstack_room
returns the amount of room availablein the current chunk. It is declared as follows:
int
obstack_room(struct obstack *obstack-ptr)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This returns the number of bytes that can be added safely to the currentgrowing object (or to an object about to be started) in obstackobstack-ptr using the fast growth functions.
While you know there is room, you can use these fast growth functionsfor adding data to a growing object:
void
obstack_1grow_fast(struct obstack *obstack-ptr, charc)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
The functionobstack_1grow_fast
adds one byte containing thecharacterc to the growing object in obstackobstack-ptr.
void
obstack_ptr_grow_fast(struct obstack *obstack-ptr, void *data)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functionobstack_ptr_grow_fast
addssizeof (void *)
bytes containing the value ofdata to the growing object inobstackobstack-ptr.
void
obstack_int_grow_fast(struct obstack *obstack-ptr, intdata)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functionobstack_int_grow_fast
addssizeof (int)
bytescontaining the value ofdata to the growing object in obstackobstack-ptr.
void
obstack_blank_fast(struct obstack *obstack-ptr, intsize)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functionobstack_blank_fast
addssize bytes to thegrowing object in obstackobstack-ptr without initializing them.
When you check for space usingobstack_room
and there is notenough room for what you want to add, the fast growth functionsare not safe. In this case, simply use the corresponding ordinarygrowth function instead. Very soon this will copy the object to anew chunk; then there will be lots of room available again.
So, each time you use an ordinary growth function, check afterward forsufficient space usingobstack_room
. Once the object is copiedto a new chunk, there will be plenty of space again, so the program willstart using the fast growth functions again.
Here is an example:
voidadd_string (struct obstack *obstack, const char *ptr, int len){ while (len > 0) { int room = obstack_room (obstack); if (room == 0) { /*Not enough room. Add one character slowly,which may copy to a new chunk and make room. */ obstack_1grow (obstack, *ptr++); len--; } else { if (room > len) room = len; /*Add fast as much as we have room for. */ len -= room; while (room-- > 0) obstack_1grow_fast (obstack, *ptr++); } }}
Next:Alignment of Data in Obstacks, Previous:Extra Fast Growing Objects, Up:Obstacks [Contents][Index]
Here are functions that provide information on the current status ofallocation in an obstack. You can use them to learn about an object whilestill growing it.
void *
obstack_base(struct obstack *obstack-ptr)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Safe | SeePOSIX Safety Concepts.
This function returns the tentative address of the beginning of thecurrently growing object inobstack-ptr. If you finish the objectimmediately, it will have that address. If you make it larger first, itmay outgrow the current chunk—then its address will change!
If no object is growing, this value says where the next object youallocate will start (once again assuming it fits in the currentchunk).
void *
obstack_next_free(struct obstack *obstack-ptr)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Safe | SeePOSIX Safety Concepts.
This function returns the address of the first free byte in the currentchunk of obstackobstack-ptr. This is the end of the currentlygrowing object. If no object is growing,obstack_next_free
returns the same value asobstack_base
.
int
obstack_object_size(struct obstack *obstack-ptr)
¶Preliminary:| MT-Safe race:obstack-ptr| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the size in bytes of the currently growing object.This is equivalent to
obstack_next_free (obstack-ptr) - obstack_base (obstack-ptr)
Next:Obstack Chunks, Previous:Status of an Obstack, Up:Obstacks [Contents][Index]
Each obstack has analignment boundary; each object allocated inthe obstack automatically starts on an address that is a multiple of thespecified boundary. By default, this boundary is aligned so thatthe object can hold any type of data.
To access an obstack’s alignment boundary, use the macroobstack_alignment_mask
, whose function prototype looks likethis:
int
obstack_alignment_mask(struct obstack *obstack-ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The value is a bit mask; a bit that is 1 indicates that the correspondingbit in the address of an object should be 0. The mask value should be oneless than a power of 2; the effect is that all object addresses aremultiples of that power of 2. The default value of the mask is a valuethat allows aligned objects to hold any type of data: for example, ifits value is 3, any type of data can be stored at locations whoseaddresses are multiples of 4. A mask value of 0 means an object can starton any multiple of 1 (that is, no alignment is required).
The expansion of the macroobstack_alignment_mask
is an lvalue,so you can alter the mask by assignment. For example, this statement:
obstack_alignment_mask (obstack_ptr) = 0;
has the effect of turning off alignment processing in the specified obstack.
Note that a change in alignment mask does not take effect untilafter the next time an object is allocated or finished in theobstack. If you are not growing an object, you can make the newalignment mask take effect immediately by callingobstack_finish
.This will finish a zero-length object and then do proper alignment forthe next object.
Next:Summary of Obstack Functions, Previous:Alignment of Data in Obstacks, Up:Obstacks [Contents][Index]
Obstacks work by allocating space for themselves in large chunks, andthen parceling out space in the chunks to satisfy your requests. Chunksare normally 4096 bytes long unless you specify a different chunk size.The chunk size includes 8 bytes of overhead that are not actually usedfor storing objects. Regardless of the specified size, longer chunkswill be allocated when necessary for long objects.
The obstack library allocates chunks by calling the functionobstack_chunk_alloc
, which you must define. When a chunk is nolonger needed because you have freed all the objects in it, the obstacklibrary frees the chunk by callingobstack_chunk_free
, which youmust also define.
These two must be defined (as macros) or declared (as functions) in eachsource file that usesobstack_init
(seeCreating Obstacks).Most often they are defined as macros like this:
#define obstack_chunk_alloc malloc#define obstack_chunk_free free
Note that these are simple macros (no arguments). Macro definitions witharguments will not work! It is necessary thatobstack_chunk_alloc
orobstack_chunk_free
, alone, expand into a function name if it isnot itself a function name.
If you allocate chunks withmalloc
, the chunk size should be apower of 2. The default chunk size, 4096, was chosen because it is longenough to satisfy many typical requests on the obstack yet short enoughnot to waste too much memory in the portion of the last chunk not yet used.
int
obstack_chunk_size(struct obstack *obstack-ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This returns the chunk size of the given obstack.
Since this macro expands to an lvalue, you can specify a new chunk size byassigning it a new value. Doing so does not affect the chunks alreadyallocated, but will change the size of chunks allocated for that particularobstack in the future. It is unlikely to be useful to make the chunk sizesmaller, but making it larger might improve efficiency if you areallocating many objects whose size is comparable to the chunk size. Hereis how to do so cleanly:
if (obstack_chunk_size (obstack_ptr) <new-chunk-size) obstack_chunk_size (obstack_ptr) =new-chunk-size;
Previous:Obstack Chunks, Up:Obstacks [Contents][Index]
Here is a summary of all the functions associated with obstacks. Eachtakes the address of an obstack (struct obstack *
) as its firstargument.
void obstack_init (struct obstack *obstack-ptr)
Initialize use of an obstack. SeeCreating Obstacks.
void *obstack_alloc (struct obstack *obstack-ptr, intsize)
Allocate an object ofsize uninitialized bytes.SeeAllocation in an Obstack.
void *obstack_copy (struct obstack *obstack-ptr, void *address, intsize)
Allocate an object ofsize bytes, with contents copied fromaddress. SeeAllocation in an Obstack.
void *obstack_copy0 (struct obstack *obstack-ptr, void *address, intsize)
Allocate an object ofsize+1 bytes, withsize of them copiedfromaddress, followed by a null character at the end.SeeAllocation in an Obstack.
void obstack_free (struct obstack *obstack-ptr, void *object)
Freeobject (and everything allocated in the specified obstackmore recently thanobject). SeeFreeing Objects in an Obstack.
void obstack_blank (struct obstack *obstack-ptr, intsize)
Addsize uninitialized bytes to a growing object.SeeGrowing Objects.
void obstack_grow (struct obstack *obstack-ptr, void *address, intsize)
Addsize bytes, copied fromaddress, to a growing object.SeeGrowing Objects.
void obstack_grow0 (struct obstack *obstack-ptr, void *address, intsize)
Addsize bytes, copied fromaddress, to a growing object,and then add another byte containing a null character. SeeGrowing Objects.
void obstack_1grow (struct obstack *obstack-ptr, chardata-char)
Add one byte containingdata-char to a growing object.SeeGrowing Objects.
void *obstack_finish (struct obstack *obstack-ptr)
Finalize the object that is growing and return its permanent address.SeeGrowing Objects.
int obstack_object_size (struct obstack *obstack-ptr)
Get the current size of the currently growing object. SeeGrowing Objects.
void obstack_blank_fast (struct obstack *obstack-ptr, intsize)
Addsize uninitialized bytes to a growing object without checkingthat there is enough room. SeeExtra Fast Growing Objects.
void obstack_1grow_fast (struct obstack *obstack-ptr, chardata-char)
Add one byte containingdata-char to a growing object withoutchecking that there is enough room. SeeExtra Fast Growing Objects.
int obstack_room (struct obstack *obstack-ptr)
Get the amount of room now available for growing the current object.SeeExtra Fast Growing Objects.
int obstack_alignment_mask (struct obstack *obstack-ptr)
The mask used for aligning the beginning of an object. This is anlvalue. SeeAlignment of Data in Obstacks.
int obstack_chunk_size (struct obstack *obstack-ptr)
The size for allocating chunks. This is an lvalue. SeeObstack Chunks.
void *obstack_base (struct obstack *obstack-ptr)
Tentative starting address of the currently growing object.SeeStatus of an Obstack.
void *obstack_next_free (struct obstack *obstack-ptr)
Address just after the end of the currently growing object.SeeStatus of an Obstack.
Previous:Obstacks, Up:Allocating Storage For Program Data [Contents][Index]
The functionalloca
supports a kind of half-dynamic allocation inwhich blocks are allocated dynamically but freed automatically.
Allocating a block withalloca
is an explicit action; you canallocate as many blocks as you wish, and compute the size at run time. Butall the blocks are freed when you exit the function thatalloca
wascalled from, just as if they were automatic variables declared in thatfunction. There is no way to free the space explicitly.
The prototype foralloca
is instdlib.h. This function isa BSD extension.
void *
alloca(size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The return value ofalloca
is the address of a block ofsizebytes of memory, allocated in the stack frame of the calling function.
Do not usealloca
inside the arguments of a function call—youwill get unpredictable results, because the stack space for thealloca
would appear on the stack in the middle of the space forthe function arguments. An example of what to avoid isfoo (x,alloca (4), y)
.
alloca
Example ¶As an example of the use ofalloca
, here is a function that opensa file name made from concatenating two argument strings, and returns afile descriptor or minus one signifying failure:
intopen2 (char *str1, char *str2, int flags, int mode){ char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1); stpcpy (stpcpy (name, str1), str2); return open (name, flags, mode);}
Here is how you would get the same results withmalloc
andfree
:
intopen2 (char *str1, char *str2, int flags, int mode){ char *name = malloc (strlen (str1) + strlen (str2) + 1); int desc; if (name == 0) fatal ("virtual memory exceeded"); stpcpy (stpcpy (name, str1), str2); desc = open (name, flags, mode); free (name); return desc;}
As you can see, it is simpler withalloca
. Butalloca
hasother, more important advantages, and some disadvantages.
Next:Disadvantages ofalloca
, Previous:alloca
Example, Up:Automatic Storage with Variable Size [Contents][Index]
alloca
¶Here are the reasons whyalloca
may be preferable tomalloc
:
alloca
wastes very little space and is very fast. (It isopen-coded by the GNU C compiler.)alloca
does not have separate pools for different sizes ofblocks, space used for any size block can be reused for any other size.alloca
does not cause memory fragmentation.longjmp
(seeNon-Local Exits)automatically free the space allocated withalloca
when they exitthrough the function that calledalloca
. This is the mostimportant reason to usealloca
.To illustrate this, suppose you have a functionopen_or_report_error
which returns a descriptor, likeopen
, if it succeeds, but does not return to its caller if itfails. If the file cannot be opened, it prints an error message andjumps out to the command level of your program usinglongjmp
.Let’s changeopen2
(seealloca
Example) to use thissubroutine:
intopen2 (char *str1, char *str2, int flags, int mode){ char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1); stpcpy (stpcpy (name, str1), str2); return open_or_report_error (name, flags, mode);}
Because of the wayalloca
works, the memory it allocates isfreed even when an error occurs, with no special effort required.
By contrast, the previous definition ofopen2
(which usesmalloc
andfree
) would develop a memory leak if it werechanged in this way. Even if you are willing to make more changes tofix it, there is no easy way to do so.
Next:GNU C Variable-Size Arrays, Previous:Advantages ofalloca
, Up:Automatic Storage with Variable Size [Contents][Index]
alloca
¶These are the disadvantages ofalloca
in comparison withmalloc
:
alloca
, so it is lessportable. However, a slower emulation ofalloca
written in Cis available for use on systems with this deficiency.Previous:Disadvantages ofalloca
, Up:Automatic Storage with Variable Size [Contents][Index]
In GNU C, you can replace most uses ofalloca
with an array ofvariable size. Here is howopen2
would look then:
int open2 (char *str1, char *str2, int flags, int mode){ char name[strlen (str1) + strlen (str2) + 1]; stpcpy (stpcpy (name, str1), str2); return open (name, flags, mode);}
Butalloca
is not always equivalent to a variable-sized array, forseveral reasons:
alloca
remains until the end of the function.alloca
within a loop, allocating anadditional block on each iteration. This is impossible withvariable-sized arrays.NB: If you mix use ofalloca
and variable-sized arrayswithin one function, exiting a scope in which a variable-sized array wasdeclared frees all blocks allocated withalloca
during theexecution of that scope.
Next:Memory Protection, Previous:Allocating Storage For Program Data, Up:Virtual Memory Allocation And Paging [Contents][Index]
The symbols in this section are declared inunistd.h.
You will not normally use the functions in this section, because thefunctions described inAllocating Storage For Program Data are easier to use. Thoseare interfaces to a GNU C Library memory allocator that uses thefunctions below itself. The functions below are simple interfaces tosystem calls.
int
brk(void *addr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
brk
sets the high end of the calling process’ data segment toaddr.
The address of the end of a segment is defined to be the address of thelast byte in the segment plus 1.
The function has no effect ifaddr is lower than the low end ofthe data segment. (This is considered success, by the way.)
The function fails if it would cause the data segment to overlap anothersegment or exceed the process’ data storage limit (seeLimiting Resource Usage).
The function is named for a common historical case where data storageand the stack are in the same segment. Data storage allocation growsupward from the bottom of the segment while the stack grows downwardtoward it from the top of the segment and the curtain between them iscalled thebreak.
The return value is zero on success. On failure, the return value is-1
anderrno
is set accordingly. The followingerrno
values are specific to this function:
ENOMEM
The request would cause the data segment to overlap another segment orexceed the process’ data storage limit.
void *
sbrk(ptrdiff_tdelta)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is the same asbrk
except that you specify the newend of the data segment as an offsetdelta from the current endand on success the return value is the address of the resulting end ofthe data segment instead of zero.
This means you can use ‘sbrk(0)’ to find out what the current endof the data segment is.
Next:Locking Pages, Previous:Resizing the Data Segment, Up:Virtual Memory Allocation And Paging [Contents][Index]
When a page is mapped usingmmap
, page protection flags can bespecified using the protection flags argument. SeeMemory-mapped I/O.
The following flags are available:
PROT_WRITE
¶The memory can be written to.
PROT_READ
¶The memory can be read. On some architectures, this flag implies thatthe memory can be executed as well (as ifPROT_EXEC
had beenspecified at the same time).
PROT_EXEC
¶The memory can be used to store instructions which can then be executed.On most architectures, this flag implies that the memory can be read (asifPROT_READ
had been specified).
PROT_NONE
¶This flag must be specified on its own.
The memory is reserved, but cannot be read, written, or executed. Ifthis flag is specified in a call tommap
, a virtual memory areawill be set aside for future use in the process, andmmap
callswithout theMAP_FIXED
flag will not use it for subsequentallocations. For anonymous mappings, the kernel will not reserve anyphysical memory for the allocation at the time the mapping is created.
The operating system may keep track of these flags separately even ifthe underlying hardware treats them the same for the purposes of accesschecking (as happens withPROT_READ
andPROT_EXEC
on someplatforms). On GNU systems,PROT_EXEC
always impliesPROT_READ
, so that users can view the machine code which isexecuting on their system.
Inappropriate access will cause a segfault (seeProgram Error Signals).
After allocation, protection flags can be changed using themprotect
function.
int
mprotect(void *address, size_tlength, intprotection)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
A successful call to themprotect
function changes the protectionflags of at leastlength bytes of memory, starting ataddress.
address must be aligned to the page size for the mapping. Thesystem page size can be obtained by callingsysconf
with the_SC_PAGESIZE
parameter (seeDefinition ofsysconf
). The systempage size is the granularity in which the page protection of anonymousmemory mappings and most file mappings can be changed. Memory which ismapped from special files or devices may have larger page granularitythan the system page size and may require larger alignment.
length is the number of bytes whose protection flags must bechanged. It is automatically rounded up to the next multiple of thesystem page size.
protection is a combination of thePROT_*
flags describedabove.
Themprotect
function returns0 on success and-1on failure.
The followingerrno
error conditions are defined for thisfunction:
ENOMEM
The system was not able to allocate resources to fulfill the request.This can happen if there is not enough physical memory in the system forthe allocation of backing storage. The error can also occur if the newprotection flags would cause the memory region to be split from itsneighbors, and the process limit for the number of such distinct memoryregions would be exceeded.
EINVAL
address is not properly aligned to a page boundary for themapping, orlength (after rounding up to the system page size) isnot a multiple of the applicable page size for the mapping, or thecombination of flags inprotection is not valid.
EACCES
The file for a file-based mapping was not opened with open flags whichare compatible withprotection.
EPERM
The system security policy does not allow a mapping with the specifiedflags. For example, mappings which are bothPROT_EXEC
andPROT_WRITE
at the same time might not be allowed.
If themprotect
function is used to make a region of memoryinaccessible by specifying thePROT_NONE
protection flag andaccess is later restored, the memory retains its previous contents.
On some systems, it may not be possible to specify additional flagswhich were not present when the mapping was first created. For example,an attempt to make a region of memory executable could fail if theinitial protection flags were ‘PROT_READ | PROT_WRITE’.
In general, themprotect
function can be used to change anyprocess memory, no matter how it was allocated. However, portable useof the function requires that it is only used with memory regionsreturned bymmap
ormmap64
.
On some systems, further access restrictions can be added to specific pagesusingmemory protection keys. These restrictions work as follows:
pkey_alloc
function, and applied to pages usingpkey_mprotect
.pkey_set
andpkey_get
functions.PROT_
* protection flagsset bymprotect
orpkey_mprotect
.New threads and subprocesses inherit the access restrictions of the currentthread. If a protection key is allocated subsequently, existing threads(except the current) will use an unspecified system default for theaccess restrictions associated with newly allocated keys.
Upon entering a signal handler, the system resets the access restrictions ofthe current thread so that pages with the default key can be accessed,but the access restrictions for other protection keys are unspecified.
Applications are expected to allocate a key once usingpkey_alloc
, and apply the key to memory regions which needspecial protection withpkey_mprotect
:
int key = pkey_alloc (0, PKEY_DISABLE_ACCESS); if (key < 0) /* Perform error checking, including fallback for lack of support. */ ...; /* Apply the key to a special memory region used to store critical data. */ if (pkey_mprotect (region, region_length, PROT_READ | PROT_WRITE, key) < 0) ...; /* Perform error checking (generally fatal). */
If the key allocation fails due to lack of support for memory protectionkeys, thepkey_mprotect
call can usually be skipped. In thiscase, the region will not be protected by default. It is also possibleto callpkey_mprotect
with a key value of-1, in whichcase it will behave in the same way asmprotect
.
After key allocation assignment to memory pages,pkey_set
can beused to temporarily acquire access to the memory region and relinquishit again:
if (key >= 0 && pkey_set (key, PKEY_UNRESTRICTED) < 0) ...; /* Perform error checking (generally fatal). */ /* At this point, the current thread has read-write access to the memory region. */ ... /* Revoke access again. */ if (key >= 0 && pkey_set (key, PKEY_DISABLE_ACCESS) < 0) ...; /* Perform error checking (generally fatal). */
In this example, a negative key value indicates that no key had beenallocated, which means that the system lacks support for memoryprotection keys and it is not necessary to change the the access restrictionsof the current thread (because it always has access).
Compared to usingmprotect
to change the page protection flags,this approach has two advantages: It is thread-safe in the sense thatthe access restrictions are only changed for the current thread, so anotherthread which changes its own access restrictions concurrently to gain accessto the mapping will not suddenly see its access restrictions updated. Andpkey_set
typically does not involve a call into the kernel and acontext switch, so it is more efficient.
int
pkey_alloc(unsigned intflags, unsigned intaccess_restrictions)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Allocate a new protection key. Theflags argument is reserved andmust be zero. Theaccess_restrictions argument specifies access restrictionswhich are applied to the current thread (as if withpkey_set
below). Access restrictions of other threads are not changed.
The function returns the new protection key, a non-negative number, or-1 on error.
The followingerrno
error conditions are defined for thisfunction:
ENOSYS
The system does not implement memory protection keys.
EINVAL
Theflags argument is not zero.
Theaccess_restrictions argument is invalid.
The system does not implement memory protection keys or runs in a modein which memory protection keys are disabled.
ENOSPC
All available protection keys already have been allocated.
The system does not implement memory protection keys or runs in a modein which memory protection keys are disabled.
int
pkey_free(intkey)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Deallocate the protection key, so that it can be reused bypkey_alloc
.
Calling this function does not change the access restrictions of the freedprotection key. The calling thread and other threads may retain accessto it, even if it is subsequently allocated again. For this reason, itis not recommended to call thepkey_free
function.
ENOSYS
The system does not implement memory protection keys.
EINVAL
Thekey argument is not a valid protection key.
int
pkey_mprotect(void *address, size_tlength, intprotection, intkey)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Similar tomprotect
, but also set the memory protection key forthe memory region tokey
.
Some systems use memory protection keys to emulate certain combinationsofprotection flags. Under such circumstances, specifying anexplicit protection key may behave as if additional flags have beenspecified inprotection, even though this does not happen with thedefault protection key. For example, some systems can supportPROT_EXEC
-only mappings only with a default protection key, andmemory with a key which was allocated usingpkey_alloc
will stillbe readable ifPROT_EXEC
is specified withoutPROT_READ
.
Ifkey is-1, the default protection key is applied to themapping, just as ifmprotect
had been called.
Thepkey_mprotect
function returns0 on success and-1 on failure. The sameerrno
error conditions as formprotect
are defined for this function, with the followingaddition:
EINVAL
Thekey argument is not-1 or a valid memory protectionkey allocated usingpkey_alloc
.
ENOSYS
The system does not implement memory protection keys, andkey isnot-1.
int
pkey_set(intkey, unsigned intaccess_restrictions)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Change the access restrictions of the current thread for memory pages withthe protection keykey toaccess_restrictions. Ifaccess_restrictions isPKEY_UNRESTRICTED
(zero), no additionalaccess restrictions on top of the page protection flags are applied. Otherwise,access_restrictions is a combination of the following flags:
PKEY_DISABLE_READ
¶Subsequent attempts to read from memory with the specified protectionkey will fault. At present only AArch64 platforms with enabled Stage 1permission overlays feature support this type of restriction.
PKEY_DISABLE_WRITE
¶Subsequent attempts to write to memory with the specified protectionkey will fault.
PKEY_DISABLE_ACCESS
¶Subsequent attempts to write to or read from memory with the specifiedprotection key will fault. On AArch64 platforms with enabled Stage 1permission overlays feature this restriction value has the same effectas combination ofPKEY_DISABLE_READ
andPKEY_DISABLE_WRITE
.
PKEY_DISABLE_EXECUTE
¶Subsequent attempts to execute from memory with the specified protectionkey will fault. At present only AArch64 platforms with enabled Stage 1permission overlays feature support this type of restriction.
Operations not specified as flags are not restricted. In particular,this means that the memory region will remain executable if it wasmapped with thePROT_EXEC
protection flag andPKEY_DISABLE_ACCESS
has been specified.
Calling thepkey_set
function with a protection key which was notallocated bypkey_alloc
results in undefined behavior. Thismeans that calling this function on systems which do not support memoryprotection keys is undefined.
Thepkey_set
function returns0 on success and-1on failure.
The followingerrno
error conditions are defined for thisfunction:
EINVAL
The system does not support the access restrictions expressed intheaccess_restrictions argument.
int
pkey_get(intkey)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Return the access restrictions of the current thread for memory pageswith protection keykey. The return value is zero or a combination ofthePKEY_DISABLE_
* flags; see thepkey_set
function.
The returned value should be checked for presence or absence of specific flagsusing bitwise operations. Comparing the returned value with any of the flagsor their combination using equals will almost certainly fail.
Calling thepkey_get
function with a protection key which was notallocated bypkey_alloc
results in undefined behavior. Thismeans that calling this function on systems which do not support memoryprotection keys is undefined.
Previous:Memory Protection, Up:Virtual Memory Allocation And Paging [Contents][Index]
You can tell the system to associate a particular virtual memory pagewith a real page frame and keep it that way — i.e., cause the page tobe paged in if it isn’t already and mark it so it will never be pagedout and consequently will never cause a page fault. This is calledlocking a page.
The functions in this chapter lock and unlock the calling process’pages.
Next:Locked Memory Details, Up:Locking Pages [Contents][Index]
Because page faults cause paged out pages to be paged in transparently,a process rarely needs to be concerned about locking pages. However,there are two reasons people sometimes are:
A process that needs to lock pages for this reason probably also needspriority among other processes for use of the CPU. SeeProcess CPU Priority And Scheduling.
In some cases, the programmer knows better than the system’s demandpaging allocator which pages should remain in real memory to optimizesystem performance. In this case, locking pages can help.
Be aware that when you lock a page, that’s one fewer page frame that canbe used to back other virtual memory (by the same or other processes),which can mean more page faults, which means the system runs moreslowly. In fact, if you lock enough memory, some programs may not beable to run at all for lack of real memory.
Next:Functions To Lock And Unlock Pages, Previous:Why Lock Pages, Up:Locking Pages [Contents][Index]
A memory lock is associated with a virtual page, not a real frame. Thepaging rule is: If a frame backs at least one locked page, don’t page itout.
Memory locks do not stack. I.e., you can’t lock a particular page twiceso that it has to be unlocked twice before it is truly unlocked. It iseither locked or it isn’t.
A memory lock persists until the process that owns the memory explicitlyunlocks it. (But process termination and exec cause the virtual memoryto cease to exist, which you might say means it isn’t locked any more).
Memory locks are not inherited by child processes. (But note that on amodern Unix system, immediately after a fork, the parent’s and thechild’s virtual address space are backed by the same real page frames,so the child enjoys the parent’s locks). SeeCreating a Process.
Because of its ability to impact other processes, only the superuser canlock a page. Any process can unlock its own page.
The system sets limits on the amount of memory a process can have lockedand the amount of real memory it can have dedicated to it. SeeLimiting Resource Usage.
In Linux, locked pages aren’t as locked as you might think.Two virtual pages that are not shared memory can nonetheless be backedby the same real frame. The kernel does this in the name of efficiencywhen it knows both virtual pages contain identical data, and does iteven if one or both of the virtual pages are locked.
But when a process modifies one of those pages, the kernel must get it aseparate frame and fill it with the page’s data. This is known as acopy-on-write page fault. It takes a small amount of time and ina pathological case, getting that frame may require I/O.
To make sure this doesn’t happen to your program, don’t just lock thepages. Write to them as well, unless you know you won’t write to themever. And to make sure you have pre-allocated frames for your stack,enter a scope that declares a C automatic variable larger than themaximum stack size you will need, set it to something, then return fromits scope.
Previous:Locked Memory Details, Up:Locking Pages [Contents][Index]
The symbols in this section are declared insys/mman.h. Thesefunctions are defined by POSIX.1b, but their availability depends onyour kernel. If your kernel doesn’t allow these functions, they existbut always fail. Theyare available with a Linux kernel.
Portability Note: POSIX.1b requires that when themlock
andmunlock
functions are available, the fileunistd.hdefine the macro_POSIX_MEMLOCK_RANGE
and the filelimits.h
define the macroPAGESIZE
to be the size of amemory page in bytes. It requires that when themlockall
andmunlockall
functions are available, theunistd.h filedefine the macro_POSIX_MEMLOCK
. The GNU C Library conforms tothis requirement.
int
mlock(const void *addr, size_tlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
mlock
locks a range of the calling process’ virtual pages.
The range of memory starts at addressaddr and islen byteslong. Actually, since you must lock whole pages, it is the range ofpages that include any part of the specified range.
When the function returns successfully, each of those pages is backed by(connected to) a real frame (is resident) and is marked to stay thatway. This means the function may cause page-ins and have to wait forthem.
When the function fails, it does not affect the lock status of anypages.
The return value is zero if the function succeeds. Otherwise, it is-1
anderrno
is set accordingly.errno
valuesspecific to this function are:
ENOMEM
EPERM
The calling process is not superuser.
EINVAL
len is not positive.
ENOSYS
The kernel does not providemlock
capability.
int
mlock2(const void *addr, size_tlen, unsigned intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar tomlock
. Ifflags is zero, acall tomlock2
behaves exactly as the equivalent call tomlock
.
Theflags argument must be a combination of zero or more of thefollowing flags:
MLOCK_ONFAULT
¶Only those pages in the specified address range which are already inmemory are locked immediately. Additional pages in the range areautomatically locked in case of a page fault and allocation of memory.
Likemlock
,mlock2
returns zero on success and-1
on failure, settingerrno
accordingly. Additionalerrno
values defined formlock2
are:
EINVAL
The specified (non-zero)flags argument is not supported by thissystem.
You can lockall a process’ memory withmlockall
. Youunlock memory withmunlock
ormunlockall
.
To avoid all page faults in a C program, you have to usemlockall
, because some of the memory a program uses is hiddenfrom the C code, e.g. the stack and automatic variables, and youwouldn’t know what address to tellmlock
.
int
munlock(const void *addr, size_tlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
munlock
unlocks a range of the calling process’ virtual pages.
munlock
is the inverse ofmlock
and functions completelyanalogously tomlock
, except that there is noEPERM
failure.
int
mlockall(intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
mlockall
locks all the pages in a process’ virtual memory addressspace, and/or any that are added to it in the future. This includes thepages of the code, data and stack segment, as well as shared libraries,user space kernel data, shared memory, and memory mapped files.
flags is a string of single bit flags represented by the followingmacros. They tellmlockall
which of its functions you want. Allother bits must be zero.
MCL_CURRENT
¶Lock all pages which currently exist in the calling process’ virtualaddress space.
MCL_FUTURE
¶Set a mode such that any pages added to the process’ virtual addressspace in the future will be locked from birth. This mode does notaffect future address spaces owned by the same process so exec, whichreplaces a process’ address space, wipes outMCL_FUTURE
.SeeExecuting a File.
When the function returns successfully, and you specifiedMCL_CURRENT
, all of the process’ pages are backed by (connectedto) real frames (they are resident) and are marked to stay that way.This means the function may cause page-ins and have to wait for them.
When the process is inMCL_FUTURE
mode because it successfullyexecuted this function and specifiedMCL_CURRENT
, any system callby the process that requires space be added to its virtual address spacefails witherrno
=ENOMEM
if locking the additional spacewould cause the process to exceed its locked page limit. In the casethat the address space addition that can’t be accommodated is stackexpansion, the stack expansion fails and the kernel sends aSIGSEGV
signal to the process.
When the function fails, it does not affect the lock status of any pagesor the future locking mode.
The return value is zero if the function succeeds. Otherwise, it is-1
anderrno
is set accordingly.errno
valuesspecific to this function are:
ENOMEM
EPERM
The calling process is not superuser.
EINVAL
Undefined bits inflags are not zero.
ENOSYS
The kernel does not providemlockall
capability.
You can lock just specific pages withmlock
. You unlock pageswithmunlockall
andmunlock
.
int
munlockall(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
munlockall
unlocks every page in the calling process’ virtualaddress space and turns offMCL_FUTURE
future locking mode.
The return value is zero if the function succeeds. Otherwise, it is-1
anderrno
is set accordingly. The only way thisfunction can fail is for generic reasons that all functions and systemcalls can fail, so there are no specificerrno
values.
Next:String and Array Utilities, Previous:Virtual Memory Allocation And Paging, Up:Main Menu [Contents][Index]
Programs that work with characters and strings often need to classify acharacter—is it alphabetic, is it a digit, is it whitespace, and soon—and perform case conversion operations on characters. Thefunctions in the header filectype.h are provided for thispurpose.
Since the choice of locale and character set can alter theclassifications of particular character codes, all of these functionsare affected by the current locale. (More precisely, they are affectedby the locale currently selected for character classification—theLC_CTYPE
category; seeLocale Categories.)
The ISO C standard specifies two different sets of functions. Theone set works onchar
type characters, the other one onwchar_t
wide characters (seeIntroduction to Extended Characters).
Next:Case Conversion, Up:Character Handling [Contents][Index]
This section explains the library functions for classifying characters.For example,isalpha
is the function to test for an alphabeticcharacter. It takes one argument, the character to test as anunsigned char
value, and returns a nonzero integer if thecharacter is alphabetic, and zero otherwise. You would use it likethis:
if (isalpha ((unsigned char) c)) printf ("The character `%c' is alphabetic.\n", c);
Each of the functions in this section tests for membership in aparticular class of characters; each has a name starting with ‘is’.Each of them takes one argument, which is a character to test. Thecharacter argument must be in the value range ofunsigned char
(0to 255 for the GNU C Library). On a machine where thechar
type issigned, it may be necessary to cast the argument tounsignedchar
, or mask it with ‘& 0xff’. (Onunsigned char
machines, this step is harmless, so portable code should always performit.) The ‘is’ functions return anint
which is treated as aboolean value.
All ‘is’ functions accept the special valueEOF
and returnzero. (Note thatEOF
must not be cast tounsigned char
for this to work.)
As an extension, the GNU C Library accepts signedchar
values as‘is’ functions arguments in the range -128 to -2, and returns theresult for the corresponding unsigned character. However, as theremight be an actual character corresponding to theEOF
integerconstant, doing so may introduce bugs, and it is recommended to applythe conversion to the unsigned character range as appropriate.
The attributes of any given character can vary between locales.SeeLocales and Internationalization, for more information on locales.
These functions are declared in the header filectype.h.
int
islower(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is a lower-case letter. The letter need not befrom the Latin alphabet, any alphabet representable is valid.
int
isupper(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is an upper-case letter. The letter need not befrom the Latin alphabet, any alphabet representable is valid.
int
isalpha(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is an alphabetic character (a letter). Ifislower
orisupper
is true of a character, thenisalpha
is also true.
In some locales, there may be additional characters for whichisalpha
is true—letters which are neither upper case nor lowercase. But in the standard"C"
locale, there are no suchadditional characters.
int
isdigit(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is a decimal digit (‘0’ through ‘9’).
int
isalnum(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is an alphanumeric character (a letter ornumber); in other words, if eitherisalpha
orisdigit
istrue of a character, thenisalnum
is also true.
int
isxdigit(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is a hexadecimal digit.Hexadecimal digits include the normal decimal digits ‘0’ through‘9’ and the letters ‘A’ through ‘F’ and‘a’ through ‘f’.
int
ispunct(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is a punctuation character.This means any printing character that is not alphanumeric or a spacecharacter.
int
isspace(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is awhitespace character. In the standard"C"
locale,isspace
returns true for only the standardwhitespace characters:
' '
space
'\f'
formfeed
'\n'
newline
'\r'
carriage return
'\t'
horizontal tab
'\v'
vertical tab
int
isblank(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is a blank character; that is, a space or a tab.This function was originally a GNU extension, but was added in ISO C99.
int
isgraph(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is a graphic character; that is, a characterthat has a glyph associated with it. The whitespace characters are notconsidered graphic.
int
isprint(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is a printing character. Printing charactersinclude all the graphic characters, plus the space (‘’) character.
int
iscntrl(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is a control character (that is, a character thatis not a printing character).
int
isascii(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifc is a 7-bitunsigned char
value that fitsinto the US/UK ASCII character set. This function is a BSD extensionand is also an SVID extension.
Next:Character class determination for wide characters, Previous:Classification of Characters, Up:Character Handling [Contents][Index]
This section explains the library functions for performing conversionssuch as case mappings on characters. For example,toupper
converts any character to upper case if possible. If the charactercan’t be converted,toupper
returns it unchanged.
These functions take one argument of typeint
, which is thecharacter to convert, and return the converted character as anint
. If the conversion is not applicable to the argument given,the argument is returned unchanged.
Compatibility Note: In pre-ISO C dialects, instead ofreturning the argument unchanged, these functions may fail when theargument is not suitable for the conversion. Thus for portability, youmay need to writeislower(c) ? toupper(c) : c
rather than justtoupper(c)
.
These functions are declared in the header filectype.h.
int
tolower(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Ifc is an upper-case letter,tolower
returns the correspondinglower-case letter. Ifc is not an upper-case letter,c is returned unchanged.
int
toupper(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Ifc is a lower-case letter,toupper
returns the correspondingupper-case letter. Otherwisec is returned unchanged.
int
toascii(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function convertsc to a 7-bitunsigned char
valuethat fits into the US/UK ASCII character set, by clearing the high-orderbits. This function is a BSD extension and is also an SVID extension.
int
_tolower(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is identical totolower
, and is provided for compatibilitywith the SVID. SeeSVID (The System V Interface Description).
int
_toupper(intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is identical totoupper
, and is provided for compatibilitywith the SVID.
Next:Notes on using the wide character classes, Previous:Case Conversion, Up:Character Handling [Contents][Index]
Amendment 1 to ISO C90 defines functions to classify widecharacters. Although the original ISO C90 standard already definedthe typewchar_t
, no functions operating on them were defined.
The general design of the classification functions for wide charactersis more general. It allows extensions to the set of availableclassifications, beyond those which are always available. The POSIXstandard specifies how extensions can be made, and this is alreadyimplemented in the GNU C Library implementation of thelocaledef
program.
The character class functions are normally implemented with bitsets,with a bitset per character. For a given character, the appropriatebitset is read from a table and a test is performed as to whether acertain bit is set. Which bit is tested for is determined by theclass.
For the wide character classification functions this is made visible.There is a type classification type defined, a function to retrieve thisvalue for a given class, and a function to test whether a givencharacter is in this class, using the classification value. On top ofthis the normal character classification functions as used forchar
objects can be defined.
Thewctype_t
can hold a value which represents a character class.The only defined way to generate such a value is by using thewctype
function.
This type is defined inwctype.h.
wctype_t
wctype(const char *property)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
wctype
returns a value representing a class of widecharacters which is identified by the stringproperty. Besidessome standard properties each locale can define its own ones. In caseno property with the given name is known for the current localeselected for theLC_CTYPE
category, the function returns zero.
The properties known in every locale are:
"alnum" | "alpha" | "cntrl" | "digit" |
"graph" | "lower" | "print" | "punct" |
"space" | "upper" | "xdigit" |
This function is declared inwctype.h.
To test the membership of a character to one of the non-standard classesthe ISO C standard defines a completely new function.
int
iswctype(wint_twc, wctype_tdesc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns a nonzero value ifwc is in the characterclass specified bydesc.desc must previously be returnedby a successful call towctype
.
This function is declared inwctype.h.
To make it easier to use the commonly-used classification functions,they are defined in the C library. There is no need to usewctype
if the property string is one of the known characterclasses. In some situations it is desirable to construct the propertystrings, and then it is important thatwctype
can also handle thestandard classes.
int
iswalnum(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns a nonzero value ifwc is an alphanumericcharacter (a letter or number); in other words, if eitheriswalpha
oriswdigit
is true of a character, theniswalnum
is alsotrue.
This function can be implemented using
iswctype (wc, wctype ("alnum"))
It is declared inwctype.h.
int
iswalpha(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is an alphabetic character (a letter). Ifiswlower
oriswupper
is true of a character, theniswalpha
is also true.
In some locales, there may be additional characters for whichiswalpha
is true—letters which are neither upper case nor lowercase. But in the standard"C"
locale, there are no suchadditional characters.
This function can be implemented using
iswctype (wc, wctype ("alpha"))
It is declared inwctype.h.
int
iswcntrl(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is a control character (that is, a character thatis not a printing character).
This function can be implemented using
iswctype (wc, wctype ("cntrl"))
It is declared inwctype.h.
int
iswdigit(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is a digit (e.g., ‘0’ through ‘9’).Please note that this function does not only return a nonzero value fordecimal digits, but for all kinds of digits. A consequence isthat code like the following willnot work unconditionally forwide characters:
n = 0;while (iswdigit (*wc)) { n *= 10; n += *wc++ - L'0'; }
This function can be implemented using
iswctype (wc, wctype ("digit"))
It is declared inwctype.h.
int
iswgraph(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is a graphic character; that is, a characterthat has a glyph associated with it. The whitespace characters are notconsidered graphic.
This function can be implemented using
iswctype (wc, wctype ("graph"))
It is declared inwctype.h.
int
iswlower(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is a lower-case letter. The letter need not befrom the Latin alphabet, any alphabet representable is valid.
This function can be implemented using
iswctype (wc, wctype ("lower"))
It is declared inwctype.h.
int
iswprint(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is a printing character. Printing charactersinclude all the graphic characters, plus the space (‘’) character.
This function can be implemented using
iswctype (wc, wctype ("print"))
It is declared inwctype.h.
int
iswpunct(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is a punctuation character.This means any printing character that is not alphanumeric or a spacecharacter.
This function can be implemented using
iswctype (wc, wctype ("punct"))
It is declared inwctype.h.
int
iswspace(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is awhitespace character. In the standard"C"
locale,iswspace
returns true for only the standardwhitespace characters:
L' '
space
L'\f'
formfeed
L'\n'
newline
L'\r'
carriage return
L'\t'
horizontal tab
L'\v'
vertical tab
This function can be implemented using
iswctype (wc, wctype ("space"))
It is declared inwctype.h.
int
iswupper(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is an upper-case letter. The letter need not befrom the Latin alphabet, any alphabet representable is valid.
This function can be implemented using
iswctype (wc, wctype ("upper"))
It is declared inwctype.h.
int
iswxdigit(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is a hexadecimal digit.Hexadecimal digits include the normal decimal digits ‘0’ through‘9’ and the letters ‘A’ through ‘F’ and‘a’ through ‘f’.
This function can be implemented using
iswctype (wc, wctype ("xdigit"))
It is declared inwctype.h.
The GNU C Library also provides a function which is not defined in theISO C standard but which is available as a version for single bytecharacters as well.
int
iswblank(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns true ifwc is a blank character; that is, a space or a tab.This function was originally a GNU extension, but was added in ISO C99.It is declared inwchar.h.
Next:Mapping of wide characters., Previous:Character class determination for wide characters, Up:Character Handling [Contents][Index]
The first note is probably not astonishing but still occasionally acause of problems. TheiswXXX
functions can be implementedusing macros and in fact, the GNU C Library does this. They are stillavailable as real functions but when thewctype.h header isincluded the macros will be used. This is the same as thechar
type versions of these functions.
The second note covers something new. It can be best illustrated by a(real-world) example. The first piece of code is an excerpt from theoriginal code. It is truncated a bit but the intention should be clear.
intis_in_class (int c, const char *class){ if (strcmp (class, "alnum") == 0) return isalnum (c); if (strcmp (class, "alpha") == 0) return isalpha (c); if (strcmp (class, "cntrl") == 0) return iscntrl (c); ... return 0;}
Now, with thewctype
andiswctype
you can avoid theif
cascades, but rewriting the code as follows is wrong:
intis_in_class (int c, const char *class){ wctype_t desc = wctype (class); return desc ? iswctype ((wint_t) c, desc) : 0;}
The problem is that it is not guaranteed that the wide characterrepresentation of a single-byte character can be found using casting.In fact, usually this fails miserably. The correct solution to thisproblem is to write the code as follows:
intis_in_class (int c, const char *class){ wctype_t desc = wctype (class); return desc ? iswctype (btowc (c), desc) : 0;}
SeeConverting Single Characters, for more information onbtowc
.Note that this change probably does not improve the performanceof the program a lot since thewctype
function still has to makethe string comparisons. It gets really interesting if theis_in_class
function is called more than once for thesame class name. In this case the variabledesc could be computedonce and reused for all the calls. Therefore the above form of thefunction is probably not the final one.
Previous:Notes on using the wide character classes, Up:Character Handling [Contents][Index]
The classification functions are also generalized by the ISO Cstandard. Instead of just allowing the two standard mappings, alocale can contain others. Again, thelocaledef
programalready supports generating such locale data files.
This data type is defined as a scalar type which can hold a valuerepresenting the locale-dependent character mapping. There is no way toconstruct such a value apart from using the return value of thewctrans
function.
This type is defined inwctype.h.
wctrans_t
wctrans(const char *property)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewctrans
function has to be used to find out whether a namedmapping is defined in the current locale selected for theLC_CTYPE
category. If the returned value is non-zero, you can useit afterwards in calls totowctrans
. If the return value iszero no such mapping is known in the current locale.
Beside locale-specific mappings there are two mappings which areguaranteed to be available in every locale:
"tolower" | "toupper" |
These functions are declared inwctype.h.
wint_t
towctrans(wint_twc, wctrans_tdesc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
towctrans
maps the input characterwcaccording to the rules of the mapping for whichdesc is adescriptor, and returns the value it finds.desc must beobtained by a successful call towctrans
.
This function is declared inwctype.h.
For the generally available mappings, the ISO C standard definesconvenient shortcuts so that it is not necessary to callwctrans
for them.
wint_t
towlower(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Ifwc is an upper-case letter,towlower
returns the correspondinglower-case letter. Ifwc is not an upper-case letter,wc is returned unchanged.
towlower
can be implemented using
towctrans (wc, wctrans ("tolower"))
This function is declared inwctype.h.
wint_t
towupper(wint_twc)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Ifwc is a lower-case letter,towupper
returns the correspondingupper-case letter. Otherwisewc is returned unchanged.
towupper
can be implemented using
towctrans (wc, wctrans ("toupper"))
This function is declared inwctype.h.
The same warnings given in the last section for the use of the widecharacter classification functions apply here. It is not possible tosimply cast achar
type value to awint_t
and use it as anargument totowctrans
calls.
Next:Character Set Handling, Previous:Character Handling, Up:Main Menu [Contents][Index]
Operations on strings (null-terminated byte sequences) are an important part ofmany programs. The GNU C Library provides an extensive set of stringutility functions, including functions for copying, concatenating,comparing, and searching strings. Many of these functions can alsooperate on arbitrary regions of storage; for example, thememcpy
function can be used to copy the contents of any kind of array.
It’s fairly common for beginning C programmers to “reinvent the wheel”by duplicating this functionality in their own code, but it pays tobecome familiar with the library functions and to make use of them,since this offers benefits in maintenance, efficiency, and portability.
For instance, you could easily compare one string to another in twolines of C code, but if you use the built-instrcmp
function,you’re less likely to make a mistake. And, since these libraryfunctions are typically highly optimized, your program may run fastertoo.
This section is a quick summary of string concepts for beginning Cprogrammers. It describes how strings are represented in Cand some common pitfalls. If you are already familiar with thismaterial, you can skip this section.
Astring is a null-terminated array of bytes of typechar
,including the terminating null byte. String-valuedvariables are usually declared to be pointers of typechar *
.Such variables do not include space for the contents of a string; that hasto be stored somewhere else—in an array variable, a string constant,or dynamically allocated memory (seeAllocating Storage For Program Data). It’s up toyou to store the address of the chosen memory space into the pointervariable. Alternatively you can store anull pointer in thepointer variable. The null pointer does not point anywhere, soattempting to reference the string it points to gets an error.
Amultibyte character is a sequence of one or more bytes thatrepresents a single character using the locale’s encoding scheme; anull byte always represents the null character. Amultibytestring is a string that consists entirely of multibytecharacters. In contrast, awide string is a null-terminatedsequence ofwchar_t
objects. A wide-string variable is usuallydeclared to be a pointer of typewchar_t *
, by analogy withstring variables andchar *
. SeeIntroduction to Extended Characters.
By convention, thenull byte,'\0'
,marks the end of a string and thenull wide character,L'\0'
, marks the end of a wide string. For example, intesting to see whether thechar *
variablep points to anull byte marking the end of a string, you can write!*p
or*p == '\0'
.
A null byte is quite different conceptually from a null pointer,although both are represented by the integer constant0
.
Astring literal appears in C program source as a multibytestring between double-quote characters (‘"’). If theinitial double-quote character is immediately preceded by a capital‘L’ (ell) character (as inL"foo"
), it is a wide stringliteral. String literals can also contribute tostringconcatenation:"a" "b"
is the same as"ab"
.For wide strings one can use eitherL"a" L"b"
orL"a" "b"
. Modification of string literals isnot allowed by the GNU C compiler, because literals are placed inread-only storage.
Arrays that are declaredconst
cannot be modifiedeither. It’s generally good style to declare non-modifiable stringpointers to be of typeconst char *
, since this often allows theC compiler to detect accidental modifications as well as providing someamount of documentation about what your program intends to do with thestring.
The amount of memory allocated for a byte array may extend past the null bytethat marks the end of the string that the array contains. In thisdocument, the termallocated size is always used to refer to thetotal amount of memory allocated for an array, while the termlength refers to the number of bytes up to (but not including)the terminating null byte. Wide strings are similar, except theirsizes and lengths count wide characters, not bytes.
A notorious source of program bugs is trying to put more bytes into astring than fit in its allocated size. When writing code that extendsstrings or moves bytes into a pre-allocated array, you should bevery careful to keep track of the length of the string and make explicitchecks for overflowing the array. Many of the library functionsdo not do this for you! Remember also that you need to allocatean extra byte to hold the null byte that marks the end of thestring.
Originally strings were sequences of bytes where each byte represented asingle character. This is still true today if the strings are encodedusing a single-byte character encoding. Things are different if thestrings are encoded using a multibyte encoding (for more information onencodings seeIntroduction to Extended Characters). There is no difference inthe programming interface for these two kind of strings; the programmerhas to be aware of this and interpret the byte sequences accordingly.
But since there is no separate interface taking care of thesedifferences the byte-based string functions are sometimes hard to use.Since the count parameters of these functions specify bytes a call tomemcpy
could cut a multibyte character in the middle and put anincomplete (and therefore unusable) byte sequence in the target buffer.
To avoid these problems later versions of the ISO C standardintroduce a second set of functions which are operating onwidecharacters (seeIntroduction to Extended Characters). These functions don’t havethe problems the single-byte versions have since every wide character isa legal, interpretable value. This does not mean that cutting widestrings at arbitrary points is without problems. It normallyis for alphabet-based languages (except for non-normalized text) butlanguages based on syllables still have the problem that more than onewide character is necessary to complete a logical unit. This is ahigher level problem which the C library functions are not designedto solve. But it is at least good that no invalid byte sequences can becreated. Also, the higher level functions can also much more easily operateon wide characters than on multibyte characters so that a common strategyis to use wide characters internally whenever text is more than simplycopied.
The remaining of this chapter will discuss the functions for handlingwide strings in parallel with the discussion ofstrings since there is almost always an exact equivalentavailable.
Next:String Length, Previous:Representation of Strings, Up:String and Array Utilities [Contents][Index]
This chapter describes both functions that work on arbitrary arrays orblocks of memory, and functions that are specific to strings and widestrings.
Functions that operate on arbitrary blocks of memory have namesbeginning with ‘mem’ and ‘wmem’ (such asmemcpy
andwmemcpy
) and invariably take an argument which specifies the size(in bytes and wide characters respectively) of the block of memory tooperate on. The array arguments and return values for these functionshave typevoid *
orwchar_t *
. As a matter of style, theelements of the arrays used with the ‘mem’ functions are referredto as “bytes”. You can pass any kind of pointer to these functions,and thesizeof
operator is useful in computing the value for thesize argument. Parameters to the ‘wmem’ functions must be of typewchar_t *
. These functions are not really usable with anythingbut arrays of this type.
In contrast, functions that operate specifically on strings and widestrings have names beginning with ‘str’ and ‘wcs’respectively (such asstrcpy
andwcscpy
) and look for aterminating null byte or null wide character instead of requiring an explicitsize argument to be passed. (Some of these functions accept a specifiedmaximum length, but they also check for premature termination.)The array arguments and return values for thesefunctions have typechar *
andwchar_t *
respectively, andthe array elements are referred to as “bytes” and “widecharacters”.
In many cases, there are both ‘mem’ and ‘str’/‘wcs’versions of a function. The one that is more appropriate to use dependson the exact situation. When your program is manipulating arbitraryarrays or blocks of storage, then you should always use the ‘mem’functions. On the other hand, when you are manipulatingstrings it is usually more convenient to use the ‘str’/‘wcs’functions, unless you already know the length of the string in advance.The ‘wmem’ functions should be used for wide character arrays withknown size.
Some of the memory and string functions take single characters asarguments. Since a value of typechar
is automatically promotedinto a value of typeint
when used as a parameter, the functionsare declared withint
as the type of the parameter in question.In case of the wide character functions the situation is similar: theparameter type for a single wide character iswint_t
and notwchar_t
. This would for many implementations not be necessarysincewchar_t
is large enough to not be automaticallypromoted, but since the ISO C standard does not require such achoice of types thewint_t
type is used.
Next:Copying Strings and Arrays, Previous:String and Array Conventions, Up:String and Array Utilities [Contents][Index]
You can get the length of a string using thestrlen
function.This function is declared in the header filestring.h.
size_t
strlen(const char *s)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrlen
function returns the length of thestrings in bytes. (In other words, it returns the offset of theterminating null byte within the array.)
For example,
strlen ("hello, world") ⇒ 12
When applied to an array, thestrlen
function returnsthe length of the string stored there, not its allocated size. You canget the allocated size of the array that holds a string usingthesizeof
operator:
char string[32] = "hello, world";sizeof (string) ⇒ 32strlen (string) ⇒ 12
But beware, this will not work unlessstring is thearray itself, not a pointer to it. For example:
char string[32] = "hello, world";char *ptr = string;sizeof (string) ⇒ 32sizeof (ptr) ⇒ 4 /*(on a machine with 4 byte pointers) */
This is an easy mistake to make when you are working with functions thattake string arguments; those arguments are always pointers, not arrays.
It must also be noted that for multibyte encoded strings the returnvalue does not have to correspond to the number of characters in thestring. To get this value the string can be converted to widecharacters andwcslen
can be used or something like the followingcode can be used:
/*The input is instring
.The length is expected inn
. */{ mbstate_t t; char *scopy = string; /* In initial state. */ memset (&t, '\0', sizeof (t)); /* Determine number of characters. */ n = mbsrtowcs (NULL, &scopy, strlen (scopy), &t);}
This is cumbersome to do so if the number of characters (as opposed tobytes) is needed often it is better to work with wide characters.
The wide character equivalent is declared inwchar.h.
size_t
wcslen(const wchar_t *ws)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcslen
function is the wide character equivalent tostrlen
. The return value is the number of wide characters in thewide string pointed to byws (this is also the offset ofthe terminating null wide character ofws).
Since there are no multi wide character sequences making up one widecharacter the return value is not only the offset in the array, it isalso the number of wide characters.
This function was introduced in Amendment 1 to ISO C90.
size_t
strnlen(const char *s, size_tmaxlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This returns the offset of the first null byte in the arrays,except that it returnsmaxlen if the firstmaxlen bytesare all non-null.Therefore this function is equivalent to(strlen (s) <maxlen ? strlen (s) :maxlen)
but itis more efficient and works even ifs is not null-terminated solong asmaxlen does not exceed the size ofs’s array.
char string[32] = "hello, world";strnlen (string, 32) ⇒ 12strnlen (string, 5) ⇒ 5
This function is part of POSIX.1-2008 and later editions, but wasavailable in the GNU C Library and other systems as an extension long beforeit was standardized. It is declared instring.h.
size_t
wcsnlen(const wchar_t *ws, size_tmaxlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
wcsnlen
is the wide character equivalent tostrnlen
. Themaxlen parameter specifies the maximum number of wide characters.
This function is part of POSIX.1-2008 and later editions, and isdeclared inwchar.h.
Next:Concatenating Strings, Previous:String Length, Up:String and Array Utilities [Contents][Index]
You can use the functions described in this section to copy the contentsof strings, wide strings, and arrays. The ‘str’ and ‘mem’functions are declared instring.h while the ‘w’ functionsare declared inwchar.h.
A helpful way to remember the ordering of the arguments to the functionsin this section is that it corresponds to an assignment expression, withthe destination array specified to the left of the source array. Mostof these functions return the address of the destination array; a fewreturn the address of the destination’s terminating null, or of justpast the destination.
Most of these functions do not work properly if the source anddestination arrays overlap. For example, if the beginning of thedestination array overlaps the end of the source array, the originalcontents of that part of the source array may get overwritten before itis copied. Even worse, in the case of the string functions, the nullbyte marking the end of the string may be lost, and the copyfunction might get stuck in a loop trashing all the memory allocated toyour program.
All functions that have problems copying between overlapping arrays areexplicitly identified in this manual. In addition to functions in thissection, there are a few others likesprintf
(seeFormatted Output Functions) andscanf
(seeFormatted Input Functions).
void *
memcpy(void *restrictto, const void *restrictfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thememcpy
function copiessize bytes from the objectbeginning atfrom into the object beginning atto. Thebehavior of this function is undefined if the two arraysto andfrom overlap; usememmove
instead if overlapping is possible.
The value returned bymemcpy
is the value ofto.
Here is an example of how you might usememcpy
to copy thecontents of an array:
struct foo *oldarray, *newarray;int arraysize;...memcpy (new, old, arraysize * sizeof (struct foo));
wchar_t *
wmemcpy(wchar_t *restrictwto, const wchar_t *restrictwfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewmemcpy
function copiessize wide characters from the objectbeginning atwfrom into the object beginning atwto. Thebehavior of this function is undefined if the two arrayswto andwfrom overlap; usewmemmove
instead if overlapping is possible.
The following is a possible implementation ofwmemcpy
but thereare more optimizations possible.
wchar_t *wmemcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom, size_t size){ return (wchar_t *) memcpy (wto, wfrom, size * sizeof (wchar_t));}
The value returned bywmemcpy
is the value ofwto.
This function was introduced in Amendment 1 to ISO C90.
void *
mempcpy(void *restrictto, const void *restrictfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Themempcpy
function is nearly identical to thememcpy
function. It copiessize bytes from the object beginning atfrom
into the object pointed to byto. But instead ofreturning the value ofto it returns a pointer to the bytefollowing the last written byte in the object beginning atto.I.e., the value is((void *) ((char *)to +size))
.
This function is useful in situations where a number of objects shall becopied to consecutive memory positions.
void *combine (void *o1, size_t s1, void *o2, size_t s2){ void *result = malloc (s1 + s2); if (result != NULL) mempcpy (mempcpy (result, o1, s1), o2, s2); return result;}
This function is a GNU extension.
wchar_t *
wmempcpy(wchar_t *restrictwto, const wchar_t *restrictwfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewmempcpy
function is nearly identical to thewmemcpy
function. It copiessize wide characters from the objectbeginning atwfrom
into the object pointed to bywto. Butinstead of returning the value ofwto it returns a pointer to thewide character following the last written wide character in the objectbeginning atwto. I.e., the value iswto +size
.
This function is useful in situations where a number of objects shall becopied to consecutive memory positions.
The following is a possible implementation ofwmemcpy
but thereare more optimizations possible.
wchar_t *wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom, size_t size){ return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));}
This function is a GNU extension.
void *
memmove(void *to, const void *from, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
memmove
copies thesize bytes atfrom into thesize bytes atto, even if those two blocks of spaceoverlap. In the case of overlap,memmove
is careful to copy theoriginal values of the bytes in the block atfrom, including thosebytes which also belong to the block atto.
The value returned bymemmove
is the value ofto.
wchar_t *
wmemmove(wchar_t *wto, const wchar_t *wfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
wmemmove
copies thesize wide characters atwfrominto thesize wide characters atwto, even if those twoblocks of space overlap. In the case of overlap,wmemmove
iscareful to copy the original values of the wide characters in the blockatwfrom, including those wide characters which also belong to theblock atwto.
The following is a possible implementation ofwmemcpy
but thereare more optimizations possible.
wchar_t *wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom, size_t size){ return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));}
The value returned bywmemmove
is the value ofwto.
This function is a GNU extension.
void *
memccpy(void *restrictto, const void *restrictfrom, intc, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function copies no more thansize bytes fromfrom toto, stopping if a byte matchingc is found. The returnvalue is a pointer intoto one byte past wherec was copied,or a null pointer if no byte matchingc appeared in the firstsize bytes offrom.
void *
memset(void *block, intc, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function copies the value ofc (converted to anunsigned char
) into each of the firstsize bytes of theobject beginning atblock. It returns the value ofblock.
wchar_t *
wmemset(wchar_t *block, wchar_twc, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function copies the value ofwc into each of the firstsize wide characters of the object beginning atblock. Itreturns the value ofblock.
char *
strcpy(char *restrictto, const char *restrictfrom)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This copies bytes from the stringfrom (up to and includingthe terminating null byte) into the stringto. Likememcpy
, this function has undefined results if the stringsoverlap. The return value is the value ofto.
wchar_t *
wcscpy(wchar_t *restrictwto, const wchar_t *restrictwfrom)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This copies wide characters from the wide stringwfrom (up to andincluding the terminating null wide character) into the stringwto. Likewmemcpy
, this function has undefined results ifthe strings overlap. The return value is the value ofwto.
char *
strdup(const char *s)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function copies the strings into a newlyallocated string. The string is allocated usingmalloc
; seeUnconstrained Allocation. Ifmalloc
cannot allocate spacefor the new string,strdup
returns a null pointer. Otherwise itreturns a pointer to the new string.
wchar_t *
wcsdup(const wchar_t *ws)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function copies the wide stringwsinto a newly allocated string. The string is allocated usingmalloc
; seeUnconstrained Allocation. Ifmalloc
cannot allocate space for the new string,wcsdup
returns a nullpointer. Otherwise it returns a pointer to the new wide string.
This function is a GNU extension.
char *
stpcpy(char *restrictto, const char *restrictfrom)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likestrcpy
, except that it returns a pointer tothe end of the stringto (that is, the address of the terminatingnull byteto + strlen (from)
) rather than the beginning.
For example, this program usesstpcpy
to concatenate ‘foo’and ‘bar’ to produce ‘foobar’, which it then prints.
#include <string.h>#include <stdio.h>intmain (void){ char buffer[10]; char *to = buffer; to = stpcpy (to, "foo"); to = stpcpy (to, "bar"); puts (buffer); return 0;}
This function is part of POSIX.1-2008 and later editions, but wasavailable in the GNU C Library and other systems as an extension long beforeit was standardized.
Its behavior is undefined if the strings overlap. The function isdeclared instring.h.
wchar_t *
wcpcpy(wchar_t *restrictwto, const wchar_t *restrictwfrom)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likewcscpy
, except that it returns a pointer tothe end of the stringwto (that is, the address of the terminatingnull wide characterwto + wcslen (wfrom)
) rather than the beginning.
This function is not part of ISO or POSIX but was found useful whiledeveloping the GNU C Library itself.
The behavior ofwcpcpy
is undefined if the strings overlap.
wcpcpy
is a GNU extension and is declared inwchar.h.
char *
strdupa(const char *s)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro is similar tostrdup
but allocates the new stringusingalloca
instead ofmalloc
(seeAutomatic Storage with Variable Size). This means of course the returned string has the samelimitations as any block of memory allocated usingalloca
.
For obvious reasonsstrdupa
is implemented only as a macro;you cannot get the address of this function. Despite this limitationit is a useful function. The following code shows a situation whereusingmalloc
would be a lot more expensive.
#include <paths.h>#include <string.h>#include <stdio.h>const char path[] = _PATH_STDPATH;intmain (void){ char *wr_path = strdupa (path); char *cp = strtok (wr_path, ":"); while (cp != NULL) { puts (cp); cp = strtok (NULL, ":"); } return 0;}
Please note that callingstrtok
usingpath directly isinvalid. It is also not allowed to callstrdupa
in the argumentlist ofstrtok
sincestrdupa
usesalloca
(seeAutomatic Storage with Variable Size) can interfere with the parameterpassing.
This function is only available if GNU CC is used.
void
bcopy(const void *from, void *to, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is a partially obsolete alternative formemmove
, derived fromBSD. Note that it is not quite equivalent tomemmove
, because thearguments are not in the same order and there is no return value.
void
bzero(void *block, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is a partially obsolete alternative formemset
, derived fromBSD. Note that it is not as general asmemset
, because the onlyvalue it can store is zero.
Next:Truncating Strings while Copying, Previous:Copying Strings and Arrays, Up:String and Array Utilities [Contents][Index]
The functions described in this section concatenate the contents of astring or wide string to another. They follow the string-copyingfunctions in their conventions. SeeCopying Strings and Arrays.‘strcat’ is declared in the header filestring.h while‘wcscat’ is declared inwchar.h.
As noted below, these functions are problematic as their callers mayhave performance issues.
char *
strcat(char *restrictto, const char *restrictfrom)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrcat
function is similar tostrcpy
, except that thebytes fromfrom are concatenated or appended to the end ofto, instead of overwriting it. That is, the first byte fromfrom overwrites the null byte marking the end ofto.
An equivalent definition forstrcat
would be:
char *strcat (char *restrict to, const char *restrict from){ strcpy (to + strlen (to), from); return to;}
This function has undefined results if the strings overlap.
As noted below, this function has significant performance issues.
wchar_t *
wcscat(wchar_t *restrictwto, const wchar_t *restrictwfrom)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcscat
function is similar towcscpy
, except that thewide characters fromwfrom are concatenated or appended to the end ofwto, instead of overwriting it. That is, the first wide character fromwfrom overwrites the null wide character marking the end ofwto.
An equivalent definition forwcscat
would be:
wchar_t *wcscat (wchar_t *wto, const wchar_t *wfrom){ wcscpy (wto + wcslen (wto), wfrom); return wto;}
This function has undefined results if the strings overlap.
As noted below, this function has significant performance issues.
Programmers using thestrcat
orwcscat
functions (or thestrlcat
,strncat
andwcsncat
functions defined ina later section, for that matter)can easily be recognized as lazy and reckless. In almost all situationsthe lengths of the participating strings are known (it better should besince how can one otherwise ensure the allocated size of the buffer issufficient?) Or at least, one could know them if one keeps track of theresults of the various function calls. But then it is very inefficientto usestrcat
/wcscat
. A lot of time is wasted finding theend of the destination string so that the actual copying can start.This is a common example:
/*This function concatenates arbitrarily many strings. The lastparameter must beNULL
. */char *concat (const char *str, ...){ va_list ap, ap2; size_t total = 1; va_start (ap, str); va_copy (ap2, ap); /*Determine how much space we need. */ for (const char *s = str; s != NULL; s = va_arg (ap, const char *)) total += strlen (s); va_end (ap); char *result = malloc (total); if (result != NULL) { result[0] = '\0'; /*Copy the strings. */ for (s = str; s != NULL; s = va_arg (ap2, const char *)) strcat (result, s); } va_end (ap2); return result;}
This looks quite simple, especially the second loop where the stringsare actually copied. But these innocent lines hide a major performancepenalty. Just imagine that ten strings of 100 bytes each have to beconcatenated. For the second string we search the already stored 100bytes for the end of the string so that we can append the next string.For all strings in total the comparisons necessary to find the end ofthe intermediate results sums up to 5500! If we combine the copyingwith the search for the allocation we can write this function moreefficiently:
char *concat (const char *str, ...){ size_t allocated = 100; char *result = malloc (allocated); if (result != NULL) { va_list ap; size_t resultlen = 0; char *newp; va_start (ap, str); for (const char *s = str; s != NULL; s = va_arg (ap, const char *)) { size_t len = strlen (s); /*Resize the allocated memory if necessary. */ if (resultlen + len + 1 > allocated) { allocated += len; newp = reallocarray (result, allocated, 2); allocated *= 2; if (newp == NULL) { free (result); return NULL; } result = newp; } memcpy (result + resultlen, s, len); resultlen += len; } /*Terminate the result string. */ result[resultlen++] = '\0'; /*Resize memory to the optimal size. */ newp = realloc (result, resultlen); if (newp != NULL) result = newp; va_end (ap); } return result;}
With a bit more knowledge about the input strings one could fine-tunethe memory allocation. The difference we are pointing to here is thatwe don’t usestrcat
anymore. We always keep track of the lengthof the current intermediate result so we can save ourselves the search for theend of the string and usemempcpy
. Please note that we alsodon’t usestpcpy
which might seem more natural since we are handlingstrings. But this is not necessary since we already know thelength of the string and therefore can use the faster memory copyingfunction. The example would work for wide characters the same way.
Whenever a programmer feels the need to usestrcat
she or heshould think twice and look through the program to see whether the code cannotbe rewritten to take advantage of already calculated results.The related functionsstrlcat
,strncat
,wcscat
andwcsncat
are almost always unnecessary, too.Again: it is almost always unnecessary to use functions likestrcat
.
Next:String/Array Comparison, Previous:Concatenating Strings, Up:String and Array Utilities [Contents][Index]
The functions described in this section copy or concatenate thepossibly-truncated contents of a string or array to another, andsimilarly for wide strings. They follow the string-copying functionsin their header conventions. SeeCopying Strings and Arrays. The‘str’ functions are declared in the header filestring.hand the ‘wc’ functions are declared in the filewchar.h.
As noted below, these functions are problematic as their callers mayhave truncation-related bugs and performance issues.
char *
strncpy(char *restrictto, const char *restrictfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar tostrcpy
but always copies exactlysize bytes intoto.
Iffrom does not contain a null byte in its firstsizebytes,strncpy
copies just the firstsize bytes. In thiscase no null terminator is written intoto.
Otherwisefrom must be a string with length less thansize. In this casestrncpy
copies all offrom,followed by enough null bytes to add up tosize bytes in all.
The behavior ofstrncpy
is undefined if the strings overlap.
This function was designed for now-rarely-used arrays consisting ofnon-null bytes followed by zero or more null bytes. It needs to setallsize bytes of the destination, even whensize is muchgreater than the length offrom. As noted below, this functionis generally a poor choice for processing strings.
wchar_t *
wcsncpy(wchar_t *restrictwto, const wchar_t *restrictwfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar towcscpy
but always copies exactlysize wide characters intowto.
Ifwfrom does not contain a null wide character in its firstsize wide characters, thenwcsncpy
copies just the firstsize wide characters. In this case no null terminator iswritten intowto.
Otherwisewfrom must be a wide string with length less thansize. In this casewcsncpy
copies all ofwfrom,followed by enough null wide characters to add up tosize widecharacters in all.
The behavior ofwcsncpy
is undefined if the strings overlap.
This function is the wide-character counterpart ofstrncpy
andsuffers from most of the problems thatstrncpy
does. Forexample, as noted below, this function is generally a poor choice forprocessing strings.
char *
strndup(const char *s, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function is similar tostrdup
but always copies at mostsize bytes into the newly allocated string.
If the length ofs is more thansize, thenstrndup
copies just the firstsize bytes and adds a closing null byte.Otherwise all bytes are copied and the string is terminated.
This function differs fromstrncpy
in that it always terminatesthe destination string.
As noted below, this function is generally a poor choice forprocessing strings.
strndup
is a GNU extension.
char *
strndupa(const char *s, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar tostrndup
but likestrdupa
itallocates the new string usingalloca
seeAutomatic Storage with Variable Size. The same advantages and limitations ofstrdupa
arevalid forstrndupa
, too.
This function is implemented only as a macro, just likestrdupa
.Just asstrdupa
this macro also must not be used inside theparameter list in a function call.
As noted below, this function is generally a poor choice forprocessing strings.
strndupa
is only available if GNU CC is used.
char *
stpncpy(char *restrictto, const char *restrictfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar tostpcpy
but copies always exactlysize bytes intoto.
If the length offrom is more thansize, thenstpncpy
copies just the firstsize bytes and returns a pointer to thebyte directly following the one which was copied last. Note that inthis case there is no null terminator written intoto.
If the length offrom is less thansize, thenstpncpy
copies all offrom, followed by enough null bytes to add uptosize bytes in all. This behavior is rarely useful, but itis implemented to be useful in contexts where this behavior of thestrncpy
is used.stpncpy
returns a pointer to thefirst written null byte.
This function is not part of ISO or POSIX but was found useful whiledeveloping the GNU C Library itself.
Its behavior is undefined if the strings overlap. The function isdeclared instring.h.
As noted below, this function is generally a poor choice forprocessing strings.
wchar_t *
wcpncpy(wchar_t *restrictwto, const wchar_t *restrictwfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar towcpcpy
but copies always exactlywsize wide characters intowto.
If the length ofwfrom is more thansize, thenwcpncpy
copies just the firstsize wide characters andreturns a pointer to the wide character directly following the lastnon-null wide character which was copied last. Note that in this casethere is no null terminator written intowto.
If the length ofwfrom is less thansize, thenwcpncpy
copies all ofwfrom, followed by enough null wide characters to add uptosize wide characters in all. This behavior is rarely useful, but itis implemented to be useful in contexts where this behavior of thewcsncpy
is used.wcpncpy
returns a pointer to thefirst written null wide character.
This function is not part of ISO or POSIX but was found useful whiledeveloping the GNU C Library itself.
Its behavior is undefined if the strings overlap.
As noted below, this function is generally a poor choice forprocessing strings.
wcpncpy
is a GNU extension.
char *
strncat(char *restrictto, const char *restrictfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likestrcat
except that not more thansizebytes fromfrom are appended to the end ofto, andfrom need not be null-terminated. A single null byte is alsoalways appended toto, so the totalallocated size ofto must be at leastsize + 1
byteslonger than its initial length.
Thestrncat
function could be implemented like this:
char *strncat (char *to, const char *from, size_t size){ size_t len = strlen (to); memcpy (to + len, from, strnlen (from, size)); to[len + strnlen (from, size)] = '\0'; return to;}
The behavior ofstrncat
is undefined if the strings overlap.
As a companion tostrncpy
,strncat
was designed fornow-rarely-used arrays consisting of non-null bytes followed by zeroor more null bytes. However, As noted below, this function is generally a poorchoice for processing strings. Also, this function has significantperformance issues. SeeConcatenating Strings.
wchar_t *
wcsncat(wchar_t *restrictwto, const wchar_t *restrictwfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likewcscat
except that not more thansizewide characters fromfrom are appended to the end ofto,andfrom need not be null-terminated. A single null widecharacter is also always appended toto, so the total allocatedsize ofto must be at leastwcsnlen (wfrom,size) + 1
wide characters longer than its initial length.
Thewcsncat
function could be implemented like this:
wchar_t *wcsncat (wchar_t *restrict wto, const wchar_t *restrict wfrom, size_t size){ size_t len = wcslen (wto); memcpy (wto + len, wfrom, wcsnlen (wfrom, size) * sizeof (wchar_t)); wto[len + wcsnlen (wfrom, size)] = L'\0'; return wto;}
The behavior ofwcsncat
is undefined if the strings overlap.
As noted below, this function is generally a poor choice forprocessing strings. Also, this function has significant performanceissues. SeeConcatenating Strings.
size_t
strlcpy(char *restrictto, const char *restrictfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function copies the stringfrom to the destination arrayto, limiting the result’s size (including the null terminator)tosize. The caller should ensure thatsize includes roomfor the result’s terminating null byte.
Ifsize is greater than the length of the stringfrom,this function copies the non-null bytes of the stringfrom to the destination arrayto,and terminates the copy with a null byte. Like otherstring functions such asstrcpy
, but unlikestrncpy
, anyremaining bytes in the destination array remain unchanged.
Ifsize is nonzero and less than or equal to the the length of the stringfrom, this function copies only the first ‘size - 1’bytes to the destination arrayto, and writes a terminating nullbyte to the last byte of the array.
This function returns the length of the stringfrom. This meansthat truncation occurs if and only if the returned value is greaterthan or equal tosize.
The behavior is undefined ifto orfrom is a null pointer,or if the destination array’s size is less thansize, or if thestringfrom overlaps the firstsize bytes of thedestination array.
As noted below, this function is generally a poor choice forprocessing strings. Also, this function has a performance issue,as its time cost is proportional to the length offromeven whensize is small.
This function was originally derived from OpenBSD 2.4, but was added inPOSIX.1-2024.
size_t
wcslcpy(wchar_t *restrictto, const wchar_t *restrictfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is a variant ofstrlcpy
for wide strings.Thesize argument counts the length of the destination buffer inwide characters (and not bytes).
This function was originally a BSD extension, but was added inPOSIX.1-2024.
size_t
strlcat(char *restrictto, const char *restrictfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function appends the stringfrom to thestringto, limiting the result’s total size (including the nullterminator) tosize. The caller should ensure thatsizeincludes room for the result’s terminating null byte.
This function copies as much as possible of the stringfrom intothe array atto ofsize bytes, starting at the terminatingnull byte of the original stringto. In effect, this appendsthe stringfrom to the stringto. Although the resultingstring will contain a null terminator, it can be truncated (not allbytes infrom may be copied).
This function returns the sum of the original length ofto andthe length offrom. This means that truncation occurs if andonly if the returned value is greater than or equal tosize.
The behavior is undefined ifto orfrom is a null pointer,or if the destination array’s size is less thansize, or if thedestination array does not contain a null byte in its firstsizebytes, or if the stringfrom overlaps the firstsize bytesof the destination array.
As noted below, this function is generally a poor choice forprocessing strings. Also, this function has significant performanceissues. SeeConcatenating Strings.
This function was originally derived from OpenBSD 2.4, but was added inPOSIX.1-2024.
size_t
wcslcat(wchar_t *restrictto, const wchar_t *restrictfrom, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is a variant ofstrlcat
for wide strings.Thesize argument counts the length of the destination buffer inwide characters (and not bytes).
This function was originally a BSD extension, but was added inPOSIX.1-2024.
Because these functions can abruptly truncate strings or wide strings,they are generally poor choices for processing them. When copying orconcatening multibyte strings, they can truncate within a multibytecharacter so that the result is not a valid multibyte string. Whencombining or concatenating multibyte or wide strings, they maytruncate the output after a combining character, resulting in acorrupted grapheme. They can cause bugs even when processingsingle-byte strings: for example, when calculating an ASCII-only username, a truncated name can identify the wrong user.
Although some buffer overruns can be prevented by manually replacingcalls to copying functions with calls to truncation functions, thereare often easier and safer automatic techniques, such as fortification(seeFortification of function calls) and AddressSanitizer(seeProgram Instrumentation Options inUsing GCC).Because truncation functions can maskapplication bugs that would otherwise be caught by the automatictechniques, these functions should be used only when the application’sunderlying logic requires truncation.
Note: GNU programs should not truncate strings or widestrings to fit arbitrary size limits. SeeWritingRobust Programs inThe GNU Coding Standards. Instead ofstring-truncation functions, it is usually better to use dynamicmemory allocation (seeUnconstrained Allocation) and functionssuch asstrdup
orasprintf
to construct strings.
Next:Collation Functions, Previous:Truncating Strings while Copying, Up:String and Array Utilities [Contents][Index]
You can use the functions in this section to perform comparisons on thecontents of strings and arrays. As well as checking for equality, thesefunctions can also be used as the ordering functions for sortingoperations. SeeSearching and Sorting, for an example of this.
Unlike most comparison operations in C, the string comparison functionsreturn a nonzero value if the strings arenot equivalent ratherthan if they are. The sign of the value indicates the relative orderingof the first part of the strings that are not equivalent: anegative value indicates that the first string is “less” than thesecond, while a positive value indicates that the first string is“greater”.
The most common use of these functions is to check only for equality.This is canonically done with an expression like ‘! strcmp (s1, s2)’.
All of these functions are declared in the header filestring.h.
int
memcmp(const void *a1, const void *a2, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functionmemcmp
compares thesize bytes of memorybeginning ata1 against thesize bytes of memory beginningata2. The value returned has the same sign as the differencebetween the first differing pair of bytes (interpreted asunsignedchar
objects, then promoted toint
).
If the contents of the two blocks are equal,memcmp
returns0
.
int
wmemcmp(const wchar_t *a1, const wchar_t *a2, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functionwmemcmp
compares thesize wide charactersbeginning ata1 against thesize wide characters beginningata2. The value returned is smaller than or larger than zerodepending on whether the first differing wide character isa1 issmaller or larger than the corresponding wide character ina2.
If the contents of the two blocks are equal,wmemcmp
returns0
.
On arbitrary arrays, thememcmp
function is mostly useful fortesting equality. It usually isn’t meaningful to do byte-wise orderingcomparisons on arrays of things other than bytes. For example, abyte-wise comparison on the bytes that make up floating-point numbersisn’t likely to tell you anything about the relationship between thevalues of the floating-point numbers.
wmemcmp
is really only useful to compare arrays of typewchar_t
since the function looks atsizeof (wchar_t)
bytesat a time and this number of bytes is system dependent.
You should also be careful about usingmemcmp
to compare objectsthat can contain “holes”, such as the padding inserted into structureobjects to enforce alignment requirements, extra space at the end ofunions, and extra bytes at the ends of strings whose length is lessthan their allocated size. The contents of these “holes” areindeterminate and may cause strange behavior when performing byte-wisecomparisons. For more predictable results, perform an explicitcomponent-wise comparison.
For example, given a structure type definition like:
struct foo { unsigned char tag; union { double f; long i; char *p; } value; };
you are better off writing a specialized comparison function to comparestruct foo
objects instead of comparing them withmemcmp
.
int
strcmp(const char *s1, const char *s2)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrcmp
function compares the strings1 againsts2, returning a value that has the same sign as the differencebetween the first differing pair of bytes (interpreted asunsigned char
objects, then promoted toint
).
If the two strings are equal,strcmp
returns0
.
A consequence of the ordering used bystrcmp
is that ifs1is an initial substring ofs2, thens1 is considered to be“less than”s2.
strcmp
does not take sorting conventions of the language thestrings are written in into account. To get that one has to usestrcoll
.
int
wcscmp(const wchar_t *ws1, const wchar_t *ws2)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcscmp
function compares the wide stringws1againstws2. The value returned is smaller than or larger than zerodepending on whether the first differing wide character isws1 issmaller or larger than the corresponding wide character inws2.
If the two strings are equal,wcscmp
returns0
.
A consequence of the ordering used bywcscmp
is that ifws1is an initial substring ofws2, thenws1 is considered to be“less than”ws2.
wcscmp
does not take sorting conventions of the language thestrings are written in into account. To get that one has to usewcscoll
.
int
strcasecmp(const char *s1, const char *s2)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likestrcmp
, except that differences in case areignored, and its arguments must be multibyte strings.How uppercase and lowercase characters are related isdetermined by the currently selected locale. In the standard"C"
locale the characters Ä and ä do not match but in a locale whichregards these characters as parts of the alphabet they do match.
strcasecmp
is derived from BSD.
int
wcscasecmp(const wchar_t *ws1, const wchar_t *ws2)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likewcscmp
, except that differences in case areignored. How uppercase and lowercase characters are related isdetermined by the currently selected locale. In the standard"C"
locale the characters Ä and ä do not match but in a locale whichregards these characters as parts of the alphabet they do match.
wcscasecmp
is a GNU extension.
int
strncmp(const char *s1, const char *s2, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is the similar tostrcmp
, except that no more thansize bytes are compared. In other words, if the twostrings are the same in their firstsize bytes, thereturn value is zero.
int
wcsncmp(const wchar_t *ws1, const wchar_t *ws2, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar towcscmp
, except that no more thansize wide characters are compared. In other words, if the twostrings are the same in their firstsize wide characters, thereturn value is zero.
int
strncasecmp(const char *s1, const char *s2, size_tn)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likestrncmp
, except that differences in caseare ignored, and the compared parts of the arguments should consist ofvalid multibyte characters.Likestrcasecmp
, it is locale dependent howuppercase and lowercase characters are related.
strncasecmp
is a GNU extension.
int
wcsncasecmp(const wchar_t *ws1, const wchar_t *s2, size_tn)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likewcsncmp
, except that differences in caseare ignored. Likewcscasecmp
, it is locale dependent howuppercase and lowercase characters are related.
wcsncasecmp
is a GNU extension.
Here are some examples showing the use ofstrcmp
andstrncmp
(equivalent examples can be constructed for the widecharacter functions). These examples assume the use of the ASCIIcharacter set. (If some other character set—say, EBCDIC—is usedinstead, then the glyphs are associated with different numeric codes,and the return values and ordering may differ.)
strcmp ("hello", "hello") ⇒ 0 /*These two strings are the same. */strcmp ("hello", "Hello") ⇒ 32 /*Comparisons are case-sensitive. */strcmp ("hello", "world") ⇒ -15 /*The byte'h'
comes before'w'
. */strcmp ("hello", "hello, world") ⇒ -44 /*Comparing a null byte against a comma. */strncmp ("hello", "hello, world", 5) ⇒ 0 /*The initial 5 bytes are the same. */strncmp ("hello, world", "hello, stupid world!!!", 5) ⇒ 0 /*The initial 5 bytes are the same. */
int
strverscmp(const char *s1, const char *s2)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrverscmp
function compares the strings1 againsts2, considering them as holding indices/version numbers. Thereturn value follows the same conventions as found in thestrcmp
function. In fact, ifs1 ands2 contain nodigits,strverscmp
behaves likestrcmp
(in the sense that the sign of the result is the same).
The comparison algorithm which thestrverscmp
function implementsdiffers slightly from other version-comparison algorithms. Theimplementation is based on a finite-state machine, whose behavior isapproximated below.
isdigit
function and arethus subject to the current locale.The treatment of leading zeros and the tie-breaking extension characters(which in effect propagate across non-digit/digit sequence boundaries)differs from other version-comparison algorithms.
strverscmp ("no digit", "no digit") ⇒ 0 /*same behavior as strcmp. */strverscmp ("item#99", "item#100") ⇒ <0 /*same prefix, but 99 < 100. */strverscmp ("alpha1", "alpha001") ⇒ >0 /*different number of leading zeros (0 and 2). */strverscmp ("part1_f012", "part1_f01") ⇒ >0 /*lexicographical comparison with leading zeros. */strverscmp ("foo.009", "foo.0") ⇒ <0 /*different number of leading zeros (2 and 1). */
strverscmp
is a GNU extension.
int
bcmp(const void *a1, const void *a2, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is an obsolete alias formemcmp
, derived from BSD.
Next:Search Functions, Previous:String/Array Comparison, Up:String and Array Utilities [Contents][Index]
In some locales, the conventions for lexicographic ordering differ fromthe strict numeric ordering of character codes. For example, in Spanishmost glyphs with diacritical marks such as accents are not considereddistinct letters for the purposes of collation. On the other hand, inCzech the two-character sequence ‘ch’ is treated as a single letterthat is collated between ‘h’ and ‘i’.
You can use the functionsstrcoll
andstrxfrm
(declared inthe headers filestring.h) andwcscoll
andwcsxfrm
(declared in the headers filewchar) to compare strings using acollation ordering appropriate for the current locale. The locale usedby these functions in particular can be specified by setting the localefor theLC_COLLATE
category; seeLocales and Internationalization.
In the standard C locale, the collation sequence forstrcoll
isthe same as that forstrcmp
. Similarly,wcscoll
andwcscmp
are the same in this situation.
Effectively, the way these functions work is by applying a mapping totransform the characters in a multibyte string to a bytesequence that representsthe string’s position in the collating sequence of the current locale.Comparing two such byte sequences in a simple fashion is equivalent tocomparing the strings with the locale’s collating sequence.
The functionsstrcoll
andwcscoll
perform this translationimplicitly, in order to do one comparison. By contrast,strxfrm
andwcsxfrm
perform the mapping explicitly. If you are makingmultiple comparisons using the same string or set of strings, it islikely to be more efficient to usestrxfrm
orwcsxfrm
totransform all the strings just once, and subsequently compare thetransformed strings withstrcmp
orwcscmp
.
int
strcoll(const char *s1, const char *s2)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thestrcoll
function is similar tostrcmp
but uses thecollating sequence of the current locale for collation (theLC_COLLATE
locale). The arguments are multibyte strings.
int
wcscoll(const wchar_t *ws1, const wchar_t *ws2)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thewcscoll
function is similar towcscmp
but uses thecollating sequence of the current locale for collation (theLC_COLLATE
locale).
Here is an example of sorting an array of strings, usingstrcoll
to compare them. The actual sort algorithm is not written here; itcomes fromqsort
(seeArray Sort Function). The job of thecode shown here is to say how to compare the strings while sorting them.(Later on in this section, we will show a way to do this moreefficiently usingstrxfrm
.)
/*This is the comparison function used withqsort
. */intcompare_elements (const void *v1, const void *v2){ char * const *p1 = v1; char * const *p2 = v2; return strcoll (*p1, *p2);}/*This is the entry point—the function to sortstrings using the locale’s collating sequence. */voidsort_strings (char **array, int nstrings){ /*Sorttemp_array
by comparing the strings. */ qsort (array, nstrings, sizeof (char *), compare_elements);}
size_t
strxfrm(char *restrictto, const char *restrictfrom, size_tsize)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
The functionstrxfrm
transforms the multibyte stringfrom using thecollation transformation determined by the locale currently selected forcollation, and stores the transformed string in the arrayto. Uptosize bytes (including a terminating null byte) arestored.
The behavior is undefined if the stringsto andfromoverlap; seeCopying Strings and Arrays.
The return value is the length of the entire transformed string. Thisvalue is not affected by the value ofsize, but if it is greateror equal thansize, it means that the transformed string did notentirely fit in the arrayto. In this case, only as much of thestring as actually fits was stored. To get the whole transformedstring, callstrxfrm
again with a bigger output array.
The transformed string may be longer than the original string, and itmay also be shorter.
Ifsize is zero, no bytes are stored into. In thiscase,strxfrm
simply returns the number of bytes that wouldbe the length of the transformed string. This is useful for determiningwhat size the allocated array should be. It does not matter whatto is ifsize is zero;to may even be a null pointer.
size_t
wcsxfrm(wchar_t *restrictwto, const wchar_t *wfrom, size_tsize)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
The functionwcsxfrm
transforms wide stringwfromusing the collation transformation determined by the locale currentlyselected for collation, and stores the transformed string in the arraywto. Up tosize wide characters (including a terminating nullwide character) are stored.
The behavior is undefined if the stringswto andwfromoverlap; seeCopying Strings and Arrays.
The return value is the length of the entire transformed widestring. This value is not affected by the value ofsize, but ifit is greater or equal thansize, it means that the transformedwide string did not entirely fit in the arraywto. Inthis case, only as much of the wide string as actually fitswas stored. To get the whole transformed wide string, callwcsxfrm
again with a bigger output array.
The transformed wide string may be longer than the originalwide string, and it may also be shorter.
Ifsize is zero, no wide characters are stored into. In thiscase,wcsxfrm
simply returns the number of wide characters thatwould be the length of the transformed wide string. This isuseful for determining what size the allocated array should be (rememberto multiply withsizeof (wchar_t)
). It does not matter whatwto is ifsize is zero;wto may even be a null pointer.
Here is an example of how you can usestrxfrm
whenyou plan to do many comparisons. It does the same thing as the previousexample, but much faster, because it has to transform each string onlyonce, no matter how many times it is compared with other strings. Eventhe time needed to allocate and free storage is much less than the timewe save, when there are many strings.
struct sorter { char *input; char *transformed; };/*This is the comparison function used withqsort
to sort an array ofstruct sorter
. */intcompare_elements (const void *v1, const void *v2){ const struct sorter *p1 = v1; const struct sorter *p2 = v2; return strcmp (p1->transformed, p2->transformed);}/*This is the entry point—the function to sortstrings using the locale’s collating sequence. */voidsort_strings_fast (char **array, int nstrings){ struct sorter temp_array[nstrings]; int i; /*Set uptemp_array
. Each element containsone input string and its transformed string. */ for (i = 0; i < nstrings; i++) { size_t length = strlen (array[i]) * 2; char *transformed; size_t transformed_length; temp_array[i].input = array[i]; /*First try a buffer perhaps big enough. */ transformed = (char *) xmalloc (length); /*Transformarray[i]
. */ transformed_length = strxfrm (transformed, array[i], length); /*If the buffer was not large enough, resize itand try again. */ if (transformed_length >= length) { /*Allocate the needed space. +1 for terminating'\0'
byte. */ transformed = xrealloc (transformed, transformed_length + 1); /*The return value is not interesting because we knowhow long the transformed string is. */ (void) strxfrm (transformed, array[i], transformed_length + 1); } temp_array[i].transformed = transformed; } /*Sorttemp_array
by comparing transformed strings. */ qsort (temp_array, nstrings, sizeof (struct sorter), compare_elements); /*Put the elements back in the permanent arrayin their sorted order. */ for (i = 0; i < nstrings; i++) array[i] = temp_array[i].input; /*Free the strings we allocated. */ for (i = 0; i < nstrings; i++) free (temp_array[i].transformed);}
The interesting part of this code for the wide character version wouldlook like this:
voidsort_strings_fast (wchar_t **array, int nstrings){ ... /*Transformarray[i]
. */ transformed_length = wcsxfrm (transformed, array[i], length); /*If the buffer was not large enough, resize itand try again. */ if (transformed_length >= length) { /*Allocate the needed space. +1 for terminatingL'\0'
wide character. */ transformed = xreallocarray (transformed, transformed_length + 1, sizeof *transformed); /*The return value is not interesting because we knowhow long the transformed string is. */ (void) wcsxfrm (transformed, array[i], transformed_length + 1); } ...
Note the additional multiplication withsizeof (wchar_t)
in therealloc
call.
Compatibility Note: The string collation functions are a newfeature of ISO C90. Older C dialects have no equivalent feature.The wide character versions were introduced in Amendment 1 to ISO C90.
Next:Finding Tokens in a String, Previous:Collation Functions, Up:String and Array Utilities [Contents][Index]
This section describes library functions which perform various kindsof searching operations on strings and arrays. These functions aredeclared in the header filestring.h.
void *
memchr(const void *block, intc, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function finds the first occurrence of the bytec (convertedto anunsigned char
) in the initialsize bytes of theobject beginning atblock. The return value is a pointer to thelocated byte, or a null pointer if no match was found.
wchar_t *
wmemchr(const wchar_t *block, wchar_twc, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function finds the first occurrence of the wide characterwcin the initialsize wide characters of the object beginning atblock. The return value is a pointer to the located widecharacter, or a null pointer if no match was found.
void *
rawmemchr(const void *block, intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Often thememchr
function is used with the knowledge that thebytec is available in the memory block specified by theparameters. But this means that thesize parameter is not reallyneeded and that the tests performed with it at runtime (to check whetherthe end of the block is reached) are not needed.
Therawmemchr
function exists for just this situation which issurprisingly frequent. The interface is similar tomemchr
exceptthat thesize parameter is missing. The function will look beyondthe end of the block pointed to byblock in case the programmermade an error in assuming that the bytec is present in the block.In this case the result is unspecified. Otherwise the return value is apointer to the located byte.
When looking for the end of a string, usestrchr
.
This function is a GNU extension.
void *
memrchr(const void *block, intc, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functionmemrchr
is likememchr
, except that it searchesbackwards from the end of the block defined byblock andsize(instead of forwards from the front).
This function is a GNU extension.
char *
strchr(const char *string, intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrchr
function finds the first occurrence of the bytec (converted to achar
) in the stringbeginning atstring. The return value is a pointer to the locatedbyte, or a null pointer if no match was found.
For example,
strchr ("hello, world", 'l') ⇒ "llo, world"strchr ("hello, world", '?') ⇒ NULL
The terminating null byte is considered to be part of the string,so you can use this function get a pointer to the end of a string byspecifying zero as the value of thec argument.
Whenstrchr
returns a null pointer, it does not let you knowthe position of the terminating null byte it has found. If youneed that information, it is better (but less portable) to usestrchrnul
than to search for it a second time.
wchar_t *
wcschr(const wchar_t *wstring, wchar_twc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcschr
function finds the first occurrence of the widecharacterwc in the wide stringbeginning atwstring. The return value is a pointer to thelocated wide character, or a null pointer if no match was found.
The terminating null wide character is considered to be part of the widestring, so you can use this function get a pointer to the endof a wide string by specifying a null wide character as thevalue of thewc argument. It would be better (but less portable)to usewcschrnul
in this case, though.
char *
strchrnul(const char *string, intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
strchrnul
is the same asstrchr
except that if it doesnot find the byte, it returns a pointer to string’s terminatingnull byte rather than a null pointer.
This function is a GNU extension.
wchar_t *
wcschrnul(const wchar_t *wstring, wchar_twc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
wcschrnul
is the same aswcschr
except that if it does notfind the wide character, it returns a pointer to the wide string’sterminating null wide character rather than a null pointer.
This function is a GNU extension.
One useful, but unusual, use of thestrchr
function is when one wants to have a pointer pointing to the null byteterminating a string. This is often written in this way:
s += strlen (s);
This is almost optimal but the addition operation duplicated a bit ofthe work already done in thestrlen
function. A better solutionis this:
s = strchr (s, '\0');
There is no restriction on the second parameter ofstrchr
so itcould very well also be zero. Those readers thinking veryhard about this might now point out that thestrchr
function ismore expensive than thestrlen
function since we have two abortcriteria. This is right. But in the GNU C Library the implementation ofstrchr
is optimized in a special way so thatstrchr
actually is faster.
char *
strrchr(const char *string, intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functionstrrchr
is likestrchr
, except that it searchesbackwards from the end of the stringstring (instead of forwardsfrom the front).
For example,
strrchr ("hello, world", 'l') ⇒ "ld"
wchar_t *
wcsrchr(const wchar_t *wstring, wchar_twc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functionwcsrchr
is likewcschr
, except that it searchesbackwards from the end of the stringwstring (instead of forwardsfrom the front).
char *
strstr(const char *haystack, const char *needle)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is likestrchr
, except that it searcheshaystack for asubstringneedle rather than just a single byte. Itreturns a pointer into the stringhaystack that is the firstbyte of the substring, or a null pointer if no match was found. Ifneedle is an empty string, the function returnshaystack.
For example,
strstr ("hello, world", "l") ⇒ "llo, world"strstr ("hello, world", "wo") ⇒ "world"
wchar_t *
wcsstr(const wchar_t *haystack, const wchar_t *needle)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is likewcschr
, except that it searcheshaystack for asubstringneedle rather than just a single wide character. Itreturns a pointer into the stringhaystack that is the first widecharacter of the substring, or a null pointer if no match was found. Ifneedle is an empty string, the function returnshaystack.
wchar_t *
wcswcs(const wchar_t *haystack, const wchar_t *needle)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
wcswcs
is a deprecated alias forwcsstr
. This is thename originally used in the X/Open Portability Guide before theAmendment 1 to ISO C90 was published.
char *
strcasestr(const char *haystack, const char *needle)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is likestrstr
, except that it ignores case in searching forthe substring. Likestrcasecmp
, it is locale dependent howuppercase and lowercase characters are related, and arguments aremultibyte strings.
For example,
strcasestr ("hello, world", "L") ⇒ "llo, world"strcasestr ("hello, World", "wo") ⇒ "World"
void *
memmem(const void *haystack, size_thaystack-len,
const void *needle, size_tneedle-len)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is likestrstr
, butneedle andhaystack are bytearrays rather than strings.needle-len is thelength ofneedle andhaystack-len is the length ofhaystack.
This function was originally a GNU extension, but was added inPOSIX.1-2024.
size_t
strspn(const char *string, const char *skipset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrspn
(“string span”) function returns the length of theinitial substring ofstring that consists entirely of bytes thatare members of the set specified by the stringskipset. The orderof the bytes inskipset is not important.
For example,
strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz") ⇒ 5
In a multibyte string, characters consisting ofmore than one byte are not treated as single entities. Each byte is treatedseparately. The function is not locale-dependent.
size_t
wcsspn(const wchar_t *wstring, const wchar_t *skipset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcsspn
(“wide character string span”) function returns thelength of the initial substring ofwstring that consists entirelyof wide characters that are members of the set specified by the stringskipset. The order of the wide characters inskipset is notimportant.
size_t
strcspn(const char *string, const char *stopset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrcspn
(“string complement span”) function returns the lengthof the initial substring ofstring that consists entirely of bytesthat arenot members of the set specified by the stringstopset.(In other words, it returns the offset of the first byte instringthat is a member of the setstopset.)
For example,
strcspn ("hello, world", " \t\n,.;!?") ⇒ 5
In a multibyte string, characters consisting ofmore than one byte are not treated as a single entities. Each byte is treatedseparately. The function is not locale-dependent.
size_t
wcscspn(const wchar_t *wstring, const wchar_t *stopset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcscspn
(“wide character string complement span”) functionreturns the length of the initial substring ofwstring thatconsists entirely of wide characters that arenot members of theset specified by the stringstopset. (In other words, it returnsthe offset of the first wide character instring that is a member ofthe setstopset.)
char *
strpbrk(const char *string, const char *stopset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrpbrk
(“string pointer break”) function is related tostrcspn
, except that it returns a pointer to the first byteinstring that is a member of the setstopset instead of thelength of the initial substring. It returns a null pointer if no suchbyte fromstopset is found.
For example,
strpbrk ("hello, world", " \t\n,.;!?") ⇒ ", world"
In a multibyte string, characters consisting ofmore than one byte are not treated as single entities. Each byte is treatedseparately. The function is not locale-dependent.
wchar_t *
wcspbrk(const wchar_t *wstring, const wchar_t *stopset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcspbrk
(“wide character string pointer break”) function isrelated towcscspn
, except that it returns a pointer to the firstwide character inwstring that is a member of the setstopset instead of the length of the initial substring. Itreturns a null pointer if no such wide character fromstopset is found.
char *
index(const char *string, intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
index
is another name forstrchr
; they are exactly the same.New code should always usestrchr
since this name is defined inISO C whileindex
is a BSD invention which never was availableon System V derived systems.
char *
rindex(const char *string, intc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
rindex
is another name forstrrchr
; they are exactly the same.New code should always usestrrchr
since this name is defined inISO C whilerindex
is a BSD invention which never was availableon System V derived systems.
Next:Erasing Sensitive Data, Previous:Search Functions, Up:String and Array Utilities [Contents][Index]
It’s fairly common for programs to have a need to do some simple kindsof lexical analysis and parsing, such as splitting a command string upinto tokens. You can do this with thestrtok
function, declaredin the header filestring.h.
char *
strtok(char *restrictnewstring, const char *restrictdelimiters)
¶Preliminary:| MT-Unsafe race:strtok| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
A string can be split into tokens by making a series of calls to thefunctionstrtok
.
The string to be split up is passed as thenewstring argument onthe first call only. Thestrtok
function uses this to set upsome internal state information. Subsequent calls to get additionaltokens from the same string are indicated by passing a null pointer asthenewstring argument. Callingstrtok
with anothernon-nullnewstring argument reinitializes the state information.It is guaranteed that no other library function ever callsstrtok
behind your back (which would mess up this internal state information).
Thedelimiters argument is a string that specifies a set of delimitersthat may surround the token being extracted. All the initial bytesthat are members of this set are discarded. The first byte that isnot a member of this set of delimiters marks the beginning of thenext token. The end of the token is found by looking for the nextbyte that is a member of the delimiter set. This byte in theoriginal stringnewstring is overwritten by a null byte, and thepointer to the beginning of the token innewstring is returned.
On the next call tostrtok
, the searching begins at the nextbyte beyond the one that marked the end of the previous token.Note that the set of delimitersdelimiters do not have to be thesame on every call in a series of calls tostrtok
.
If the end of the stringnewstring is reached, or if the remainder ofstring consists only of delimiter bytes,strtok
returnsa null pointer.
In a multibyte string, characters consisting ofmore than one byte are not treated as single entities. Each byte is treatedseparately. The function is not locale-dependent.
wchar_t *
wcstok(wchar_t *newstring, const wchar_t *delimiters, wchar_t **save_ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
A string can be split into tokens by making a series of calls to thefunctionwcstok
.
The string to be split up is passed as thenewstring argument onthe first call only. Thewcstok
function uses this to set upsome internal state information. Subsequent calls to get additionaltokens from the same wide string are indicated by passing anull pointer as thenewstring argument, which causes the pointerpreviously stored insave_ptr to be used instead.
Thedelimiters argument is a wide string that specifiesa set of delimiters that may surround the token being extracted. Allthe initial wide characters that are members of this set are discarded.The first wide character that isnot a member of this set ofdelimiters marks the beginning of the next token. The end of the tokenis found by looking for the next wide character that is a member of thedelimiter set. This wide character in the original widestringnewstring is overwritten by a null wide character, thepointer past the overwritten wide character is saved insave_ptr,and the pointer to the beginning of the token innewstring isreturned.
On the next call towcstok
, the searching begins at the nextwide character beyond the one that marked the end of the previous token.Note that the set of delimitersdelimiters do not have to be thesame on every call in a series of calls towcstok
.
If the end of the wide stringnewstring is reached, orif the remainder of string consists only of delimiter wide characters,wcstok
returns a null pointer.
Warning: Sincestrtok
andwcstok
alter the stringthey is parsing, you should always copy the string to a temporary bufferbefore parsing it withstrtok
/wcstok
(seeCopying Strings and Arrays). If you allowstrtok
orwcstok
to modifya string that came from another part of your program, you are asking fortrouble; that string might be used for other purposes afterstrtok
orwcstok
has modified it, and it would not havethe expected value.
The string that you are operating on might even be a constant. Thenwhenstrtok
orwcstok
tries to modify it, your programwill get a fatal signal for writing in read-only memory. SeeProgram Error Signals. Even if the operation ofstrtok
orwcstok
would not require a modification of the string (e.g., if there isexactly one token) the string can (and in the GNU C Library case will) bemodified.
This is a special case of a general principle: if a part of a programdoes not have as its purpose the modification of a certain datastructure, then it is error-prone to modify the data structuretemporarily.
The functionstrtok
is not reentrant, whereaswcstok
is.SeeSignal Handling and Nonreentrant Functions, for a discussion of where and why reentrancy isimportant.
Here is a simple example showing the use ofstrtok
.
#include <string.h>#include <stddef.h>...const char string[] = "words separated by spaces -- and, punctuation!";const char delimiters[] = " .,;:!-";char *token, *cp;...cp = strdupa (string); /* Make writable copy. */token = strtok (cp, delimiters); /* token => "words" */token = strtok (NULL, delimiters); /* token => "separated" */token = strtok (NULL, delimiters); /* token => "by" */token = strtok (NULL, delimiters); /* token => "spaces" */token = strtok (NULL, delimiters); /* token => "and" */token = strtok (NULL, delimiters); /* token => "punctuation" */token = strtok (NULL, delimiters); /* token => NULL */
The GNU C Library contains two more functions for tokenizing a stringwhich overcome the limitation of non-reentrancy. They are notavailable available for wide strings.
char *
strtok_r(char *newstring, const char *delimiters, char **save_ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Just likestrtok
, this function splits the string into severaltokens which can be accessed by successive calls tostrtok_r
.The difference is that, as inwcstok
, the information about thenext token is stored in the space pointed to by the third argument,save_ptr, which is a pointer to a string pointer. Callingstrtok_r
with a null pointer fornewstring and leavingsave_ptr between the calls unchanged does the job withouthindering reentrancy.
This function is defined in POSIX.1 and can be found on many systemswhich support multi-threading.
char *
strsep(char **string_ptr, const char *delimiter)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function has a similar functionality asstrtok_r
with thenewstring argument replaced by thesave_ptr argument. Theinitialization of the moving pointer has to be done by the user.Successive calls tostrsep
move the pointer along the tokensseparated bydelimiter, returning the address of the next tokenand updatingstring_ptr to point to the beginning of the nexttoken.
One difference betweenstrsep
andstrtok_r
is that if theinput string contains more than one byte fromdelimiter in arowstrsep
returns an empty string for each pair of bytesfromdelimiter. This means that a program normally should testforstrsep
returning an empty string before processing it.
This function was introduced in 4.3BSD and therefore is widely available.
Here is how the above example looks like whenstrsep
is used.
#include <string.h>#include <stddef.h>...const char string[] = "words separated by spaces -- and, punctuation!";const char delimiters[] = " .,;:!-";char *running;char *token;...running = strdupa (string);token = strsep (&running, delimiters); /* token => "words" */token = strsep (&running, delimiters); /* token => "separated" */token = strsep (&running, delimiters); /* token => "by" */token = strsep (&running, delimiters); /* token => "spaces" */token = strsep (&running, delimiters); /* token => "" */token = strsep (&running, delimiters); /* token => "" */token = strsep (&running, delimiters); /* token => "" */token = strsep (&running, delimiters); /* token => "and" */token = strsep (&running, delimiters); /* token => "" */token = strsep (&running, delimiters); /* token => "punctuation" */token = strsep (&running, delimiters); /* token => "" */token = strsep (&running, delimiters); /* token => NULL */
char *
basename(const char *filename)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The GNU version of thebasename
function returns the lastcomponent of the path infilename. This function is the preferredusage, since it does not modify the argument,filename, andrespects trailing slashes. The prototype forbasename
can befound instring.h. Note, this function is overridden by the XPGversion, iflibgen.h is included.
Example of using GNUbasename
:
#include <string.h>intmain (int argc, char *argv[]){ char *prog = basename (argv[0]); if (argc < 2) { fprintf (stderr, "Usage %s <arg>\n", prog); exit (1); } ...}
Portability Note: This function may produce different resultson different systems.
char *
basename(char *path)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is the standard XPG definedbasename
. It is similar inspirit to the GNU version, but may modify thepath by removingtrailing ’/’ bytes. If thepath is made up entirely of ’/’bytes, then "/" will be returned. Also, ifpath isNULL
or an empty string, then "." is returned. The prototype forthe XPG version can be found inlibgen.h.
Example of using XPGbasename
:
#include <libgen.h>intmain (int argc, char *argv[]){ char *prog; char *path = strdupa (argv[0]); prog = basename (path); if (argc < 2) { fprintf (stderr, "Usage %s <arg>\n", prog); exit (1); } ...}
char *
dirname(char *path)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thedirname
function is the compliment to the XPG version ofbasename
. It returns the parent directory of the file specifiedbypath. Ifpath isNULL
, an empty string, orcontains no ’/’ bytes, then "." is returned. The prototype for thisfunction can be found inlibgen.h.
Next:Shuffling Bytes, Previous:Finding Tokens in a String, Up:String and Array Utilities [Contents][Index]
Sensitive data, such as cryptographic keys, should be erased frommemory after use, to reduce the risk that a bug will expose it to theoutside world. However, compiler optimizations may determine that anerasure operation is “unnecessary,” and remove it from the generatedcode, because nocorrect program could access the variable orheap object containing the sensitive data after it’s deallocated.Since erasure is a precaution against bugs, this optimization isinappropriate.
The functionexplicit_bzero
erases a block of memory, andguarantees that the compiler will not remove the erasure as“unnecessary.”
#include <string.h>extern void encrypt (const char *key, const char *in, char *out, size_t n);extern void genkey (const char *phrase, char *key);void encrypt_with_phrase (const char *phrase, const char *in, char *out, size_t n){ char key[16]; genkey (phrase, key); encrypt (key, in, out, n); explicit_bzero (key, 16);}
In this example, ifmemset
,bzero
, or a hand-writtenloop had been used, the compiler might remove them as “unnecessary.”
Warning:explicit_bzero
does not guarantee thatsensitive data iscompletely erased from the computer’s memory.There may be copies in temporary storage areas, such as registers and“scratch” stack space; since these are invisible to the source code,a library function cannot erase them.
Also,explicit_bzero
only operates on RAM. If a sensitive dataobject never needs to have its address taken other than to callexplicit_bzero
, it might be stored entirely in CPU registersuntil the call toexplicit_bzero
. Then it will becopied into RAM, the copy will be erased, and the original will remainintact. Data in RAM is more likely to be exposed by a bug than datain registers, so this creates a brief window where the data is atgreater risk of exposure than it would have been if the program didn’ttry to erase it at all.
Declaring sensitive variables asvolatile
will make both theabove problemsworse; avolatile
variable will be storedin memory for its entire lifetime, and the compiler will makemore copies of it than it would otherwise have. Attempting toerase a normal variable “by hand” through avolatile
-qualified pointer doesn’t work at all—because thevariable itself is notvolatile
, some compilers will ignore thequalification on the pointer and remove the erasure anyway.
Having said all that, in most situations, usingexplicit_bzero
is better than not using it. At present, the only way to do a morethorough job is to write the entire sensitive operation in assemblylanguage. We anticipate that future compilers will recognize calls toexplicit_bzero
and take appropriate steps to erase all thecopies of the affected data, wherever they may be.
void
explicit_bzero(void *block, size_tlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
explicit_bzero
writes zero intolen bytes of memorybeginning atblock, just asbzero
would. The zeroes arealways written, even if the compiler could determine that this is“unnecessary” because no correct program could read them back.
Note: Theonly optimization thatexplicit_bzero
disables is removal of “unnecessary” writes to memory. The compilercan perform all the other optimizations that it could for a call tomemset
. For instance, it may replace the function call withinline memory writes, and it may assume thatblock cannot be anull pointer.
Portability Note: This function first appeared in OpenBSD 5.5and has not been standardized. Other systems may provide the samefunctionality under a different name, such asexplicit_memset
,memset_s
, orSecureZeroMemory
.
The GNU C Library declares this function instring.h, but on othersystems it may be instrings.h instead.
Next:Obfuscating Data, Previous:Erasing Sensitive Data, Up:String and Array Utilities [Contents][Index]
The function below addresses the perennial programming quandary: “How doI take good data in string form and painlessly turn it into garbage?”This is not a difficult thing to code for oneself, but the authors ofthe GNU C Library wish to make it as convenient as possible.
Toerase data, useexplicit_bzero
(seeErasing Sensitive Data); to obfuscate it reversibly, usememfrob
(seeObfuscating Data).
char *
strfry(char *string)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
strfry
performs an in-place shuffle onstring. Eachcharacter is swapped to a position selected at random, within theportion of the string starting with the character’s original position.(This is the Fisher-Yates algorithm for unbiased shuffling.)
Callingstrfry
will not disturb any of the random numbergenerators that have global state (seePseudo-Random Numbers).
The return value ofstrfry
is alwaysstring.
Portability Note: This function is unique to the GNU C Library.It is declared instring.h.
Next:Encode Binary Data, Previous:Shuffling Bytes, Up:String and Array Utilities [Contents][Index]
Thememfrob
function reversibly obfuscates an array of binarydata. This is not true encryption; the obfuscated data still bears aclear relationship to the original, and no secret key is required toundo the obfuscation. It is analogous to the “Rot13” cipher used onUsenet for obscuring offensive jokes, spoilers for works of fiction,and so on, but it can be applied to arbitrary binary data.
Programs that need true encryption—a transformation that completelyobscures the original and cannot be reversed without knowledge of asecret key—should use a dedicated cryptography library, such aslibgcrypt.
Programs that need todestroy data should useexplicit_bzero
(seeErasing Sensitive Data), or possiblystrfry
(seeShuffling Bytes).
void *
memfrob(void *mem, size_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functionmemfrob
obfuscateslength bytes of databeginning atmem, in place. Each byte is bitwise xor-ed withthe binary pattern 00101010 (hexadecimal 0x2A). The return value isalwaysmem.
memfrob
a second time on the same data returns it toits original state.
Portability Note: This function is unique to the GNU C Library.It is declared instring.h.
Next:Argz and Envz Vectors, Previous:Obfuscating Data, Up:String and Array Utilities [Contents][Index]
To store or transfer binary data in environments which only support textone has to encode the binary data by mapping the input bytes tobytes in the range allowed for storing or transferring. SVIDsystems (and nowadays XPG compliant systems) provide minimal support forthis task.
char *
l64a(long intn)
¶Preliminary:| MT-Unsafe race:l64a| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
This function encodes a 32-bit input value using bytes from thebasic character set. It returns a pointer to a 7 byte buffer whichcontains an encoded version ofn. To encode a series of bytes theuser must copy the returned string to a destination buffer. It returnsthe empty string ifn is zero, which is somewhat bizarre butmandated by the standard.
Warning: Since a static buffer is used this function should notbe used in multi-threaded programs. There is no thread-safe alternativeto this function in the C library.
Compatibility Note: The XPG standard states that the returnvalue ofl64a
is undefined ifn is negative. In the GNUimplementation,l64a
treats its argument as unsigned, so it willreturn a sensible encoding for any nonzeron; however, portableprograms should not rely on this.
To encode a large bufferl64a
must be called in a loop, once foreach 32-bit word of the buffer. For example, one could do somethinglike this:
char *encode (const void *buf, size_t len){ /*We know in advance how long the buffer has to be. */ unsigned char *in = (unsigned char *) buf; char *out = malloc (6 + ((len + 3) / 4) * 6 + 1); char *cp = out, *p; /*Encode the length. */ /*Using ‘htonl’ is necessary so that the data can bedecoded even on machines with different byte order.‘l64a’ can return a string shorter than 6 bytes, sowe pad it with encoding of 0 ('.') at the end byhand. */ p = stpcpy (cp, l64a (htonl (len))); cp = mempcpy (p, "......", 6 - (p - cp)); while (len > 3) { unsigned long int n = *in++; n = (n << 8) | *in++; n = (n << 8) | *in++; n = (n << 8) | *in++; len -= 4; p = stpcpy (cp, l64a (htonl (n))); cp = mempcpy (p, "......", 6 - (p - cp)); } if (len > 0) { unsigned long int n = *in++; if (--len > 0) { n = (n << 8) | *in++; if (--len > 0) n = (n << 8) | *in; } cp = stpcpy (cp, l64a (htonl (n))); } *cp = '\0'; return out;}
It is strange that the library does not provide the completefunctionality needed but so be it.
To decode data produced withl64a
the following function should beused.
long int
a64l(const char *string)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The parameterstring should contain a string which was produced bya call tol64a
. The function processes at least 6 bytes ofthis string, and decodes the bytes it finds according to the tablebelow. It stops decoding when it finds a byte not in the table,rather likeatoi
; if you have a buffer which has been broken intolines, you must be careful to skip over the end-of-line bytes.
The decoded number is returned as along int
value.
Thel64a
anda64l
functions use a base 64 encoding, inwhich each byte of an encoded string represents six bits of aninput word. These symbols are used for the base 64 digits:
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
0 | . | / | 0 | 1 | 2 | 3 | 4 | 5 |
8 | 6 | 7 | 8 | 9 | A | B | C | D |
16 | E | F | G | H | I | J | K | L |
24 | M | N | O | P | Q | R | S | T |
32 | U | V | W | X | Y | Z | a | b |
40 | c | d | e | f | g | h | i | j |
48 | k | l | m | n | o | p | q | r |
56 | s | t | u | v | w | x | y | z |
This encoding scheme is not standard. There are some other encodingmethods which are much more widely used (UU encoding, MIME encoding).Generally, it is better to use one of these encodings.
Previous:Encode Binary Data, Up:String and Array Utilities [Contents][Index]
argz vectors are vectors of strings in a contiguous block ofmemory, each element separated from its neighbors by null bytes('\0'
).
Envz vectors are an extension of argz vectors where each element is aname-value pair, separated by a'='
byte (as in a Unixenvironment).
Next:Envz Functions, Up:Argz and Envz Vectors [Contents][Index]
Each argz vector is represented by a pointer to the first element, oftypechar *
, and a size, of typesize_t
, both of which canbe initialized to0
to represent an empty argz vector. All argzfunctions accept either a pointer and a size argument, or pointers tothem, if they will be modified.
The argz functions usemalloc
/realloc
to allocate/growargz vectors, and so any argz vector created using these functions maybe freed by usingfree
; conversely, any argz function that maygrow a string expects that string to have been allocated usingmalloc
(those argz functions that only examine their arguments ormodify them in place will work on any sort of memory).SeeUnconstrained Allocation.
All argz functions that do memory allocation have a return type oferror_t
, and return0
for success, andENOMEM
if anallocation error occurs.
These functions are declared in the standard include fileargz.h.
error_t
argz_create(char *constargv[], char **argz, size_t *argz_len)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Theargz_create
function converts the Unix-style argument vectorargv (a vector of pointers to normal C strings, terminated by(char *)0
; seeProgram Arguments) into an argz vector withthe same elements, which is returned inargz andargz_len.
error_t
argz_create_sep(const char *string, intsep, char **argz, size_t *argz_len)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Theargz_create_sep
function converts the stringstring into an argz vector (returned inargz andargz_len) by splitting it into elements at every occurrence of thebytesep.
size_t
argz_count(const char *argz, size_targz_len)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns the number of elements in the argz vectorargz andargz_len.
void
argz_extract(const char *argz, size_targz_len, char **argv)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theargz_extract
function converts the argz vectorargz andargz_len into a Unix-style argument vector stored inargv,by putting pointers to every element inargz into successivepositions inargv, followed by a terminator of0
.Argv must be pre-allocated with enough space to hold all theelements inargz plus the terminating(char *)0
((argz_count (argz,argz_len) + 1) * sizeof (char *)
bytes should be enough). Note that the string pointers stored intoargv point intoargz—they are not copies—and soargz must be copied if it will be changed whileargv isstill active. This function is useful for passing the elements inargz to an exec function (seeExecuting a File).
void
argz_stringify(char *argz, size_tlen, intsep)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theargz_stringify
convertsargz into a normal string withthe elements separated by the bytesep, by replacing each'\0'
insideargz (except the last one, which terminates thestring) withsep. This is handy for printingargz in areadable manner.
error_t
argz_add(char **argz, size_t *argz_len, const char *str)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Theargz_add
function adds the stringstr to the end of theargz vector*argz
, and updates*argz
and*argz_len
accordingly.
error_t
argz_add_sep(char **argz, size_t *argz_len, const char *str, intdelim)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Theargz_add_sep
function is similar toargz_add
, butstr is split into separate elements in the result at occurrences ofthe bytedelim. This is useful, for instance, foradding the components of a Unix search path to an argz vector, by usinga value of':'
fordelim.
error_t
argz_append(char **argz, size_t *argz_len, const char *buf, size_tbuf_len)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Theargz_append
function appendsbuf_len bytes starting atbuf to the argz vector*argz
, reallocating*argz
to accommodate it, and addingbuf_len to*argz_len
.
void
argz_delete(char **argz, size_t *argz_len, char *entry)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Ifentry points to the beginning of one of the elements in theargz vector*argz
, theargz_delete
function willremove this entry and reallocate*argz
, modifying*argz
and*argz_len
accordingly. Note that asdestructive argz functions usually reallocate their argz argument,pointers into argz vectors such asentry will then become invalid.
error_t
argz_insert(char **argz, size_t *argz_len, char *before, const char *entry)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Theargz_insert
function inserts the stringentry into theargz vector*argz
at a point just before the existingelement pointed to bybefore, reallocating*argz
andupdating*argz
and*argz_len
. Ifbeforeis0
,entry is added to the end instead (as if byargz_add
). Since the first element is in fact the same as*argz
, passing in*argz
as the value ofbefore will result inentry being inserted at the beginning.
char *
argz_next(const char *argz, size_targz_len, const char *entry)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theargz_next
function provides a convenient way of iteratingover the elements in the argz vectorargz. It returns a pointerto the next element inargz after the elemententry, or0
if there are no elements followingentry. Ifentryis0
, the first element ofargz is returned.
This behavior suggests two styles of iteration:
char *entry = 0; while ((entry = argz_next (argz,argz_len, entry)))action;
(the double parentheses are necessary to make some C compilers shut upabout what they consider a questionablewhile
-test) and:
char *entry; for (entry =argz; entry; entry = argz_next (argz,argz_len, entry))action;
Note that the latter depends onargz having a value of0
ifit is empty (rather than a pointer to an empty block of memory); thisinvariant is maintained for argz vectors created by the functions here.
error_t
argz_replace(char **argz, size_t *argz_len, const char *str, const char *with, unsigned *replace_count)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Replace any occurrences of the stringstr inargz withwith, reallocatingargz as necessary. Ifreplace_count is non-zero,*replace_count
will beincremented by the number of replacements performed.
Previous:Argz Functions, Up:Argz and Envz Vectors [Contents][Index]
Envz vectors are just argz vectors with additional constraints on the formof each element; as such, argz functions can also be used on them, where itmakes sense.
Each element in an envz vector is a name-value pair, separated by a'='
byte; if multiple'='
bytes are present in an element, thoseafter the first are considered part of the value, and treated like all othernon-'\0'
bytes.
Ifno'='
bytes are present in an element, that element isconsidered the name of a “null” entry, as distinct from an entry with anempty value:envz_get
will return0
if given the name of nullentry, whereas an entry with an empty value would result in a value of""
;envz_entry
will still find such entries, however. Nullentries can be removed with theenvz_strip
function.
As with argz functions, envz functions that may allocate memory (and thusfail) have a return type oferror_t
, and return either0
orENOMEM
.
These functions are declared in the standard include fileenvz.h.
char *
envz_entry(const char *envz, size_tenvz_len, const char *name)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theenvz_entry
function finds the entry inenvz with the namename, and returns a pointer to the whole entry—that is, the argzelement which begins withname followed by a'='
byte. Ifthere is no entry with that name,0
is returned.
char *
envz_get(const char *envz, size_tenvz_len, const char *name)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theenvz_get
function finds the entry inenvz with the namename (likeenvz_entry
), and returns a pointer to the valueportion of that entry (following the'='
). If there is no entry withthat name (or only a null entry),0
is returned.
error_t
envz_add(char **envz, size_t *envz_len, const char *name, const char *value)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Theenvz_add
function adds an entry to*envz
(updating*envz
and*envz_len
) with the namename, and valuevalue. If an entry with the same namealready exists inenvz, it is removed first. Ifvalue is0
, then the new entry will be the special null type of entry(mentioned above).
error_t
envz_merge(char **envz, size_t *envz_len, const char *envz2, size_tenvz2_len, intoverride)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Theenvz_merge
function adds each entry inenvz2 toenvz,as if withenvz_add
, updating*envz
and*envz_len
. Ifoverride is true, then values inenvz2will supersede those with the same name inenvz, otherwise not.
Null entries are treated just like other entries in this respect, so a nullentry inenvz can prevent an entry of the same name inenvz2 frombeing added toenvz, ifoverride is false.
void
envz_strip(char **envz, size_t *envz_len)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theenvz_strip
function removes any null entries fromenvz,updating*envz
and*envz_len
.
void
envz_remove(char **envz, size_t *envz_len, const char *name)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Theenvz_remove
function removes an entry namedname fromenvz, updating*envz
and*envz_len
.
Next:Locales and Internationalization, Previous:String and Array Utilities, Up:Main Menu [Contents][Index]
Character sets used in the early days of computing had only six, seven,or eight bits for each character: there was never a case where more thaneight bits (one byte) were used to represent a single character. Thelimitations of this approach became more apparent as more peoplegrappled with non-Roman character sets, where not all the charactersthat make up a language’s character set can be represented by2^8choices. This chapter shows the functionality that was added to the Clibrary to support multiple character sets.
A variety of solutions are available to overcome the differences betweencharacter sets with a 1:1 relation between bytes and characters andcharacter sets with ratios of 2:1 or 4:1. The remainder of thissection gives a few examples to help understand the design decisionsmade while developing the functionality of the C library.
A distinction we have to make right away is between internal andexternal representation.Internal representation means therepresentation used by a program while keeping the text in memory.External representations are used when text is stored or transmittedthrough some communication channel. Examples of externalrepresentations include files waiting in a directory to beread and parsed.
Traditionally there has been no difference between the two representations.It was equally comfortable and useful to use the same single-byterepresentation internally and externally. This comfort level decreaseswith more and larger character sets.
One of the problems to overcome with the internal representation ishandling text that is externally encoded using different charactersets. Assume a program that reads two texts and compares them usingsome metric. The comparison can be usefully done only if the texts areinternally kept in a common format.
For such a common format (= character set) eight bits are certainlyno longer enough. So the smallest entity will have to grow:widecharacters will now be used. Instead of one byte per character, two orfour will be used instead. (Three are not good to address in memory andmore than four bytes seem not to be necessary).
As shown in some other part of this manual,a completely new family has been created of functions that can handle widecharacter texts in memory. The most commonly used character sets for suchinternal wide character representations are Unicode and ISO 10646(also known as UCS for Universal Character Set). Unicode was originallyplanned as a 16-bit character set; whereas, ISO 10646 was designed tobe a 31-bit large code space. The two standards are practically identical.They have the same character repertoire and code table, but Unicode specifiesadded semantics. At the moment, only characters in the first0x10000
code positions (the so-called Basic Multilingual Plane, BMP) have beenassigned, but the assignment of more specialized characters outside this16-bit space is already in progress. A number of encodings have beendefined for Unicode and ISO 10646 characters:UCS-2 is a 16-bit word that can only represent charactersfrom the BMP, UCS-4 is a 32-bit word than can represent any Unicodeand ISO 10646 character, UTF-8 is an ASCII compatible encoding whereASCII characters are represented by ASCII bytes and non-ASCII charactersby sequences of 2-6 non-ASCII bytes, and finally UTF-16 is an extensionof UCS-2 in which pairs of certain UCS-2 words can be used to encodenon-BMP characters up to0x10ffff
.
To represent wide characters thechar
type is not suitable. Forthis reason the ISO C standard introduces a new type that isdesigned to keep one character of a wide character string. To maintainthe similarity there is also a type corresponding toint
forthose functions that take a single wide character.
This data type is used as the base type for wide character strings.In other words, arrays of objects of this type are the equivalent ofchar[]
for multibyte character strings. The type is defined instddef.h.
The ISO C90 standard, wherewchar_t
was introduced, does notsay anything specific about the representation. It only requires thatthis type is capable of storing all elements of the basic character set.Therefore it would be legitimate to definewchar_t
aschar
,which might make sense for embedded systems.
But in the GNU C Librarywchar_t
is always 32 bits wide and, therefore,capable of representing all UCS-4 values and, therefore, covering all ofISO 10646. Some Unix systems definewchar_t
as a 16-bit typeand thereby follow Unicode very strictly. This definition is perfectlyfine with the standard, but it also means that to represent allcharacters from Unicode and ISO 10646 one has to use UTF-16 surrogatecharacters, which is in fact a multi-wide-character encoding. Butresorting to multi-wide-character encoding contradicts the purpose of thewchar_t
type.
wint_t
is a data type used for parameters and variables thatcontain a single wide character. As the name suggests this type is theequivalent ofint
when using the normalchar
strings. Thetypeswchar_t
andwint_t
often have the samerepresentation if their size is 32 bits wide but ifwchar_t
isdefined aschar
the typewint_t
must be defined asint
due to the parameter promotion.
This type is defined inwchar.h and was introduced inAmendment 1 to ISO C90.
As there are for thechar
data type macros are available forspecifying the minimum and maximum value representable in an object oftypewchar_t
.
wint_t
WCHAR_MIN ¶The macroWCHAR_MIN
evaluates to the minimum value representableby an object of typewint_t
.
This macro was introduced in Amendment 1 to ISO C90.
wint_t
WCHAR_MAX ¶The macroWCHAR_MAX
evaluates to the maximum value representableby an object of typewint_t
.
This macro was introduced in Amendment 1 to ISO C90.
Another special wide character value is the equivalent toEOF
.
wint_t
WEOF ¶The macroWEOF
evaluates to a constant expression of typewint_t
whose value is different from any member of the extendedcharacter set.
WEOF
need not be the same value asEOF
and unlikeEOF
it also neednot be negative. In other words, sloppycode like
{ int c; ... while ((c = getc (fp)) < 0) ...}
has to be rewritten to useWEOF
explicitly when wide charactersare used:
{ wint_t c; ... while ((c = getwc (fp)) != WEOF) ...}
This macro was introduced in Amendment 1 to ISO C90 and isdefined inwchar.h.
These internal representations present problems when it comes to storageand transmittal. Because each single wide character consists of morethan one byte, they are affected by byte-ordering. Thus, machines withdifferent endianesses would see different values when accessing the samedata. This byte ordering concern also applies for communication protocolsthat are all byte-based and therefore require that the sender has todecide about splitting the wide character in bytes. A last (but not leastimportant) point is that wide characters often require more storage spacethan a customized byte-oriented character set.
For all the above reasons, an external encoding that is different fromthe internal encoding is often used if the latter is UCS-2 or UCS-4.The external encoding is byte-based and can be chosen appropriately forthe environment and for the texts to be handled. A variety of differentcharacter sets can be used for this external encoding (information thatwill not be exhaustively presented here–instead, a description of themajor groups will suffice). All of the ASCII-based character setsfulfill one requirement: they are "filesystem safe." This means thatthe character'/'
is used in the encodingonly torepresent itself. Things are a bit different for character sets likeEBCDIC (Extended Binary Coded Decimal Interchange Code, a character setfamily used by IBM), but if the operating system does not understandEBCDIC directly the parameters-to-system calls have to be convertedfirst anyhow.
In most uses of ISO 2022 the defined character sets do not allowstate changes that cover more than the next character. This has thebig advantage that whenever one can identify the beginning of the bytesequence of a character one can interpret a text correctly. Examples ofcharacter sets using this policy are the various EUC character sets(used by Sun’s operating systems, EUC-JP, EUC-KR, EUC-TW, and EUC-CN)or Shift_JIS (SJIS, a Japanese encoding).
But there are also character sets using a state that is valid for morethan one character and has to be changed by another byte sequence.Examples for this are ISO-2022-JP, ISO-2022-KR, and ISO-2022-CN.
0xc2 0x61
(non-spacing acute accent, followed by lower-case ‘a’) to get the “smalla with acute” character. To get the acute accent character on its own,one has to write0xc2 0x20
(the non-spacing acute followed by aspace).Character sets like ISO 6937 are used in some embedded systems suchas teletex.
There were a few other attempts to encode ISO 10646 such as UTF-7,but UTF-8 is today the only encoding that should be used. In fact, withany luck UTF-8 will soon be the only external encoding that has to besupported. It proves to be universally usable and its only disadvantageis that it favors Roman languages by making the byte stringrepresentation of other scripts (Cyrillic, Greek, Asian scripts) longerthan necessary if using a specific character set for these scripts.Methods like the Unicode compression scheme can alleviate theseproblems.
The question remaining is: how to select the character set or encodingto use. The answer: you cannot decide about it yourself, it is decidedby the developers of the system or the majority of the users. Since thegoal is interoperability one has to use whatever the other people oneworks with use. If there are no constraints, the selection is based onthe requirements the expected circle of users will have. In other words,if a project is expected to be used in only, say, Russia it is fine to useKOI8-R or a similar character set. But if at the same time people from,say, Greece are participating one should use a character set that allowsall people to collaborate.
The most widely useful solution seems to be: go with the most generalcharacter set, namely ISO 10646. Use UTF-8 as the external encodingand problems about users not being able to use their own languageadequately are a thing of the past.
One final comment about the choice of the wide character representationis necessary at this point. We have said above that the natural choiceis using Unicode or ISO 10646. This is not required, but at leastencouraged, by the ISO C standard. The standard defines at least amacro__STDC_ISO_10646__
that is only defined on systems wherethewchar_t
type encodes ISO 10646 characters. If thissymbol is not defined one should avoid making assumptions about the widecharacter representation. If the programmer uses only the functionsprovided by the C library to handle wide character strings there shouldbe no compatibility problems with other systems.
Next:Restartable Multibyte Conversion Functions, Previous:Introduction to Extended Characters, Up:Character Set Handling [Contents][Index]
A Unix C library contains three different sets of functions in twofamilies to handle character set conversion. One of the function families(the most commonly used) is specified in the ISO C90 standard and,therefore, is portable even beyond the Unix world. Unfortunately thisfamily is the least useful one. These functions should be avoidedwhenever possible, especially when developing libraries (as opposed toapplications).
The second family of functions got introduced in the early Unix standards(XPG2) and is still part of the latest and greatest Unix standard:Unix 98. It is also the most powerful and useful set of functions.But we will start with the functions defined in Amendment 1 toISO C90.
Next:Non-reentrant Conversion Function, Previous:Overview about Character Handling Functions, Up:Character Set Handling [Contents][Index]
The ISO C standard defines functions to convert strings from amultibyte representation to wide character strings. There are a numberof peculiarities:
LC_CTYPE
category of the current locale is used; seeLocale Categories.Despite these limitations the ISO C functions can be used in manycontexts. In graphical user interfaces, for instance, it is notuncommon to have functions that require text to be displayed in a widecharacter string if the text is not simple ASCII. The text itself mightcome from a file with translations and the user should decide about thecurrent locale, which determines the translation and therefore also theexternal encoding used. In such a situation (and many others) thefunctions described here are perfect. If more freedom while performingthe conversion is necessary take a look at theiconv
functions(seeGeneric Charset Conversion).
Next:Representing the state of the conversion, Up:Restartable Multibyte Conversion Functions [Contents][Index]
We already said above that the currently selected locale for theLC_CTYPE
category decides the conversion that is performedby the functions we are about to describe. Each locale uses its owncharacter set (given as an argument tolocaledef
) and this is theone assumed as the external multibyte encoding. The wide characterset is always UCS-4 in the GNU C Library.
A characteristic of each multibyte character set is the maximum numberof bytes that can be necessary to represent one character. Thisinformation is quite important when writing code that uses theconversion functions (as shown in the examples below).The ISO C standard defines two macros that provide this information.
int
MB_LEN_MAX ¶MB_LEN_MAX
specifies the maximum number of bytes in the multibytesequence for a single character in any of the supported locales. It isa compile-time constant and is defined inlimits.h.
int
MB_CUR_MAX ¶MB_CUR_MAX
expands into a positive integer expression that is themaximum number of bytes in a multibyte character in the current locale.The value is never greater thanMB_LEN_MAX
. UnlikeMB_LEN_MAX
this macro need not be a compile-time constant, and inthe GNU C Library it is not.
MB_CUR_MAX
is defined instdlib.h.
Two different macros are necessary since strictly ISO C90 compilersdo not allow variable length array definitions, but still it is desirableto avoid dynamic allocation. This incomplete piece of code shows theproblem:
{ char buf[MB_LEN_MAX]; ssize_t len = 0; while (! feof (fp)) { fread (&buf[len], 1, MB_CUR_MAX - len, fp); /*... process buf */ len -= used; }}
The code in the inner loop is expected to have always enough bytes inthe arraybuf to convert one multibyte character. The arraybuf has to be sized statically since many compilers do not allow avariable size. Thefread
call makes sure thatMB_CUR_MAX
bytes are always available inbuf. Note that it isn’ta problem ifMB_CUR_MAX
is not a compile-time constant.
Next:Converting Single Characters, Previous:Selecting the conversion and its properties, Up:Restartable Multibyte Conversion Functions [Contents][Index]
In the introduction of this chapter it was said that certain charactersets use astateful encoding. That is, the encoded values dependin some way on the previous bytes in the text.
Since the conversion functions allow converting a text in more than onestep we must have a way to pass this information from one call of thefunctions to another.
A variable of typembstate_t
can contain all the informationabout theshift state needed from one call to a conversionfunction to another.
mbstate_t
is defined inwchar.h. It was introduced inAmendment 1 to ISO C90.
To use objects of typembstate_t
the programmer has to define suchobjects (normally as local variables on the stack) and pass a pointer tothe object to the conversion functions. This way the conversion functioncan update the object if the current multibyte character set is stateful.
There is no specific function or initializer to put the state object inany specific state. The rules are that the object should alwaysrepresent the initial state before the first use, and this is achieved byclearing the whole variable with code such as follows:
{ mbstate_t state; memset (&state, '\0', sizeof (state)); /*from now onstate can be used. */ ...}
When using the conversion functions to generate output it is oftennecessary to test whether the current state corresponds to the initialstate. This is necessary, for example, to decide whether to emitescape sequences to set the state to the initial state at certainsequence points. Communication protocols often require this.
int
mbsinit(const mbstate_t *ps)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thembsinit
function determines whether the state object pointedto byps is in the initial state. Ifps is a null pointer orthe object is in the initial state the return value is nonzero. Otherwiseit is zero.
mbsinit
was introduced in Amendment 1 to ISO C90 and isdeclared inwchar.h.
Code usingmbsinit
often looks similar to this:
{ mbstate_t state; memset (&state, '\0', sizeof (state)); /*Usestate. */ ... if (! mbsinit (&state)) { /*Emit code to return to initial state. */ const wchar_t empty[] = L""; const wchar_t *srcp = empty; wcsrtombs (outbuf, &srcp, outbuflen, &state); } ...}
The code to emit the escape sequence to get back to the initial state isinteresting. Thewcsrtombs
function can be used to determine thenecessary output code (seeConverting Multibyte and Wide Character Strings). Please note that withthe GNU C Library it is not necessary to perform this extra action for theconversion from multibyte text to wide character text since the widecharacter encoding is not stateful. But there is nothing mentioned inany standard that prohibits makingwchar_t
use a statefulencoding.
Next:Converting Multibyte and Wide Character Strings, Previous:Representing the state of the conversion, Up:Restartable Multibyte Conversion Functions [Contents][Index]
The most fundamental of the conversion functions are those dealing withsingle characters. Please note that this does not always mean singlebytes. But since there is very often a subset of the multibytecharacter set that consists of single byte sequences, there arefunctions to help with converting bytes. Frequently, ASCII is a subsetof the multibyte character set. In such a scenario, each ASCII characterstands for itself, and all other characters have at least a first bytethat is beyond the range0 to127.
wint_t
btowc(intc)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thebtowc
function (“byte to wide character”) converts a validsingle byte characterc in the initial shift state into the widecharacter equivalent using the conversion rules from the currentlyselected locale of theLC_CTYPE
category.
If(unsigned char)c
is no valid single byte multibytecharacter or ifc isEOF
, the function returnsWEOF
.
Please note the restriction ofc being tested for validity only inthe initial shift state. Nombstate_t
object is used fromwhich the state information is taken, and the function also does not useany static state.
Thebtowc
function was introduced in Amendment 1 to ISO C90and is declared inwchar.h.
Despite the limitation that the single byte value is always interpretedin the initial state, this function is actually useful most of the time.Most characters are either entirely single-byte character sets or theyare extensions to ASCII. But then it is possible to write code like this(not that this specific example is very useful):
wchar_t *itow (unsigned long int val){ static wchar_t buf[30]; wchar_t *wcp = &buf[29]; *wcp = L'\0'; while (val != 0) { *--wcp = btowc ('0' + val % 10); val /= 10; } if (wcp == &buf[29]) *--wcp = L'0'; return wcp;}
Why is it necessary to use such a complicated implementation and notsimply cast'0' + val % 10
to a wide character? The answer isthat there is no guarantee that one can perform this kind of arithmeticon the character of the character set used forwchar_t
representation. In other situations the bytes are not constant atcompile time and so the compiler cannot do the work. In situations likethis, usingbtowc
is required.
There is also a function for the conversion in the other direction.
int
wctob(wint_tc)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thewctob
function (“wide character to byte”) takes as theparameter a valid wide character. If the multibyte representation forthis character in the initial state is exactly one byte long, the returnvalue of this function is this character. Otherwise the return value isEOF
.
wctob
was introduced in Amendment 1 to ISO C90 andis declared inwchar.h.
There are more general functions to convert single characters frommultibyte representation to wide characters and vice versa. Thesefunctions pose no limit on the length of the multibyte representationand they also do not require it to be in the initial state.
size_t
mbrtowc(wchar_t *restrictpwc, const char *restricts, size_tn, mbstate_t *restrictps)
¶Preliminary:| MT-Unsafe race:mbrtowc/!ps| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thembrtowc
function (“multibyte restartable to widecharacter”) converts the next multibyte character in the string pointedto bys into a wide character and stores it in the locationpointed to bypwc. The conversion is performed accordingto the locale currently selected for theLC_CTYPE
category. Ifthe conversion for the character set used in the locale requires a state,the multibyte string is interpreted in the state represented by theobject pointed to byps. Ifps is a null pointer, a static,internal state variable used only by thembrtowc
function isused.
If the next multibyte character corresponds to the null wide character,the return value of the function is0 and the state object isafterwards in the initial state. If the nextn or fewer bytesform a correct multibyte character, the return value is the number ofbytes starting froms that form the multibyte character. Theconversion state is updated according to the bytes consumed in theconversion. In both cases the wide character (either theL'\0'
or the one found in the conversion) is stored in the string pointed tobypwc ifpwc is not null.
If the firstn bytes of the multibyte string possibly form a validmultibyte character but there are more thann bytes needed tocomplete it, the return value of the function is(size_t) -2
andno value is stored in*pwc
. The conversion state isupdated and alln input bytes are consumed and should not besubmitted again. Please note that this can happen even ifn has avalue greater than or equal toMB_CUR_MAX
since the input mightcontain redundant shift sequences.
If the firstn
bytes of the multibyte string cannot possibly forma valid multibyte character, no value is stored, the global variableerrno
is set to the valueEILSEQ
, and the function returns(size_t) -1
. The conversion state is afterwards undefined.
As specified, thembrtowc
function could deal with multibytesequences which contain embedded null bytes (which happens in Unicodeencodings such as UTF-16), but the GNU C Library does not support suchmultibyte encodings. When encountering a null input byte, the functionwill either return zero, or return(size_t) -1)
and report aEILSEQ
error. Theiconv
function can be used forconverting between arbitrary encodings. SeeGeneric Character Set Conversion Interface.
mbrtowc
was introduced in Amendment 1 to ISO C90 andis declared inwchar.h.
A function that copies a multibyte string into a wide character stringwhile at the same time converting all lowercase characters intouppercase could look like this:
wchar_t *mbstouwcs (const char *s){ /*Include the null terminator in the conversion. */ size_t len = strlen (s) + 1; wchar_t *result = reallocarray (NULL, len, sizeof (wchar_t)); if (result == NULL) return NULL; wchar_t *wcp = result; mbstate_t state; memset (&state, '\0', sizeof (state)); while (true) { wchar_t wc; size_t nbytes = mbrtowc (&wc, s, len, &state); if (nbytes == 0) { /*Terminate the result string. */ *wcp = L'\0'; break; } else if (nbytes == (size_t) -2) { /*Truncated input string. */ errno = EILSEQ; free (result); return NULL; } else if (nbytes == (size_t) -1) { /*Some other error (including EILSEQ). */ free (result); return NULL; } else { /*A character was converted. */ *wcp++ = towupper (wc); len -= nbytes; s += nbytes; } } return result;}
In the inner loop, a single wide character is stored inwc
, andthe number of consumed bytes is stored in the variablenbytes
.If the conversion is successful, the uppercase variant of the widecharacter is stored in theresult
array and the pointer to theinput string and the number of available bytes is adjusted. If thembrtowc
function returns zero, the null input byte has not beenconverted, so it must be stored explicitly in the result.
The above code uses the fact that there can never be more widecharacters in the converted result than there are bytes in the multibyteinput string. This method yields a pessimistic guess about the size ofthe result, and if many wide character strings have to be constructedthis way or if the strings are long, the extra memory required to beallocated because the input string contains multibyte characters mightbe significant. The allocated memory block can be resized to thecorrect size before returning it, but a better solution might be toallocate just the right amount of space for the result right away.Unfortunately there is no function to compute the length of the widecharacter string directly from the multibyte string. There is, however,a function that does part of the work.
size_t
mbrlen(const char *restricts, size_tn, mbstate_t *ps)
¶Preliminary:| MT-Unsafe race:mbrlen/!ps| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thembrlen
function (“multibyte restartable length”) computesthe number of at mostn bytes starting ats, which form thenext valid and complete multibyte character.
If the next multibyte character corresponds to the NUL wide character,the return value is0. If the nextn bytes form a validmultibyte character, the number of bytes belonging to this multibytecharacter byte sequence is returned.
If the firstn bytes possibly form a valid multibytecharacter but the character is incomplete, the return value is(size_t) -2
. Otherwise the multibyte character sequence is invalidand the return value is(size_t) -1
.
The multibyte sequence is interpreted in the state represented by theobject pointed to byps. Ifps is a null pointer, a stateobject local tombrlen
is used.
mbrlen
was introduced in Amendment 1 to ISO C90 andis declared inwchar.h.
The attentive reader now will note thatmbrlen
can be implementedas
mbrtowc (NULL, s, n, ps != NULL ? ps : &internal)
This is true and in fact is mentioned in the official specification.How can this function be used to determine the length of the widecharacter string created from a multibyte character string? It is notdirectly usable, but we can define a functionmbslen
using it:
size_tmbslen (const char *s){ mbstate_t state; size_t result = 0; size_t nbytes; memset (&state, '\0', sizeof (state)); while ((nbytes = mbrlen (s, MB_LEN_MAX, &state)) > 0) { if (nbytes >= (size_t) -2) /*Something is wrong. */ return (size_t) -1; s += nbytes; ++result; } return result;}
This function simply callsmbrlen
for each multibyte characterin the string and counts the number of function calls. Please note thatwe here useMB_LEN_MAX
as the size argument in thembrlen
call. This is acceptable since a) this value is larger than the length ofthe longest multibyte character sequence and b) we know that the strings ends with a NUL byte, which cannot be part of any other multibytecharacter sequence but the one representing the NUL wide character.Therefore, thembrlen
function will never read invalid memory.
Now that this function is available (just to make this clear, thisfunction isnot part of the GNU C Library) we can compute thenumber of wide characters required to store the converted multibytecharacter strings using
wcs_bytes = (mbslen (s) + 1) * sizeof (wchar_t);
Please note that thembslen
function is quite inefficient. Theimplementation ofmbstouwcs
withmbslen
would have toperform the conversion of the multibyte character input string twice, andthis conversion might be quite expensive. So it is necessary to thinkabout the consequences of using the easier but imprecise method beforedoing the work twice.
size_t
wcrtomb(char *restricts, wchar_twc, mbstate_t *restrictps)
¶Preliminary:| MT-Unsafe race:wcrtomb/!ps| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thewcrtomb
function (“wide character restartable tomultibyte”) converts a single wide character into a multibyte stringcorresponding to that wide character.
Ifs is a null pointer, the function resets the state stored inthe object pointed to byps (or the internalmbstate_t
object) to the initial state. This can also be achieved by a call likethis:
wcrtombs (temp_buf, L'\0', ps)
since, ifs is a null pointer,wcrtomb
performs as if itwrites into an internal buffer, which is guaranteed to be large enough.
Ifwc is the NUL wide character,wcrtomb
emits, ifnecessary, a shift sequence to get the stateps into the initialstate followed by a single NUL byte, which is stored in the strings.
Otherwise a byte sequence (possibly including shift sequences) is writteninto the strings. This only happens ifwc is a valid widecharacter (i.e., it has a multibyte representation in the character setselected by locale of theLC_CTYPE
category). Ifwc is novalid wide character, nothing is stored in the stringss,errno
is set toEILSEQ
, the conversion state inpsis undefined and the return value is(size_t) -1
.
If no error occurred the function returns the number of bytes stored inthe strings. This includes all bytes representing shiftsequences.
One word about the interface of the function: there is no parameterspecifying the length of the arrays, so the caller has to make surethat there is enough space available, otherwise buffer overruns can occur.This version of the GNU C Library does not assume thats is at leastMB_CUR_MAX bytes long, but programs that need to run on GNU C Libraryversions that have this assumption documented in the manual must complywith this limit.
wcrtomb
was introduced in Amendment 1 to ISO C90 and isdeclared inwchar.h.
Usingwcrtomb
is as easy as usingmbrtowc
. The followingexample appends a wide character string to a multibyte character string.Again, the code is not really useful (or correct), it is simply here todemonstrate the use and some problems.
char *mbscatwcs (char *s, size_t len, const wchar_t *ws){ mbstate_t state; /*Find the end of the existing string. */ char *wp = strchr (s, '\0'); len -= wp - s; memset (&state, '\0', sizeof (state)); do { size_t nbytes; if (len < MB_CUR_LEN) { /*We cannot guarantee that the nextcharacter fits into the buffer, soreturn an error. */ errno = E2BIG; return NULL; } nbytes = wcrtomb (wp, *ws, &state); if (nbytes == (size_t) -1) /*Error in the conversion. */ return NULL; len -= nbytes; wp += nbytes; } while (*ws++ != L'\0'); return s;}
First the function has to find the end of the string currently in thearrays. Thestrchr
call does this very efficiently since arequirement for multibyte character representations is that the NUL byteis never used except to represent itself (and in this context, the endof the string).
After initializing the state object the loop is entered where the firsttask is to make sure there is enough room in the arrays. Weabort if there are not at leastMB_CUR_LEN
bytes available. Thisis not always optimal but we have no other choice. We might have lessthanMB_CUR_LEN
bytes available but the next multibyte charactermight also be only one byte long. At the time thewcrtomb
callreturns it is too late to decide whether the buffer was large enough. Ifthis solution is unsuitable, there is a very slow but more accuratesolution.
... if (len < MB_CUR_LEN) { mbstate_t temp_state; memcpy (&temp_state, &state, sizeof (state)); if (wcrtomb (NULL, *ws, &temp_state) > len) { /*We cannot guarantee that the nextcharacter fits into the buffer, soreturn an error. */ errno = E2BIG; return NULL; } } ...
Here we perform the conversion that might overflow the buffer so thatwe are afterwards in the position to make an exact decision about thebuffer size. Please note theNULL
argument for the destinationbuffer in the newwcrtomb
call; since we are not interested in theconverted text at this point, this is a nice way to express this. Themost unusual thing about this piece of code certainly is the duplicationof the conversion state object, but if a change of the state is necessaryto emit the next multibyte character, we want to have the same shift statechange performed in the real conversion. Therefore, we have to preservethe initial shift state information.
There are certainly many more and even better solutions to this problem.This example is only provided for educational purposes.
Next:A Complete Multibyte Conversion Example, Previous:Converting Single Characters, Up:Restartable Multibyte Conversion Functions [Contents][Index]
The functions described in the previous section only convert a singlecharacter at a time. Most operations to be performed in real-worldprograms include strings and therefore the ISO C standard alsodefines conversions on entire strings. However, the defined set offunctions is quite limited; therefore, the GNU C Library contains a fewextensions that can help in some important situations.
size_t
mbsrtowcs(wchar_t *restrictdst, const char **restrictsrc, size_tlen, mbstate_t *restrictps)
¶Preliminary:| MT-Unsafe race:mbsrtowcs/!ps| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thembsrtowcs
function (“multibyte string restartable to widecharacter string”) converts the NUL-terminated multibyte characterstring at*src
into an equivalent wide character string,including the NUL wide character at the end. The conversion is startedusing the state information from the object pointed to byps orfrom an internal object ofmbsrtowcs
ifps is a nullpointer. Before returning, the state object is updated to match the stateafter the last converted character. The state is the initial state if theterminating NUL byte is reached and converted.
Ifdst is not a null pointer, the result is stored in the arraypointed to bydst; otherwise, the conversion result is notavailable since it is stored in an internal buffer.
Iflen wide characters are stored in the arraydst beforereaching the end of the input string, the conversion stops andlenis returned. Ifdst is a null pointer,len is never checked.
Another reason for a premature return from the function call is if theinput string contains an invalid multibyte sequence. In this case theglobal variableerrno
is set toEILSEQ
and the functionreturns(size_t) -1
.
In all other cases the function returns the number of wide charactersconverted during this call. Ifdst is not null,mbsrtowcs
stores in the pointer pointed to bysrc either a null pointer (ifthe NUL byte in the input string was reached) or the address of the bytefollowing the last converted multibyte character.
Likembstowcs
thedst parameter may be a null pointer andthe function can be used to count the number of wide characters thatwould be required.
mbsrtowcs
was introduced in Amendment 1 to ISO C90 and isdeclared inwchar.h.
The definition of thembsrtowcs
function has one importantlimitation. The requirement thatdst has to be a NUL-terminatedstring provides problems if one wants to convert buffers with text. Abuffer is not normally a collection of NUL-terminated strings but instead acontinuous collection of lines, separated by newline characters. Nowassume that a function to convert one line from a buffer is needed. Sincethe line is not NUL-terminated, the source pointer cannot directly pointinto the unmodified text buffer. This means, either one inserts the NULbyte at the appropriate place for the time of thembsrtowcs
function call (which is not doable for a read-only buffer or in amulti-threaded application) or one copies the line in an extra bufferwhere it can be terminated by a NUL byte. Note that it is not in generalpossible to limit the number of characters to convert by setting theparameterlen to any specific value. Since it is not known howmany bytes each multibyte character sequence is in length, one can onlyguess.
There is still a problem with the method of NUL-terminating a line rightafter the newline character, which could lead to very strange results.As said in the description of thembsrtowcs
function above, theconversion state is guaranteed to be in the initial shift state afterprocessing the NUL byte at the end of the input string. But this NULbyte is not really part of the text (i.e., the conversion state afterthe newline in the original text could be something different than theinitial shift state and therefore the first character of the next lineis encoded using this state). But the state in question is neveraccessible to the user since the conversion stops after the NUL byte(which resets the state). Most stateful character sets in use todayrequire that the shift state after a newline be the initial state–butthis is not a strict guarantee. Therefore, simply NUL-terminating apiece of a running text is not always an adequate solution and,therefore, should never be used in generally used code.
The generic conversion interface (seeGeneric Charset Conversion)does not have this limitation (it simply works on buffers, notstrings), and the GNU C Library contains a set of functions that takeadditional parameters specifying the maximal number of bytes that areconsumed from the input string. This way the problem ofmbsrtowcs
’s example above could be solved by determining the linelength and passing this length to the function.
size_t
wcsrtombs(char *restrictdst, const wchar_t **restrictsrc, size_tlen, mbstate_t *restrictps)
¶Preliminary:| MT-Unsafe race:wcsrtombs/!ps| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thewcsrtombs
function (“wide character string restartable tomultibyte string”) converts the NUL-terminated wide character string at*src
into an equivalent multibyte character string andstores the result in the array pointed to bydst. The NUL widecharacter is also converted. The conversion starts in the statedescribed in the object pointed to byps or by a state objectlocal towcsrtombs
in caseps is a null pointer. Ifdst is a null pointer, the conversion is performed as usual but theresult is not available. If all characters of the input string weresuccessfully converted and ifdst is not a null pointer, thepointer pointed to bysrc gets assigned a null pointer.
If one of the wide characters in the input string has no valid multibytecharacter equivalent, the conversion stops early, sets the globalvariableerrno
toEILSEQ
, and returns(size_t) -1
.
Another reason for a premature stop is ifdst is not a nullpointer and the next converted character would require more thanlen bytes in total to the arraydst. In this case (and ifdst is not a null pointer) the pointer pointed to bysrc isassigned a value pointing to the wide character right after the last onesuccessfully converted.
Except in the case of an encoding error the return value of thewcsrtombs
function is the number of bytes in all the multibytecharacter sequences which were or would have been (ifdst wasnot a null) stored indst. Before returning, the state in theobject pointed to byps (or the internal object in casepsis a null pointer) is updated to reflect the state after the lastconversion. The state is the initial shift state in case theterminating NUL wide character was converted.
Thewcsrtombs
function was introduced in Amendment 1 toISO C90 and is declared inwchar.h.
The restriction mentioned above for thembsrtowcs
function applieshere also. There is no possibility of directly controlling the number ofinput characters. One has to place the NUL wide character at the correctplace or control the consumed input indirectly via the available outputarray size (thelen parameter).
size_t
mbsnrtowcs(wchar_t *restrictdst, const char **restrictsrc, size_tnmc, size_tlen, mbstate_t *restrictps)
¶Preliminary:| MT-Unsafe race:mbsnrtowcs/!ps| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thembsnrtowcs
function is very similar to thembsrtowcs
function. All the parameters are the same except fornmc, which isnew. The return value is the same as formbsrtowcs
.
This new parameter specifies how many bytes at most can be used from themultibyte character string. In other words, the multibyte characterstring*src
need not be NUL-terminated. But if a NUL byteis found within thenmc first bytes of the string, the conversionstops there.
Likembstowcs
thedst parameter may be a null pointer andthe function can be used to count the number of wide characters thatwould be required.
This function is a GNU extension. It is meant to work around theproblems mentioned above. Now it is possible to convert a buffer withmultibyte character text piece by piece without having to care aboutinserting NUL bytes and the effect of NUL bytes on the conversion state.
A function to convert a multibyte string into a wide character stringand display it could be written like this (this is not a really usefulexample):
voidshowmbs (const char *src, FILE *fp){ mbstate_t state; int cnt = 0; memset (&state, '\0', sizeof (state)); while (1) { wchar_t linebuf[100]; const char *endp = strchr (src, '\n'); size_t n; /*Exit if there is no more line. */ if (endp == NULL) break; n = mbsnrtowcs (linebuf, &src, endp - src, 99, &state); linebuf[n] = L'\0'; fprintf (fp, "line %d: \"%S\"\n", linebuf); }}
There is no problem with the state after a call tombsnrtowcs
.Since we don’t insert characters in the strings that were not in thereright from the beginning and we usestate only for the conversionof the given buffer, there is no problem with altering the state.
size_t
wcsnrtombs(char *restrictdst, const wchar_t **restrictsrc, size_tnwc, size_tlen, mbstate_t *restrictps)
¶Preliminary:| MT-Unsafe race:wcsnrtombs/!ps| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thewcsnrtombs
function implements the conversion from widecharacter strings to multibyte character strings. It is similar towcsrtombs
but, just likembsnrtowcs
, it takes an extraparameter, which specifies the length of the input string.
No more thannwc wide characters from the input string*src
are converted. If the input string contains a NULwide character in the firstnwc characters, the conversion stops atthis place.
Thewcsnrtombs
function is a GNU extension and just likembsnrtowcs
helps in situations where no NUL-terminated inputstrings are available.
Previous:Converting Multibyte and Wide Character Strings, Up:Restartable Multibyte Conversion Functions [Contents][Index]
The example programs given in the last sections are only brief and donot contain all the error checking, etc. Presented here is a completeand documented example. It features thembrtowc
function but itshould be easy to derive versions using the other functions.
intfile_mbsrtowcs (int input, int output){ /*Note the use ofMB_LEN_MAX
.MB_CUR_MAX
cannot portably be used here. */ char buffer[BUFSIZ + MB_LEN_MAX]; mbstate_t state; int filled = 0; int eof = 0; /*Initialize the state. */ memset (&state, '\0', sizeof (state)); while (!eof) { ssize_t nread; ssize_t nwrite; char *inp = buffer; wchar_t outbuf[BUFSIZ]; wchar_t *outp = outbuf; /*Fill up the buffer from the input file. */ nread = read (input, buffer + filled, BUFSIZ); if (nread < 0) { perror ("read"); return 0; } /*If we reach end of file, make a note to read no more. */ if (nread == 0) eof = 1; /*filled
is now the number of bytes inbuffer
. */ filled += nread; /*Convert those bytes to wide characters–as many as we can. */ while (1) { size_t thislen = mbrtowc (outp, inp, filled, &state); /*Stop converting at invalid character;this can mean we have read just the first partof a valid character. */ if (thislen == (size_t) -1) break; /*We want to handle embedded NUL bytesbut the return value is 0. Correct this. */ if (thislen == 0) thislen = 1; /*Advance past this character. */ inp += thislen; filled -= thislen; ++outp; } /*Write the wide characters we just made. */ nwrite = write (output, outbuf, (outp - outbuf) * sizeof (wchar_t)); if (nwrite < 0) { perror ("write"); return 0; } /*See if we have areal invalid character. */ if ((eof && filled > 0) || filled >= MB_CUR_MAX) { error (0, 0, "invalid multibyte character"); return 0; } /*If any characters must be carried forward,put them at the beginning ofbuffer
. */ if (filled > 0) memmove (buffer, inp, filled); } return 1;}
Next:Generic Charset Conversion, Previous:Restartable Multibyte Conversion Functions, Up:Character Set Handling [Contents][Index]
The functions described in the previous chapter are defined inAmendment 1 to ISO C90, but the original ISO C90 standardalso contained functions for character set conversion. The reason thatthese original functions are not described first is that they are almostentirely useless.
The problem is that all the conversion functions described in theoriginal ISO C90 use a local state. Using a local state implies thatmultiple conversions at the same time (not only when using threads)cannot be done, and that you cannot first convert single characters andthen strings since you cannot tell the conversion functions which stateto use.
These original functions are therefore usable only in a very limited setof situations. One must complete converting the entire string beforestarting a new one, and each string/text must be converted with the samefunction (there is no problem with the library itself; it is guaranteedthat no library function changes the state of any of these functions).For the above reasons it is highly requested that the functionsdescribed in the previous section be used in place of non-reentrantconversion functions.
int
mbtowc(wchar_t *restrictresult, const char *restrictstring, size_tsize)
¶Preliminary:| MT-Unsafe race| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thembtowc
(“multibyte to wide character”) function when calledwith non-nullstring converts the first multibyte characterbeginning atstring to its corresponding wide character code. Itstores the result in*result
.
mbtowc
never examines more thansize bytes. (The idea isto supply forsize the number of bytes of data you have in hand.)
mbtowc
with non-nullstring distinguishes threepossibilities: the firstsize bytes atstring start withvalid multibyte characters, they start with an invalid byte sequence orjust part of a character, orstring points to an empty string (anull character).
For a valid multibyte character,mbtowc
converts it to a widecharacter and stores that in*result
, and returns thenumber of bytes in that character (always at least1 and nevermore thansize).
For an invalid byte sequence,mbtowc
returns-1. For anempty string, it returns0, also storing'\0'
in*result
.
If the multibyte character code uses shift characters, thenmbtowc
maintains and updates a shift state as it scans. If youcallmbtowc
with a null pointer forstring, thatinitializes the shift state to its standard initial value. It alsoreturns nonzero if the multibyte character code in use actually has ashift state. SeeStates in Non-reentrant Functions.
int
wctomb(char *string, wchar_twchar)
¶Preliminary:| MT-Unsafe race| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thewctomb
(“wide character to multibyte”) function convertsthe wide character codewchar to its corresponding multibytecharacter sequence, and stores the result in bytes starting atstring. At mostMB_CUR_MAX
characters are stored.
wctomb
with non-nullstring distinguishes threepossibilities forwchar: a valid wide character code (one that canbe translated to a multibyte character), an invalid code, andL'\0'
.
Given a valid code,wctomb
converts it to a multibyte character,storing the bytes starting atstring. Then it returns the numberof bytes in that character (always at least1 and never morethanMB_CUR_MAX
).
Ifwchar is an invalid wide character code,wctomb
returns-1. Ifwchar isL'\0'
, it returns0
, alsostoring'\0'
in*string
.
If the multibyte character code uses shift characters, thenwctomb
maintains and updates a shift state as it scans. If youcallwctomb
with a null pointer forstring, thatinitializes the shift state to its standard initial value. It alsoreturns nonzero if the multibyte character code in use actually has ashift state. SeeStates in Non-reentrant Functions.
Calling this function with awchar argument of zero whenstring is not null has the side-effect of reinitializing thestored shift stateas well as storing the multibyte character'\0'
and returning0.
Similar tombrlen
there is also a non-reentrant function thatcomputes the length of a multibyte character. It can be defined interms ofmbtowc
.
int
mblen(const char *string, size_tsize)
¶Preliminary:| MT-Unsafe race| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Themblen
function with a non-nullstring argument returnsthe number of bytes that make up the multibyte character beginning atstring, never examining more thansize bytes. (The idea isto supply forsize the number of bytes of data you have in hand.)
The return value ofmblen
distinguishes three possibilities: thefirstsize bytes atstring start with valid multibytecharacters, they start with an invalid byte sequence or just part of acharacter, orstring points to an empty string (a null character).
For a valid multibyte character,mblen
returns the number ofbytes in that character (always at least1
and never more thansize). For an invalid byte sequence,mblen
returns-1. For an empty string, it returns0.
If the multibyte character code uses shift characters, thenmblen
maintains and updates a shift state as it scans. If you callmblen
with a null pointer forstring, that initializes theshift state to its standard initial value. It also returns a nonzerovalue if the multibyte character code in use actually has a shift state.SeeStates in Non-reentrant Functions.
The functionmblen
is declared instdlib.h.
Next:States in Non-reentrant Functions, Previous:Non-reentrant Conversion of Single Characters, Up:Non-reentrant Conversion Function [Contents][Index]
For convenience the ISO C90 standard also defines functions toconvert entire strings instead of single characters. These functionssuffer from the same problems as their reentrant counterparts fromAmendment 1 to ISO C90; seeConverting Multibyte and Wide Character Strings.
size_t
mbstowcs(wchar_t *wstring, const char *string, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thembstowcs
(“multibyte string to wide character string”)function converts the null-terminated string of multibyte charactersstring to an array of wide character codes, storing not more thansize wide characters into the array beginning atwstring.The terminating null character counts towards the size, so ifsizeis less than the actual number of wide characters resulting fromstring, no terminating null character is stored.
The conversion of characters fromstring begins in the initialshift state.
If an invalid multibyte character sequence is found, thembstowcs
function returns a value of-1. Otherwise, it returns the numberof wide characters stored in the arraywstring. This number doesnot include the terminating null character, which is present if thenumber is less thansize.
Here is an example showing how to convert a string of multibytecharacters, allocating enough space for the result.
wchar_t *mbstowcs_alloc (const char *string){ size_t size = strlen (string) + 1; wchar_t *buf = xmalloc (size * sizeof (wchar_t)); size = mbstowcs (buf, string, size); if (size == (size_t) -1) return NULL; buf = xreallocarray (buf, size + 1, sizeof *buf); return buf;}
Ifwstring is a null pointer then no output is written and theconversion proceeds as above, and the result is returned. In practicesuch behaviour is useful for calculating the exact number of widecharacters required to convertstring. This behaviour ofaccepting a null pointer forwstring is an XPG4.2 extensionthat is not specified in ISO C and is optional in POSIX.
size_t
wcstombs(char *string, const wchar_t *wstring, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thewcstombs
(“wide character string to multibyte string”)function converts the null-terminated wide character arraywstringinto a string containing multibyte characters, storing not more thansize bytes starting atstring, followed by a terminatingnull character if there is room. The conversion of characters begins inthe initial shift state.
The terminating null character counts towards the size, so ifsizeis less than or equal to the number of bytes needed inwstring, noterminating null character is stored.
If a code that does not correspond to a valid multibyte character isfound, thewcstombs
function returns a value of-1.Otherwise, the return value is the number of bytes stored in the arraystring. This number does not include the terminating null character,which is present if the number is less thansize.
Previous:Non-reentrant Conversion of Strings, Up:Non-reentrant Conversion Function [Contents][Index]
In some multibyte character codes, themeaning of any particularbyte sequence is not fixed; it depends on what other sequences have comeearlier in the same string. Typically there are just a few sequences thatcan change the meaning of other sequences; these few are calledshift sequences and we say that they set theshift state forother sequences that follow.
To illustrate shift state and shift sequences, suppose we decide thatthe sequence0200
(just one byte) enters Japanese mode, in whichpairs of bytes in the range from0240
to0377
are singlecharacters, while0201
enters Latin-1 mode, in which single bytesin the range from0240
to0377
are characters, andinterpreted according to the ISO Latin-1 character set. This is amultibyte code that has two alternative shift states (“Japanese mode”and “Latin-1 mode”), and two shift sequences that specify particularshift states.
When the multibyte character code in use has shift states, thenmblen
,mbtowc
, andwctomb
must maintain and updatethe current shift state as they scan the string. To make this workproperly, you must follow these rules:
mblen (NULL,0)
. This initializes the shift state to its standard initial value.Here is an example of usingmblen
following these rules:
voidscan_string (char *s){ int length = strlen (s); /*Initialize shift state. */ mblen (NULL, 0); while (1) { int thischar = mblen (s, length); /*Deal with end of string and invalid characters. */ if (thischar == 0) break; if (thischar == -1) { error ("invalid multibyte character"); break; } /*Advance past this character. */ s += thischar; length -= thischar; }}
The functionsmblen
,mbtowc
andwctomb
are notreentrant when using a multibyte code that uses a shift state. However,no other library functions call these functions, so you don’t have toworry that the shift state will be changed mysteriously.
Previous:Non-reentrant Conversion Function, Up:Character Set Handling [Contents][Index]
The conversion functions mentioned so far in this chapter all had incommon that they operate on character sets that are not directlyspecified by the functions. The multibyte encoding used is specified bythe currently selected locale for theLC_CTYPE
category. Thewide character set is fixed by the implementation (in the case of the GNU C Libraryit is always UCS-4 encoded ISO 10646).
This has of course several problems when it comes to general characterconversion:
LC_CTYPE
category, one has to change theLC_CTYPE
locale usingsetlocale
.Changing theLC_CTYPE
locale introduces major problems for the restof the programs since several more functions (e.g., the characterclassification functions, seeClassification of Characters) use theLC_CTYPE
category.
LC_CTYPE
selection is global and shared by allthreads.wchar_t
representation, there is at least a two-stepprocess necessary to convert a text using the functions above. One wouldhave to select the source character set as the multibyte encoding,convert the text into awchar_t
text, select the destinationcharacter set as the multibyte encoding, and convert the wide charactertext to the multibyte (= destination) character set.Even if this is possible (which is not guaranteed) it is a very tiringwork. Plus it suffers from the other two raised points even more due tothe steady changing of the locale.
The XPG2 standard defines a completely new set of functions, which hasnone of these limitations. They are not at all coupled to the selectedlocales, and they have no constraints on the character sets selected forsource and destination. Only the set of available conversions limitsthem. The standard does not specify that any conversion at all must beavailable. Such availability is a measure of the quality of theimplementation.
In the following text first the interface toiconv
and then theconversion function, will be described. Comparisons with otherimplementations will show what obstacles stand in the way of portableapplications. Finally, the implementation is described in so far as mightinterest the advanced user who wants to extend conversion capabilities.
iconv
exampleiconv
Implementationsiconv
Implementation in the GNU C LibraryThis set of functions follows the traditional cycle of using a resource:open–use–close. The interface consists of three functions, each ofwhich implements one step.
Before the interfaces are described it is necessary to introduce adata type. Just like other open–use–close interfaces the functionsintroduced here work using handles and theiconv.h headerdefines a special type for the handles used.
This data type is an abstract type defined iniconv.h. The usermust not assume anything about the definition of this type; it must becompletely opaque.
Objects of this type can be assigned handles for the conversions usingtheiconv
functions. The objects themselves need not be freed, butthe conversions for which the handles stand for have to.
The first step is the function to create a handle.
iconv_t
iconv_open(const char *tocode, const char *fromcode)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Theiconv_open
function has to be used before starting aconversion. The two parameters this function takes determine thesource and destination character set for the conversion, and if theimplementation has the possibility to perform such a conversion, thefunction returns a handle.
If the wanted conversion is not available, theiconv_open
functionreturns(iconv_t) -1
. In this case the global variableerrno
can have the following values:
EMFILE
The process already hasOPEN_MAX
file descriptors open.
ENFILE
The system limit of open files is reached.
ENOMEM
Not enough memory to carry out the operation.
EINVAL
The conversion fromfromcode totocode is not supported.
It is not possible to use the same descriptor in different threads toperform independent conversions. The data structures associatedwith the descriptor include information about the conversion state.This must not be messed up by using it in different conversions.
Aniconv
descriptor is like a file descriptor as for every use anew descriptor must be created. The descriptor does not stand for allof the conversions fromfromset totoset.
The GNU C Library implementation oficonv_open
has onesignificant extension to other implementations. To ease the extensionof the set of available conversions, the implementation allows storingthe necessary files with data and code in an arbitrary number ofdirectories. How this extension must be written will be explained below(seeTheiconv
Implementation in the GNU C Library). Here it is only important to saythat all directories mentioned in theGCONV_PATH
environmentvariable are considered only if they contain a filegconv-modules.These directories need not necessarily be created by the systemadministrator. In fact, this extension is introduced to help userswriting and using their own, new conversions. Of course, this does notwork for security reasons in SUID binaries; in this case only the systemdirectory is considered and this normally isprefix/lib/gconv. TheGCONV_PATH
environmentvariable is examined exactly once at the first call of theiconv_open
function. Later modifications of the variable have noeffect.
Theiconv_open
function was introduced early in the X/OpenPortability Guide, version 2. It is supported by all commercialUnices as it is required for the Unix branding. However, the quality andcompleteness of the implementation varies widely. Theiconv_open
function is declared iniconv.h.
Theiconv
implementation can associate large data structure withthe handle returned byiconv_open
. Therefore, it is crucial tofree all the resources once all conversions are carried out and theconversion is not needed anymore.
int
iconv_close(iconv_tcd)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Theiconv_close
function frees all resources associated with thehandlecd, which must have been returned by a successful call totheiconv_open
function.
If the function call was successful the return value is0.Otherwise it is-1 anderrno
is set appropriately.Defined errors are:
EBADF
The conversion descriptor is invalid.
Theiconv_close
function was introduced together with the restof theiconv
functions in XPG2 and is declared iniconv.h.
The standard defines only one actual conversion function. This has,therefore, the most general interface: it allows conversion from onebuffer to another. Conversion from a file to a buffer, vice versa, oreven file to file can be implemented on top of it.
size_t
iconv(iconv_tcd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft)
¶Preliminary:| MT-Safe race:cd| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theiconv
function converts the text in the input bufferaccording to the rules associated with the descriptorcd andstores the result in the output buffer. It is possible to call thefunction for the same text several times in a row since for statefulcharacter sets the necessary state information is kept in the datastructures associated with the descriptor.
The input buffer is specified by*inbuf
and it contains*inbytesleft
bytes. The extra indirection is necessary forcommunicating the used input back to the caller (see below). It isimportant to note that the buffer pointer is of typechar
and thelength is measured in bytes even if the input text is encoded in widecharacters.
The output buffer is specified in a similar way.*outbuf
points to the beginning of the buffer with at least*outbytesleft
bytes room for the result. The bufferpointer again is of typechar
and the length is measured inbytes. Ifoutbuf or*outbuf
is a null pointer, theconversion is performed but no output is available.
Ifinbuf is a null pointer, theiconv
function performs thenecessary action to put the state of the conversion into the initialstate. This is obviously a no-op for non-stateful encodings, but if theencoding has a state, such a function call might put some byte sequencesin the output buffer, which perform the necessary state changes. Thenext call withinbuf not being a null pointer then simply goes onfrom the initial state. It is important that the programmer never makesany assumption as to whether the conversion has to deal with states.Even if the input and output character sets are not stateful, theimplementation might still have to keep states. This is due to theimplementation chosen for the GNU C Library as it is described below.Therefore aniconv
call to reset the state should always beperformed if some protocol requires this for the output text.
The conversion stops for one of three reasons. The first is that allcharacters from the input buffer are converted. This actually can meantwo things: either all bytes from the input buffer are consumed orthere are some bytes at the end of the buffer that possibly can form acomplete character but the input is incomplete. The second reason for astop is that the output buffer is full. And the third reason is thatthe input contains invalid characters.
In all of these cases the buffer pointers after the last successfulconversion, for the input and output buffers, are stored ininbuf andoutbuf, and the available room in each buffer is stored ininbytesleft andoutbytesleft.
Since the character sets selected in theiconv_open
call can bealmost arbitrary, there can be situations where the input buffer containsvalid characters, which have no identical representation in the outputcharacter set. The behavior in this situation is undefined. Thecurrent behavior of the GNU C Library in this situation is toreturn with an error immediately. This certainly is not the mostdesirable solution; therefore, future versions will provide better ones,but they are not yet finished.
If all input from the input buffer is successfully converted and storedin the output buffer, the function returns the number of non-reversibleconversions performed. In all other cases the return value is(size_t) -1
anderrno
is set appropriately. In such casesthe value pointed to byinbytesleft is nonzero.
EILSEQ
The conversion stopped because of an invalid byte sequence in the input.After the call,*inbuf
points at the first byte of theinvalid byte sequence.
E2BIG
The conversion stopped because it ran out of space in the output buffer.
EINVAL
The conversion stopped because of an incomplete byte sequence at the endof the input buffer.
EBADF
Thecd argument is invalid.
Theiconv
function was introduced in the XPG2 standard and isdeclared in theiconv.h header.
The definition of theiconv
function is quite good overall. Itprovides quite flexible functionality. The only problems lie in theboundary cases, which are incomplete byte sequences at the end of theinput buffer and invalid input. A third problem, which is not reallya design problem, is the way conversions are selected. The standarddoes not say anything about the legitimate names, a minimal set ofavailable conversions. We will see how this negatively impacts otherimplementations, as demonstrated below.
Next:Some Details about othericonv
Implementations, Previous:Generic Character Set Conversion Interface, Up:Generic Charset Conversion [Contents][Index]
iconv
example ¶The example below features a solution for a common problem. Given thatone knows the internal encoding used by the system forwchar_t
strings, one often is in the position to read text from a file and storeit in wide character buffers. One can do this usingmbsrtowcs
,but then we run into the problems discussed above.
intfile2wcs (int fd, const char *charset, wchar_t *outbuf, size_t avail){ char inbuf[BUFSIZ]; size_t insize = 0; char *wrptr = (char *) outbuf; int result = 0; iconv_t cd; cd = iconv_open ("WCHAR_T", charset); if (cd == (iconv_t) -1) { /*Something went wrong. */ if (errno == EINVAL) error (0, 0, "conversion from '%s' to wchar_t not available", charset); else perror ("iconv_open"); /*Terminate the output string. */ *outbuf = L'\0'; return -1; } while (avail > 0) { size_t nread; size_t nconv; char *inptr = inbuf; /*Read more input. */ nread = read (fd, inbuf + insize, sizeof (inbuf) - insize); if (nread == 0) { /*When we come here the file is completely read.This still could mean there are some unusedcharacters in theinbuf
. Put them back. */ if (lseek (fd, -insize, SEEK_CUR) == -1) result = -1; /*Now write out the byte sequence to get into theinitial state if this is necessary. */ iconv (cd, NULL, NULL, &wrptr, &avail); break; } insize += nread; /*Do the conversion. */ nconv = iconv (cd, &inptr, &insize, &wrptr, &avail); if (nconv == (size_t) -1) { /*Not everything went right. It might only bean unfinished byte sequence at the end of thebuffer. Or it is a real problem. */ if (errno == EINVAL) /*This is harmless. Simply move the unusedbytes to the beginning of the buffer so thatthey can be used in the next round. */ memmove (inbuf, inptr, insize); else { /*It is a real problem. Maybe we ran out ofspace in the output buffer or we have invalidinput. In any case back the file pointer tothe position of the last processed byte. */ lseek (fd, -insize, SEEK_CUR); result = -1; break; } } } /*Terminate the output string. */ if (avail >= sizeof (wchar_t)) *((wchar_t *) wrptr) = L'\0'; if (iconv_close (cd) != 0) perror ("iconv_close"); return (wchar_t *) wrptr - outbuf;}
This example shows the most important aspects of using theiconv
functions. It shows how successive calls toiconv
can be used toconvert large amounts of text. The user does not have to care aboutstateful encodings as the functions take care of everything.
An interesting point is the case whereiconv
returns an error anderrno
is set toEINVAL
. This is not really an error in thetransformation. It can happen whenever the input character set containsbyte sequences of more than one byte for some character and texts are notprocessed in one piece. In this case there is a chance that a multibytesequence is cut. The caller can then simply read the remainder of thetakes and feed the offending bytes together with new character from theinput toiconv
and continue the work. The internal state kept inthe descriptor isnot unspecified after such an event as is thecase with the conversion functions from the ISO C standard.
The example also shows the problem of using wide character strings withiconv
. As explained in the description of theiconv
function above, the function always takes a pointer to achar
array and the available space is measured in bytes. In the example, theoutput buffer is a wide character buffer; therefore, we use a localvariablewrptr of typechar *
, which is used in theiconv
calls.
This looks rather innocent but can lead to problems on platforms thathave tight restriction on alignment. Therefore the caller oficonv
has to make sure that the pointers passed are suitable for access ofcharacters from the appropriate character set. Since, in theabove case, the input parameter to the function is awchar_t
pointer, this is the case (unless the user violates alignment whencomputing the parameter). But in other situations, especially whenwriting generic functions where one does not know what type of characterset one uses and, therefore, treats text as a sequence of bytes, it mightbecome tricky.
Next:Theiconv
Implementation in the GNU C Library, Previous:A completeiconv
example, Up:Generic Charset Conversion [Contents][Index]
iconv
Implementations ¶This is not really the place to discuss theiconv
implementationof other systems but it is necessary to know a bit about them to writeportable programs. The above mentioned problems with the specificationof theiconv
functions can lead to portability issues.
The first thing to notice is that, due to the large number of charactersets in use, it is certainly not practical to encode the conversionsdirectly in the C library. Therefore, the conversion information mustcome from files outside the C library. This is usually done in one orboth of the following ways:
This solution is problematic as it requires a great deal of effort toapply to all character sets (potentially an infinite set). Thedifferences in the structure of the different character sets is so largethat many different variants of the table-processing functions must bedeveloped. In addition, the generic nature of these functions make themslower than specifically implemented functions.
This solution provides much more flexibility. The C library itselfcontains only very little code and therefore reduces the general memoryfootprint. Also, with a documented interface between the C library andthe loadable modules it is possible for third parties to extend the setof available conversion modules. A drawback of this solution is thatdynamic loading must be available.
Some implementations in commercial Unices implement a mixture of thesepossibilities; the majority implement only the second solution. Usingloadable modules moves the code out of the library itself and keepsthe door open for extensions and improvements, but this design is alsolimiting on some platforms since not many platforms support dynamicloading in statically linked programs. On platforms without thiscapability it is therefore not possible to use this interface instatically linked programs. The GNU C Library has, on ELF platforms, noproblems with dynamic loading in these situations; therefore, thispoint is moot. The danger is that one gets acquainted with thissituation and forgets about the restrictions on other systems.
A second thing to know about othericonv
implementations is thatthe number of available conversions is often very limited. Someimplementations provide, in the standard release (not specialinternational or developer releases), at most 100 to 200 conversionpossibilities. This does not mean 200 different character sets aresupported; for example, conversions from one character set to a set of 10others might count as 10 conversions. Together with the other directionthis makes 20 conversion possibilities used up by one character set. Onecan imagine the thin coverage these platforms provide. Some Unix vendorseven provide only a handful of conversions, which renders them useless foralmost all uses.
This directly leads to a third and probably the most problematic point.The way theiconv
conversion functions are implemented on allknown Unix systems and the availability of the conversion functions fromcharacter setA toB and the conversion fromB toC doesnot imply that theconversion fromA toC is available.
This might not seem unreasonable and problematic at first, but it is aquite big problem as one will notice shortly after hitting it. To showthe problem we assume to write a program that has to convert fromA toC. A call like
cd = iconv_open ("C", "A");
fails according to the assumption above. But what does the programdo now? The conversion is necessary; therefore, simply giving up is notan option.
This is a nuisance. Theiconv
function should take care of this.But how should the program proceed from here on? If it tries to convertto character setB, first the twoiconv_open
calls
cd1 = iconv_open ("B", "A");
and
cd2 = iconv_open ("C", "B");
will succeed, but how to findB?
Unfortunately, the answer is: there is no general solution. On somesystems guessing might help. On those systems most character sets canconvert to and from UTF-8 encoded ISO 10646 or Unicode text. Besidesthis only some very system-specific methods can help. Since theconversion functions come from loadable modules and these modules mustbe stored somewhere in the filesystem, onecould try to find themand determine from the available file which conversions are availableand whether there is an indirect route fromA toC.
This example shows one of the design errors oficonv
mentionedabove. It should at least be possible to determine the list of availableconversions programmatically so that ificonv_open
says there is nosuch conversion, one could make sure this also is true for indirectroutes.
Previous:Some Details about othericonv
Implementations, Up:Generic Charset Conversion [Contents][Index]
iconv
Implementation in the GNU C Library ¶After reading about the problems oficonv
implementations in thelast section it is certainly good to note that the implementation inthe GNU C Library has none of the problems mentioned above. Whatfollows is a step-by-step analysis of the points raised above. Theevaluation is based on the current state of the development (as ofJanuary 1999). The development of theiconv
functions is notcomplete, but basic functionality has solidified.
The GNU C Library’siconv
implementation uses shared loadablemodules to implement the conversions. A very small number ofconversions are built into the library itself but these are only rathertrivial conversions.
All the benefits of loadable modules are available in the GNU C Libraryimplementation. This is especially appealing since the interface iswell documented (see below), and it, therefore, is easy to write newconversion modules. The drawback of using loadable objects is not aproblem in the GNU C Library, at least on ELF systems. Since thelibrary is able to load shared objects even in statically linkedbinaries, static linking need not be forbidden in case one wants to useiconv
.
The second mentioned problem is the number of supported conversions.Currently, the GNU C Library supports more than 150 character sets. Theway the implementation is designed the number of supported conversionsis greater than 22350 (150 times149). If any conversionfrom or to a character set is missing, it can be added easily.
Particularly impressive as it may be, this high number is due to thefact that the GNU C Library implementation oficonv
does not havethe third problem mentioned above (i.e., whenever there is a conversionfrom a character setA toB and fromB toC it is always possible to convert fromA toC directly). If theiconv_open
returns an error and setserrno
toEINVAL
, there is noknown way, directly or indirectly, to perform the wanted conversion.
Triangulation is achieved by providing for each character set aconversion from and to UCS-4 encoded ISO 10646. Using ISO 10646as an intermediate representation it is possible totriangulate(i.e., convert with an intermediate representation).
There is no inherent requirement to provide a conversion to ISO 10646 for a new character set, and it is also possible to provide otherconversions where neither source nor destination character set is ISO 10646. The existing set of conversions is simply meant to cover allconversions that might be of interest.
All currently available conversions use the triangulation method above,making conversion run unnecessarily slow. If, for example, somebodyoften needs the conversion from ISO-2022-JP to EUC-JP, a quicker solutionwould involve direct conversion between the two character sets, skippingthe input to ISO 10646 first. The two character sets of interestare much more similar to each other than to ISO 10646.
In such a situation one easily can write a new conversion and provide itas a better alternative. The GNU C Libraryiconv
implementationwould automatically use the module implementing the conversion if it isspecified to be more efficient.
iconv
iconv
module data structuresiconv
module interfacesAll information about the available conversions comes from a file namedgconv-modules, which can be found in any of the directories alongtheGCONV_PATH
. Thegconv-modules files are line-orientedtext files, where each of the lines has one of the following formats:
alias
define an alias name for a characterset. Two more words are expected on the line. The first worddefines the alias name, and the second defines the original name of thecharacter set. The effect is that it is possible to use the alias namein thefromset ortoset parameters oficonv_open
andachieve the same result as when using the real character set name.This is quite important as a character set has often many differentnames. There is normally an official name but this need not correspond tothe most popular name. Besides this many character sets have specialnames that are somehow constructed. For example, all character setsspecified by the ISO have an alias of the formISO-IR-nnn
wherennn is the registration number. This allows programs thatknow about the registration number to construct character set names anduse them iniconv_open
calls. More on the available names andaliases follows below.
module
introduce an available conversionmodule. These lines must contain three or four more words.The first word specifies the source character set, the second word thedestination character set of conversion implemented in this module, andthe third word is the name of the loadable module. The filename isconstructed by appending the usual shared object suffix (normally.so) and this file is then supposed to be found in the samedirectory thegconv-modules file is in. The last word on the line,which is optional, is a numeric value representing the cost of theconversion. If this word is missing, a cost of1 is assumed. Thenumeric value itself does not matter that much; what counts are therelative values of the sums of costs for all possible conversion paths.Below is a more precise description of the use of the cost value.
Returning to the example above where one has written a module to directlyconvert from ISO-2022-JP to EUC-JP and back. All that has to be done isto put the new module, let its name be ISO2022JP-EUCJP.so, in a directoryand add a filegconv-modules with the following content in thesame directory:
module ISO-2022-JP// EUC-JP// ISO2022JP-EUCJP 1module EUC-JP// ISO-2022-JP// ISO2022JP-EUCJP 1
To see why this is sufficient, it is necessary to understand how theconversion used byiconv
(and described in the descriptor) isselected. The approach to this problem is quite simple.
At the first call of theiconv_open
function the program readsall availablegconv-modules files and builds up two tables: onecontaining all the known aliases and another that contains theinformation about the conversions and which shared object implementsthem.
iconv
¶The set of available conversions form a directed graph with weightededges. The weights on the edges are the costs specified in thegconv-modules files. Theiconv_open
function uses analgorithm suitable for search for the best path in such a graph and soconstructs a list of conversions that must be performed in successionto get the transformation from the source to the destination characterset.
Explaining why the abovegconv-modules files allows theiconv
implementation to resolve the specific ISO-2022-JP toEUC-JP conversion module instead of the conversion coming with thelibrary itself is straightforward. Since the latter conversion takes twosteps (from ISO-2022-JP to ISO 10646 and then from ISO 10646 toEUC-JP), the cost is1+1 = 2. The abovegconv-modulesfile, however, specifies that the new conversion modules can perform thisconversion with only the cost of1.
A mysterious item about thegconv-modules file above (and alsothe file coming with the GNU C Library) are the names of the charactersets specified in themodule
lines. Why do almost all the namesend in//
? And this is not all: the names can actually beregular expressions. At this point in time this mystery should not berevealed, unless you have the relevant spell-casting materials: ashesfrom an original DOS 6.2 boot disk burnt in effigy, a crucifixblessed by St. Emacs, assorted herbal roots from Central America, sandfrom Cebu, etc. Sorry!The part of the implementation wherethis is used is not yet finished. For now please simply follow theexisting examples. It’ll become clearer once it is. –drepper
A last remark about thegconv-modules is about the names notending with//
. A character set namedINTERNAL
is oftenmentioned. From the discussion above and the chosen name it should havebecome clear that this is the name for the representation used in theintermediate step of the triangulation. We have said that this is UCS-4but actually that is not quite right. The UCS-4 specification alsoincludes the specification of the byte ordering used. Since a UCS-4 valueconsists of four bytes, a stored value is affected by byte ordering. Theinternal representation isnot the same as UCS-4 in case the byteordering of the processor (or at least the running process) is not thesame as the one required for UCS-4. This is done for performance reasonsas one does not want to perform unnecessary byte-swapping operations ifone is not interested in actually seeing the result in UCS-4. To avoidtrouble with endianness, the internal representation consistently is namedINTERNAL
even on big-endian systems where the representations areidentical.
iconv
module data structures ¶So far this section has described how modules are located and consideredto be used. What remains to be described is the interface of the modulesso that one can write new ones. This section describes the interface asit is in use in January 1999. The interface will change a bit in thefuture but, with luck, only in an upwardly compatible way.
The definitions necessary to write new modules are publicly availablein the non-standard headergconv.h. The following text,therefore, describes the definitions from this header file. First,however, it is necessary to get an overview.
From the perspective of the user oficonv
the interface is quitesimple: theiconv_open
function returns a handle that can be usedin calls toiconv
, and finally the handle is freed with a call toiconv_close
. The problem is that the handle has to be able torepresent the possibly long sequences of conversion steps and also thestate of each conversion since the handle is all that is passed to theiconv
function. Therefore, the data structures are really theelements necessary to understanding the implementation.
We need two different kinds of data structures. The first describes theconversion and the second describes the state etc. There are really twotype definitions like this ingconv.h.
This data structure describes one conversion a module can perform. Foreach function in a loaded module with conversion functions there isexactly one object of this type. This object is shared by all users ofthe conversion (i.e., this object does not contain any informationcorresponding to an actual conversion; it only describes the conversionitself).
struct __gconv_loaded_object *__shlib_handle
const char *__modname
int __counter
All these elements of the structure are used internally in the C libraryto coordinate loading and unloading the shared object. One must not expect anyof the other elements to be available or initialized.
const char *__from_name
const char *__to_name
__from_name
and__to_name
contain the names of the source anddestination character sets. They can be used to identify the actualconversion to be carried out since one module might implement conversionsfor more than one character set and/or direction.
gconv_fct __fct
gconv_init_fct __init_fct
gconv_end_fct __end_fct
These elements contain pointers to the functions in the loadable module.The interface will be explained below.
int __min_needed_from
int __max_needed_from
int __min_needed_to
int __max_needed_to;
These values have to be supplied in the init function of the module. The__min_needed_from
value specifies how many bytes a character ofthe source character set at least needs. The__max_needed_from
specifies the maximum value that also includes possible shift sequences.
The__min_needed_to
and__max_needed_to
values serve thesame purpose as__min_needed_from
and__max_needed_from
butthis time for the destination character set.
It is crucial that these values be accurate since otherwise theconversion functions will have problems or not work at all.
int __stateful
This element must also be initialized by the init function.int __stateful
is nonzero if the source character set is stateful.Otherwise it is zero.
void *__data
This element can be used freely by the conversion functions in themodule.void *__data
can be used to communicate extra informationfrom one call to another.void *__data
need not be initialized ifnot needed at all. Ifvoid *__data
element is assigned a pointerto dynamically allocated memory (presumably in the init function) it hasto be made sure that the end function deallocates the memory. Otherwisethe application will leak memory.
It is important to be aware that this data structure is shared by allusers of this specification conversion and therefore the__data
element must not contain data specific to one specific use of theconversion function.
This is the data structure that contains the information specific toeach use of the conversion functions.
char *__outbuf
char *__outbufend
These elements specify the output buffer for the conversion step. The__outbuf
element points to the beginning of the buffer, and__outbufend
points to the byte following the last byte in thebuffer. The conversion function must not assume anything about the sizeof the buffer but it can be safely assumed there is room for atleast one complete character in the output buffer.
Once the conversion is finished, if the conversion is the last step, the__outbuf
element must be modified to point after the last bytewritten into the buffer to signal how much output is available. If thisconversion step is not the last one, the element must not be modified.The__outbufend
element must not be modified.
int __flags
This field is a set of flags. The__GCONV_IS_LAST
bit is set ifthis conversion step is the last one. This information is necessary forthe recursion. See the description of the conversion function internalsbelow. This element must never be modified.
int __invocation_counter
The conversion function can use this element to see how many calls ofthe conversion function already happened. Some character sets require acertain prolog when generating output, and by comparing this value withzero, one can find out whether it is the first call and whether,therefore, the prolog should be emitted. This element must never bemodified.
int __internal_use
This element is another one rarely used but needed in certainsituations. It is assigned a nonzero value in case the conversionfunctions are used to implementmbsrtowcs
et.al. (i.e., thefunction is not used directly through theiconv
interface).
This sometimes makes a difference as it is expected that theiconv
functions are used to translate entire texts while thembsrtowcs
functions are normally used only to convert singlestrings and might be used multiple times to convert entire texts.
But in this situation we would have problem complying with some rules ofthe character set specification. Some character sets require a prolog,which must appear exactly once for an entire text. If a number ofmbsrtowcs
calls are used to convert the text, only the first callmust add the prolog. However, because there is no communication between thedifferent calls ofmbsrtowcs
, the conversion functions have nopossibility to find this out. The situation is different for sequencesoficonv
calls since the handle allows access to the neededinformation.
Theint __internal_use
element is mostly used together with__invocation_counter
as follows:
if (!data->__internal_use && data->__invocation_counter == 0) /*Emit prolog. */ ...
This element must never be modified.
mbstate_t *__statep
The__statep
element points to an object of typembstate_t
(seeRepresenting the state of the conversion). The conversion of a stateful characterset must use the object pointed to by__statep
to storeinformation about the conversion state. The__statep
elementitself must never be modified.
mbstate_t __state
This element mustnever be used directly. It is only part ofthis structure to have the needed space allocated.
iconv
module interfaces ¶With the knowledge about the data structures we now can describe theconversion function itself. To understand the interface a bit ofknowledge is necessary about the functionality in the C library thatloads the objects with the conversions.
It is often the case that one conversion is used more than once (i.e.,there are severaliconv_open
calls for the same set of charactersets during one program run). Thembsrtowcs
et.al. functions inthe GNU C Library also use theiconv
functionality, whichincreases the number of uses of the same functions even more.
Because of this multiple use of conversions, the modules do not getloaded exclusively for one conversion. Instead a module once loaded canbe used by an arbitrary number oficonv
ormbsrtowcs
callsat the same time. The splitting of the information between conversion-function-specific information and conversion data makes this possible.The last section showed the two data structures used to do this.
This is of course also reflected in the interface and semantics of thefunctions that the modules must provide. There are three functions thatmust have the following names:
gconv_init
Thegconv_init
function initializes the conversion functionspecific data structure. This very same object is shared by allconversions that use this conversion and, therefore, no state informationabout the conversion itself must be stored in here. If a moduleimplements more than one conversion, thegconv_init
function willbe called multiple times.
gconv_end
Thegconv_end
function is responsible for freeing all resourcesallocated by thegconv_init
function. If there is nothing to do,this function can be missing. Special care must be taken if the moduleimplements more than one conversion and thegconv_init
functiondoes not allocate the same resources for all conversions.
gconv
This is the actual conversion function. It is called to convert oneblock of text. It gets passed the conversion step informationinitialized bygconv_init
and the conversion data, specific tothis use of the conversion functions.
There are three data types defined for the three module interfacefunctions and these define the interface.
int
(*__gconv_init_fct)(struct __gconv_step *)
¶This specifies the interface of the initialization function of themodule. It is called exactly once for each conversion the moduleimplements.
As explained in the description of thestruct __gconv_step
datastructure above the initialization function has to initialize parts ofit.
__min_needed_from
__max_needed_from
__min_needed_to
__max_needed_to
These elements must be initialized to the exact numbers of the minimumand maximum number of bytes used by one character in the source anddestination character sets, respectively. If the characters all have thesame size, the minimum and maximum values are the same.
__stateful
This element must be initialized to a nonzero value if the sourcecharacter set is stateful. Otherwise it must be zero.
If the initialization function needs to communicate some informationto the conversion function, this communication can happen using the__data
element of the__gconv_step
structure. But sincethis data is shared by all the conversions, it must not be modified bythe conversion function. The example below shows how this can be used.
#define MIN_NEEDED_FROM 1#define MAX_NEEDED_FROM 4#define MIN_NEEDED_TO 4#define MAX_NEEDED_TO 4intgconv_init (struct __gconv_step *step){ /*Determine which direction. */ struct iso2022jp_data *new_data; enum direction dir = illegal_dir; enum variant var = illegal_var; int result; if (__strcasecmp (step->__from_name, "ISO-2022-JP//") == 0) { dir = from_iso2022jp; var = iso2022jp; } else if (__strcasecmp (step->__to_name, "ISO-2022-JP//") == 0) { dir = to_iso2022jp; var = iso2022jp; } else if (__strcasecmp (step->__from_name, "ISO-2022-JP-2//") == 0) { dir = from_iso2022jp; var = iso2022jp2; } else if (__strcasecmp (step->__to_name, "ISO-2022-JP-2//") == 0) { dir = to_iso2022jp; var = iso2022jp2; } result = __GCONV_NOCONV; if (dir != illegal_dir) { new_data = (struct iso2022jp_data *) malloc (sizeof (struct iso2022jp_data)); result = __GCONV_NOMEM; if (new_data != NULL) { new_data->dir = dir; new_data->var = var; step->__data = new_data; if (dir == from_iso2022jp) { step->__min_needed_from = MIN_NEEDED_FROM; step->__max_needed_from = MAX_NEEDED_FROM; step->__min_needed_to = MIN_NEEDED_TO; step->__max_needed_to = MAX_NEEDED_TO; } else { step->__min_needed_from = MIN_NEEDED_TO; step->__max_needed_from = MAX_NEEDED_TO; step->__min_needed_to = MIN_NEEDED_FROM; step->__max_needed_to = MAX_NEEDED_FROM + 2; } /*Yes, this is a stateful encoding. */ step->__stateful = 1; result = __GCONV_OK; } } return result;}
The function first checks which conversion is wanted. The module fromwhich this function is taken implements four different conversions;which one is selected can be determined by comparing the names. Thecomparison should always be done without paying attention to the case.
Next, a data structure, which contains the necessary information aboutwhich conversion is selected, is allocated. The data structurestruct iso2022jp_data
is locally defined since, outside themodule, this data is not used at all. Please note that if all fourconversions this module supports are requested there are four datablocks.
One interesting thing is the initialization of the__min_
and__max_
elements of the step data object. A single ISO-2022-JPcharacter can consist of one to four bytes. Therefore theMIN_NEEDED_FROM
andMAX_NEEDED_FROM
macros are definedthis way. The output is always theINTERNAL
character set (akaUCS-4) and therefore each character consists of exactly four bytes. Forthe conversion fromINTERNAL
to ISO-2022-JP we have to take intoaccount that escape sequences might be necessary to switch the charactersets. Therefore the__max_needed_to
element for this directiongets assignedMAX_NEEDED_FROM + 2
. This takes into account thetwo bytes needed for the escape sequences to signal the switching. Theasymmetry in the maximum values for the two directions can be explainedeasily: when reading ISO-2022-JP text, escape sequences can be handledalone (i.e., it is not necessary to process a real character since theeffect of the escape sequence can be recorded in the state information).The situation is different for the other direction. Since it is ingeneral not known which character comes next, one cannot emit escapesequences to change the state in advance. This means the escapesequences have to be emitted together with the next character.Therefore one needs more room than only for the character itself.
The possible return values of the initialization function are:
__GCONV_OK
The initialization succeeded
__GCONV_NOCONV
The requested conversion is not supported in the module. This canhappen if thegconv-modules file has errors.
__GCONV_NOMEM
Memory required to store additional information could not be allocated.
The function called before the module is unloaded is significantlyeasier. It often has nothing at all to do; in which case it can be leftout completely.
void
(*__gconv_end_fct)(struct gconv_step *)
¶The task of this function is to free all resources allocated in theinitialization function. Therefore only the__data
element ofthe object pointed to by the argument is of interest. Continuing theexample from the initialization function, the finalization functionlooks like this:
voidgconv_end (struct __gconv_step *data){ free (data->__data);}
The most important function is the conversion function itself, which canget quite complicated for complex character sets. But since this is notof interest here, we will only describe a possible skeleton for theconversion function.
int
(*__gconv_fct)(struct __gconv_step *, struct __gconv_step_data *, const char **, const char *, size_t *, int)
¶The conversion function can be called for two basic reasons: to converttext or to reset the state. From the description of theiconv
function it can be seen why the flushing mode is necessary. What modeis selected is determined by the sixth argument, an integer. Thisargument being nonzero means that flushing is selected.
Common to both modes is where the output buffer can be found. Theinformation about this buffer is stored in the conversion step data. Apointer to this information is passed as the second argument to thisfunction. The description of thestruct __gconv_step_data
structure has more information on the conversion step data.
What has to be done for flushing depends on the source character set.If the source character set is not stateful, nothing has to be done.Otherwise the function has to emit a byte sequence to bring the stateobject into the initial state. Once this all happened the otherconversion modules in the chain of conversions have to get the samechance. Whether another step follows can be determined from the__GCONV_IS_LAST
flag in the__flags
field of the stepdata structure to which the first parameter points.
The more interesting mode is when actual text has to be converted. Thefirst step in this case is to convert as much text as possible from theinput buffer and store the result in the output buffer. The start of theinput buffer is determined by the third argument, which is a pointer to apointer variable referencing the beginning of the buffer. The fourthargument is a pointer to the byte right after the last byte in the buffer.
The conversion has to be performed according to the current state if thecharacter set is stateful. The state is stored in an object pointed toby the__statep
element of the step data (second argument). Onceeither the input buffer is empty or the output buffer is full theconversion stops. At this point, the pointer variable referenced by thethird parameter must point to the byte following the last processedbyte (i.e., if all of the input is consumed, this pointer and the fourthparameter have the same value).
What now happens depends on whether this step is the last one. If it isthe last step, the only thing that has to be done is to update the__outbuf
element of the step data structure to point after thelast written byte. This update gives the caller the information on howmuch text is available in the output buffer. In addition, the variablepointed to by the fifth parameter, which is of typesize_t
, mustbe incremented by the number of characters (not bytes) that wereconverted in a non-reversible way. Then, the function can return.
In case the step is not the last one, the later conversion functions haveto get a chance to do their work. Therefore, the appropriate conversionfunction has to be called. The information about the functions isstored in the conversion data structures, passed as the first parameter.This information and the step data are stored in arrays, so the nextelement in both cases can be found by simple pointer arithmetic:
intgconv (struct __gconv_step *step, struct __gconv_step_data *data, const char **inbuf, const char *inbufend, size_t *written, int do_flush){ struct __gconv_step *next_step = step + 1; struct __gconv_step_data *next_data = data + 1; ...
Thenext_step
pointer references the next step information andnext_data
the next data record. The call of the next functiontherefore will look similar to this:
next_step->__fct (next_step, next_data, &outerr, outbuf, written, 0)
But this is not yet all. Once the function call returns the conversionfunction might have some more to do. If the return value of the functionis__GCONV_EMPTY_INPUT
, more room is available in the outputbuffer. Unless the input buffer is empty, the conversion functions startall over again and process the rest of the input buffer. If the returnvalue is not__GCONV_EMPTY_INPUT
, something went wrong and we haveto recover from this.
A requirement for the conversion function is that the input bufferpointer (the third argument) always point to the last character thatwas put in converted form into the output buffer. This is triviallytrue after the conversion performed in the current step, but if theconversion functions deeper downstream stop prematurely, not allcharacters from the output buffer are consumed and, therefore, the inputbuffer pointers must be backed off to the right position.
Correcting the input buffers is easy to do if the input and outputcharacter sets have a fixed width for all characters. In this situationwe can compute how many characters are left in the output buffer and,therefore, can correct the input buffer pointer appropriately with asimilar computation. Things are getting tricky if either character sethas characters represented with variable length byte sequences, and itgets even more complicated if the conversion has to take care of thestate. In these cases the conversion has to be performed once again, fromthe known state before the initial conversion (i.e., if necessary thestate of the conversion has to be reset and the conversion loop has to beexecuted again). The difference now is that it is known how much inputmust be created, and the conversion can stop before converting the firstunused character. Once this is done the input buffer pointers must beupdated again and the function can return.
One final thing should be mentioned. If it is necessary for theconversion to know whether it is the first invocation (in case a prologhas to be emitted), the conversion function should increment the__invocation_counter
element of the step data structure justbefore returning to the caller. See the description of thestruct__gconv_step_data
structure above for more information on how this canbe used.
The return value must be one of the following values:
__GCONV_EMPTY_INPUT
All input was consumed and there is room left in the output buffer.
__GCONV_FULL_OUTPUT
No more room in the output buffer. In case this is not the last stepthis value is propagated down from the call of the next conversionfunction in the chain.
__GCONV_INCOMPLETE_INPUT
The input buffer is not entirely empty since it contains an incompletecharacter sequence.
The following example provides a framework for a conversion function.In case a new conversion has to be written the holes in thisimplementation have to be filled and that is it.
intgconv (struct __gconv_step *step, struct __gconv_step_data *data, const char **inbuf, const char *inbufend, size_t *written, int do_flush){ struct __gconv_step *next_step = step + 1; struct __gconv_step_data *next_data = data + 1; gconv_fct fct = next_step->__fct; int status; /*If the function is called with no input this means we haveto reset to the initial state. The possibly partlyconverted input is dropped. */ if (do_flush) { status = __GCONV_OK; /*Possible emit a byte sequence which put the state objectinto the initial state. */ /*Call the steps down the chain if there are any but onlyif we successfully emitted the escape sequence. */ if (status == __GCONV_OK && ! (data->__flags & __GCONV_IS_LAST)) status = fct (next_step, next_data, NULL, NULL, written, 1); } else { /*We preserve the initial values of the pointer variables. */ const char *inptr = *inbuf; char *outbuf = data->__outbuf; char *outend = data->__outbufend; char *outptr; do { /*Remember the start value for this round. */ inptr = *inbuf; /*The outbuf buffer is empty. */ outptr = outbuf; /*For stateful encodings the state must be safe here. */ /*Run the conversion loop.status
is setappropriately afterwards. */ /*If this is the last step, leave the loop. There isnothing we can do. */ if (data->__flags & __GCONV_IS_LAST) { /*Store information about how many bytes areavailable. */ data->__outbuf = outbuf; /*If any non-reversible conversions were performed,add the number to*written
. */ break; } /*Write out all output that was produced. */ if (outbuf > outptr) { const char *outerr = data->__outbuf; int result; result = fct (next_step, next_data, &outerr, outbuf, written, 0); if (result != __GCONV_EMPTY_INPUT) { if (outerr != outbuf) { /*Reset the input buffer pointer. Wedocument here the complex case. */ size_t nstatus; /*Reload the pointers. */ *inbuf = inptr; outbuf = outptr; /*Possibly reset the state. */ /*Redo the conversion, but this timethe end of the output buffer is atouterr
. */ } /*Change the status. */ status = result; } else /*All the output is consumed, we can make another run if everything was ok. */ if (status == __GCONV_FULL_OUTPUT) status = __GCONV_OK; } } while (status == __GCONV_OK); /*We finished one use of this step. */ ++data->__invocation_counter; } return status;}
This information should be sufficient to write new modules. Anybodydoing so should also take a look at the available source code in theGNU C Library sources. It contains many examples of working and optimizedmodules.
Next:Message Translation, Previous:Character Set Handling, Up:Main Menu [Contents][Index]
Different countries and cultures have varying conventions for how tocommunicate. These conventions range from very simple ones, such as theformat for representing dates and times, to very complex ones, such asthe language spoken.
Internationalization of software means programming it to be ableto adapt to the user’s favorite conventions. In ISO C,internationalization works by means oflocales. Each localespecifies a collection of conventions, one convention for each purpose.The user chooses a set of conventions by specifying a locale (viaenvironment variables).
All programs inherit the chosen locale as part of their environment.Provided the programs are written to obey the choice of locale, theywill follow the conventions preferred by the user.
Each locale specifies conventions for several purposes, including thefollowing:
Some aspects of adapting to the specified locale are handledautomatically by the library subroutines. For example, all your programneeds to do in order to use the collating sequence of the chosen localeis to usestrcoll
orstrxfrm
to compare strings.
Other aspects of locales are beyond the comprehension of the library.For example, the library can’t automatically translate your program’soutput messages into other languages. The only way you can supportoutput in the user’s favorite language is to program this more or lessby hand. The C library provides functions to handle translations formultiple languages easily.
This chapter discusses the mechanism by which you can modify the currentlocale. The effects of the current locale on specific library functionsare discussed in more detail in the descriptions of those functions.
Next:Locale Categories, Previous:What Effects a Locale Has, Up:Locales and Internationalization [Contents][Index]
The simplest way for the user to choose a locale is to set theenvironment variableLANG
. This specifies a single locale to usefor all purposes. For example, a user could specify a hypotheticallocale named ‘espana-castellano’ to use the standard conventions ofmost of Spain.
The set of locales supported depends on the operating system you areusing, and so do their names, except that the standard locale called‘C’ or ‘POSIX’ always exist. SeeLocale Names.
In order to force the system to always use the default locale, theuser can set theLC_ALL
environment variable to ‘C’.
A user also has the option of specifying different locales fordifferent purposes—in effect, choosing a mixture of multiplelocales. SeeLocale Categories.
For example, the user might specify the locale ‘espana-castellano’for most purposes, but specify the locale ‘usa-english’ forcurrency formatting. This might make sense if the user is aSpanish-speaking American, working in Spanish, but representing monetaryamounts in US dollars.
Note that both locales ‘espana-castellano’ and ‘usa-english’,like all locales, would include conventions for all of the purposes towhich locales apply. However, the user can choose to use each localefor a particular subset of those purposes.
Next:How Programs Set the Locale, Previous:Choosing a Locale, Up:Locales and Internationalization [Contents][Index]
The purposes that locales serve are grouped intocategories, sothat a user or a program can choose the locale for each categoryindependently. Here is a table of categories; each name is both anenvironment variable that a user can set, and a macro name that you canuse as the first argument tosetlocale
.
The contents of the environment variable (or the string in the secondargument tosetlocale
) has to be a valid locale name.SeeLocale Names.
LC_COLLATE
¶This category applies to collation of strings (functionsstrcoll
andstrxfrm
); seeCollation Functions.
LC_CTYPE
¶This category applies to classification and conversion of characters,and to multibyte and wide characters;seeCharacter Handling, andCharacter Set Handling.
LC_MONETARY
¶This category applies to formatting monetary values; seeGeneric Numeric Formatting Parameters.
LC_NUMERIC
¶This category applies to formatting numeric values that are notmonetary; seeGeneric Numeric Formatting Parameters.
LC_TIME
¶This category applies to formatting date and time values; seeFormatting Calendar Time.
LC_MESSAGES
¶This category applies to selecting the language used in the userinterface for message translation (seeThe Uniforum approach to Message Translation;seeX/Open Message Catalog Handling) and contains regular expressionsfor affirmative and negative responses.
LC_ALL
¶This is not a category; it is only a macro that you can usewithsetlocale
to set a single locale for all purposes. Settingthis environment variable overwrites all selections by the otherLC_*
variables orLANG
.
LANG
¶If this environment variable is defined, its value specifies the localeto use for all purposes except as overridden by the variables above.
When developing the message translation functions it was felt that thefunctionality provided by the variables above is not sufficient. Forexample, it should be possible to specify more than one locale name.Take a Swedish user who better speaks German than English, and a programwhose messages are output in English by default. It should be possibleto specify that the first choice of language is Swedish, the secondGerman, and if this also fails to use English. This ispossible with the variableLANGUAGE
. For further description ofthis GNU extension seeUser influence ongettext
.
Next:Standard Locales, Previous:Locale Categories, Up:Locales and Internationalization [Contents][Index]
A C program inherits its locale environment variables when it starts up.This happens automatically. However, these variables do notautomatically control the locale used by the library functions, becauseISO C says that all programs start by default in the standard ‘C’locale. To use the locales specified by the environment, you must callsetlocale
. Call it as follows:
setlocale (LC_ALL, "");
to select a locale based on the user choice of the appropriateenvironment variables.
You can also usesetlocale
to specify a particular locale, forgeneral use or for a specific category.
The symbols in this section are defined in the header filelocale.h.
char *
setlocale(intcategory, const char *locale)
¶Preliminary:| MT-Unsafe const:locale env| AS-Unsafe init lock heap corrupt| AC-Unsafe init corrupt lock mem fd| SeePOSIX Safety Concepts.
The functionsetlocale
sets the current locale for categorycategory tolocale.
Ifcategory isLC_ALL
, this specifies the locale for allpurposes. The other possible values ofcategory specify asingle purpose (seeLocale Categories).
You can also use this function to find out the current locale by passinga null pointer as thelocale argument. In this case,setlocale
returns a string that is the name of the localecurrently selected for categorycategory.
The string returned bysetlocale
can be overwritten by subsequentcalls, so you should make a copy of the string (seeCopying Strings and Arrays) if you want to save it past any further calls tosetlocale
. (The standard library is guaranteed never to callsetlocale
itself.)
You should not modify the string returned bysetlocale
. It mightbe the same string that was passed as an argument in a previous call tosetlocale
. One requirement is that thecategory must bethe same in the call the string was returned and the one when the stringis passed in aslocale parameter.
When you read the current locale for categoryLC_ALL
, the valueencodes the entire combination of selected locales for all categories.If you specify the same “locale name” withLC_ALL
in asubsequent call tosetlocale
, it restores the same combinationof locale selections.
To be sure you can use the returned string encoding the currently selectedlocale at a later time, you must make a copy of the string. It is notguaranteed that the returned pointer remains valid over time.
When thelocale argument is not a null pointer, the string returnedbysetlocale
reflects the newly-modified locale.
If you specify an empty string forlocale, this means to read theappropriate environment variable and use its value to select the localeforcategory.
If a nonempty string is given forlocale, then the locale of thatname is used if possible.
The effective locale name (either the second argument tosetlocale
, or if the argument is an empty string, the nameobtained from the process environment) must be a valid locale name.SeeLocale Names.
If you specify an invalid locale name,setlocale
returns a nullpointer and leaves the current locale unchanged.
Here is an example showing how you might usesetlocale
totemporarily switch to a new locale.
#include <stddef.h>#include <locale.h>#include <stdlib.h>#include <string.h>voidwith_other_locale (char *new_locale, void (*subroutine) (int), int argument){ char *old_locale, *saved_locale; /*Get the name of the current locale. */ old_locale = setlocale (LC_ALL, NULL); /*Copy the name so it won’t be clobbered bysetlocale
. */ saved_locale = strdup (old_locale); if (saved_locale == NULL) fatal ("Out of memory"); /*Now change the locale and do some stuff with it. */ setlocale (LC_ALL, new_locale); (*subroutine) (argument); /*Restore the original locale. */ setlocale (LC_ALL, saved_locale); free (saved_locale);}
Portability Note: Some ISO C systems may define additionallocale categories, and future versions of the library will do so. Forportability, assume that any symbol beginning with ‘LC_’ might bedefined inlocale.h.
Next:Locale Names, Previous:How Programs Set the Locale, Up:Locales and Internationalization [Contents][Index]
The only locale names you can count on finding on all operating systemsare these three standard ones:
"C"
This is the standard C locale. The attributes and behavior it providesare specified in the ISO C standard. When your program starts up, itinitially uses this locale by default.
"POSIX"
This is the standard POSIX locale. Currently, it is an alias for thestandard C locale.
""
The empty name says to select a locale based on environment variables.SeeLocale Categories.
Defining and installing named locales is normally a responsibility ofthe system administrator at your site (or the person who installedthe GNU C Library). It is also possible for the user to create privatelocales. All this will be discussed later when describing the tool todo so.
If your program needs to use something other than the ‘C’ locale,it will be more portable if you use whatever locale the user specifieswith the environment, rather than trying to specify some non-standardlocale explicitly by name. Remember, different machines might havedifferent sets of locales installed.
Next:Accessing Locale Information, Previous:Standard Locales, Up:Locales and Internationalization [Contents][Index]
The following command prints a list of locales supported by thesystem:
locale -a
Portability Note: With the notable exception of the standardlocale names ‘C’ and ‘POSIX’, locale names aresystem-specific.
Most locale names follow XPG syntax and consist of up to four parts:
language[_territory[.codeset]][@modifier]
Beside the first part, all of them are allowed to be missing. If thefull specified locale is not found, less specific ones are looked for.The various parts will be stripped off, in the following order:
For example, the locale name ‘de_AT.iso885915@euro’ denotes aGerman-language locale for use in Austria, using the ISO-8859-15(Latin-9) character set, and with the Euro as the currency symbol.
In addition to locale names which follow XPG syntax, systems mayprovide aliases such as ‘german’. Both categories of names mustnot contain the slash character ‘/’.
If the locale name starts with a slash ‘/’, it is treated as apath relative to the configured locale directories; seeLOCPATH
below. The specified path must not contain a component ‘..’, orthe name is invalid, andsetlocale
will fail.
Portability Note: POSIX suggests that if a locale name startswith a slash ‘/’, it is resolved as an absolute path. However,the GNU C Library treats it as a relative path under the directories listedinLOCPATH
(or the default locale directory ifLOCPATH
is unset).
Locale names which are longer than an implementation-defined limit areinvalid and causesetlocale
to fail.
As a special case, locale names used withLC_ALL
can combineseveral locales, reflecting different locale settings for differentcategories. For example, you might want to use a U.S. locale with ISOA4 paper format, so you setLANG
to ‘en_US.UTF-8’, andLC_PAPER
to ‘de_DE.UTF-8’. In this case, theLC_ALL
-style combined locale name is
LC_CTYPE=en_US.UTF-8;LC_TIME=en_US.UTF-8;LC_PAPER=de_DE.UTF-8;...
followed by other category settings not shown here.
The path used for finding locale data can be set using theLOCPATH
environment variable. This variable lists thedirectories in which to search for locale definitions, separated by acolon ‘:’.
The default path for finding locale data is system specific. A typicalvalue for theLOCPATH
default is:
/usr/share/locale
The value ofLOCPATH
is ignored by privileged programs forsecurity reasons, and only the default directory is used.
Next:A dedicated function to format numbers, Previous:Locale Names, Up:Locales and Internationalization [Contents][Index]
There are several ways to access locale information. The simplestway is to let the C library itself do the work. Several of thefunctions in this library implicitly access the locale data, and usewhat information is provided by the currently selected locale. This ishow the locale model is meant to work normally.
As an example take thestrftime
function, which is meant to nicelyformat date and time information (seeFormatting Calendar Time).Part of the standard information contained in theLC_TIME
category is the names of the months. Instead of requiring theprogrammer to take care of providing the translations thestrftime
function does this all by itself.%A
in the format string is replaced by the appropriate weekdayname of the locale currently selected byLC_TIME
. This is aneasy example, and wherever possible functions do things automaticallyin this way.
But there are quite often situations when there is simply no functionto perform the task, or it is simply not possible to do the workautomatically. For these cases it is necessary to access theinformation in the locale directly. To do this the C library providestwo functions:localeconv
andnl_langinfo
. The former ispart of ISO C and therefore portable, but has a brain-damagedinterface. The second is part of the Unix interface and is portable inas far as the system follows the Unix standards.
localeconv
: It is portable but … ¶Together with thesetlocale
function the ISO C peopleinvented thelocaleconv
function. It is a masterpiece of poordesign. It is expensive to use, not extensible, and not generallyusable as it provides access to onlyLC_MONETARY
andLC_NUMERIC
related information. Nevertheless, if it isapplicable to a given situation it should be used since it is veryportable. The functionstrfmon
formats monetary amountsaccording to the selected locale using this information.
struct lconv *
localeconv(void)
¶Preliminary:| MT-Unsafe race:localeconv locale| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
Thelocaleconv
function returns a pointer to a structure whosecomponents contain information about how numeric and monetary valuesshould be formatted in the current locale.
You should not modify the structure or its contents. The structure mightbe overwritten by subsequent calls tolocaleconv
, or by calls tosetlocale
, but no other function in the library overwrites thisvalue.
localeconv
’s return value is of this data type. Its elements aredescribed in the following subsections.
If a member of the structurestruct lconv
has typechar
,and the value isCHAR_MAX
, it means that the current locale hasno value for that parameter.
These are the standard members ofstruct lconv
; there may beothers.
char *decimal_point
char *mon_decimal_point
These are the decimal-point separators used in formatting non-monetaryand monetary quantities, respectively. In the ‘C’ locale, thevalue ofdecimal_point
is"."
, and the value ofmon_decimal_point
is""
.
char *thousands_sep
char *mon_thousands_sep
These are the separators used to delimit groups of digits to the left ofthe decimal point in formatting non-monetary and monetary quantities,respectively. In the ‘C’ locale, both members have a value of""
(the empty string).
char *grouping
char *mon_grouping
These are strings that specify how to group the digits to the left ofthe decimal point.grouping
applies to non-monetary quantitiesandmon_grouping
applies to monetary quantities. Use eitherthousands_sep
ormon_thousands_sep
to separate the digitgroups.
Each member of these strings is to be interpreted as an integer value oftypechar
. Successive numbers (from left to right) give thesizes of successive groups (from right to left, starting at the decimalpoint.) The last member is either0
, in which case the previousmember is used over and over again for all the remaining groups, orCHAR_MAX
, in which case there is no more grouping—or, putanother way, any remaining digits form one large group withoutseparators.
For example, ifgrouping
is"\04\03\02"
, the correctgrouping for the number123456787654321
is ‘12’, ‘34’,‘56’, ‘78’, ‘765’, ‘4321’. This uses a group of 4digits at the end, preceded by a group of 3 digits, preceded by groupsof 2 digits (as many as needed). With a separator of ‘,’, thenumber would be printed as ‘12,34,56,78,765,4321’.
A value of"\03"
indicates repeated groups of three digits, asnormally used in the U.S.
In the standard ‘C’ locale, bothgrouping
andmon_grouping
have a value of""
. This value specifies nogrouping at all.
char int_frac_digits
char frac_digits
These are small integers indicating how many fractional digits (to theright of the decimal point) should be displayed in a monetary value ininternational and local formats, respectively. (Most often, bothmembers have the same value.)
In the standard ‘C’ locale, both of these members have the valueCHAR_MAX
, meaning “unspecified”. The ISO standard doesn’t saywhat to do when you find this value; we recommend printing nofractional digits. (This locale also specifies the empty string formon_decimal_point
, so printing any fractional digits would beconfusing!)
Next:Printing the Sign of a Monetary Amount, Previous:Generic Numeric Formatting Parameters, Up:localeconv
: It is portable but … [Contents][Index]
These members of thestruct lconv
structure specify how to printthe symbol to identify a monetary value—the international analog of‘$’ for US dollars.
Each country has two standard currency symbols. Thelocal currencysymbol is used commonly within the country, while theinternational currency symbol is used internationally to refer tothat country’s currency when it is necessary to indicate the countryunambiguously.
For example, many countries use the dollar as their monetary unit, andwhen dealing with international currencies it’s important to specifythat one is dealing with (say) Canadian dollars instead of U.S. dollarsor Australian dollars. But when the context is known to be Canada,there is no need to make this explicit—dollar amounts are implicitlyassumed to be in Canadian dollars.
char *currency_symbol
The local currency symbol for the selected locale.
In the standard ‘C’ locale, this member has a value of""
(the empty string), meaning “unspecified”. The ISO standard doesn’tsay what to do when you find this value; we recommend you simply printthe empty string as you would print any other string pointed to by thisvariable.
char *int_curr_symbol
The international currency symbol for the selected locale.
The value ofint_curr_symbol
should normally consist of athree-letter abbreviation determined by the international standardISO 4217 Codes for the Representation of Currency and Funds,followed by a one-character separator (often a space).
In the standard ‘C’ locale, this member has a value of""
(the empty string), meaning “unspecified”. We recommend you simply printthe empty string as you would print any other string pointed to by thisvariable.
char p_cs_precedes
char n_cs_precedes
char int_p_cs_precedes
char int_n_cs_precedes
These members are1
if thecurrency_symbol
orint_curr_symbol
strings should precede the value of a monetaryamount, or0
if the strings should follow the value. Thep_cs_precedes
andint_p_cs_precedes
members apply topositive amounts (or zero), and then_cs_precedes
andint_n_cs_precedes
members apply to negative amounts.
In the standard ‘C’ locale, all of these members have a value ofCHAR_MAX
, meaning “unspecified”. The ISO standard doesn’t saywhat to do when you find this value. We recommend printing thecurrency symbol before the amount, which is right for most countries.In other words, treat all nonzero values alike in these members.
The members with theint_
prefix apply to theint_curr_symbol
while the other two apply tocurrency_symbol
.
char p_sep_by_space
char n_sep_by_space
char int_p_sep_by_space
char int_n_sep_by_space
These members are1
if a space should appear between thecurrency_symbol
orint_curr_symbol
strings and theamount, or0
if no space should appear. Thep_sep_by_space
andint_p_sep_by_space
members apply topositive amounts (or zero), and then_sep_by_space
andint_n_sep_by_space
members apply to negative amounts.
In the standard ‘C’ locale, all of these members have a value ofCHAR_MAX
, meaning “unspecified”. The ISO standard doesn’t saywhat you should do when you find this value; we suggest you treat it as1 (print a space). In other words, treat all nonzero values alike inthese members.
The members with theint_
prefix apply to theint_curr_symbol
while the other two apply tocurrency_symbol
. There is one specialty with theint_curr_symbol
, though. Since all legal values contain a spaceat the end of the string one either prints this space (if the currencysymbol must appear in front and must be separated) or one has to avoidprinting this character at all (especially when at the end of thestring).
Previous:Printing the Currency Symbol, Up:localeconv
: It is portable but … [Contents][Index]
These members of thestruct lconv
structure specify how to printthe sign (if any) of a monetary value.
char *positive_sign
char *negative_sign
These are strings used to indicate positive (or zero) and negativemonetary quantities, respectively.
In the standard ‘C’ locale, both of these members have a value of""
(the empty string), meaning “unspecified”.
The ISO standard doesn’t say what to do when you find this value; werecommend printingpositive_sign
as you find it, even if it isempty. For a negative value, printnegative_sign
as you find itunless both it andpositive_sign
are empty, in which case print‘-’ instead. (Failing to indicate the sign at all seems ratherunreasonable.)
char p_sign_posn
char n_sign_posn
char int_p_sign_posn
char int_n_sign_posn
These members are small integers that indicate how toposition the sign for nonnegative and negative monetary quantities,respectively. (The string used for the sign is what was specified withpositive_sign
ornegative_sign
.) The possible values areas follows:
0
The currency symbol and quantity should be surrounded by parentheses.
1
Print the sign string before the quantity and currency symbol.
2
Print the sign string after the quantity and currency symbol.
3
Print the sign string right before the currency symbol.
4
Print the sign string right after the currency symbol.
CHAR_MAX
“Unspecified”. Both members have this value in the standard‘C’ locale.
The ISO standard doesn’t say what you should do when the value isCHAR_MAX
. We recommend you print the sign after the currencysymbol.
The members with theint_
prefix apply to theint_curr_symbol
while the other two apply tocurrency_symbol
.
Previous:localeconv
: It is portable but …, Up:Accessing Locale Information [Contents][Index]
When writing the X/Open Portability Guide the authors realized that thelocaleconv
function is not enough to provide reasonable access tolocale information. The information which was meant to be availablein the locale (as later specified in the POSIX.1 standard) requires moreways to access it. Therefore thenl_langinfo
functionwas introduced.
char *
nl_langinfo(nl_itemitem)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thenl_langinfo
function can be used to access individualelements of the locale categories. Unlike thelocaleconv
function, which returns all the information,nl_langinfo
lets the caller select what information it requires. This is veryfast and it is not a problem to call this function multiple times.
A second advantage is that in addition to the numeric and monetaryformatting information, information from theLC_TIME
andLC_MESSAGES
categories is available.
The typenl_item
is defined innl_types.h. The argumentitem is a numeric value defined in the headerlanginfo.h.The X/Open standard defines the following values:
CODESET
¶nl_langinfo
returns a string with the name of the coded characterset used in the selected locale.
ABDAY_1
¶ABDAY_2
¶ABDAY_3
¶ABDAY_4
¶ABDAY_5
¶ABDAY_6
¶ABDAY_7
¶nl_langinfo
returns the abbreviated weekday name.ABDAY_1
corresponds to Sunday.
DAY_1
¶DAY_2
¶DAY_3
¶DAY_4
¶DAY_5
¶DAY_6
¶DAY_7
¶Similar toABDAY_1
, etc., but here the return value is theunabbreviated weekday name.
ABMON_1
¶ABMON_2
¶ABMON_3
¶ABMON_4
¶ABMON_5
¶ABMON_6
¶ABMON_7
¶ABMON_8
¶ABMON_9
¶ABMON_10
¶ABMON_11
¶ABMON_12
¶The return value is the abbreviated name of the month, in thegrammatical form used when the month forms part of a complete date.ABMON_1
corresponds to January.
MON_1
¶MON_2
¶MON_3
¶MON_4
¶MON_5
¶MON_6
¶MON_7
¶MON_8
¶MON_9
¶MON_10
¶MON_11
¶MON_12
¶Similar toABMON_1
, etc., but here the month names are notabbreviated. Here the first valueMON_1
also corresponds toJanuary.
ALTMON_1
¶ALTMON_2
¶ALTMON_3
¶ALTMON_4
¶ALTMON_5
¶ALTMON_6
¶ALTMON_7
¶ALTMON_8
¶ALTMON_9
¶ALTMON_10
¶ALTMON_11
¶ALTMON_12
¶Similar toMON_1
, etc., but here the month names are in thegrammatical form used when the month is named by itself. Thestrftime
functions use these month names for the conversionspecifier%OB
(seeFormatting Calendar Time).
Note that not all languages need two different forms of the month names,so the strings returned forMON_…
andALTMON_…
may or may not be the same, depending on the locale.
NB:ABALTMON_…
constants corresponding to the%Ob
conversion specifier are not currently provided, but areexpected to be in a future release. In the meantime, it is possibleto use_NL_ABALTMON_…
.
AM_STR
¶PM_STR
¶The return values are strings which can be used in the representation of timeas an hour from 1 to 12 plus an am/pm specifier.
Note that in locales which do not use this time representationthese strings might be empty, in which case the am/pm formatcannot be used at all.
D_T_FMT
¶The return value can be used as a format string forstrftime
torepresent time and date in a locale-specific way.
D_FMT
¶The return value can be used as a format string forstrftime
torepresent a date in a locale-specific way.
T_FMT
¶The return value can be used as a format string forstrftime
torepresent time in a locale-specific way.
T_FMT_AMPM
¶The return value can be used as a format string forstrftime
torepresent time in the am/pm format.
Note that if the am/pm format does not make any sense for theselected locale, the return value might be the same as the one forT_FMT
.
ERA
¶The return value represents the era used in the current locale.
Most locales do not define this value. An example of a locale whichdoes define this value is the Japanese one. In Japan, the traditionalrepresentation of dates includes the name of the era corresponding tothe then-emperor’s reign.
Normally it should not be necessary to use this value directly.Specifying theE
modifier in their format strings causes thestrftime
functions to use this information. The format of thereturned string is not specified, and therefore you should not assumeknowledge of it on different systems.
ERA_YEAR
¶The return value gives the year in the relevant era of the locale.As forERA
it should not be necessary to use this value directly.
ERA_D_T_FMT
¶This return value can be used as a format string forstrftime
torepresent dates and times in a locale-specific era-based way.
ERA_D_FMT
¶This return value can be used as a format string forstrftime
torepresent a date in a locale-specific era-based way.
ERA_T_FMT
¶This return value can be used as a format string forstrftime
torepresent time in a locale-specific era-based way.
ALT_DIGITS
¶The return value is a representation of up to100 values used torepresent the values0 to99. As forERA
thisvalue is not intended to be used directly, but instead indirectlythrough thestrftime
function. When the modifierO
isused in a format which would otherwise use numerals to represent hours,minutes, seconds, weekdays, months, or weeks, the appropriate value forthe locale is used instead.
INT_CURR_SYMBOL
¶The same as the value returned bylocaleconv
in theint_curr_symbol
element of thestruct lconv
.
CURRENCY_SYMBOL
¶CRNCYSTR
¶The same as the value returned bylocaleconv
in thecurrency_symbol
element of thestruct lconv
.
CRNCYSTR
is a deprecated alias still required by Unix98.
MON_DECIMAL_POINT
¶The same as the value returned bylocaleconv
in themon_decimal_point
element of thestruct lconv
.
MON_THOUSANDS_SEP
¶The same as the value returned bylocaleconv
in themon_thousands_sep
element of thestruct lconv
.
MON_GROUPING
¶The same as the value returned bylocaleconv
in themon_grouping
element of thestruct lconv
.
POSITIVE_SIGN
¶The same as the value returned bylocaleconv
in thepositive_sign
element of thestruct lconv
.
NEGATIVE_SIGN
¶The same as the value returned bylocaleconv
in thenegative_sign
element of thestruct lconv
.
INT_FRAC_DIGITS
¶The same as the value returned bylocaleconv
in theint_frac_digits
element of thestruct lconv
.
FRAC_DIGITS
¶The same as the value returned bylocaleconv
in thefrac_digits
element of thestruct lconv
.
P_CS_PRECEDES
¶The same as the value returned bylocaleconv
in thep_cs_precedes
element of thestruct lconv
.
P_SEP_BY_SPACE
¶The same as the value returned bylocaleconv
in thep_sep_by_space
element of thestruct lconv
.
N_CS_PRECEDES
¶The same as the value returned bylocaleconv
in then_cs_precedes
element of thestruct lconv
.
N_SEP_BY_SPACE
¶The same as the value returned bylocaleconv
in then_sep_by_space
element of thestruct lconv
.
P_SIGN_POSN
¶The same as the value returned bylocaleconv
in thep_sign_posn
element of thestruct lconv
.
N_SIGN_POSN
¶The same as the value returned bylocaleconv
in then_sign_posn
element of thestruct lconv
.
INT_P_CS_PRECEDES
¶The same as the value returned bylocaleconv
in theint_p_cs_precedes
element of thestruct lconv
.
INT_P_SEP_BY_SPACE
¶The same as the value returned bylocaleconv
in theint_p_sep_by_space
element of thestruct lconv
.
INT_N_CS_PRECEDES
¶The same as the value returned bylocaleconv
in theint_n_cs_precedes
element of thestruct lconv
.
INT_N_SEP_BY_SPACE
¶The same as the value returned bylocaleconv
in theint_n_sep_by_space
element of thestruct lconv
.
INT_P_SIGN_POSN
¶The same as the value returned bylocaleconv
in theint_p_sign_posn
element of thestruct lconv
.
INT_N_SIGN_POSN
¶The same as the value returned bylocaleconv
in theint_n_sign_posn
element of thestruct lconv
.
DECIMAL_POINT
¶RADIXCHAR
¶The same as the value returned bylocaleconv
in thedecimal_point
element of thestruct lconv
.
The nameRADIXCHAR
is a deprecated alias still used in Unix98.
THOUSANDS_SEP
¶THOUSEP
¶The same as the value returned bylocaleconv
in thethousands_sep
element of thestruct lconv
.
The nameTHOUSEP
is a deprecated alias still used in Unix98.
GROUPING
¶The same as the value returned bylocaleconv
in thegrouping
element of thestruct lconv
.
YESEXPR
¶The return value is a regular expression which can be used with theregex
function to recognize a positive response to a yes/noquestion. The GNU C Library provides therpmatch
function foreasier handling in applications.
NOEXPR
¶The return value is a regular expression which can be used with theregex
function to recognize a negative response to a yes/noquestion.
YESSTR
¶The return value is a locale-specific translation of the positive responseto a yes/no question.
Using this value is deprecated since it is a very special case ofmessage translation, and is better handled by the messagetranslation functions (seeMessage Translation).
The use of this symbol is deprecated. Instead message translationshould be used.
NOSTR
¶The return value is a locale-specific translation of the negative responseto a yes/no question. What is said forYESSTR
is also true here.
The use of this symbol is deprecated. Instead message translationshould be used.
The filelanginfo.h defines a lot more symbols but none of themare official. Using them is not portable, and the format of thereturn values might change. Therefore we recommended you not usethem.
Note that the return value for any valid argument can be usedin all situations (with the possible exception of the am/pm time formattingcodes). If the user has not selected any locale for theappropriate category,nl_langinfo
returns the information from the"C"
locale. It is therefore possible to use this function asshown in the example below.
If the argumentitem is not valid, a pointer to an empty string isreturned.
An example ofnl_langinfo
usage is a function which has toprint a given date and time in a locale-specific way. At first onemight think that, sincestrftime
internally uses the localeinformation, writing something like the following is enough:
size_ti18n_time_n_data (char *s, size_t len, const struct tm *tp){ return strftime (s, len, "%X %D", tp);}
The format contains no weekday or month names and therefore isinternationally usable. Wrong! The output produced is something like"hh:mm:ss MM/DD/YY"
. This format is only recognizable in theUSA. Other countries use different formats. Therefore the functionshould be rewritten like this:
size_ti18n_time_n_data (char *s, size_t len, const struct tm *tp){ return strftime (s, len, nl_langinfo (D_T_FMT), tp);}
Now it uses the date and time format of the localeselected when the program runs. If the user selects the localecorrectly there should never be a misunderstanding over the time anddate format.
Next:Yes-or-No Questions, Previous:Accessing Locale Information, Up:Locales and Internationalization [Contents][Index]
We have seen that the structure returned bylocaleconv
as well asthe values given tonl_langinfo
allow you to retrieve the variouspieces of locale-specific information to format numbers and monetaryamounts. We have also seen that the underlying rules are quite complex.
Therefore the X/Open standards introduce a function which uses suchlocale information, making it easier for the user to formatnumbers according to these rules.
ssize_t
strfmon(char *s, size_tmaxsize, const char *format, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thestrfmon
function is similar to thestrftime
functionin that it takes a buffer, its size, a format string,and values to write into the buffer as text in a form specifiedby the format string. Likestrftime
, the functionalso returns the number of bytes written into the buffer.
There are two differences:strfmon
can take more than oneargument, and, of course, the format specification is different. Likestrftime
, the format string consists of normal text, which isoutput as is, and format specifiers, which are indicated by a ‘%’.Immediately after the ‘%’, you can optionally specify various flagsand formatting information before the main formatting character, in asimilar way toprintf
:
The single byte characterf is used for this field as the numericfill character. By default this character is a space character.Filling with this character is only performed if a left precisionis specified. It is not just to fill to the given field width.
The number is printed without grouping the digits according to the rulesof the current locale. By default grouping is enabled.
At most one of these flags can be used. They select which format torepresent the sign of a currency amount. By default, and if‘+’ is given, the locale equivalent of+/- is used. If‘(’ is given, negative amounts are enclosed in parentheses. Theexact format is determined by the values of theLC_MONETARY
category of the locale selected at program runtime.
The output will not contain the currency symbol.
The output will be formatted left-justified instead of right-justified ifit does not fill the entire field width.
The next part of the specification is an optional field width. If nowidth is specified0 is taken. During output, the function firstdetermines how much space is required. If it requires at least as manycharacters as given by the field width, it is output using as much spaceas necessary. Otherwise, it is extended to use the full width byfilling with the space character. The presence or absence of the‘-’ flag determines the side at which such padding occurs. Ifpresent, the spaces are added at the right making the outputleft-justified, and vice versa.
So far the format looks familiar, being similar to theprintf
andstrftime
formats. However, the next two optional fieldsintroduce something new. The first one is a ‘#’ character followedby a decimal digit string. The value of the digit string specifies thenumber ofdigit positions to the left of the decimal point (orequivalent). This doesnot include the grouping character whenthe ‘^’ flag is not given. If the space needed to print the numberdoes not fill the whole width, the field is padded at the left side withthe fill character, which can be selected using the ‘=’ flag and bydefault is a space. For example, if the field width is selected as 6and the number is123, the fill character is ‘*’ the resultwill be ‘***123’.
The second optional field starts with a ‘.’ (period) and consistsof another decimal digit string. Its value describes the number ofcharacters printed after the decimal point. The default is selectedfrom the current locale (frac_digits
,int_frac_digits
, seeseeGeneric Numeric Formatting Parameters). If the exact representation needs more digitsthan given by the field width, the displayed value is rounded. If thenumber of fractional digits is selected to be zero, no decimal point isprinted.
As a GNU extension, thestrfmon
implementation in the GNU C Libraryallows an optional ‘L’ next as a format modifier. If this modifieris given, the argument is expected to be along double
instead ofadouble
value.
Finally, the last component is a format specifier. There are threespecifiers defined:
Use the locale’s rules for formatting an international currency value.
Use the locale’s rules for formatting a national currency value.
Place a ‘%’ in the output. There must be no flag, widthspecifier or modifier given, only ‘%%’ is allowed.
As forprintf
, the function reads the format stringfrom left to right and uses the values passed to the function followingthe format string. The values are expected to be either of typedouble
orlong double
, depending on the presence of themodifier ‘L’. The result is stored in the buffer pointed to bys. At mostmaxsize characters are stored.
The return value of the function is the number of characters stored ins, including the terminatingNULL
byte. If the number ofcharacters stored would exceedmaxsize, the function returns-1 and the content of the buffers is unspecified. In thiscaseerrno
is set toE2BIG
.
A few examples should make clear how the function works. It isassumed that all the following pieces of code are executed in a programwhich uses the USA locale (en_US
). The simplestform of the format is this:
strfmon (buf, 100, "@%n@%n@%n@", 123.45, -567.89, 12345.678);
The output produced is
"@$123.45@-$567.89@$12,345.68@"
We can notice several things here. First, the widths of the outputnumbers are different. We have not specified a width in the formatstring, and so this is no wonder. Second, the third number is printedusing thousands separators. The thousands separator for theen_US
locale is a comma. The number is also rounded..678 is rounded to.68 since the format does not specify aprecision and the default value in the locale is2. Finally,note that the national currency symbol is printed since ‘%n’ wasused, not ‘i’. The next example shows how we can align the output.
strfmon (buf, 100, "@%=*11n@%=*11n@%=*11n@", 123.45, -567.89, 12345.678);
The output this time is:
"@ $123.45@ -$567.89@ $12,345.68@"
Two things stand out. Firstly, all fields have the same width (elevencharacters) since this is the width given in the format and since nonumber required more characters to be printed. The second importantpoint is that the fill character is not used. This is correct since thewhite space was not used to achieve a precision given by a ‘#’modifier, but instead to fill to the given width. The differencebecomes obvious if we now add a width specification.
strfmon (buf, 100, "@%=*11#5n@%=*11#5n@%=*11#5n@", 123.45, -567.89, 12345.678);
The output is
"@ $***123.45@-$***567.89@ $12,456.68@"
Here we can see that all the currency symbols are now aligned, and thatthe space between the currency sign and the number is filled with theselected fill character. Note that although the width is selected to be5 and123.45 has three digits left of the decimal point,the space is filled with three asterisks. This is correct since, asexplained above, the width does not include the positions used to storethousands separators. One last example should explain the remainingfunctionality.
strfmon (buf, 100, "@%=0(16#5.3i@%=0(16#5.3i@%=0(16#5.3i@", 123.45, -567.89, 12345.678);
This rather complex format string produces the following output:
"@ USD 000123,450 @(USD 000567.890)@ USD 12,345.678 @"
The most noticeable change is the alternative way of representingnegative numbers. In financial circles this is often done usingparentheses, and this is what the ‘(’ flag selected. The fillcharacter is now ‘0’. Note that this ‘0’ character is notregarded as a numeric zero, and therefore the first and second numbersare not printed using a thousands separator. Since we used the formatspecifier ‘i’ instead of ‘n’, the international form of thecurrency symbol is used. This is a four letter string, in this case"USD "
. The last point is that since the precision right of thedecimal point is selected to be three, the first and second numbers areprinted with an extra zero at the end and the third number is printedwithout rounding.
Previous:A dedicated function to format numbers, Up:Locales and Internationalization [Contents][Index]
Some non GUI programs ask a yes-or-no question. If the messages(especially the questions) are translated into foreign languages, besure that you localize the answers too. It would be very bad habit toask a question in one language and request the answer in another, oftenEnglish.
The GNU C Library containsrpmatch
to give applications easyaccess to the corresponding locale definitions.
int
rpmatch(const char *response)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
The functionrpmatch
checks the string inresponse for whetheror not it is a correct yes-or-no answer and if yes, which one. Thecheck uses theYESEXPR
andNOEXPR
data in theLC_MESSAGES
category of the currently selected locale. Thereturn value is as follows:
1
The user entered an affirmative answer.
0
The user entered a negative answer.
-1
The answer matched neither theYESEXPR
nor theNOEXPR
regular expression.
This function is not standardized but available beside in the GNU C Library atleast also in the IBM AIX library.
This function would normally be used like this:
... /*Use a safe default. */ _Bool doit = false; fputs (gettext ("Do you really want to do this? "), stdout); fflush (stdout); /*Prepare thegetline
call. */ line = NULL; len = 0; while (getline (&line, &len, stdin) >= 0) { /*Check the response. */ int res = rpmatch (line); if (res >= 0) { /*We got a definitive answer. */ if (res > 0) doit = true; break; } } /*Free whatgetline
allocated. */ free (line);
Note that the loop continues until a read error is detected or until adefinitive (positive or negative) answer is read.
Next:Searching and Sorting, Previous:Locales and Internationalization, Up:Main Menu [Contents][Index]
The program’s interface with the user should be designed to ease the user’stask. One way to ease the user’s task is to use messages in whateverlanguage the user prefers.
Printing messages in different languages can be implemented in differentways. One could add all the different languages in the source code andchoose among the variants every time a message has to be printed. This iscertainly not a good solution since extending the set of languages iscumbersome (the code must be changed) and the code itself can becomereally big with dozens of message sets.
A better solution is to keep the message sets for each languagein separate files which are loaded at runtime depending on the languageselection of the user.
The GNU C Library provides two different sets of functions to supportmessage translation. Thecatgets
family of functions werepreviously the only family defined in the X/Open standard but they werederived from industry decisions and therefore not necessarily based onreasonable decisions. However, the preferablegettext
family offunctions was standardized in POSIX-1.2024.
As mentioned above, the message catalog handling provides easyextendability by using external data files which contain the messagetranslations. I.e., these files contain for each of the messages usedin the program a translation for the appropriate language. So the tasksof the message handling functions are
The two approaches mainly differ in the implementation of this laststep. Decisions made in the last step influence the rest of the design.
Thecatgets
functions are based on the simple scheme:
Associate every message to translate in the source code with a uniqueidentifier. To retrieve a message from a catalog file solely theidentifier is used.
This means for the author of the program that s/he will have to makesure the meaning of the identifier in the program code and in themessage catalogs is always the same.
Before a message can be translated the catalog file must be located.The user of the program must be able to guide the responsible functionto find whatever catalog the user wants. This is separated from whatthe programmer had in mind.
All the types, constants and functions for thecatgets
functionsare defined/declared in thenl_types.h header file.
catgets
function familycatgets
interfacecatgets
function family ¶nl_catd
catopen(const char *cat_name, intflag)
¶Preliminary:| MT-Safe env| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thecatopen
function tries to locate the message data file namedcat_name and loads it when found. The return value is of anopaque type and can be used in calls to the other functions to refer tothis loaded catalog.
The return value is(nl_catd) -1
in case the function failed andno catalog was loaded. The global variableerrno
contains a codefor the error causing the failure. But even if the function callsucceeded this does not mean that all messages can be translated.
Locating the catalog file must happen in a way which lets the user ofthe program influence the decision. It is up to the user to decideabout the language to use and sometimes it is useful to use alternatecatalog files. All this can be specified by the user by setting someenvironment variables.
The first problem is to find out where all the message catalogs arestored. Every program could have its own place to keep all thedifferent files but usually the catalog files are grouped by languagesand the catalogs for all programs are kept in the same place.
To tell thecatopen
function where the catalog for the programcan be found the user can set the environment variableNLSPATH
toa value which describes her/his choice. Since this value must be usablefor different languages and locales it cannot be a simple string.Instead it is a format string (similar toprintf
’s). An exampleis
/usr/share/locale/%L/%N:/usr/share/locale/%L/LC_MESSAGES/%N
First one can see that more than one directory can be specified (withthe usual syntax of separating them by colons). The next things toobserve are the format string,%L
and%N
in this case.Thecatopen
function knows about several of them and thereplacement for all of them is of course different.
%N
This format element is substituted with the name of the catalog file.This is the value of thecat_name argument given tocatgets
.
%L
This format element is substituted with the name of the currentlyselected locale for translating messages. How this is determined isexplained below.
%l
(This is the lowercase ell.) This format element is substituted with thelanguage element of the locale name. The string describing the selectedlocale is expected to have the formlang[_terr[.codeset]]
and this format uses thefirst partlang.
%t
This format element is substituted by the territory partterr ofthe name of the currently selected locale. See the explanation of theformat above.
%c
This format element is substituted by the codeset partcodeset ofthe name of the currently selected locale. See the explanation of theformat above.
%%
Since%
is used as a meta character there must be a way toexpress the%
character in the result itself. Using%%
does this just like it works forprintf
.
UsingNLSPATH
allows arbitrary directories to be searched formessage catalogs while still allowing different languages to be used.If theNLSPATH
environment variable is not set, the default valueis
prefix/share/locale/%L/%N:prefix/share/locale/%L/LC_MESSAGES/%N
whereprefix is given toconfigure
while installing the GNU C Library(this value is in many cases/usr
or the empty string).
The remaining problem is to decide which must be used. The valuedecides about the substitution of the format elements mentioned above.First of all the user can specify a path in the message catalog name(i.e., the name contains a slash character). In this situation theNLSPATH
environment variable is not used. The catalog must existas specified in the program, perhaps relative to the current workingdirectory. This situation in not desirable and catalogs names nevershould be written this way. Beside this, this behavior is not portableto all other platforms providing thecatgets
interface.
Otherwise the values of environment variables from the standardenvironment are examined (seeStandard Environment Variables). Whichvariables are examined is decided by theflag parameter ofcatopen
. If the value isNL_CAT_LOCALE
(which is definedinnl_types.h) then thecatopen
function uses the name ofthe locale currently selected for theLC_MESSAGES
category.
Ifflag is zero theLANG
environment variable is examined.This is a left-over from the early days when the concept of localeshad not even reached the level of POSIX locales.
The environment variable and the locale name should have a value of theformlang[_terr[.codeset]]
as explained above.If no environment variable is set the"C"
locale is used whichprevents any translation.
The return value of the function is in any case a valid string. Eitherit is a translation from a message catalog or it is the same as thestring parameter. So a piece of code to decide whether atranslation actually happened must look like this:
{ char *trans = catgets (desc, set, msg, input_string); if (trans == input_string) { /* Something went wrong. */ }}
When an error occurs the global variableerrno
is set to
The catalog does not exist.
The set/message tuple does not name an existing element in themessage catalog.
While it sometimes can be useful to test for errors programs normallywill avoid any test. If the translation is not available it is no bigproblem if the original, untranslated message is printed. Either theuser understands this as well or s/he will look for the reason why themessages are not translated.
Please note that the currently selected locale does not depend on a callto thesetlocale
function. It is not necessary that the localedata files for this locale exist and callingsetlocale
succeeds.Thecatopen
function directly reads the values of the environmentvariables.
char *
catgets(nl_catdcatalog_desc, intset, intmessage, const char *string)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functioncatgets
has to be used to access the message catalogpreviously opened using thecatopen
function. Thecatalog_desc parameter must be a value previously returned bycatopen
.
The next two parameters,set andmessage, reflect theinternal organization of the message catalog files. This will beexplained in detail below. For now it is interesting to know that acatalog can consist of several sets and the messages in each thread areindividually numbered using numbers. Neither the set number nor themessage number must be consecutive. They can be arbitrarily chosen.But each message (unless equal to another one) must have its own uniquepair of set and message numbers.
Since it is not guaranteed that the message catalog for the languageselected by the user exists the last parameterstring helps tohandle this case gracefully. If no matching string can be foundstring is returned. This means for the programmer that
It is somewhat uncomfortable to write a program using thecatgets
functions if no supporting functionality is available. Since eachset/message number tuple must be unique the programmer must keep listsof the messages at the same time the code is written. And the workbetween several people working on the same project must be coordinated.We will see how some of these problems can be relaxed a bit (seeHow to use thecatgets
interface).
int
catclose(nl_catdcatalog_desc)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Thecatclose
function can be used to free the resourcesassociated with a message catalog which previously was opened by a calltocatopen
. If the resources can be successfully freed thefunction returns0
. Otherwise it returns−1
and theglobal variableerrno
is set. Errors can occur if the catalogdescriptorcatalog_desc is not valid in which caseerrno
isset toEBADF
.
Next:Generate Message Catalogs files, Previous:Thecatgets
function family, Up:X/Open Message Catalog Handling [Contents][Index]
The only reasonable way to translate all the messages of a function andstore the result in a message catalog file which can be read by thecatopen
function is to write all the message text to thetranslator and let her/him translate them all. I.e., we must have afile with entries which associate the set/message tuple with a specifictranslation. This file format is specified in the X/Open standard andis as follows:
$
followed by a whitespace character are comment and are also ignored.$set
followed by a whitespace character an additional argumentis required to follow. This argument can either be:How to use the symbolic names is explained in sectionHow to use thecatgets
interface.
It is an error if a symbol name appears more than once. All followingmessages are placed in a set with this number.
$delset
followed by a whitespace character an additional argumentis required to follow. This argument can either be:In both cases all messages in the specified set will be removed. Theywill not appear in the output. But if this set is later again selectedwith a$set
command again messages could be added and thesemessages will appear in the output.
$quote
, the quoting character used for this input file ischanged to the first non-whitespace character following$quote
. If no non-whitespace character is present before theline ends quoting is disabled.By default no quoting character is used. In this mode strings areterminated with the first unescaped line break. If there is a$quote
sequence present newline need not be escaped. Instead astring is terminated with the first unescaped appearance of the quotecharacter.
A common usage of this feature would be to set the quote character to"
. Then any appearance of the"
in the strings mustbe escaped using the backslash (i.e.,\"
must be written).
If the start of the line is a number the message number is obvious. Itis an error if the same message number already appeared for this set.
If the leading token was an identifier the message number getsautomatically assigned. The value is the current maximum messagenumber for this set plus one. It is an error if the identifier wasalready used for a message in this set. It is OK to reuse theidentifier for a message in another thread. How to use the symbolicidentifiers will be explained below (seeHow to use thecatgets
interface). There isone limitation with the identifier: it must not beSet
. Thereason will be explained below.
The text of the messages can contain escape characters. The usual bunchof characters known from the ISO C language are recognized(\n
,\t
,\v
,\b
,\r
,\f
,\\
, and\nnn
, wherennn is the octal coding ofa character code).
Important: The handling of identifiers instead of numbers forthe set and messages is a GNU extension. Systems strictly following theX/Open specification do not have this feature. An example for a messagecatalog file is this:
$ This is a leading comment.$quote "$set SetOne1 Message with ID 1.two " Message with ID \"two\", which gets the value 2 assigned"$set SetTwo$ Since the last set got the number 1 assigned this set has number 2.4000 "The numbers can be arbitrary, they need not start at one."
This small example shows various aspects:
$
followed bya whitespace."
. Otherwise the quotes in themessage definition would have to be omitted and in this case themessage with the identifiertwo
would lose its leading whitespace.While this file format is pretty easy it is not the best possible foruse in a running program. Thecatopen
function would have toparse the file and handle syntactic errors gracefully. This is not soeasy and the whole process is pretty slow. Therefore thecatgets
functions expect the data in another more compact and ready-to-use fileformat. There is a special programgencat
which is explained indetail in the next section.
Files in this other format are not human readable. To be easy to use byprograms it is a binary file. But the format is byte order independentso translation files can be shared by systems of arbitrary architecture(as long as they use the GNU C Library).
Details about the binary file format are not important to know sincethese files are always created by thegencat
program. Thesources of the GNU C Library also provide the sources for thegencat
program and so the interested reader can look throughthese source files to learn about the file format.
Next:How to use thecatgets
interface, Previous:Format of the message catalog files, Up:X/Open Message Catalog Handling [Contents][Index]
Thegencat
program is specified in the X/Open standard and theGNU implementation follows this specification and so processesall correctly formed input files. Additionally some extension areimplemented which help to work in a more reasonable way with thecatgets
functions.
Thegencat
program can be invoked in two ways:
`gencat [Option ...] [Output-File [Input-File ...]]`
This is the interface defined in the X/Open standard. If noInput-File parameter is given, input will be read from standardinput. Multiple input files will be read as if they were concatenated.IfOutput-File is also missing, the output will be written tostandard output. To provide the interface one is used to from otherprograms a second interface is provided.
`gencat [Option ...] -oOutput-File [Input-File ...]`
The option ‘-o’ is used to specify the output file and all filearguments are used as input files.
Beside this one can use- or/dev/stdin forInput-File to denote the standard input. Corresponding one canuse- and/dev/stdout forOutput-File to denotestandard output. Using- as a file name is allowed in X/Openwhile using the device names is a GNU extension.
Thegencat
program works by concatenating all input files andthenmerging the resulting collection of message sets with apossibly existing output file. This is done by removing all messageswith set/message number tuples matching any of the generated messagesfrom the output file and then adding all the new messages. Toregenerate a catalog file while ignoring the old contents thereforerequires removing the output file if it exists. If the output iswritten to standard output no merging takes place.
The following table shows the options understood by thegencat
program. The X/Open standard does not specify any options for theprogram so all of these are GNU extensions.
Print the version information and exit.
Print a usage message listing all available options, then exit successfully.
Do not merge the new messages from the input files with the old contentof the output file. The old content of the output file is discarded.
This option is used to emit the symbolic names given to sets andmessages in the input files for use in the program. Details about howto use this are given in the next section. Thename parameter tothis option specifies the name of the output file. It will contain anumber of C preprocessor#define
s to associate a name with anumber.
Please note that the generated file only contains the symbols from theinput files. If the output is merged with the previous content of theoutput file the possibly existing symbols from the file(s) whichgenerated the old output files are not in the generated header file.
Previous:Generate Message Catalogs files, Up:X/Open Message Catalog Handling [Contents][Index]
catgets
interface ¶Thecatgets
functions can be used in two different ways. Byfollowing slavishly the X/Open specs and not relying on the extensionand by using the GNU extensions. We will take a look at the formermethod first to understand the benefits of extensions.
Since the X/Open format of the message catalog files does not allowsymbol names we have to work with numbers all the time. When we startwriting a program we have to replace all appearances of translatablestrings with something like
catgets (catdesc, set, msg, "string")
catgets is retrieved from a call tocatopen
which isnormally done once at the program start. The"string"
is thestring we want to translate. The problems start with the set andmessage numbers.
In a bigger program several programmers usually work at the same time onthe program and so coordinating the number allocation is crucial.Though no two different strings must be indexed by the same tuple ofnumbers it is highly desirable to reuse the numbers for equal stringswith equal translations (please note that there might be strings whichare equal in one language but have different translations due todifference contexts).
The allocation process can be relaxed a bit by different set numbers fordifferent parts of the program. So the number of developers who have tocoordinate the allocation can be reduced. But still lists must be keeptrack of the allocation and errors can easily happen. These errorscannot be discovered by the compiler or thecatgets
functions.Only the user of the program might see wrong messages printed. In theworst cases the messages are so irritating that they cannot berecognized as wrong. Think about the translations for"true"
and"false"
being exchanged. This could result in a disaster.
The problems mentioned in the last section derive from the fact that:
By constantly using symbolic names and by providing a method which mapsthe string content to a symbolic name (however this will happen) one canprevent both problems above. The cost of this is that the programmerhas to write a complete message catalog file while s/he is writing theprogram itself.
This is necessary since the symbolic names must be mapped to numbersbefore the program sources can be compiled. In the last section it wasdescribed how to generate a header containing the mapping of the names.E.g., for the example message file given in the last section we couldcall thegencat
program as follows (assumeex.msg containsthe sources).
gencat -H ex.h -o ex.cat ex.msg
This generates a header file with the following content:
#define SetTwoSet 0x2 /* ex.msg:8 */#define SetOneSet 0x1 /* ex.msg:4 */#define SetOnetwo 0x2 /* ex.msg:6 */
As can be seen the various symbols given in the source file are mangledto generate unique identifiers and these identifiers get numbersassigned. Reading the source file and knowing about the rules willallow to predict the content of the header file (it is deterministic)but this is not necessary. Thegencat
program can take care foreverything. All the programmer has to do is to put the generated headerfile in the dependency list of the source files of her/his project andadd a rule to regenerate the header if any of the input files change.
One word about the symbol mangling. Every symbol consists of two parts:the name of the message set plus the name of the message or the specialstringSet
. SoSetOnetwo
means this macro can be used toaccess the translation with identifiertwo
in the message setSetOne
.
The other names denote the names of the message sets. The specialstringSet
is used in the place of the message identifier.
If in the code the second string of the setSetOne
is used the Ccode should look like this:
catgets (catdesc, SetOneSet, SetOnetwo, " Message with ID \"two\", which gets the value 2 assigned")
Writing the function this way will allow to change the message numberand even the set number without requiring any change in the C sourcecode. (The text of the string is normally not the same; this is onlyfor this example.)
To illustrate the usual way to work with the symbolic version numbershere is a little example. Assume we want to write the very complex andfamous greeting program. We start by writing the code as usual:
#include <stdio.h>intmain (void){ printf ("Hello, world!\n"); return 0;}
Now we want to internationalize the message and therefore replace themessage with whatever the user wants.
#include <nl_types.h>#include <stdio.h>#include "msgnrs.h"intmain (void){ nl_catd catdesc = catopen ("hello.cat", NL_CAT_LOCALE); printf (catgets (catdesc, SetMainSet, SetMainHello, "Hello, world!\n")); catclose (catdesc); return 0;}
We see how the catalog object is opened and the returned descriptor usedin the other function calls. It is not really necessary to check forfailure of any of the functions since even in these situations thefunctions will behave reasonable. They simply will be return atranslation.
What remains unspecified here are the constantsSetMainSet
andSetMainHello
. These are the symbolic names describing themessage. To get the actual definitions which match the information inthe catalog file we have to create the message catalog source file andprocess it using thegencat
program.
$ Messages for the famous greeting program.$quote "$set MainHello "Hallo, Welt!\n"
Now we can start building the program (assume the message catalog sourcefile is namedhello.msg and the program source filehello.c):
% gencat -H msgnrs.h -o hello.cat hello.msg% cat msgnrs.h#define MainSet 0x1 /* hello.msg:4 */#define MainHello 0x1 /* hello.msg:5 */% gcc -o hello hello.c -I.% cp hello.cat /usr/share/locale/de/LC_MESSAGES% echo $LC_ALLde% ./helloHallo, Welt!%
The call of thegencat
program creates the missing header filemsgnrs.h as well as the message catalog binary. The former isused in the compilation ofhello.c while the later is placed in adirectory in which thecatopen
function will try to locate it.Please check theLC_ALL
environment variable and the default pathforcatopen
presented in the description above.
Previous:X/Open Message Catalog Handling, Up:Message Translation [Contents][Index]
Sun Microsystems tried to standardize a different approach to messagetranslation in the Uniforum group. There never was a real standarddefined but still the interface was used in Sun’s operating systems.Since this approach fits better in the development process of freesoftware it is also used throughout the GNU project and the GNUgettext package provides support for this outside the GNU C Library.
The code of thelibintl from GNUgettext is the same asthe code in the GNU C Library. So the documentation in the GNUgettext manual is also valid for the functionality here. Thefollowing text will describe the library functions in detail. But thenumerous helper programs are not described in this manual. Insteadpeople should read the GNUgettext manual(seeGNU gettext utilities inNative Language Support Library and Tools).We will only give a short overview.
Though thecatgets
functions are available by default on moresystems thegettext
interface is at least as portable as theformer. The GNUgettext package can be used wherever thefunctions are not available.
Next:Programs to handle message catalogs forgettext
, Up:The Uniforum approach to Message Translation [Contents][Index]
gettext
family of functions ¶The paradigms underlying thegettext
approach to messagetranslations is different from that of thecatgets
functions thebasic functionally is equivalent. There are functions of the followingcategories:
gettext
usesgettext
in GUI programsgettext
Thegettext
functions have a very simple interface. The mostbasic function just takes the string which shall be translated as theargument and it returns the translation. This is fundamentallydifferent from thecatgets
approach where an extra key isnecessary and the original string is only used for the error case.
If the string which has to be translated is the only argument this ofcourse means the string itself is the key. I.e., the translation willbe selected based on the original string. The message catalogs musttherefore contain the original strings plus one translation for any suchstring. The task of thegettext
function is to compare theargument string with the available strings in the catalog and return theappropriate translation. Of course this process is optimized so thatthis process is not more expensive than an access using an atomic keylike incatgets
.
Thegettext
approach has some advantages but also somedisadvantages. Please see the GNUgettext manual for a detaileddiscussion of the pros and cons.
All the definitions and declarations forgettext
can be found inthelibintl.h header file. On systems where these functions arenot part of the C library they can be found in a separate library namedlibintl.a (or accordingly different for shared libraries).
char *
gettext(const char *msgid)
¶Preliminary:| MT-Safe env| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegettext
function searches the currently selected messagecatalogs for a string which is equal tomsgid. If there is such astring available it is returned. Otherwise the argument stringmsgid is returned.
Please note that although the return value ischar *
thereturned string must not be changed. This broken type results from thehistory of the function and does not reflect the way the function shouldbe used.
Please note that above we wrote “message catalogs” (plural). This isa specialty of the GNU implementation of these functions and we willsay more about this when we talk about the ways message catalogs areselected (seeHow to determine which catalog to be used).
Thegettext
function does not modify the value of the globalerrno
variable. This is necessary to make it possible to writesomething like
printf (gettext ("Operation failed: %m\n"));
Here theerrno
value is used in theprintf
function whileprocessing the%m
format element and if thegettext
function would change this value (it is called beforeprintf
iscalled) we would get a wrong message.
So there is no easy way to detect a missing message catalog besidescomparing the argument string with the result. But it is normally thetask of the user to react on missing catalogs. The program cannot guesswhen a message catalog is really necessary since for a user who speaksthe language the program was developed in, the message does not need any translation.
The remaining two functions to access the message catalog add somefunctionality to select a message catalog which is not the default one.This is important if parts of the program are developed independently.Every part can have its own message catalog and all of them can be usedat the same time. The C library itself is an example: internally ituses thegettext
functions but since it must not depend on acurrently selected default message catalog it must specify all ambiguousinformation.
char *
dgettext(const char *domainname, const char *msgid)
¶Preliminary:| MT-Safe env| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thedgettext
function acts just like thegettext
function. It only takes an additional first argumentdomainnamewhich guides the selection of the message catalogs which are searchedfor the translation. If thedomainname parameter is the nullpointer thedgettext
function is exactly equivalent togettext
since the default value for the domain name is used.
As forgettext
the return value type ischar *
which is ananachronism. The returned string must never be modified.
char *
dcgettext(const char *domainname, const char *msgid, intcategory)
¶Preliminary:| MT-Safe env| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thedcgettext
adds another argument to those whichdgettext
takes. This argumentcategory specifies the lastpiece of information needed to localize the message catalog. I.e., thedomain name and the locale category exactly specify which messagecatalog has to be used (relative to a given directory, see below).
Thedgettext
function can be expressed in terms ofdcgettext
by using
dcgettext (domain, string, LC_MESSAGES)
instead of
dgettext (domain, string)
This also shows which values are expected for the third parameter. Onehas to use the available selectors for the categories available inlocale.h. Normally the available values areLC_CTYPE
,LC_COLLATE
,LC_MESSAGES
,LC_MONETARY
,LC_NUMERIC
, andLC_TIME
. Please note thatLC_ALL
must not be used and even though the names might suggest this, there isno relation to the environment variable of this name.
Thedcgettext
function is only implemented for compatibility withother systems which havegettext
functions. There is not reallyany situation where it is necessary (or useful) to use a different valuethanLC_MESSAGES
for thecategory parameter. We aredealing with messages here and any other choice can only be irritating.
As forgettext
the return value type ischar *
which is ananachronism. The returned string must never be modified.
When using the three functions above in a program it is a frequent casethat themsgid argument is a constant string. So it is worthwhile tooptimize this case. Thinking shortly about this one will realize thatas long as no new message catalog is loaded the translation of a messagewill not change. This optimization is actually implemented by thegettext
,dgettext
anddcgettext
functions.
Next:Additional functions for more complicated situations, Previous:What has to be done to translate a message?, Up:Thegettext
family of functions [Contents][Index]
The functions to retrieve the translations for a given message have aremarkable simple interface. But to provide the user of the programstill the opportunity to select exactly the translation s/he wants andalso to provide the programmer the possibility to influence the way tolocate the search for catalogs files there is a quite complicatedunderlying mechanism which controls all this. The code is complicatedthe use is easy.
Basically we have two different tasks to perform which can also beperformed by thecatgets
functions:
There can be arbitrarily many packages installed and they can followdifferent guidelines for the placement of their files.
This is the functionality required by the specifications forgettext
and this is also what thecatgets
functions areable to do. But there are some problems unresolved:
de
,german
, ordeutsch
and the program should always react the same.de_DE.ISO-8859-1
which means German, spoken in Germany,coded using the ISO 8859-1 character set there is the possibilitythat a message catalog matching this exactly is not available. Butthere could be a catalog matchingde
and if the character setused on the machine is always ISO 8859-1 there is no reason why thislater message catalog should not be used. (We call thismessageinheritance.)We can divide the configuration actions in two parts: the one isperformed by the programmer, the other by the user. We will start withthe functions the programmer can use since the user configuration willbe based on this.
As the functions described in the last sections already mention separatesets of messages can be selected by adomain name. This is asimple string which should be unique for each program part that uses aseparate domain. It is possible to use in one program arbitrarily manydomains at the same time. E.g., the GNU C Library itself uses a domainnamedlibc
while the program using the C Library could use adomain namedfoo
. The important point is that at any timeexactly one domain is active. This is controlled with the followingfunction.
char *
textdomain(const char *domainname)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
Thetextdomain
function sets the default domain, which is used inall futuregettext
calls, todomainname. Please note thatdgettext
anddcgettext
calls are not influenced if thedomainname parameter of these functions is not the null pointer.
Before the first call totextdomain
the default domain ismessages
. This is the name specified in the specification ofthegettext
API. This name is as good as any other name. Noprogram should ever really use a domain with this name since this canonly lead to problems.
The function returns the value which is from now on taken as the defaultdomain. If the system went out of memory the returned value isNULL
and the global variableerrno
is set toENOMEM
.Despite the return value type beingchar *
the return string mustnot be changed. It is allocated internally by thetextdomain
function.
If thedomainname parameter is the null pointer no new defaultdomain is set. Instead the currently selected default domain isreturned.
If thedomainname parameter is the empty string the default domainis reset to its initial value, the domain with the namemessages
.This possibility is questionable to use since the domainmessages
really never should be used.
char *
bindtextdomain(const char *domainname, const char *dirname)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thebindtextdomain
function can be used to specify the directorywhich contains the message catalogs for domaindomainname for thedifferent languages. To be correct, this is the directory where thehierarchy of directories is expected. Details are explained below.
For the programmer it is important to note that the translations whichcome with the program have to be placed in a directory hierarchy startingat, say,/foo/bar. Then the program should make abindtextdomain
call to bind the domain for the current program tothis directory. So it is made sure the catalogs are found. A correctlyrunning program does not depend on the user setting an environmentvariable.
Thebindtextdomain
function can be used several times and if thedomainname argument is different the previously bound domainswill not be overwritten.
If the program which wish to usebindtextdomain
at some point oftime use thechdir
function to change the current workingdirectory it is important that thedirname strings ought to be anabsolute pathname. Otherwise the addressed directory might vary withthe time.
If thedirname parameter is the null pointerbindtextdomain
returns the currently selected directory for the domain with the namedomainname.
Thebindtextdomain
function returns a pointer to a stringcontaining the name of the selected directory name. The string isallocated internally in the function and must not be changed by theuser. If the system went out of core during the execution ofbindtextdomain
the return value isNULL
and the globalvariableerrno
is set accordingly.
Next:How to specify the output character setgettext
uses, Previous:How to determine which catalog to be used, Up:Thegettext
family of functions [Contents][Index]
The functions of thegettext
family described so far (and all thecatgets
functions as well) have one problem in the real worldwhich has been neglected completely in all existing approaches. Whatis meant here is the handling of plural forms.
Looking through Unix source code before the time anybody thought aboutinternationalization (and, sadly, even afterwards) one can often findcode similar to the following:
printf ("%d file%s deleted", n, n == 1 ? "" : "s");
After the first complaints from people internationalizing the code peopleeither completely avoided formulations like this or used strings like"file(s)"
. Both look unnatural and should be avoided. Firsttries to solve the problem correctly looked like this:
if (n == 1) printf ("%d file deleted", n); else printf ("%d files deleted", n);
But this does not solve the problem. It helps languages where theplural form of a noun is not simply constructed by adding an ‘s’ butthat is all. Once again people fell into the trap of believing therules their language uses are universal. But the handling of pluralforms differs widely between the language families. There are twothings we can differ between (and even inside language families);
But other language families have only one form or many forms. Moreinformation on this in an extra section.
The consequence of this is that application writers should not try tosolve the problem in their code. This would be localization since it isonly usable for certain, hardcoded language environments. Instead theextendedgettext
interface should be used.
These extra functions are taking instead of the one key string twostrings and a numerical argument. The idea behind this is that usingthe numerical argument and the first string as a key, the implementationcan select using rules specified by the translator the right pluralform. The two string arguments then will be used to provide a returnvalue in case no message catalog is found (similar to the normalgettext
behavior). In this case the rules for Germanic languageare used and it is assumed that the first string argument is the singularform, the second the plural form.
This has the consequence that programs without language catalogs candisplay the correct strings only if the program itself is written usinga Germanic language. This is a limitation but since the GNU C Library(as well as the GNUgettext
package) is written as part of theGNU package and the coding standards for the GNU project require programsto be written in English, this solution nevertheless fulfills itspurpose.
char *
ngettext(const char *msgid1, const char *msgid2, unsigned long intn)
¶Preliminary:| MT-Safe env| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thengettext
function is similar to thegettext
functionas it finds the message catalogs in the same way. But it takes twoextra arguments. Themsgid1 parameter must contain the singularform of the string to be converted. It is also used as the key for thesearch in the catalog. Themsgid2 parameter is the plural form.The parametern is used to determine the plural form. If nomessage catalog is foundmsgid1 is returned ifn == 1
,otherwisemsgid2
.
An example for the use of this function is:
printf (ngettext ("%d file removed", "%d files removed", n), n);
Please note that the numeric valuen has to be passed to theprintf
function as well. It is not sufficient to pass it only tongettext
.
char *
dngettext(const char *domain, const char *msgid1, const char *msgid2, unsigned long intn)
¶Preliminary:| MT-Safe env| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thedngettext
is similar to thedgettext
function in theway the message catalog is selected. The difference is that it takestwo extra parameters to provide the correct plural form. These twoparameters are handled in the same wayngettext
handles them.
char *
dcngettext(const char *domain, const char *msgid1, const char *msgid2, unsigned long intn, intcategory)
¶Preliminary:| MT-Safe env| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thedcngettext
is similar to thedcgettext
function in theway the message catalog is selected. The difference is that it takestwo extra parameters to provide the correct plural form. These twoparameters are handled in the same wayngettext
handles them.
A description of the problem can be found at the beginning of the lastsection. Now there is the question how to solve it. Without the inputof linguists (which was not available) it was not possible to determinewhether there are only a few different forms in which plural forms areformed or whether the number can increase with every new supportedlanguage.
Therefore the solution implemented is to allow the translator to specifythe rules of how to select the plural form. Since the formula varieswith every language this is the only viable solution except forhardcoding the information in the code (which still would require thepossibility of extensions to not prevent the use of new languages). Thedetails are explained in the GNUgettext
manual. Here only abit of information is provided.
The information about the plural form selection has to be stored in theheader entry (the one with the emptymsgid
string). It lookslike this:
Plural-Forms: nplurals=2; plural=n == 1 ? 0 : 1;
Thenplurals
value must be a decimal number which specifies howmany different plural forms exist for this language. The stringfollowingplural
is an expression using the C languagesyntax. Exceptions are that no negative numbers are allowed, numbersmust be decimal, and the only variable allowed isn
. Thisexpression will be evaluated whenever one of the functionsngettext
,dngettext
, ordcngettext
is called. Thenumeric value passed to these functions is then substituted for all usesof the variablen
in the expression. The resulting value thenmust be greater or equal to zero and smaller than the value given as thevalue ofnplurals
.
The following rules are known at this point. The language with familiesare listed. But this does not necessarily mean the information can begeneralized for the whole family (as can be easily seen in the tablebelow).2
Some languages only require one single form. There is no distinctionbetween the singular and plural form. An appropriate header entrywould look like this:
Plural-Forms: nplurals=1; plural=0;
Languages with this property include:
Hungarian
Japanese, Korean
Turkish
This is the form used in most existing programs since it is what Englishuses. A header entry would look like this:
Plural-Forms: nplurals=2; plural=n != 1;
(Note: this uses the feature of C expressions that boolean expressionshave to value zero or one.)
Languages with this property include:
Danish, Dutch, English, German, Norwegian, Swedish
Estonian, Finnish
Greek
Hebrew
Italian, Portuguese, Spanish
Esperanto
Exceptional case in the language family. The header entry would be:
Plural-Forms: nplurals=2; plural=n>1;
Languages with this property include:
French, Brazilian Portuguese
The header entry would be:
Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2;
Languages with this property include:
Latvian
The header entry would be:
Plural-Forms: nplurals=3; plural=n==1 ? 0 : n==2 ? 1 : 2;
Languages with this property include:
Gaeilge (Irish)
The header entry would look like this:
Plural-Forms: nplurals=3; \ plural=n%10==1 && n%100!=11 ? 0 : \ n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2;
Languages with this property include:
Lithuanian
The header entry would look like this:
Plural-Forms: nplurals=3; \ plural=n%100/10==1 ? 2 : n%10==1 ? 0 : (n+9)%10>3 ? 2 : 1;
Languages with this property include:
Croatian, Czech, Russian, Ukrainian
The header entry would look like this:
Plural-Forms: nplurals=3; \ plural=(n==1) ? 1 : (n>=2 && n<=4) ? 2 : 0;
Languages with this property include:
Slovak
The header entry would look like this:
Plural-Forms: nplurals=3; \ plural=n==1 ? 0 : \ n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
Languages with this property include:
Polish
The header entry would look like this:
Plural-Forms: nplurals=4; \ plural=n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3;
Languages with this property include:
Slovenian
Next:How to usegettext
in GUI programs, Previous:Additional functions for more complicated situations, Up:Thegettext
family of functions [Contents][Index]
gettext
uses ¶gettext
not only looks up a translation in a message catalog, italso converts the translation on the fly to the desired output characterset. This is useful if the user is working in a different character setthan the translator who created the message catalog, because it avoidsdistributing variants of message catalogs which differ only in thecharacter set.
The output character set is, by default, the value ofnl_langinfo(CODESET)
, which depends on theLC_CTYPE
part of the currentlocale. But programs which store strings in a locale independent way(e.g. UTF-8) can request thatgettext
and related functionsreturn the translations in that encoding, by use of thebind_textdomain_codeset
function.
Note that themsgid argument togettext
is not subject tocharacter set conversion. Also, whengettext
does not find atranslation formsgid, it returnsmsgid unchanged –independently of the current output character set. It is thereforerecommended that allmsgids be US-ASCII strings.
char *
bind_textdomain_codeset(const char *domainname, const char *codeset)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thebind_textdomain_codeset
function can be used to specify theoutput character set for message catalogs for domaindomainname.Thecodeset argument must be a valid codeset name which can be usedfor theiconv_open
function, or a null pointer.
If thecodeset parameter is the null pointer,bind_textdomain_codeset
returns the currently selected codesetfor the domain with the namedomainname. It returnsNULL
ifno codeset has yet been selected.
Thebind_textdomain_codeset
function can be used several times.If used multiple times with the samedomainname argument, thelater call overrides the settings made by the earlier one.
Thebind_textdomain_codeset
function returns a pointer to astring containing the name of the selected codeset. The string isallocated internally in the function and must not be changed by theuser. If the system went out of core during the execution ofbind_textdomain_codeset
, the return value isNULL
and theglobal variableerrno
is set accordingly.
Next:User influence ongettext
, Previous:How to specify the output character setgettext
uses, Up:Thegettext
family of functions [Contents][Index]
gettext
in GUI programs ¶One place where thegettext
functions, if used normally, have bigproblems is within programs with graphical user interfaces (GUIs). Theproblem is that many of the strings which have to be translated are veryshort. They have to appear in pull-down menus which restricts thelength. But strings which are not containing entire sentences or atleast large fragments of a sentence may appear in more than onesituation in the program but might have different translations. This isespecially true for the one-word strings which are frequently used inGUI programs.
As a consequence many people say that thegettext
approach iswrong and insteadcatgets
should be used which indeed does nothave this problem. But there is a very simple and powerful method tohandle these kind of problems with thegettext
functions.
As an example consider the following fictional situation. A GUI programhas a menu bar with the following entries:
+------------+------------+--------------------------------------+| File | Printer | |+------------+------------+--------------------------------------+| Open | | Select || New | | Open |+----------+ | Connect | +----------+
To have the stringsFile
,Printer
,Open
,New
,Select
, andConnect
translated there has to beat some point in the code a call to a function of thegettext
family. But in two places the string passed into the function would beOpen
. The translations might not be the same and therefore weare in the dilemma described above.
One solution to this problem is to artificially extend the stringsto make them unambiguous. But what would the program do if notranslation is available? The extended string is not what should beprinted. So we should use a slightly modified version of the functions.
To extend the strings a uniform method should be used. E.g., in theexample above, the strings could be chosen as
Menu|FileMenu|PrinterMenu|File|OpenMenu|File|NewMenu|Printer|SelectMenu|Printer|OpenMenu|Printer|Connect
Now all the strings are different and if now instead ofgettext
the following little wrapper function is used, everything works justfine:
char * sgettext (const char *msgid) { char *msgval = gettext (msgid); if (msgval == msgid) msgval = strrchr (msgid, '|') + 1; return msgval; }
What this little function does is to recognize the case when notranslation is available. This can be done very efficiently by apointer comparison since the return value is the input value. If thereis no translation we know that the input string is in the format we usedfor the Menu entries and therefore contains a|
character. Wesimply search for the last occurrence of this character and return apointer to the character following it. That’s it!
If one now consistently uses the extended string form and replacesthegettext
calls with calls tosgettext
(this is normallylimited to very few places in the GUI implementation) then it ispossible to produce a program which can be internationalized.
With advanced compilers (such as GNU C) one can write thesgettext
functions as an inline function or as a macro like this:
#define sgettext(msgid) \ ({ const char *__msgid = (msgid); \ char *__msgstr = gettext (__msgid); \ if (__msgval == __msgid) \ __msgval = strrchr (__msgid, '|') + 1; \ __msgval; })
The othergettext
functions (dgettext
,dcgettext
and thengettext
equivalents) can and should have correspondingfunctions as well which look almost identical, except for the parametersand the call to the underlying function.
Now there is of course the question why such functions do not exist inthe GNU C Library? There are two parts of the answer to this question.
|
which is a quite good choice because itresembles a notation frequently used in this context and it also is acharacter not often used in message strings.But what if the character is used in message strings. Or if the chosecharacter is not available in the character set on the machine onecompiles (e.g.,|
is not required to exist for ISO C; this iswhy theiso646.h file exists in ISO C programming environments).
There is only one more comment to make left. The wrapper function aboverequires that the translations strings are not extended themselves.This is only logical. There is no need to disambiguate the strings(since they are never used as keys for a search) and one also savesquite some memory and disk space by doing this.
Previous:How to usegettext
in GUI programs, Up:Thegettext
family of functions [Contents][Index]
gettext
¶The last sections described what the programmer can do tointernationalize the messages of the program. But it is finally up tothe user to select the message s/he wants to see. S/He must understandthem.
The POSIX locale model uses the environment variablesLC_COLLATE
,LC_CTYPE
,LC_MESSAGES
,LC_MONETARY
,LC_NUMERIC
,andLC_TIME
to select the locale which is to be used. This waythe user can influence lots of functions. As we mentioned above, thegettext
functions also take advantage of this.
To understand how this happens it is necessary to take a look at thevarious components of the filename which gets computed to locate amessage catalog. It is composed as follows:
dir_name/locale/LC_category/domain_name.mo
The default value fordir_name is system specific. It is computedfrom the value given as the prefix while configuring the C library.This value normally is/usr or/. For the former thecompletedir_name is:
/usr/share/locale
We can use/usr/share since the.mo files containing themessage catalogs are system independent, so all systems can use the samefiles. If the program executed thebindtextdomain
function forthe message domain that is currently handled, thedir_name
component is exactly the value which was given to the function asthe second parameter. I.e.,bindtextdomain
allows overwritingthe only system dependent and fixed value to make it possible toaddress files anywhere in the filesystem.
Thecategory is the name of the locale category which was selectedin the program code. Forgettext
anddgettext
this isalwaysLC_MESSAGES
, fordcgettext
this is selected by thevalue of the third parameter. As said above it should be avoided toever use a category other thanLC_MESSAGES
.
Thelocale component is computed based on the category used. Justlike for thesetlocale
function here comes the user selectioninto the play. Some environment variables are examined in a fixed orderand the first environment variable set determines the return value ofthe lookup process. In detail, for the categoryLC_xxx
thefollowing variables in this order are examined:
LANGUAGE
LC_ALL
LC_xxx
LANG
This looks very familiar. With the exception of theLANGUAGE
environment variable this is exactly the lookup order thesetlocale
function uses. But why introduce theLANGUAGE
variable?
The reason is that the syntax of the values these variables can have isdifferent to what is expected by thesetlocale
function. If wewould setLC_ALL
to a value following the extended syntax thatwould mean thesetlocale
function will never be able to use thevalue of this variable as well. An additional variable removes thisproblem plus we can select the language independently of the localesetting which sometimes is useful.
While for theLC_xxx
variables the value should consist ofexactly one specification of a locale theLANGUAGE
variable’svalue can consist of a colon separated list of locale names. Theattentive reader will realize that this is the way we manage toimplement one of our additional demands above: we want to be able tospecify an ordered list of languages.
Back to the constructed filename we have only one component missing.Thedomain_name part is the name which was either registered usingthetextdomain
function or which was given todgettext
ordcgettext
as the first parameter. Now it becomes obvious that agood choice for the domain name in the program code is a string which isclosely related to the program/package name. E.g., for the GNU C Librarythe domain name islibc
.
A limited piece of example code should show how the program is supposedto work:
{ setlocale (LC_ALL, ""); textdomain ("test-package"); bindtextdomain ("test-package", "/usr/local/share/locale"); puts (gettext ("Hello, world!"));}
At the program start the default domain ismessages
, and thedefault locale is "C". Thesetlocale
call sets the localeaccording to the user’s environment variables; remember that correctfunctioning ofgettext
relies on the correct setting of theLC_MESSAGES
locale (for looking up the message catalog) andof theLC_CTYPE
locale (for the character set conversion).Thetextdomain
call changes the default domain totest-package
. Thebindtextdomain
call specifies thatthe message catalogs for the domaintest-package
can be foundbelow the directory/usr/local/share/locale.
If the user sets in her/his environment the variableLANGUAGE
tode
thegettext
function will try to use thetranslations from the file
/usr/local/share/locale/de/LC_MESSAGES/test-package.mo
From the above descriptions it should be clear which component of thisfilename is determined by which source.
In the above example we assumed theLANGUAGE
environmentvariable to bede
. This might be an appropriate selection but whathappens if the user wants to useLC_ALL
because of the widerusability and here the required value isde_DE.ISO-8859-1
? Wealready mentioned above that a situation like this is not infrequent.E.g., a person might prefer reading a dialect and if this is notavailable fall back on the standard language.
Thegettext
functions know about situations like this and canhandle them gracefully. The functions recognize the format of the valueof the environment variable. It can split the value is different piecesand by leaving out the only or the other part it can construct newvalues. This happens of course in a predictable way. To understandthis one must know the format of the environment variable value. Thereis one more or less standardized form, originally from the X/Openspecification:
language[_territory[.codeset]][@modifier]
Less specific locale names will be stripped in the order of thefollowing list:
codeset
normalized codeset
territory
modifier
Thelanguage
field will never be dropped for obvious reasons.
The only new thing is thenormalized codeset
entry. This isanother goodie which is introduced to help reduce the chaos whichderives from the inability of people to standardize the names ofcharacter sets. Instead of ISO-8859-1 one can often see 8859-1,88591, iso8859-1, or iso_8859-1. Thenormalizedcodeset
value is generated from the user-provided character set name byapplying the following rules:
"iso"
.So all of the above names will be normalized toiso88591
. Thisallows the program user much more freedom in choosing the locale name.
Even this extended functionality still does not help to solve theproblem that completely different names can be used to denote the samelocale (e.g.,de
andgerman
). To be of help in thissituation the locale implementation and also thegettext
functions know about aliases.
The file/usr/share/locale/locale.alias (replace/usr withwhatever prefix you used for configuring the C library) contains amapping of alternative names to more regular names. The system manageris free to add new entries to fill her/his own needs. The selectedlocale from the environment is compared with the entries in the firstcolumn of this file ignoring the case. If they match, the value of thesecond column is used instead for the further handling.
In the description of the format of the environment variables we alreadymentioned the character set as a factor in the selection of the messagecatalog. In fact, only catalogs which contain text written using thecharacter set of the system/program can be used (directly; there willcome a solution for this some day). This means for the user that s/hewill always have to take care of this. If in the collection of themessage catalogs there are files for the same language but coded usingdifferent character sets the user has to be careful.
Previous:Thegettext
family of functions, Up:The Uniforum approach to Message Translation [Contents][Index]
gettext
¶The GNU C Library does not contain the source code for the programs tohandle message catalogs for thegettext
functions. As part ofthe GNU project the GNU gettext package contains everything thedeveloper needs. The functionality provided by the tools in thispackage by far exceeds the abilities of thegencat
programdescribed above for thecatgets
functions.
There is a programmsgfmt
which is the equivalent program to thegencat
program. It generates from the human-readable and-editable form of the message catalog a binary file which can be used bythegettext
functions. But there are several more programsavailable.
Thexgettext
program can be used to automatically extract thetranslatable messages from a source file. I.e., the programmer need nottake care of the translations and the list of messages which have to betranslated. S/He will simply wrap the translatable string in calls togettext
et.al and the rest will be done byxgettext
. Thisprogram has a lot of options which help to customize the output orhelp to understand the input better.
Other programs help to manage the development cycle when new messages appearin the source files or when a new translation of the messages appears.Here it should only be noted that using all the tools in GNU gettext itis possible tocompletely automate the handling of messagecatalogs. Besides marking the translatable strings in the source code andgenerating the translations the developers do not have anything to dothemselves.
Next:Pattern Matching, Previous:Message Translation, Up:Main Menu [Contents][Index]
This chapter describes functions for searching and sorting arrays ofarbitrary objects. You pass the appropriate comparison function to beapplied as an argument, along with the size of the objects in the arrayand the total number of elements.
hsearch
function.tsearch
function.Next:Array Search Function, Up:Searching and Sorting [Contents][Index]
In order to use the sorted array library functions, you have to describehow to compare the elements of the array.
To do this, you supply a comparison function to compare two elements ofthe array. The library will call this function, passing as argumentspointers to two array elements to be compared. Your comparison functionshould return a value the waystrcmp
(seeString/Array Comparison) does: negative if the first argument is “less” than thesecond, zero if they are “equal”, and positive if the first argumentis “greater”.
Here is an example of a comparison function which works with an array ofnumbers of typelong int
:
intcompare_long_ints (const void *a, const void *b){ const long int *la = a; const long int *lb = b; return (*la > *lb) - (*la < *lb);}
(The code would have to be more complicated for an array ofdouble
,to handle NaNs correctly.)
The header filestdlib.h defines a name for the data type ofcomparison functions. This type is a GNU extension.
int comparison_fn_t (const void *, const void *);
Next:Array Sort Function, Previous:Defining the Comparison Function, Up:Searching and Sorting [Contents][Index]
Generally searching for a specific element in an array means thatpotentially all elements must be checked. The GNU C Library containsfunctions to perform linear search. The prototypes for the followingtwo functions can be found insearch.h.
void *
lfind(const void *key, const void *base, size_t *nmemb, size_tsize, comparison_fn_tcompar)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thelfind
function searches in the array with*nmemb
elements ofsize bytes pointed to bybase for an elementwhich matches the one pointed to bykey. The function pointed tobycompar is used to decide whether two elements match.
The return value is a pointer to the matching element in the arraystarting atbase if it is found. If no matching element isavailableNULL
is returned.
The mean runtime of this function is proportional to*nmemb/2
,assuming random elements of the array are searched for. Thisfunction should be used only if elements often get added to or deleted fromthe array in which case it might not be useful to sort the array beforesearching.
void *
lsearch(const void *key, void *base, size_t *nmemb, size_tsize, comparison_fn_tcompar)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thelsearch
function is similar to thelfind
function. Itsearches the given array for an element and returns it if found. Thedifference is that if no matching element is found thelsearch
function adds the object pointed to bykey (with a size ofsize bytes) at the end of the array and it increments the value of*nmemb
to reflect this addition.
This means for the caller that if it is not sure that the array containsthe element one is searching for the memory allocated for the arraystarting atbase must have room for at leastsize morebytes. If one is sure the element is in the array it is better to uselfind
so having more room in the array is always necessary whencallinglsearch
.
To search a sorted or partially sorted array for an element matching the key,use thebsearch
function. The prototype for this function is inthe header filestdlib.h.
void *
bsearch(const void *key, const void *array, size_tcount, size_tsize, comparison_fn_tcompare)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thebsearch
function searchesarray for an elementthat is equivalent tokey. The array containscount elements,each of which is of sizesize bytes.
Thecompare function is used to perform the comparison. Thisfunction is called with arguments that point to the key and to anarray element, in that order, and should return aninteger less than, equal to, or greater than zero corresponding towhether the key is considered less than, equal to, or greater thanthe array element. The function should not alter the array’s contents,and the same array element should always compare the same way with the key.
Although the array need not be completely sorted, it should bepartially sorted with respect tokey. That is, the array shouldbegin with elements that compare less thankey, followed byelements that compare equal tokey, and ending with elementsthat compare greater thankey. Any or all of these elementsequences can be empty.
The return value is a pointer to a matching array element, or a nullpointer if no match is found. If the array contains more than one elementthat matches, the one that is returned is unspecified.
This function derives its name from the fact that it is implementedusing the binary search algorithm.
Next:Searching and Sorting Example, Previous:Array Search Function, Up:Searching and Sorting [Contents][Index]
To sort an array using an arbitrary comparison function, use theqsort
function. The prototype for this function is instdlib.h.
void
qsort(void *array, size_tcount, size_tsize, comparison_fn_tcompare)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theqsort
function sorts the arrayarray. The arraycontainscount elements, each of which is of sizesize.
Thecompare function is used to perform the comparison on thearray elements. This function is called with two pointer arguments andshould return an integer less than, equal to, or greater than zerocorresponding to whether its first argument is considered less than,equal to, or greater than its second argument.The function must not alter the array’s contents, and must define atotal ordering on the array elements, including any unusual valuessuch as floating-point NaN (seeInfinity and NaN).Because the sorting process can move elements,the function’s return value must not depend on the element addressesor the relative positions of elements within the array,as these are meaningless whileqsort
is running.
Warning: If two elements compare equal, their order aftersorting is unpredictable. That is to say, the sorting is not stable.This can make a difference when the comparison considers only part ofthe elements and two elements that compare equal may differ in otherrespects. To ensure a stable sort in this situation, you can augmenteach element with an appropriate tie-breaking value, such as itsoriginal array index.
Here is a simple example of sorting an array oflong int
in numericalorder, using the comparison function defined above (seeDefining the Comparison Function):
{ long int *array; size_t nmemb; ... qsort (array, nmemb, sizeof *array, compare_long_ints);}
Theqsort
function derives its name from the fact that it wasoriginally implemented using the “quick sort” algorithm.
The implementation ofqsort
attempts to allocate auxiliary memoryand use the merge sort algorithm, without violating C standard requirementthat arguments passed to the comparison function point within the array.If the memory allocation fails,qsort
resorts to a slower algorithm.
Next:Thehsearch
function., Previous:Array Sort Function, Up:Searching and Sorting [Contents][Index]
Here is an example showing the use ofqsort
andbsearch
with an array of structures. The elements of the array are sortedby comparing theirname
fields with thestrcmp
function.Then, we can look up individual elements based on their names.
#include <stdlib.h>#include <stdio.h>#include <string.h>/*Define an array of critters to sort. */struct critter { const char *name; const char *species; };struct critter muppets[] = { {"Kermit", "frog"}, {"Piggy", "pig"}, {"Gonzo", "whatever"}, {"Fozzie", "bear"}, {"Sam", "eagle"}, {"Robin", "frog"}, {"Animal", "animal"}, {"Camilla", "chicken"}, {"Sweetums", "monster"}, {"Dr. Strangepork", "pig"}, {"Link Hogthrob", "pig"}, {"Zoot", "human"}, {"Dr. Bunsen Honeydew", "human"}, {"Beaker", "human"}, {"Swedish Chef", "human"} };int count = sizeof (muppets) / sizeof (struct critter);/*This is the comparison function used for sorting and searching. */intcritter_cmp (const void *v1, const void *v2){ const struct critter *c1 = v1; const struct critter *c2 = v2; return strcmp (c1->name, c2->name);}/*Print information about a critter. */voidprint_critter (const struct critter *c){ printf ("%s, the %s\n", c->name, c->species);}
/*Do the lookup into the sorted array. */voidfind_critter (const char *name){ struct critter target, *result; target.name = name; result = bsearch (&target, muppets, count, sizeof (struct critter), critter_cmp); if (result) print_critter (result); else printf ("Couldn't find %s.\n", name);}
/*Main program. */intmain (void){ int i; for (i = 0; i < count; i++) print_critter (&muppets[i]); printf ("\n"); qsort (muppets, count, sizeof (struct critter), critter_cmp); for (i = 0; i < count; i++) print_critter (&muppets[i]); printf ("\n"); find_critter ("Kermit"); find_critter ("Gonzo"); find_critter ("Janice"); return 0;}
The output from this program looks like:
Kermit, the frogPiggy, the pigGonzo, the whateverFozzie, the bearSam, the eagleRobin, the frogAnimal, the animalCamilla, the chickenSweetums, the monsterDr. Strangepork, the pigLink Hogthrob, the pigZoot, the humanDr. Bunsen Honeydew, the humanBeaker, the humanSwedish Chef, the humanAnimal, the animalBeaker, the humanCamilla, the chickenDr. Bunsen Honeydew, the humanDr. Strangepork, the pigFozzie, the bearGonzo, the whateverKermit, the frogLink Hogthrob, the pigPiggy, the pigRobin, the frogSam, the eagleSwedish Chef, the humanSweetums, the monsterZoot, the humanKermit, the frogGonzo, the whateverCouldn't find Janice.
Next:Thetsearch
function., Previous:Searching and Sorting Example, Up:Searching and Sorting [Contents][Index]
hsearch
function. ¶The functions mentioned so far in this chapter are for searching in a sortedor unsorted array. There are other methods to organize informationwhich later should be searched. The costs of insert, delete and searchdiffer. One possible implementation is using hashing tables.The following functions are declared in the header filesearch.h.
int
hcreate(size_tnel)
¶Preliminary:| MT-Unsafe race:hsearch| AS-Unsafe heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Thehcreate
function creates a hashing table which can contain atleastnel elements. There is no possibility to grow this table soit is necessary to choose the value fornel wisely. The methodused to implement this function might make it necessary to make thenumber of elements in the hashing table larger than the expected maximalnumber of elements. Hashing tables usually work inefficiently if they arefilled 80% or more. The constant access time guaranteed by hashing canonly be achieved if few collisions exist. See Knuth’s “The Art ofComputer Programming, Part 3: Searching and Sorting” for moreinformation.
The weakest aspect of this function is that there can be at most onehashing table used through the whole program. The table is allocatedin local memory out of control of the programmer. As an extension the GNU C Libraryprovides an additional set of functions with a reentrantinterface which provides a similar interface but which allows keepingarbitrarily many hashing tables.
It is possible to use more than one hashing table in the program run ifthe former table is first destroyed by a call tohdestroy
.
The function returns a non-zero value if successful. If it returns zero,something went wrong. This could either mean there is already a hashingtable in use or the program ran out of memory.
void
hdestroy(void)
¶Preliminary:| MT-Unsafe race:hsearch| AS-Unsafe heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Thehdestroy
function can be used to free all the resourcesallocated in a previous call ofhcreate
. After a call to thisfunction it is again possible to callhcreate
and allocate a newtable with possibly different size.
It is important to remember that the elements contained in the hashingtable at the timehdestroy
is called arenot freed by thisfunction. It is the responsibility of the program code to free thosestrings (if necessary at all). Freeing all the element memory is notpossible without extra, separately kept information since there is nofunction to iterate through all available elements in the hashing table.If it is really necessary to free a table and all elements theprogrammer has to keep a list of all table elements and before callinghdestroy
s/he has to free all element’s data using this list.This is a very unpleasant mechanism and it also shows that this kind ofhashing table is mainly meant for tables which are created once andused until the end of the program run.
Entries of the hashing table and keys for the search are defined usingthis type:
char *key
Pointer to a zero-terminated string of characters describing the key forthe search or the element in the hashing table.
This is a limiting restriction of the functionality of thehsearch
functions: They can only be used for data sets whichuse the NUL character always and solely to terminate keys. It is notpossible to handle general binary data for keys.
void *data
Generic pointer for use by the application. The hashing tableimplementation preserves this pointer in entries, but does not use itin any way otherwise.
The underlying type ofENTRY
.
ENTRY *
hsearch(ENTRYitem, ACTIONaction)
¶Preliminary:| MT-Unsafe race:hsearch| AS-Unsafe | AC-Unsafe corrupt/action==ENTER| SeePOSIX Safety Concepts.
To search in a hashing table created usinghcreate
thehsearch
function must be used. This function can perform a simplesearch for an element (ifaction has the valueFIND
) or it canalternatively insert the key element into the hashing table. Entriesare never replaced.
The key is denoted by a pointer to an object of typeENTRY
. Forlocating the corresponding position in the hashing table only thekey
element of the structure is used.
If an entry with a matching key is found theaction parameter isirrelevant. The found entry is returned. If no matching entry is foundand theaction parameter has the valueFIND
the functionreturns aNULL
pointer. If no entry is found and theaction parameter has the valueENTER
a new entry is addedto the hashing table which is initialized with the parameteritem.A pointer to the newly added entry is returned.
As mentioned before, the hashing table used by the functions described sofar is global and there can be at any time at most one hashing table inthe program. A solution is to use the following functions which are aGNU extension. All have in common that they operate on a hashing tablewhich is described by the content of an object of the typestructhsearch_data
. This type should be treated as opaque, none of itsmembers should be changed directly.
int
hcreate_r(size_tnel, struct hsearch_data *htab)
¶Preliminary:| MT-Safe race:htab| AS-Unsafe heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Thehcreate_r
function initializes the object pointed to byhtab to contain a hashing table with at leastnel elements.So this function is equivalent to thehcreate
function exceptthat the initialized data structure is controlled by the user.
This allows having more than one hashing table at one time. The memorynecessary for thestruct hsearch_data
object can be allocateddynamically. It must be initialized with zero before calling thisfunction.
The return value is non-zero if the operation was successful. If thereturn value is zero, something went wrong, which probably means theprogram ran out of memory.
void
hdestroy_r(struct hsearch_data *htab)
¶Preliminary:| MT-Safe race:htab| AS-Unsafe heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Thehdestroy_r
function frees all resources allocated by thehcreate_r
function for this very same objecthtab. As forhdestroy
it is the program’s responsibility to free the stringsfor the elements of the table.
int
hsearch_r(ENTRYitem, ACTIONaction, ENTRY **retval, struct hsearch_data *htab)
¶Preliminary:| MT-Safe race:htab| AS-Safe | AC-Unsafe corrupt/action==ENTER| SeePOSIX Safety Concepts.
Thehsearch_r
function is equivalent tohsearch
. Themeaning of the first two arguments is identical. But instead ofoperating on a single global hashing table the function works on thetable described by the object pointed to byhtab (which isinitialized by a call tohcreate_r
).
Another difference tohcreate
is that the pointer to the foundentry in the table is not the return value of the function. It isreturned by storing it in a pointer variable pointed to by theretval parameter. The return value of the function is an integervalue indicating success if it is non-zero and failure if it is zero.In the latter case the global variableerrno
signals the reason forthe failure.
ENOMEM
The table is filled andhsearch_r
was called with a so farunknown key andaction set toENTER
.
ESRCH
Theaction parameter isFIND
and no corresponding elementis found in the table.
Previous:Thehsearch
function., Up:Searching and Sorting [Contents][Index]
tsearch
function. ¶Another common form to organize data for efficient search is to usetrees. Thetsearch
function family provides a nice interface tofunctions to organize possibly large amounts of data by providing a meanaccess time proportional to the logarithm of the number of elements.The GNU C Library implementation even guarantees that this bound isnever exceeded even for input data which cause problems for simplebinary tree implementations.
The functions described in the chapter are all described in the System V and X/Open specifications and are therefore quite portable.
In contrast to thehsearch
functions thetsearch
functionscan be used with arbitrary data and not only zero-terminated strings.
Thetsearch
functions have the advantage that no function toinitialize data structures is necessary. A simple pointer of typevoid *
initialized toNULL
is a valid tree and can beextended or searched. The prototypes for these functions can be foundin the header filesearch.h.
void *
tsearch(const void *key, void **rootp, comparison_fn_tcompar)
¶Preliminary:| MT-Safe race:rootp| AS-Unsafe heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Thetsearch
function searches in the tree pointed to by*rootp
for an element matchingkey. The functionpointed to bycompar is used to determine whether two elementsmatch. SeeDefining the Comparison Function, for a specification of the functionswhich can be used for thecompar parameter.
If the tree does not contain a matching entry thekey value willbe added to the tree.tsearch
does not make a copy of the objectpointed to bykey (how could it since the size is unknown).Instead it adds a reference to this object which means the object mustbe available as long as the tree data structure is used.
The tree is represented by a pointer to a pointer since it is sometimesnecessary to change the root node of the tree. So it must not beassumed that the variable pointed to byrootp has the same valueafter the call. This also shows that it is not safe to call thetsearch
function more than once at the same time using the sametree. It is no problem to run it more than once at a time on differenttrees.
The return value is a pointer to the matching element in the tree. If anew element was created the pointer points to the new data (which is infactkey). If an entry had to be created and the program ran outof spaceNULL
is returned.
void *
tfind(const void *key, void *const *rootp, comparison_fn_tcompar)
¶Preliminary:| MT-Safe race:rootp| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thetfind
function is similar to thetsearch
function. Itlocates an element matching the one pointed to bykey and returnsa pointer to this element. But if no matching element is available nonew element is entered (note that therootp parameter points to aconstant pointer). Instead the function returnsNULL
.
Another advantage of thetsearch
functions in contrast to thehsearch
functions is that there is an easy way to removeelements.
void *
tdelete(const void *key, void **rootp, comparison_fn_tcompar)
¶Preliminary:| MT-Safe race:rootp| AS-Unsafe heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
To remove a specific element matchingkey from the treetdelete
can be used. It locates the matching element using thesame method astfind
. The corresponding element is then removedand a pointer to the parent of the deleted node is returned by thefunction. If there is no matching entry in the tree nothing can bedeleted and the function returnsNULL
. If the root of the treeis deletedtdelete
returns some unspecified value not equal toNULL
.
void
tdestroy(void *vroot, __free_fn_tfreefct)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
If the complete search tree has to be removed one can usetdestroy
. It frees all resources allocated by thetsearch
functions to generate the tree pointed to byvroot.
For the data in each tree node the functionfreefct is called.The pointer to the data is passed as the argument to the function. Ifno such work is necessaryfreefct must point to a function doingnothing. It is called in any case.
This function is a GNU extension and not covered by the System V orX/Open specifications.
In addition to the functions to create and destroy the tree datastructure, there is another function which allows you to apply afunction to all elements of the tree. The function must have this type:
void __action_fn_t (const void *nodep, VISIT value, int level);
Thenodep is the data value of the current node (once given as thekey argument totsearch
).level is a numeric valuewhich corresponds to the depth of the current node in the tree. Theroot node has the depth0 and its children have a depth of1 and so on. TheVISIT
type is an enumeration type.
TheVISIT
value indicates the status of the current node in thetree and how the function is called. The status of a node is either‘leaf’ or ‘internal node’. For each leaf node the function is calledexactly once, for each internal node it is called three times: beforethe first child is processed, after the first child is processed andafter both children are processed. This makes it possible to handle allthree methods of tree traversal (or even a combination of them).
preorder
¶The current node is an internal node and the function is called beforethe first child was processed.
postorder
¶The current node is an internal node and the function is called afterthe first child was processed.
endorder
¶The current node is an internal node and the function is called afterthe second child was processed.
leaf
¶The current node is a leaf.
void
twalk(const void *root, __action_fn_taction)
¶Preliminary:| MT-Safe race:root| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
For each node in the tree with a node pointed to byroot, thetwalk
function calls the function provided by the parameteraction. For leaf nodes the function is called exactly once withvalue set toleaf
. For internal nodes the function iscalled three times, setting thevalue parameter oraction tothe appropriate value. Thelevel argument for theactionfunction is computed while descending the tree by increasing the valueby one for each descent to a child, starting with the value0 forthe root node.
Since the functions used for theaction parameter totwalk
must not modify the tree data, it is safe to runtwalk
in morethan one thread at the same time, working on the same tree. It is alsosafe to calltfind
in parallel. Functions which modify the treemust not be used, otherwise the behavior is undefined. However, it isdifficult to pass data external to the tree to the callback functionwithout resorting to global variables (and thread safety issues), sosee thetwalk_r
function below.
void
twalk_r(const void *root, void (*action) (const void *key, VISITwhich, void *closure), void *closure)
¶Preliminary:| MT-Safe race:root| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
For each node in the tree with a node pointed to byroot, thetwalk_r
function calls the function provided by the parameteraction. For leaf nodes the function is called exactly once withwhich set toleaf
. For internal nodes the function iscalled three times, setting thewhich parameter ofaction tothe appropriate value. Theclosure parameter is passed down toeach call of theaction function, unmodified.
It is possible to implement thetwalk
function on top of thetwalk_r
function, which is why there is no separate levelparameter.
#include <search.h>struct twalk_with_twalk_r_closure{ void (*action) (const void *, VISIT, int); int depth;};static voidtwalk_with_twalk_r_action (const void *nodep, VISIT which, void *closure0){ struct twalk_with_twalk_r_closure *closure = closure0; switch (which) { case leaf: closure->action (nodep, which, closure->depth); break; case preorder: closure->action (nodep, which, closure->depth); ++closure->depth; break; case postorder: /*The preorder action incremented the depth. */ closure->action (nodep, which, closure->depth - 1); break; case endorder: --closure->depth; closure->action (nodep, which, closure->depth); break; }}voidtwalk (const void *root, void (*action) (const void *, VISIT, int)){ struct twalk_with_twalk_r_closure closure = { action, 0 }; twalk_r (root, twalk_with_twalk_r_action, &closure);}
Next:Input/Output Overview, Previous:Searching and Sorting, Up:Main Menu [Contents][Index]
The GNU C Library provides pattern matching facilities for two kinds ofpatterns: regular expressions and file-name wildcards. The library alsoprovides a facility for expanding variable and command references andparsing text into words in the way the shell does.
Next:Globbing, Up:Pattern Matching [Contents][Index]
This section describes how to match a wildcard pattern against aparticular string. The result is a yes or no answer: does thestring fit the pattern or not. The symbols described here are alldeclared infnmatch.h.
int
fnmatch(const char *pattern, const char *string, intflags)
¶Preliminary:| MT-Safe env locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function tests whether the stringstring matches the patternpattern. It returns0
if they do match; otherwise, itreturns the nonzero valueFNM_NOMATCH
. The argumentspattern andstring are both strings.
The argumentflags is a combination of flag bits that alter thedetails of matching. See below for a list of the defined flags.
In the GNU C Library,fnmatch
might sometimes report “errors” byreturning nonzero values that are not equal toFNM_NOMATCH
.
These are the available flags for theflags argument:
FNM_FILE_NAME
¶Treat the ‘/’ character specially, for matching file names. Ifthis flag is set, wildcard constructs inpattern cannot match‘/’ instring. Thus, the only way to match ‘/’ is withan explicit ‘/’ inpattern.
FNM_PATHNAME
¶This is an alias forFNM_FILE_NAME
; it comes from POSIX.2. Wedon’t recommend this name because we don’t use the term “pathname” forfile names.
FNM_PERIOD
¶Treat the ‘.’ character specially if it appears at the beginning ofstring. If this flag is set, wildcard constructs inpatterncannot match ‘.’ as the first character ofstring.
If you set bothFNM_PERIOD
andFNM_FILE_NAME
, then thespecial treatment applies to ‘.’ following ‘/’ as well as to‘.’ at the beginning ofstring. (The shell uses theFNM_PERIOD
andFNM_FILE_NAME
flags together for matchingfile names.)
FNM_NOESCAPE
¶Don’t treat the ‘\’ character specially in patterns. Normally,‘\’ quotes the following character, turning off its special meaning(if any) so that it matches only itself. When quoting is enabled, thepattern ‘\?’ matches only the string ‘?’, because the questionmark in the pattern acts like an ordinary character.
If you useFNM_NOESCAPE
, then ‘\’ is an ordinary character.
FNM_LEADING_DIR
¶Ignore a trailing sequence of characters starting with a ‘/’ instring; that is to say, test whetherstring starts with adirectory name thatpattern matches.
If this flag is set, either ‘foo*’ or ‘foobar’ as a patternwould match the string ‘foobar/frobozz’.
FNM_CASEFOLD
¶Ignore case in comparingstring topattern.
This macro was originally a GNU extension, but was added inPOSIX.1-2024.
FNM_EXTMATCH
¶Besides the normal patterns, also recognize the extended patternsintroduced inksh. The patterns are written in the formexplained in the following table wherepattern-list is a|
separated list of patterns.
?(pattern-list)
The pattern matches if zero or one occurrences of any of the patternsin thepattern-list allow matching the input string.
*(pattern-list)
The pattern matches if zero or more occurrences of any of the patternsin thepattern-list allow matching the input string.
+(pattern-list)
The pattern matches if one or more occurrences of any of the patternsin thepattern-list allow matching the input string.
@(pattern-list)
The pattern matches if exactly one occurrence of any of the patterns inthepattern-list allows matching the input string.
!(pattern-list)
The pattern matches if the input string cannot be matched with any ofthe patterns in thepattern-list.
Next:Regular Expression Matching, Previous:Wildcard Matching, Up:Pattern Matching [Contents][Index]
The archetypal use of wildcards is for matching against the files in adirectory, and making a list of all the matches. This is calledglobbing.
You could do this usingfnmatch
, by reading the directory entriesone by one and testing each one withfnmatch
. But that would beslow (and complex, since you would have to handle subdirectories byhand).
The library provides a functionglob
to make this particular useof wildcards convenient.glob
and the other symbols in thissection are declared inglob.h.
Next:Flags for Globbing, Up:Globbing [Contents][Index]
glob
¶The result of globbing is a vector of file names (strings). To returnthis vector,glob
uses a special data type,glob_t
, whichis a structure. You passglob
the address of the structure, andit fills in the structure’s fields to tell you about the results.
This data type holds a pointer to a word vector. More precisely, itrecords both the address of the word vector and its size. The GNUimplementation contains some more fields which are non-standardextensions.
gl_pathc
The number of elements in the vector, excluding the initial null entriesif the GLOB_DOOFFS flag is used (see gl_offs below).
gl_pathv
The address of the vector. This field has typechar **
.
gl_offs
The offset of the first real element of the vector, from its nominaladdress in thegl_pathv
field. Unlike the other fields, thisis always an input toglob
, rather than an output from it.
If you use a nonzero offset, then that many elements at the beginning ofthe vector are left empty. (Theglob
function fills them withnull pointers.)
Thegl_offs
field is meaningful only if you use theGLOB_DOOFFS
flag. Otherwise, the offset is always zeroregardless of what is in this field, and the first real element comes atthe beginning of the vector.
gl_closedir
The address of an alternative implementation of theclosedir
function. It is used if theGLOB_ALTDIRFUNC
bit is set inthe flag parameter. The type of this field isvoid (*) (void *)
.
This is a GNU extension.
gl_readdir
The address of an alternative implementation of thereaddir
function used to read the contents of a directory. It is used if theGLOB_ALTDIRFUNC
bit is set in the flag parameter. The type ofthis field isstruct dirent *(*) (void *)
.
An implementation ofgl_readdir
needs to initialize the followingmembers of thestruct dirent
object:
d_type
This member should be set to the file type of the entry if it is known.Otherwise, the valueDT_UNKNOWN
can be used. Theglob
function may use the specified file type to avoid callbacks in caseswhere the file type indicates that the data is not required.
d_ino
This member needs to be non-zero, otherwiseglob
may skip thecurrent entry and call thegl_readdir
callback function again toretrieve another entry.
d_name
This member must be set to the name of the entry. It must benull-terminated.
The example below shows how to allocate astruct dirent
objectcontaining a given name.
#include <dirent.h>#include <errno.h>#include <stddef.h>#include <stdlib.h>#include <string.h>struct dirent *mkdirent (const char *name){ size_t dirent_size = offsetof (struct dirent, d_name) + 1; size_t name_length = strlen (name); size_t total_size = dirent_size + name_length; if (total_size < dirent_size) { errno = ENOMEM; return NULL; } struct dirent *result = malloc (total_size); if (result == NULL) return NULL; result->d_type = DT_UNKNOWN; result->d_ino = 1; /*Do not skip this entry. */ memcpy (result->d_name, name, name_length + 1); return result;}
Theglob
function reads thestruct dirent
members listedabove and makes a copy of the file name in thed_name
memberimmediately after thegl_readdir
callback function returns.Future invocations of any of the callback functions may deallocate orreuse the buffer. It is the responsibility of the caller of theglob
function to allocate and deallocate the buffer, around thecall toglob
or using the callback functions. For example, anapplication could allocate the buffer in thegl_readdir
callbackfunction, and deallocate it in thegl_closedir
callback function.
Thegl_readdir
member is a GNU extension.
gl_opendir
The address of an alternative implementation of theopendir
function. It is used if theGLOB_ALTDIRFUNC
bit is set inthe flag parameter. The type of this field isvoid *(*) (const char *)
.
This is a GNU extension.
gl_stat
The address of an alternative implementation of thestat
functionto get information about an object in the filesystem. It is used if theGLOB_ALTDIRFUNC
bit is set in the flag parameter. The type ofthis field isint (*) (const char *, struct stat *)
.
This is a GNU extension.
gl_lstat
The address of an alternative implementation of thelstat
function to get information about an object in the filesystems, notfollowing symbolic links. It is used if theGLOB_ALTDIRFUNC
bitis set in the flag parameter. The type of this field isint (*) (const char *, struct stat *)
.
This is a GNU extension.
gl_flags
The flags used whenglob
was called. In addition,GLOB_MAGCHAR
might be set. SeeFlags for Globbing for more details.
This is a GNU extension.
For use in theglob64
functionglob.h contains anotherdefinition for a very similar type.glob64_t
differs fromglob_t
only in the types of the membersgl_readdir
,gl_stat
, andgl_lstat
.
This data type holds a pointer to a word vector. More precisely, itrecords both the address of the word vector and its size. The GNUimplementation contains some more fields which are non-standardextensions.
gl_pathc
The number of elements in the vector, excluding the initial null entriesif the GLOB_DOOFFS flag is used (see gl_offs below).
gl_pathv
The address of the vector. This field has typechar **
.
gl_offs
The offset of the first real element of the vector, from its nominaladdress in thegl_pathv
field. Unlike the other fields, thisis always an input toglob
, rather than an output from it.
If you use a nonzero offset, then that many elements at the beginning ofthe vector are left empty. (Theglob
function fills them withnull pointers.)
Thegl_offs
field is meaningful only if you use theGLOB_DOOFFS
flag. Otherwise, the offset is always zeroregardless of what is in this field, and the first real element comes atthe beginning of the vector.
gl_closedir
The address of an alternative implementation of theclosedir
function. It is used if theGLOB_ALTDIRFUNC
bit is set inthe flag parameter. The type of this field isvoid (*) (void *)
.
This is a GNU extension.
gl_readdir
The address of an alternative implementation of thereaddir64
function used to read the contents of a directory. It is used if theGLOB_ALTDIRFUNC
bit is set in the flag parameter. The type ofthis field isstruct dirent64 *(*) (void *)
.
This is a GNU extension.
gl_opendir
The address of an alternative implementation of theopendir
function. It is used if theGLOB_ALTDIRFUNC
bit is set inthe flag parameter. The type of this field isvoid *(*) (const char *)
.
This is a GNU extension.
gl_stat
The address of an alternative implementation of thestat64
functionto get information about an object in the filesystem. It is used if theGLOB_ALTDIRFUNC
bit is set in the flag parameter. The type ofthis field isint (*) (const char *, struct stat64 *)
.
This is a GNU extension.
gl_lstat
The address of an alternative implementation of thelstat64
function to get information about an object in the filesystems, notfollowing symbolic links. It is used if theGLOB_ALTDIRFUNC
bitis set in the flag parameter. The type of this field isint (*) (const char *, struct stat64 *)
.
This is a GNU extension.
gl_flags
The flags used whenglob
was called. In addition,GLOB_MAGCHAR
might be set. SeeFlags for Globbing for more details.
This is a GNU extension.
int
glob(const char *pattern, intflags, int (*errfunc) (const char *filename, interror-code), glob_t *vector-ptr)
¶Preliminary:| MT-Unsafe race:utent env sig:ALRM timer locale| AS-Unsafe dlopen plugin corrupt heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
The functionglob
does globbing using the patternpatternin the current directory. It puts the result in a newly allocatedvector, and stores the size and address of this vector into*vector-ptr
. The argumentflags is a combination ofbit flags; seeFlags for Globbing, for details of the flags.
The result of globbing is a sequence of file names. The functionglob
allocates a string for each resulting word, thenallocates a vector of typechar **
to store the addresses ofthese strings. The last element of the vector is a null pointer.This vector is called theword vector.
To return this vector,glob
stores both its address and itslength (number of elements, not counting the terminating null pointer)into*vector-ptr
.
Normally,glob
sorts the file names alphabetically beforereturning them. You can turn this off with the flagGLOB_NOSORT
if you want to get the information as fast as possible. Usually it’sa good idea to letglob
sort them—if you process the files inalphabetical order, the users will have a feel for the rate of progressthat your application is making.
Ifglob
succeeds, it returns 0. Otherwise, it returns oneof these error codes:
GLOB_ABORTED
¶There was an error opening a directory, and you used the flagGLOB_ERR
or your specifiederrfunc returned a nonzerovalue.for an explanation of theGLOB_ERR
flag anderrfunc.
GLOB_NOMATCH
¶The pattern didn’t match any existing files. If you use theGLOB_NOCHECK
flag, then you never get this error code, becausethat flag tellsglob
topretend that the pattern matchedat least one file.
GLOB_NOSPACE
¶It was impossible to allocate memory to hold the result.
In the event of an error,glob
stores information in*vector-ptr
about all the matches it has found so far.
It is important to notice that theglob
function will not fail ifit encounters directories or files which cannot be handled without theLFS interfaces. The implementation ofglob
is supposed to usethese functions internally. This at least is the assumption made bythe Unix standard. The GNU extension of allowing the user to provide theirown directory handling andstat
functions complicates things abit. If these callback functions are used and a large file or directoryis encounteredglob
can fail.
int
glob64(const char *pattern, intflags, int (*errfunc) (const char *filename, interror-code), glob64_t *vector-ptr)
¶Preliminary:| MT-Unsafe race:utent env sig:ALRM timer locale| AS-Unsafe dlopen corrupt heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Theglob64
function was added as part of the Large File Summitextensions but is not part of the original LFS proposal. The reason forthis is simple: it is not necessary. The necessity for aglob64
function is added by the extensions of the GNUglob
implementation which allows the user to provide their own directory handlingandstat
functions. Thereaddir
andstat
functionsdo depend on the choice of_FILE_OFFSET_BITS
since the definitionof the typesstruct dirent
andstruct stat
will changedepending on the choice.
Besides this difference,glob64
works just likeglob
inall aspects.
This function is a GNU extension.
Next:More Flags for Globbing, Previous:Callingglob
, Up:Globbing [Contents][Index]
This section describes the standard flags that you can specify in theflags argument toglob
. Choose the flags you want,and combine them with the C bitwise OR operator|
.
Note that there areMore Flags for Globbing available as GNU extensions.
GLOB_APPEND
¶Append the words from this expansion to the vector of words produced byprevious calls toglob
. This way you can effectively expandseveral words as if they were concatenated with spaces between them.
In order for appending to work, you must not modify the contents of theword vector structure between calls toglob
. And, if you setGLOB_DOOFFS
in the first call toglob
, you must alsoset it when you append to the results.
Note that the pointer stored ingl_pathv
may no longer be validafter you callglob
the second time, becauseglob
mighthave relocated the vector. So always fetchgl_pathv
from theglob_t
structure after eachglob
call;never savethe pointer across calls.
GLOB_DOOFFS
¶Leave blank slots at the beginning of the vector of words.Thegl_offs
field says how many slots to leave.The blank slots contain null pointers.
GLOB_ERR
¶Give up right away and report an error if there is any difficultyreading the directories that must be read in order to expandpatternfully. Such difficulties might include a directory in which you don’thave the requisite access. Normally,glob
tries its best to keepon going despite any errors, reading whatever directories it can.
You can exercise even more control than this by specifying anerror-handler functionerrfunc when you callglob
. Iferrfunc is not a null pointer, thenglob
doesn’t give upright away when it can’t read a directory; instead, it callserrfunc with two arguments, like this:
(*errfunc) (filename,error-code)
The argumentfilename is the name of the directory thatglob
couldn’t open or couldn’t read, anderror-code is theerrno
value that was reported toglob
.
If the error handler function returns nonzero, thenglob
gives upright away. Otherwise, it continues.
GLOB_MARK
¶If the pattern matches the name of a directory, append ‘/’ to thedirectory’s name when returning it.
GLOB_NOCHECK
¶If the pattern doesn’t match any file names, return the pattern itselfas if it were a file name that had been matched. (Normally, when thepattern doesn’t match anything,glob
returns that there were nomatches.)
GLOB_NOESCAPE
¶Don’t treat the ‘\’ character specially in patterns. Normally,‘\’ quotes the following character, turning off its special meaning(if any) so that it matches only itself. When quoting is enabled, thepattern ‘\?’ matches only the string ‘?’, because the questionmark in the pattern acts like an ordinary character.
If you useGLOB_NOESCAPE
, then ‘\’ is an ordinary character.
glob
does its work by calling the functionfnmatch
repeatedly. It handles the flagGLOB_NOESCAPE
by turning on theFNM_NOESCAPE
flag in calls tofnmatch
.
GLOB_NOSORT
¶Don’t sort the file names; return them in no particular order.(In practice, the order will depend on the order of the entries inthe directory.) The only reasonnot to sort is to save time.
Previous:Flags for Globbing, Up:Globbing [Contents][Index]
Beside the flags described in the last section, the GNU implementation ofglob
allows a few more flags which are also defined in theglob.h file. Some of the extensions implement functionalitywhich is available in modern shell implementations.
GLOB_PERIOD
¶The.
character (period) is treated special. It cannot bematched by wildcards. SeeWildcard Matching,FNM_PERIOD
.
GLOB_MAGCHAR
¶TheGLOB_MAGCHAR
value is not to be given toglob
in theflags parameter. Instead,glob
sets this bit in thegl_flags element of theglob_t structure provided as theresult if the pattern used for matching contains any wildcard character.
GLOB_ALTDIRFUNC
¶Instead of using the normal functions for accessing thefilesystem theglob
implementation uses the user-suppliedfunctions specified in the structure pointed to bypglobparameter. For more information about the functions refer to thesections about directory handling seeAccessing Directories, andReading the Attributes of a File.
GLOB_BRACE
¶If this flag is given, the handling of braces in the pattern is changed.It is now required that braces appear correctly grouped. I.e., for eachopening brace there must be a closing one. Braces can be usedrecursively. So it is possible to define one brace expression inanother one. It is important to note that the range of each braceexpression is completely contained in the outer brace expression (ifthere is one).
The string between the matching braces is separated into singleexpressions by splitting at,
(comma) characters. The commasthemselves are discarded. Please note what we said above about recursivebrace expressions. The commas used to separate the subexpressions mustbe at the same level. Commas in brace subexpressions are not matched.They are used during expansion of the brace expression of the deeperlevel. The example below shows this
glob ("{foo/{,bar,biz},baz}", GLOB_BRACE, NULL, &result)
is equivalent to the sequence
glob ("foo/", GLOB_BRACE, NULL, &result)glob ("foo/bar", GLOB_BRACE|GLOB_APPEND, NULL, &result)glob ("foo/biz", GLOB_BRACE|GLOB_APPEND, NULL, &result)glob ("baz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
if we leave aside error handling.
GLOB_NOMAGIC
¶If the pattern contains no wildcard constructs (it is a literal file name),return it as the sole “matching” word, even if no file exists by that name.
GLOB_TILDE
¶If this flag is used the character~
(tilde) is handled speciallyif it appears at the beginning of the pattern. Instead of being takenverbatim it is used to represent the home directory of a known user.
If~
is the only character in pattern or it is followed by a/
(slash), the home directory of the process owner issubstituted. Usinggetlogin
andgetpwnam
the informationis read from the system databases. As an example take userbart
with his home directory at/home/bart. For him a call like
glob ("~/bin/*", GLOB_TILDE, NULL, &result)
would return the contents of the directory/home/bart/bin.Instead of referring to the own home directory it is also possible toname the home directory of other users. To do so one has to append theuser name after the tilde character. So the contents of userhomer
’sbin directory can be retrieved by
glob ("~homer/bin/*", GLOB_TILDE, NULL, &result)
If the user name is not valid or the home directory cannot be determinedfor some reason the pattern is left untouched and itself used as theresult. I.e., if in the last examplehome
is not available thetilde expansion yields to"~homer/bin/*"
andglob
is notlooking for a directory named~homer
.
This functionality is equivalent to what is available in C-shells if thenonomatch
flag is set.
GLOB_TILDE_CHECK
¶If this flag is usedglob
behaves as ifGLOB_TILDE
isgiven. The only difference is that if the user name is not available orthe home directory cannot be determined for other reasons this leads toan error.glob
will returnGLOB_NOMATCH
instead of usingthe pattern itself as the name.
This functionality is equivalent to what is available in C-shells ifthenonomatch
flag is not set.
GLOB_ONLYDIR
¶If this flag is used the globbing function takes this as ahint that the caller is only interested in directoriesmatching the pattern. If the information about the type of the fileis easily available non-directories will be rejected but no extrawork will be done to determine the information for each file. I.e.,the caller must still be able to filter directories out.
This functionality is only available with the GNUglob
implementation. It is mainly used internally to increase theperformance but might be useful for a user as well and therefore isdocumented here.
Callingglob
will in most cases allocate resources which are usedto represent the result of the function call. If the same object oftypeglob_t
is used in multiple call toglob
the resourcesare freed or reused so that no leaks appear. But this does not includethe time when allglob
calls are done.
void
globfree(glob_t *pglob)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Theglobfree
function frees all resources allocated by previouscalls toglob
associated with the object pointed to bypglob. This function should be called whenever the currently usedglob_t
typed object isn’t used anymore.
void
globfree64(glob64_t *pglob)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function is equivalent toglobfree
but it frees records oftypeglob64_t
which were allocated byglob64
.
Next:Shell-Style Word Expansion, Previous:Globbing, Up:Pattern Matching [Contents][Index]
The GNU C Library supports two interfaces for matching regularexpressions. One is the standard POSIX.2 interface, and the other iswhat the GNU C Library has had for many years.
Both interfaces are declared in the header fileregex.h.If you define_POSIX_C_SOURCE
, then only the POSIX.2functions, structures, and constants are declared.
Before you can actually match a regular expression, you mustcompile it. This is not true compilation—it produces a specialdata structure, not machine instructions. But it is like ordinarycompilation in that its purpose is to enable you to “execute” thepattern fast. (SeeMatching a Compiled POSIX Regular Expression, for how to use thecompiled regular expression for matching.)
There is a special data type for compiled regular expressions:
This type of object holds a compiled regular expression.It is actually a structure. It has just one field that your programsshould look at:
re_nsub
This field holds the number of parenthetical subexpressions in theregular expression that was compiled.
There are several other fields, but we don’t describe them here, becauseonly the functions in the library should use them.
After you create aregex_t
object, you can compile a regularexpression into it by callingregcomp
.
int
regcomp(regex_t *restrictcompiled, const char *restrictpattern, intcflags)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
The functionregcomp
“compiles” a regular expression into adata structure that you can use withregexec
to match against astring. The compiled regular expression format is designed forefficient matching.regcomp
stores it into*compiled
.
It’s up to you to allocate an object of typeregex_t
and pass itsaddress toregcomp
.
The argumentcflags lets you specify various options that controlthe syntax and semantics of regular expressions. SeeFlags for POSIX Regular Expressions.
If you use the flagREG_NOSUB
, thenregcomp
omits fromthe compiled regular expression the information necessary to recordhow subexpressions actually match. In this case, you might as wellpass0
for thematchptr andnmatch arguments whenyou callregexec
.
If you don’t useREG_NOSUB
, then the compiled regular expressiondoes have the capacity to record how subexpressions match. Also,regcomp
tells you how many subexpressionspattern has, bystoring the number incompiled->re_nsub
. You can use thatvalue to decide how long an array to allocate to hold information aboutsubexpression matches.
regcomp
returns0
if it succeeds in compiling the regularexpression; otherwise, it returns a nonzero error code (see the tablebelow). You can useregerror
to produce an error message stringdescribing the reason for a nonzero value; seePOSIX Regexp Matching Cleanup.
Here are the possible nonzero values thatregcomp
can return:
REG_BADBR
¶There was an invalid ‘\{…\}’ construct in the regularexpression. A valid ‘\{…\}’ construct must contain eithera single number, or two numbers in increasing order separated by acomma.
REG_BADPAT
¶There was a syntax error in the regular expression.
REG_BADRPT
¶A repetition operator such as ‘?’ or ‘*’ appeared in a badposition (with no preceding subexpression to act on).
REG_ECOLLATE
¶The regular expression referred to an invalid collating element (one notdefined in the current locale for string collation). SeeLocale Categories.
REG_ECTYPE
¶The regular expression referred to an invalid character class name.
REG_EESCAPE
¶The regular expression ended with ‘\’.
REG_ESUBREG
¶There was an invalid number in the ‘\digit’ construct.
REG_EBRACK
¶There were unbalanced square brackets in the regular expression.
REG_EPAREN
¶An extended regular expression had unbalanced parentheses,or a basic regular expression had unbalanced ‘\(’ and ‘\)’.
REG_EBRACE
¶The regular expression had unbalanced ‘\{’ and ‘\}’.
REG_ERANGE
¶One of the endpoints in a range expression was invalid.
REG_ESPACE
¶regcomp
ran out of memory.
Next:Matching a Compiled POSIX Regular Expression, Previous:POSIX Regular Expression Compilation, Up:Regular Expression Matching [Contents][Index]
These are the bit flags that you can use in thecflags operand whencompiling a regular expression withregcomp
.
REG_EXTENDED
¶Treat the pattern as an extended regular expression, rather than as abasic regular expression.
REG_ICASE
¶Ignore case when matching letters.
REG_NOSUB
¶Don’t bother storing the contents of thematchptr array.
REG_NEWLINE
¶Treat a newline instring as dividingstring into multiplelines, so that ‘$’ can match before the newline and ‘^’ canmatch after. Also, don’t permit ‘.’ to match a newline, and don’tpermit ‘[^…]’ to match a newline.
Otherwise, newline acts like any other ordinary character.
Next:Match Results with Subexpressions, Previous:Flags for POSIX Regular Expressions, Up:Regular Expression Matching [Contents][Index]
Once you have compiled a regular expression, as described inPOSIX Regular Expression Compilation, you can match it against strings usingregexec
. A match anywhere inside the string counts as success,unless the regular expression contains anchor characters (‘^’ or‘$’).
int
regexec(const regex_t *restrictcompiled, const char *restrictstring, size_tnmatch, regmatch_tmatchptr[restrict], inteflags)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
This function tries to match the compiled regular expression*compiled
againststring.
regexec
returns0
if the regular expression matches;otherwise, it returns a nonzero value. See the table below forwhat nonzero values mean. You can useregerror
to produce anerror message string describing the reason for a nonzero value;seePOSIX Regexp Matching Cleanup.
The argumenteflags is a word of bit flags that enable variousoptions.
If you want to get information about what part ofstring actuallymatched the regular expression or its subexpressions, use the argumentsmatchptr andnmatch. Otherwise, pass0
fornmatch, andNULL
formatchptr. SeeMatch Results with Subexpressions.
You must match the regular expression with the same set of currentlocales that were in effect when you compiled the regular expression.
The functionregexec
accepts the following flags in theeflags argument:
REG_NOTBOL
¶Do not regard the beginning of the specified string as the beginning ofa line; more generally, don’t make any assumptions about what text mightprecede it.
REG_NOTEOL
¶Do not regard the end of the specified string as the end of a line; moregenerally, don’t make any assumptions about what text might follow it.
Here are the possible nonzero values thatregexec
can return:
REG_NOMATCH
¶The pattern didn’t match the string. This isn’t really an error.
REG_ESPACE
¶regexec
ran out of memory.
Next:Complications in Subexpression Matching, Previous:Matching a Compiled POSIX Regular Expression, Up:Regular Expression Matching [Contents][Index]
Whenregexec
matches parenthetical subexpressions ofpattern, it records which parts ofstring they match. Itreturns that information by storing the offsets into an array whoseelements are structures of typeregmatch_t
. The first element ofthe array (index0
) records the part of the string that matchedthe entire regular expression. Each other element of the array recordsthe beginning and end of the part that matched a single parentheticalsubexpression.
This is the data type of thematchptr array that you pass toregexec
. It contains two structure fields, as follows:
rm_so
The offset instring of the beginning of a substring. Add thisvalue tostring to get the address of that part.
rm_eo
The offset instring of the end of the substring.
regoff_t
is an alias for another signed integer type.The fields ofregmatch_t
have typeregoff_t
.
Theregmatch_t
elements correspond to subexpressionspositionally; the first element (index1
) records where the firstsubexpression matched, the second element records the secondsubexpression, and so on. The order of the subexpressions is the orderin which they begin.
When you callregexec
, you specify how long thematchptrarray is, with thenmatch argument. This tellsregexec
howmany elements to store. If the actual regular expression has more thannmatch subexpressions, then you won’t get offset information aboutthe rest of them. But this doesn’t alter whether the pattern matches aparticular string or not.
If you don’t wantregexec
to return any information about wherethe subexpressions matched, you can either supply0
fornmatch, or use the flagREG_NOSUB
when you compile thepattern withregcomp
.
Next:POSIX Regexp Matching Cleanup, Previous:Match Results with Subexpressions, Up:Regular Expression Matching [Contents][Index]
Sometimes a subexpression matches a substring of no characters. Thishappens when ‘f\(o*\)’ matches the string ‘fum’. (It reallymatches just the ‘f’.) In this case, both of the offsets identifythe point in the string where the null substring was found. In thisexample, the offsets are both1
.
Sometimes the entire regular expression can match without using some ofits subexpressions at all—for example, when ‘ba\(na\)*’ matches thestring ‘ba’, the parenthetical subexpression is not used. Whenthis happens,regexec
stores-1
in both fields of theelement for that subexpression.
Sometimes matching the entire regular expression can match a particularsubexpression more than once—for example, when ‘ba\(na\)*’matches the string ‘bananana’, the parenthetical subexpressionmatches three times. When this happens,regexec
usually storesthe offsets of the last part of the string that matched thesubexpression. In the case of ‘bananana’, these offsets are6
and8
.
But the last match is not always the one that is chosen. It’s moreaccurate to say that the lastopportunity to match is the onethat takes precedence. What this means is that when one subexpressionappears within another, then the results reported for the innersubexpression reflect whatever happened on the last match of the outersubexpression. For an example, consider ‘\(ba\(na\)*s \)*’ matchingthe string ‘bananas bas’. The last time the inner expressionactually matches is near the end of the first word. But it isconsidered again in the second word, and fails to match there.regexec
reports nonuse of the “na” subexpression.
Another place where this rule applies is when the regular expression
\(ba\(na\)*s \|nefer\(ti\)* \)*
matches ‘bananas nefertiti’. The “na” subexpression does matchin the first word, but it doesn’t match in the second word because theother alternative is used there. Once again, the second repetition ofthe outer subexpression overrides the first, and within that secondrepetition, the “na” subexpression is not used. Soregexec
reports nonuse of the “na” subexpression.
When you are finished using a compiled regular expression, you canfree the storage it uses by callingregfree
.
void
regfree(regex_t *compiled)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Callingregfree
frees all the storage that*compiled
points to. This includes various internal fields of theregex_t
structure that aren’t documented in this manual.
regfree
does not free the object*compiled
itself.
You should always free the space in aregex_t
structure withregfree
before using the structure to compile another regularexpression.
Whenregcomp
orregexec
reports an error, you can usethe functionregerror
to turn it into an error message string.
size_t
regerror(interrcode, const regex_t *restrictcompiled, char *restrictbuffer, size_tlength)
¶Preliminary:| MT-Safe env| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function produces an error message string for the error codeerrcode, and stores the string inlength bytes of memorystarting atbuffer. For thecompiled argument, supply thesame compiled regular expression structure thatregcomp
orregexec
was working with when it got the error. Alternatively,you can supplyNULL
forcompiled; you will still get ameaningful error message, but it might not be as detailed.
If the error message can’t fit inlength bytes (including aterminating null character), thenregerror
truncates it.The string thatregerror
stores is always null-terminatedeven if it has been truncated.
The return value ofregerror
is the minimum length needed tostore the entire error message. If this is less thanlength, thenthe error message was not truncated, and you can use it. Otherwise, youshould callregerror
again with a larger buffer.
Here is a function which usesregerror
, but always dynamicallyallocates a buffer for the error message:
char *get_regerror (int errcode, regex_t *compiled){ size_t length = regerror (errcode, compiled, NULL, 0); char *buffer = xmalloc (length); (void) regerror (errcode, compiled, buffer, length); return buffer;}
Previous:Regular Expression Matching, Up:Pattern Matching [Contents][Index]
Word expansion means the process of splitting a string intowords and substituting for variables, commands, and wildcardsjust as the shell does.
For example, when you write ‘ls -l foo.c’, this string is splitinto three separate words—‘ls’, ‘-l’ and ‘foo.c’.This is the most basic function of word expansion.
When you write ‘ls *.c’, this can become many words, becausethe word ‘*.c’ can be replaced with any number of file names.This is calledwildcard expansion, and it is also a part ofword expansion.
When you use ‘echo $PATH’ to print your path, you are takingadvantage ofvariable substitution, which is also part of wordexpansion.
Ordinary programs can perform word expansion just like the shell bycalling the library functionwordexp
.
wordexp
wordexp
ExampleNext:Callingwordexp
, Up:Shell-Style Word Expansion [Contents][Index]
When word expansion is applied to a sequence of words, it performs thefollowing transformations in the order shown here:
For the details of these transformations, and how to write the constructsthat use them, seeThe BASH Manual (to appear).
Next:Flags for Word Expansion, Previous:The Stages of Word Expansion, Up:Shell-Style Word Expansion [Contents][Index]
wordexp
¶All the functions, constants and data types for word expansion aredeclared in the header filewordexp.h.
Word expansion produces a vector of words (strings). To return thisvector,wordexp
uses a special data type,wordexp_t
, whichis a structure. You passwordexp
the address of the structure,and it fills in the structure’s fields to tell you about the results.
This data type holds a pointer to a word vector. More precisely, itrecords both the address of the word vector and its size.
we_wordc
The number of elements in the vector.
we_wordv
The address of the vector. This field has typechar **
.
we_offs
The offset of the first real element of the vector, from its nominaladdress in thewe_wordv
field. Unlike the other fields, thisis always an input towordexp
, rather than an output from it.
If you use a nonzero offset, then that many elements at the beginning ofthe vector are left empty. (Thewordexp
function fills them withnull pointers.)
Thewe_offs
field is meaningful only if you use theWRDE_DOOFFS
flag. Otherwise, the offset is always zeroregardless of what is in this field, and the first real element comes atthe beginning of the vector.
int
wordexp(const char *words, wordexp_t *word-vector-ptr, intflags)
¶Preliminary:| MT-Unsafe race:utent const:env env sig:ALRM timer locale| AS-Unsafe dlopen plugin i18n heap corrupt lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Perform word expansion on the stringwords, putting the result ina newly allocated vector, and store the size and address of this vectorinto*word-vector-ptr
. The argumentflags is acombination of bit flags; seeFlags for Word Expansion, for details ofthe flags.
You shouldn’t use any of the characters ‘|&;<>’ in the stringwords unless they are quoted; likewise for newline. If you usethese characters unquoted, you will get theWRDE_BADCHAR
errorcode. Don’t use parentheses or braces unless they are quoted or part ofa word expansion construct. If you use quotation characters ‘'"`’,they should come in pairs that balance.
The results of word expansion are a sequence of words. The functionwordexp
allocates a string for each resulting word, thenallocates a vector of typechar **
to store the addresses ofthese strings. The last element of the vector is a null pointer.This vector is called theword vector.
To return this vector,wordexp
stores both its address and itslength (number of elements, not counting the terminating null pointer)into*word-vector-ptr
.
Ifwordexp
succeeds, it returns 0. Otherwise, it returns oneof these error codes:
WRDE_BADCHAR
¶The input stringwords contains an unquoted invalid character suchas ‘|’.
WRDE_BADVAL
¶The input string refers to an undefined shell variable, and you used the flagWRDE_UNDEF
to forbid such references.
WRDE_CMDSUB
¶The input string uses command substitution, and you used the flagWRDE_NOCMD
to forbid command substitution.
WRDE_NOSPACE
¶It was impossible to allocate memory to hold the result. In this case,wordexp
can store part of the results—as much as it couldallocate room for.
WRDE_SYNTAX
¶There was a syntax error in the input string. For example, an unmatchedquoting character is a syntax error. This error code is also used tosignal division by zero and overflow in arithmetic expansion.
void
wordfree(wordexp_t *word-vector-ptr)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Free the storage used for the word-strings and vector that*word-vector-ptr
points to. This does not free thestructure*word-vector-ptr
itself—only the otherdata it points to.
Next:wordexp
Example, Previous:Callingwordexp
, Up:Shell-Style Word Expansion [Contents][Index]
This section describes the flags that you can specify in theflags argument towordexp
. Choose the flags you want,and combine them with the C operator|
.
WRDE_APPEND
¶Append the words from this expansion to the vector of words produced byprevious calls towordexp
. This way you can effectively expandseveral words as if they were concatenated with spaces between them.
In order for appending to work, you must not modify the contents of theword vector structure between calls towordexp
. And, if you setWRDE_DOOFFS
in the first call towordexp
, you must alsoset it when you append to the results.
WRDE_DOOFFS
¶Leave blank slots at the beginning of the vector of words.Thewe_offs
field says how many slots to leave.The blank slots contain null pointers.
WRDE_NOCMD
¶Don’t do command substitution; if the input requests command substitution,report an error.
WRDE_REUSE
¶Reuse a word vector made by a previous call towordexp
.Instead of allocating a new vector of words, this call towordexp
will use the vector that already exists (making it larger if necessary).
Note that the vector may move, so it is not safe to save an old pointerand use it again after callingwordexp
. You must fetchwe_pathv
anew after each call.
WRDE_SHOWERR
¶Do show any error messages printed by commands run by command substitution.More precisely, allow these commands to inherit the standard error outputstream of the current process. By default,wordexp
gives thesecommands a standard error stream that discards all output.
WRDE_UNDEF
¶If the input refers to a shell variable that is not defined, report anerror.
Next:Details of Tilde Expansion, Previous:Flags for Word Expansion, Up:Shell-Style Word Expansion [Contents][Index]
wordexp
Example ¶Here is an example of usingwordexp
to expand several stringsand use the results to run a shell command. It also shows the use ofWRDE_APPEND
to concatenate the expansions and ofwordfree
to free the space allocated bywordexp
.
intexpand_and_execute (const char *program, const char **options){ wordexp_t result; pid_t pid int status, i; /*Expand the string for the program to run. */ switch (wordexp (program, &result, 0)) { case 0:/*Successful. */ break; case WRDE_NOSPACE: /*If the error wasWRDE_NOSPACE
,then perhaps part of the result was allocated. */ wordfree (&result); default: /*Some other error. */ return -1; } /*Expand the strings specified for the arguments. */ for (i = 0; options[i] != NULL; i++) { if (wordexp (options[i], &result, WRDE_APPEND)) { wordfree (&result); return -1; } } pid = fork (); if (pid == 0) { /*This is the child process. Execute the command. */ execv (result.we_wordv[0], result.we_wordv); exit (EXIT_FAILURE); } else if (pid < 0) /*The fork failed. Report failure. */ status = -1; else /*This is the parent process. Wait for the child to complete. */ if (waitpid (pid, &status, 0) != pid) status = -1; wordfree (&result); return status;}
Next:Details of Variable Substitution, Previous:wordexp
Example, Up:Shell-Style Word Expansion [Contents][Index]
It’s a standard part of shell syntax that you can use ‘~’ at thebeginning of a file name to stand for your own home directory. Youcan use ‘~user’ to stand foruser’s home directory.
Tilde expansion is the process of converting these abbreviationsto the directory names that they stand for.
Tilde expansion applies to the ‘~’ plus all following characters upto whitespace or a slash. It takes place only at the beginning of aword, and only if none of the characters to be transformed is quoted inany way.
Plain ‘~’ uses the value of the environment variableHOME
as the proper home directory name. ‘~’ followed by a user nameusesgetpwname
to look up that user in the user database, anduses whatever directory is recorded there. Thus, ‘~’ followedby your own name can give different results from plain ‘~’, ifthe value ofHOME
is not really your home directory.
Previous:Details of Tilde Expansion, Up:Shell-Style Word Expansion [Contents][Index]
Part of ordinary shell syntax is the use of ‘$variable’ tosubstitute the value of a shell variable into a command. This is calledvariable substitution, and it is one part of doing word expansion.
There are two basic ways you can write a variable reference forsubstitution:
${variable}
If you write braces around the variable name, then it is completelyunambiguous where the variable name ends. You can concatenateadditional letters onto the end of the variable value by writing themimmediately after the close brace. For example, ‘${foo}s’expands into ‘tractors’.
$variable
If you do not put braces around the variable name, then the variablename consists of all the alphanumeric characters and underscores thatfollow the ‘$’. The next punctuation character ends the variablename. Thus, ‘$foo-bar’ refers to the variablefoo
and expandsinto ‘tractor-bar’.
When you use braces, you can also use various constructs to modify thevalue that is substituted, or test it in various ways.
${variable:-default}
Substitute the value ofvariable, but if that is empty orundefined, usedefault instead.
${variable:=default}
Substitute the value ofvariable, but if that is empty orundefined, usedefault instead and set the variable todefault.
${variable:?message}
Ifvariable is defined and not empty, substitute its value.
Otherwise, printmessage as an error message on the standard errorstream, and consider word expansion a failure.
${variable:+replacement}
Substitutereplacement, but only ifvariable is defined andnonempty. Otherwise, substitute nothing for this construct.
${#variable}
Substitute a numeral which expresses in base ten the number ofcharacters in the value ofvariable. ‘${#foo}’ stands for‘7’, because ‘tractor’ is seven characters.
These variants of variable substitution let you remove part of thevariable’s value before substituting it. Theprefix andsuffix are not mere strings; they are wildcard patterns, justlike the patterns that you use to match multiple file names. Butin this context, they match against parts of the variable valuerather than against file names.
${variable%%suffix}
Substitute the value ofvariable, but first discard from thatvariable any portion at the end that matches the patternsuffix.
If there is more than one alternative for how to match againstsuffix, this construct uses the longest possible match.
Thus, ‘${foo%%r*}’ substitutes ‘t’, because the largestmatch for ‘r*’ at the end of ‘tractor’ is ‘ractor’.
${variable%suffix}
Substitute the value ofvariable, but first discard from thatvariable any portion at the end that matches the patternsuffix.
If there is more than one alternative for how to match againstsuffix, this construct uses the shortest possible alternative.
Thus, ‘${foo%r*}’ substitutes ‘tracto’, because the shortestmatch for ‘r*’ at the end of ‘tractor’ is just ‘r’.
${variable##prefix}
Substitute the value ofvariable, but first discard from thatvariable any portion at the beginning that matches the patternprefix.
If there is more than one alternative for how to match againstprefix, this construct uses the longest possible match.
Thus, ‘${foo##*t}’ substitutes ‘or’, because the largestmatch for ‘*t’ at the beginning of ‘tractor’ is ‘tract’.
${variable#prefix}
Substitute the value ofvariable, but first discard from thatvariable any portion at the beginning that matches the patternprefix.
If there is more than one alternative for how to match againstprefix, this construct uses the shortest possible alternative.
Thus, ‘${foo#*t}’ substitutes ‘ractor’, because the shortestmatch for ‘*t’ at the beginning of ‘tractor’ is just ‘t’.
Next:Input/Output on Streams, Previous:Pattern Matching, Up:Main Menu [Contents][Index]
Most programs need to do either input (reading data) or output (writingdata), or most frequently both, in order to do anything useful. The GNU C Libraryprovides such a large selection of input and output functionsthat the hardest part is often deciding which function is mostappropriate!
This chapter introduces concepts and terminology relating to inputand output. Other chapters relating to the GNU I/O facilities are:
Next:File Names, Up:Input/Output Overview [Contents][Index]
Before you can read or write the contents of a file, you must establisha connection or communications channel to the file. This process iscalledopening the file. You can open a file for reading, writing,or both.
The connection to an open file is represented either as a stream or as afile descriptor. You pass this as an argument to the functions that dothe actual read or write operations, to tell them which file to operateon. Certain functions expect streams, and others are designed tooperate on file descriptors.
When you have finished reading from or writing to the file, you canterminate the connection byclosing the file. Once you haveclosed a stream or file descriptor, you cannot do any more input oroutput operations on it.
Next:File Position, Up:Input/Output Concepts [Contents][Index]
When you want to do input or output to a file, you have a choice of twobasic mechanisms for representing the connection between your programand the file: file descriptors and streams. File descriptors arerepresented as objects of typeint
, while streams are representedasFILE *
objects.
File descriptors provide a primitive, low-level interface to input andoutput operations. Both file descriptors and streams can represent aconnection to a device (such as a terminal), or a pipe or socket forcommunicating with another process, as well as a normal file. But, ifyou want to do control operations that are specific to a particular kindof device, you must use a file descriptor; there are no facilities touse streams in this way. You must also use file descriptors if yourprogram needs to do input or output in special modes, such asnonblocking (or polled) input (seeFile Status Flags).
Streams provide a higher-level interface, layered on top of theprimitive file descriptor facilities. The stream interface treats allkinds of files pretty much alike—the sole exception being the threestyles of buffering that you can choose (seeStream Buffering).
The main advantage of using the stream interface is that the set offunctions for performing actual input and output operations (as opposedto control operations) on streams is much richer and more powerful thanthe corresponding facilities for file descriptors. The file descriptorinterface provides only simple functions for transferring blocks ofcharacters, but the stream interface also provides powerful formattedinput and output functions (printf
andscanf
) as well asfunctions for character- and line-oriented input and output.
Since streams are implemented in terms of file descriptors, you canextract the file descriptor from a stream and perform low-leveloperations directly on the file descriptor. You can also initially opena connection as a file descriptor and then make a stream associated withthat file descriptor.
In general, you should stick with using streams rather than filedescriptors, unless there is some specific operation you want to do thatcan only be done on a file descriptor. If you are a beginningprogrammer and aren’t sure what functions to use, we suggest that youconcentrate on the formatted input functions (seeFormatted Input)and formatted output functions (seeFormatted Output).
If you are concerned about portability of your programs to systems otherthan GNU, you should also be aware that file descriptors are not asportable as streams. You can expect any system running ISO C tosupport streams, but non-GNU systems may not support file descriptors atall, or may only implement a subset of the GNU functions that operate onfile descriptors. Most of the file descriptor functions in the GNU C Libraryare included in the POSIX.1 standard, however.
Previous:Streams and File Descriptors, Up:Input/Output Concepts [Contents][Index]
One of the attributes of an open file is itsfile position thatkeeps track of where in the file the next character is to be read orwritten. On GNU systems, and all POSIX.1 systems, the file positionis simply an integer representing the number of bytes from the beginningof the file.
The file position is normally set to the beginning of the file when itis opened, and each time a character is read or written, the fileposition is incremented. In other words, access to the file is normallysequential.
Ordinary files permit read or write operations at any position withinthe file. Some other kinds of files may also permit this. Files whichdo permit this are sometimes referred to asrandom-access files.You can change the file position using thefseek
function on astream (seeFile Positioning) or thelseek
function on a filedescriptor (seeInput and Output Primitives). If you try to change the fileposition on a file that doesn’t support random access, you get theESPIPE
error.
Streams and descriptors that are opened forappend access aretreated specially for output: output to such files isalwaysappended sequentially to theend of the file, regardless of thefile position. However, the file position is still used to control where inthe file reading is done.
If you think about it, you’ll realize that several programs can read agiven file at the same time. In order for each program to be able toread the file at its own pace, each program must have its own filepointer, which is not affected by anything the other programs do.
In fact, each opening of a file creates a separate file position.Thus, if you open a file twice even in the same program, you get twostreams or descriptors with independent file positions.
By contrast, if you open a descriptor and then duplicate it to getanother descriptor, these two descriptors share the same file position:changing the file position of one descriptor will affect the other.
Previous:Input/Output Concepts, Up:Input/Output Overview [Contents][Index]
In order to open a connection to a file, or to perform other operationssuch as deleting a file, you need some way to refer to the file. Nearlyall files have names that are strings—even files which are actuallydevices such as tape drives or terminals. These strings are calledfile names. You specify the file name to say which file you wantto open or operate on.
This section describes the conventions for file names and how theoperating system works with them.
Next:File Name Resolution, Up:File Names [Contents][Index]
In order to understand the syntax of file names, you need to understandhow the file system is organized into a hierarchy of directories.
Adirectory is a file that contains information to associate otherfiles with names; these associations are calledlinks ordirectory entries. Sometimes, people speak of “files in adirectory”, but in reality, a directory only contains pointers tofiles, not the files themselves.
The name of a file contained in a directory entry is called afilename component. In general, a file name consists of a sequence of oneor more such components, separated by the slash character (‘/’). Afile name which is just one component names a file with respect to itsdirectory. A file name with multiple components names a directory, andthen a file in that directory, and so on.
Some other documents, such as the POSIX standard, use the termpathname for what we call a file name, and eitherfilenameorpathname component for what this manual calls a file namecomponent. We don’t use this terminology because a “path” issomething completely different (a list of directories to search), and wethink that “pathname” used for something else will confuse users. Wealways use “file name” and “file name component” (or sometimes just“component”, where the context is obvious) in GNU documentation. Somemacros use the POSIX terminology in their names, such asPATH_MAX
. These macros are defined by the POSIX standard, so wecannot change their names.
You can find more detailed information about operations on directoriesinFile System Interface.
Next:File Name Errors, Previous:Directories, Up:File Names [Contents][Index]
A file name consists of file name components separated by slash(‘/’) characters. On the systems that the GNU C Library supports,multiple successive ‘/’ characters are equivalent to a single‘/’ character.
The process of determining what file a file name refers to is calledfile name resolution. This is performed by examining thecomponents that make up a file name in left-to-right order, and locatingeach successive component in the directory named by the previouscomponent. Of course, each of the files that are referenced asdirectories must actually exist, be directories instead of regularfiles, and have the appropriate permissions to be accessible by theprocess; otherwise the file name resolution fails.
If a file name begins with a ‘/’, the first component in the filename is located in theroot directory of the process (usually allprocesses on the system have the same root directory). Such a file nameis called anabsolute file name.
Otherwise, the first component in the file name is located in thecurrent working directory (seeWorking Directory). This kind offile name is called arelative file name.
The file name components. (“dot”) and.. (“dot-dot”)have special meanings. Every directory has entries for these file namecomponents. The file name component. refers to the directoryitself, while the file name component.. refers to itsparent directory (the directory that contains the link for thedirectory in question). As a special case,.. in the rootdirectory refers to the root directory itself, since it has no parent;thus/.. is the same as/.
Here are some examples of file names:
The file nameda, in the root directory.
The file namedb, in the directory nameda in the root directory.
The file nameda, in the current working directory.
This is the same as/a/b.
The file nameda, in the current working directory.
The file nameda, in the parent directory of the current workingdirectory.
A file name that names a directory may optionally end in a ‘/’.You can specify a file name of/ to refer to the root directory,but the empty string is not a meaningful file name. If you want torefer to the current working directory, use a file name of. or./.
Unlike some other operating systems, GNU systems don’t have anybuilt-in support for file types (or extensions) or file versions as partof its file name syntax. Many programs and utilities use conventionsfor file names—for example, files containing C source code usuallyhave names suffixed with ‘.c’—but there is nothing in the filesystem itself that enforces this kind of convention.
Next:Portability of File Names, Previous:File Name Resolution, Up:File Names [Contents][Index]
Functions that accept file name arguments usually detect theseerrno
error conditions relating to the file name syntax ortrouble finding the named file. These errors are referred to throughoutthis manual as theusual file name errors.
EACCES
The process does not have search permission for a directory componentof the file name.
ENAMETOOLONG
This error is used when either the total length of a file name isgreater thanPATH_MAX
, or when an individual file name componenthas a length greater thanNAME_MAX
. SeeLimits on File System Capacity.
On GNU/Hurd systems, there is no imposed limit on overall file namelength, but some file systems may place limits on the length of acomponent.
ENOENT
This error is reported when a file referenced as a directory componentin the file name doesn’t exist, or when a component is a symbolic linkwhose target file does not exist. SeeSymbolic Links.
ENOTDIR
A file that is referenced as a directory component in the file nameexists, but it isn’t a directory.
ELOOP
Too many symbolic links were resolved while trying to look up the filename. The system has an arbitrary limit on the number of symbolic linksthat may be resolved in looking up a single file name, as a primitiveway to detect loops. SeeSymbolic Links.
Previous:File Name Errors, Up:File Names [Contents][Index]
The rules for the syntax of file names discussed inFile Names,are the rules normally used by GNU systems and by other POSIXsystems. However, other operating systems may use other conventions.
There are two reasons why it can be important for you to be aware offile name portability issues:
The ISO C standard says very little about file name syntax, only thatfile names are strings. In addition to varying restrictions on thelength of file names and what characters can validly appear in a filename, different operating systems use different conventions and syntaxfor concepts such as structured directories and file types orextensions. Some concepts such as file versions might be supported insome operating systems and not by others.
The POSIX.1 standard allows implementations to put additionalrestrictions on file name syntax, concerning what characters arepermitted in file names and on the length of file name and file namecomponent strings. However, on GNU systems, any character exceptthe null character is permitted in a file name string, andon GNU/Hurd systems there are no limits on the length of file namestrings.
Next:Low-Level Input/Output, Previous:Input/Output Overview, Up:Main Menu [Contents][Index]
This chapter describes the functions for creating streams and performinginput and output operations on them. As discussed inInput/Output Overview, a stream is a fairly abstract, high-level conceptrepresenting a communications channel to a file, device, or process.
printf
Next:Standard Streams, Up:Input/Output on Streams [Contents][Index]
For historical reasons, the type of the C data structure that representsa stream is calledFILE
rather than “stream”. Since most ofthe library functions deal with objects of typeFILE *
, sometimesthe termfile pointer is also used to mean “stream”. This leadsto unfortunate confusion over terminology in many books on C. Thismanual, however, is careful to use the terms “file” and “stream”only in the technical sense.
TheFILE
type is declared in the header filestdio.h.
This is the data type used to represent stream objects. AFILE
object holds all of the internal state information about the connectionto the associated file, including such things as the file positionindicator and buffering information. Each stream also has error andend-of-file status indicators that can be tested with theferror
andfeof
functions; seeEnd-Of-File and Errors.
FILE
objects are allocated and managed internally by theinput/output library functions. Don’t try to create your own objects oftypeFILE
; let the library do it. Your programs shoulddeal only with pointers to these objects (that is,FILE *
values)rather than the objects themselves.
Next:Opening Streams, Previous:Streams, Up:Input/Output on Streams [Contents][Index]
When themain
function of your program is invoked, it already hasthree predefined streams open and available for use. These representthe “standard” input and output channels that have been establishedfor the process.
These streams are declared in the header filestdio.h.
FILE *
stdin ¶Thestandard input stream, which is the normal source of input for theprogram.
FILE *
stdout ¶Thestandard output stream, which is used for normal output fromthe program.
FILE *
stderr ¶Thestandard error stream, which is used for error messages anddiagnostics issued by the program.
On GNU systems, you can specify what files or processes correspond tothese streams using the pipe and redirection facilities provided by theshell. (The primitives shells use to implement these facilities aredescribed inFile System Interface.) Most other operating systemsprovide similar mechanisms, but the details of how to use them can vary.
In the GNU C Library,stdin
,stdout
, andstderr
arenormal variables which you can set just like any others. For example,to redirect the standard output to a file, you could do:
fclose (stdout);stdout = fopen ("standard-output-file", "w");
Note however, that in other systemsstdin
,stdout
, andstderr
are macros that you cannot assign to in the normal way.But you can usefreopen
to get the effect of closing one andreopening it. SeeOpening Streams.
The three streamsstdin
,stdout
, andstderr
are notunoriented at program start (seeStreams in Internationalized Applications).
Next:Closing Streams, Previous:Standard Streams, Up:Input/Output on Streams [Contents][Index]
Opening a file with thefopen
function creates a new stream andestablishes a connection between the stream and a file. This mayinvolve creating a new file.
Everything described in this section is declared in the header filestdio.h.
FILE *
fopen(const char *filename, const char *opentype)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe mem fd lock| SeePOSIX Safety Concepts.
Thefopen
function opens a stream for I/O to the filefilename, and returns a pointer to the stream.
Theopentype argument is a string that controls how the file isopened and specifies attributes of the resulting stream. It must beginwith one of the following sequences of characters:
Open an existing file for reading only.
Open the file for writing only. If the file already exists, it istruncated to zero length. Otherwise a new file is created.
Open a file for append access; that is, writing at the end of file only.If the file already exists, its initial contents are unchanged andoutput to the stream is appended to the end of the file.Otherwise, a new, empty file is created.
Open an existing file for both reading and writing. The initial contentsof the file are unchanged and the initial file position is at thebeginning of the file.
Open a file for both reading and writing. If the file already exists, itis truncated to zero length. Otherwise, a new file is created.
Open or create file for both reading and appending. If the file exists,its initial contents are unchanged. Otherwise, a new file is created.The initial file position for reading is at the beginning of the file,but output is always appended to the end of the file.
As you can see, ‘+’ requests a stream that can do both input andoutput. When using such a stream, you must callfflush
(seeStream Buffering) or a file positioning function such asfseek
(seeFile Positioning) when switching from readingto writing or vice versa. Otherwise, internal buffers might not beemptied properly.
Additional characters may appear after these to specify flags for thecall. Always put the mode (‘r’, ‘w+’, etc.) first; that isthe only part you are guaranteed will be understood by all systems.
The GNU C Library defines additional characters for use inopentype:
The file is opened with cancellation in the I/O functions disabled.
The underlying file descriptor will be closed if you use any of theexec…
functions (seeExecuting a File). (This isequivalent to having setFD_CLOEXEC
on that descriptor.SeeFile Descriptor Flags.)
The file is opened and accessed usingmmap
. This is onlysupported with files opened for reading.
Insist on creating a new file—if a filefilename alreadyexists,fopen
fails rather than opening it. If you use‘x’ you are guaranteed that you will not clobber an existingfile. This is equivalent to theO_EXCL
option to theopen
function (seeOpening and Closing Files).
The ‘x’ modifier is part of ISO C11, which says the file iscreated with exclusive access; in the GNU C Library this means theequivalent ofO_EXCL
.
The character ‘b’ inopentype has a standard meaning; itrequests a binary stream rather than a text stream. But this makes nodifference in POSIX systems (including GNU systems). If both‘+’ and ‘b’ are specified, they can appear in either order.SeeText and Binary Streams.
If theopentype string contains the sequence,ccs=STRING
thenSTRING is taken as the name of acoded character set andfopen
will mark the stream aswide-oriented with appropriate conversion functions in place to convertfrom and to the character setSTRING. Any other streamis opened initially unoriented and the orientation is decided with thefirst file operation. If the first operation is a wide characteroperation, the stream is not only marked as wide-oriented, also theconversion functions to convert to the coded character set used for thecurrent locale are loaded. This will not change anymore from this pointon even if the locale selected for theLC_CTYPE
category ischanged.
Any other characters inopentype are simply ignored. They may bemeaningful in other systems.
If the open fails,fopen
returns a null pointer.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32 bit machine this function is in factfopen64
since the LFSinterface replaces transparently the old interface.
You can have multiple streams (or file descriptors) pointing to the samefile open at the same time. If you do only input, this worksstraightforwardly, but you must be careful if any output streams areincluded. SeeDangers of Mixing Streams and Descriptors. This is equally truewhether the streams are in one program (not usual) or in severalprograms (which can easily happen). It may be advantageous to use thefile locking facilities to avoid simultaneous access. SeeFile Locks.
FILE *
fopen64(const char *filename, const char *opentype)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe mem fd lock| SeePOSIX Safety Concepts.
This function is similar tofopen
but the stream it returns apointer for is opened usingopen64
. Therefore this stream can beused even on files larger than 2^31 bytes on 32 bit machines.
Please note that the return type is stillFILE *
. There is nospecialFILE
type for the LFS interface.
If the sources are compiled with_FILE_OFFSET_BITS == 64
on a 32bits machine this function is available under the namefopen
and so transparently replaces the old interface.
int
FOPEN_MAX ¶The value of this macro is an integer constant expression thatrepresents the minimum number of streams that the implementationguarantees can be open simultaneously. You might be able to open morethan this many streams, but that is not guaranteed. The value of thisconstant is at least eight, which includes the three standard streamsstdin
,stdout
, andstderr
. In POSIX.1 systems thisvalue is determined by theOPEN_MAX
parameter; seeGeneral Capacity Limits. In BSD and GNU, it is controlled by theRLIMIT_NOFILE
resource limit; seeLimiting Resource Usage.
FILE *
freopen(const char *filename, const char *opentype, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt fd| SeePOSIX Safety Concepts.
This function is like a combination offclose
andfopen
.It first closes the stream referred to bystream, ignoring anyerrors that are detected in the process. (Because errors are ignored,you should not usefreopen
on an output stream if you haveactually done any output using the stream.) Then the file named byfilename is opened with modeopentype as forfopen
,and associated with the same stream objectstream.
If the operation fails, a null pointer is returned; otherwise,freopen
returnsstream. On Linux,freopen
may alsofail and seterrno
toEBUSY
when the kernel structure forthe old file descriptor was not initialized completely beforefreopen
was called. This can only happen in multi-threaded programs, when twothreads race to allocate the same file descriptor number. To avoid thepossibility of this race, do not useclose
to close the underlyingfile descriptor for aFILE
; either usefreopen
while thefile is still open, or useopen
and thendup2
to installthe new file descriptor.
freopen
has traditionally been used to connect a standard streamsuch asstdin
with a file of your own choice. This is useful inprograms in which use of a standard stream for certain purposes ishard-coded. In the GNU C Library, you can simply close the standardstreams and open new ones withfopen
. But other systems lackthis ability, so usingfreopen
is more portable.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32 bit machine this function is in factfreopen64
since the LFSinterface replaces transparently the old interface.
The GNU C Library only supports use offreopen
on streams opened withfopen
orfopen64
and on the original values of thestandard streamsstdin
,stdout
, andstderr
; sucha stream may be reopened multiple times withfreopen
. If it iscalled on another kind of stream (opened with functions such aspopen
,fmemopen
,open_memstream
, andfopencookie
),freopen
fails and returns a null pointer.
FILE *
freopen64(const char *filename, const char *opentype, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt fd| SeePOSIX Safety Concepts.
This function is similar tofreopen
. The only difference is thaton 32 bit machine the stream returned is able to read beyond the2^31 bytes limits imposed by the normal interface. It should benoted that the stream pointed to bystream need not be openedusingfopen64
orfreopen64
since its mode is not importantfor this function.
If the sources are compiled with_FILE_OFFSET_BITS == 64
on a 32bits machine this function is available under the namefreopen
and so transparently replaces the old interface.
In some situations it is useful to know whether a given stream isavailable for reading or writing. This information is normally notavailable and would have to be remembered separately. Solarisintroduced a few functions to get this information from the streamdescriptor and these functions are also available in the GNU C Library.
int
__freadable(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The__freadable
function determines whether the streamstream was opened to allow reading. In this case the return valueis nonzero. For write-only streams the function returns zero.
This function is declared instdio_ext.h.
int
__fwritable(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The__fwritable
function determines whether the streamstream was opened to allow writing. In this case the return valueis nonzero. For read-only streams the function returns zero.
This function is declared instdio_ext.h.
For slightly different kinds of problems there are two more functions.They provide even finer-grained information.
int
__freading(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The__freading
function determines whether the streamstream was last read from or whether it is opened read-only. Inthis case the return value is nonzero, otherwise it is zero.Determining whether a stream opened for reading and writing was lastused for writing allows to draw conclusions about the content about thebuffer, among other things.
This function is declared instdio_ext.h.
int
__fwriting(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The__fwriting
function determines whether the streamstream was last written to or whether it is opened write-only. Inthis case the return value is nonzero, otherwise it is zero.
This function is declared instdio_ext.h.
Next:Streams and Threads, Previous:Opening Streams, Up:Input/Output on Streams [Contents][Index]
When a stream is closed withfclose
, the connection between thestream and the file is canceled. After you have closed a stream, youcannot perform any additional operations on it.
int
fclose(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
This function causesstream to be closed and the connection tothe corresponding file to be broken. Any buffered output is writtenand any buffered input is discarded. Thefclose
function returnsa value of0
if the file was closed successfully, andEOF
if an error was detected.
It is important to check for errors when you callfclose
to closean output stream, because real, everyday errors can be detected at thistime. For example, whenfclose
writes the remaining bufferedoutput, it might get an error because the disk is full. Even if youknow the buffer is empty, errors can still occur when closing a file ifyou are using NFS.
The functionfclose
is declared instdio.h.
To close all streams currently available the GNU C Library providesanother function.
int
fcloseall(void)
¶Preliminary:| MT-Unsafe race:streams| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
This function causes all open streams of the process to be closed andthe connections to corresponding files to be broken. All buffered datais written and any buffered input is discarded. Thefcloseall
function returns a value of0
if all the files were closedsuccessfully, andEOF
if an error was detected.
This function should be used only in special situations, e.g., when anerror occurred and the program must be aborted. Normally each singlestream should be closed separately so that problems with individualstreams can be identified. It is also problematic since the standardstreams (seeStandard Streams) will also be closed.
The functionfcloseall
is declared instdio.h.
If themain
function to your program returns, or if you call theexit
function (seeNormal Termination), all open streams areautomatically closed properly. If your program terminates in any othermanner, such as by calling theabort
function (seeAborting a Program) or from a fatal signal (seeSignal Handling), open streamsmight not be closed properly. Buffered output might not be flushed andfiles may be incomplete. For more information on buffering of streams,seeStream Buffering.
Next:Streams in Internationalized Applications, Previous:Closing Streams, Up:Input/Output on Streams [Contents][Index]
Streams can be used in multi-threaded applications in the same way theyare used in single-threaded applications. But the programmer must beaware of the possible complications. It is important to know aboutthese also if the program one writes never use threads since the designand implementation of many stream functions are heavily influenced by therequirements added by multi-threaded programming.
The POSIX standard requires that by default the stream operations areatomic. I.e., issuing two stream operations for the same stream in twothreads at the same time will cause the operations to be executed as ifthey were issued sequentially. The buffer operations performed whilereading or writing are protected from other uses of the same stream. Todo this each stream has an internal lock object which has to be(implicitly) acquired before any work can be done.
But there are situations where this is not enough and there are alsosituations where this is not wanted. The implicit locking is not enoughif the program requires more than one stream function call to happenatomically. One example would be if an output line a program wants togenerate is created by several function calls. The functions bythemselves would ensure only atomicity of their own operation, but notatomicity over all the function calls. For this it is necessary toperform the stream locking in the application code.
void
flockfile(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe lock| SeePOSIX Safety Concepts.
Theflockfile
function acquires the internal locking objectassociated with the streamstream. This ensures that no otherthread can explicitly throughflockfile
/ftrylockfile
orimplicitly through the call of a stream function lock the stream. Thethread will block until the lock is acquired. An explicit call tofunlockfile
has to be used to release the lock.
int
ftrylockfile(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe lock| SeePOSIX Safety Concepts.
Theftrylockfile
function tries to acquire the internal lockingobject associated with the streamstream just likeflockfile
. But unlikeflockfile
this function does notblock if the lock is not available.ftrylockfile
returns zero ifthe lock was successfully acquired. Otherwise the stream is locked byanother thread.
void
funlockfile(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe lock| SeePOSIX Safety Concepts.
Thefunlockfile
function releases the internal locking object ofthe streamstream. The stream must have been locked before by acall toflockfile
or a successful call offtrylockfile
.The implicit locking performed by the stream operations do not count.Thefunlockfile
function does not return an error status and thebehavior of a call for a stream which is not locked by the currentthread is undefined.
The following example shows how the functions above can be used togenerate an output line atomically even in multi-threaded applications(yes, the same job could be done with onefprintf
call but it issometimes not possible):
FILE *fp;{ ... flockfile (fp); fputs ("This is test number ", fp); fprintf (fp, "%d\n", test); funlockfile (fp)}
Without the explicit locking it would be possible for another thread touse the streamfp after thefputs
call returns and beforefprintf
was called with the result that the number does notfollow the word ‘number’.
From this description it might already be clear that the locking objectsin streams are no simple mutexes. Since locking the same stream twicein the same thread is allowed the locking objects must be equivalent torecursive mutexes. These mutexes keep track of the owner and the numberof times the lock is acquired. The same number offunlockfile
calls by the same threads is necessary to unlock the stream completely.For instance:
voidfoo (FILE *fp){ ftrylockfile (fp); fputs ("in foo\n", fp); /*This is very wrong!!! */ funlockfile (fp);}
It is important here that thefunlockfile
function is only calledif theftrylockfile
function succeeded in locking the stream. Itis therefore always wrong to ignore the result offtrylockfile
.And it makes no sense since otherwise one would useflockfile
.The result of code like that above is that eitherfunlockfile
tries to free a stream that hasn’t been locked by the current thread or itfrees the stream prematurely. The code should look like this:
voidfoo (FILE *fp){ if (ftrylockfile (fp) == 0) { fputs ("in foo\n", fp); funlockfile (fp); }}
Now that we covered why it is necessary to have locking it isnecessary to talk about situations when locking is unwanted and what canbe done. The locking operations (explicit or implicit) don’t come forfree. Even if a lock is not taken the cost is not zero. The operationswhich have to be performed require memory operations that are safe inmulti-processor environments. With the many local caches involved insuch systems this is quite costly. So it is best to avoid the lockingcompletely if it is not needed – because the code in question is neverused in a context where two or more threads may use a stream at a time.This can be determined most of the time for application code; forlibrary code which can be used in many contexts one should default to beconservative and use locking.
There are two basic mechanisms to avoid locking. The first is to usethe_unlocked
variants of the stream operations. The POSIXstandard defines quite a few of those and the GNU C Library adds a fewmore. These variants of the functions behave just like the functionswith the name without the suffix except that they do not lock thestream. Using these functions is very desirable since they arepotentially much faster. This is not only because the lockingoperation itself is avoided. More importantly, functions likeputc
andgetc
are very simple and traditionally (before theintroduction of threads) were implemented as macros which are very fastif the buffer is not empty. With the addition of locking requirementsthese functions are no longer implemented as macros since they wouldexpand to too much code.But these macros are still available with the same functionality under the newnamesputc_unlocked
andgetc_unlocked
. This possibly hugedifference of speed also suggests the use of the_unlocked
functions even if locking is required. The difference is that thelocking then has to be performed in the program:
voidfoo (FILE *fp, char *buf){ flockfile (fp); while (*buf != '/') putc_unlocked (*buf++, fp); funlockfile (fp);}
If in this example theputc
function would be used and theexplicit locking would be missing theputc
function would have toacquire the lock in every call, potentially many times depending on whenthe loop terminates. Writing it the way illustrated above allows theputc_unlocked
macro to be used which means no locking and directmanipulation of the buffer of the stream.
A second way to avoid locking is by using a non-standard function whichwas introduced in Solaris and is available in the GNU C Library as well.
int
__fsetlocking(FILE *stream, inttype)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe lock| AC-Safe | SeePOSIX Safety Concepts.
The__fsetlocking
function can be used to select whether thestream operations will implicitly acquire the locking object of thestreamstream. By default this is done but it can be disabled andreinstated using this function. There are three values defined for thetype parameter.
FSETLOCKING_INTERNAL
¶The streamstream
will from now on use the default internallocking. Every stream operation with exception of the_unlocked
variants will implicitly lock the stream.
FSETLOCKING_BYCALLER
¶After the__fsetlocking
function returns, the user is responsiblefor locking the stream. None of the stream operations will implicitlydo this anymore until the state is set back toFSETLOCKING_INTERNAL
.
FSETLOCKING_QUERY
¶__fsetlocking
only queries the current locking state of thestream. The return value will beFSETLOCKING_INTERNAL
orFSETLOCKING_BYCALLER
depending on the state.
The return value of__fsetlocking
is eitherFSETLOCKING_INTERNAL
orFSETLOCKING_BYCALLER
depending onthe state of the stream before the call.
This function and the values for thetype parameter are declaredinstdio_ext.h.
This function is especially useful when program code has to be usedwhich is written without knowledge about the_unlocked
functions(or if the programmer was too lazy to use them).
Next:Simple Output by Characters or Lines, Previous:Streams and Threads, Up:Input/Output on Streams [Contents][Index]
ISO C90 introduced the new typewchar_t
to allow handlinglarger character sets. What was missing was a possibility to outputstrings ofwchar_t
directly. One had to convert them intomultibyte strings usingmbstowcs
(there was nombsrtowcs
yet) and then use the normal stream functions. While this is doable itis very cumbersome since performing the conversions is not trivial andgreatly increases program complexity and size.
The Unix standard early on (I think in XPG4.2) introduced two additionalformat specifiers for theprintf
andscanf
families offunctions. Printing and reading of single wide characters was madepossible using the%C
specifier and wide character strings can behandled with%S
. These modifiers behave just like%c
and%s
only that they expect the corresponding argument to have thewide character type and that the wide character and string aretransformed into/from multibyte strings before being used.
This was a beginning but it is still not good enough. Not always is itdesirable to useprintf
andscanf
. The other, smaller andfaster functions cannot handle wide characters. Second, it is notpossible to have a format string forprintf
andscanf
consisting of wide characters. The result is that format strings wouldhave to be generated if they have to contain non-basic characters.
In the Amendment 1 to ISO C90 a whole new set of functions wasadded to solve the problem. Most of the stream functions got acounterpart which take a wide character or wide character string insteadof a character or string respectively. The new functions operate on thesame streams (likestdout
). This is different from the model ofthe C++ runtime library where separate streams for wide and normal I/Oare used.
Being able to use the same stream for wide and normal operations comeswith a restriction: a stream can be used either for wide operations orfor normal operations. Once it is decided there is no way back. Only acall tofreopen
orfreopen64
can reset theorientation. The orientation can be decided in three ways:
fread
andfwrite
functions) the stream is marked as notwide oriented.fwide
function can be used to set the orientation either way.It is important to never mix the use of wide and not wide operations ona stream. There are no diagnostics issued. The application behaviorwill simply be strange or the application will simply crash. Thefwide
function can help avoid this.
int
fwide(FILE *stream, intmode)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock| SeePOSIX Safety Concepts.
Thefwide
function can be used to set and query the state of theorientation of the streamstream. If themode parameter hasa positive value the streams get wide oriented, for negative valuesnarrow oriented. It is not possible to overwrite previous orientationswithfwide
. I.e., if the streamstream was alreadyoriented before the call nothing is done.
Ifmode is zero the current orientation state is queried andnothing is changed.
Thefwide
function returns a negative value, zero, or a positivevalue if the stream is narrow, not at all, or wide orientedrespectively.
This function was introduced in Amendment 1 to ISO C90 and isdeclared inwchar.h.
It is generally a good idea to orient a stream as early as possible.This can prevent surprise especially for the standard streamsstdin
,stdout
, andstderr
. If some libraryfunction in some situations uses one of these streams and this useorients the stream in a different way the rest of the applicationexpects it one might end up with hard to reproduce errors. Rememberthat no errors are signal if the streams are used incorrectly. Leavinga stream unoriented after creation is normally only necessary forlibrary functions which create streams which can be used in differentcontexts.
When writing code which uses streams and which can be used in differentcontexts it is important to query the orientation of the stream beforeusing it (unless the rules of the library interface demand a specificorientation). The following little, silly function illustrates this.
voidprint_f (FILE *fp){ if (fwide (fp, 0) > 0) /*Positive return value means wide orientation. */ fputwc (L'f', fp); else fputc ('f', fp);}
Note that in this case the functionprint_f
decides about theorientation of the stream if it was unoriented before (will not happenif the advice above is followed).
The encoding used for thewchar_t
values is unspecified and theuser must not make any assumptions about it. For I/O ofwchar_t
values this means that it is impossible to write these values directlyto the stream. This is not what follows from the ISO C locale modeleither. What happens instead is that the bytes read from or written tothe underlying media are first converted into the internal encodingchosen by the implementation forwchar_t
. The external encodingis determined by theLC_CTYPE
category of the current locale orby the ‘ccs’ part of the mode specification given tofopen
,fopen64
,freopen
, orfreopen64
. How and when theconversion happens is unspecified and it happens invisibly to the user.
Since a stream is created in the unoriented state it has at that pointno conversion associated with it. The conversion which will be used isdetermined by theLC_CTYPE
category selected at the time thestream is oriented. If the locales are changed at the runtime thismight produce surprising results unless one pays attention. This isjust another good reason to orient the stream explicitly as soon aspossible, perhaps with a call tofwide
.
Next:Character Input, Previous:Streams in Internationalized Applications, Up:Input/Output on Streams [Contents][Index]
This section describes functions for performing character- andline-oriented output.
These narrow stream functions are declared in the header filestdio.h and the wide stream functions inwchar.h.
int
fputc(intc, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
Thefputc
function converts the characterc to typeunsigned char
, and writes it to the streamstream.EOF
is returned if a write error occurs; otherwise thecharacterc is returned.
wint_t
fputwc(wchar_twc, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
Thefputwc
function writes the wide characterwc to thestreamstream.WEOF
is returned if a write error occurs;otherwise the characterwc is returned.
int
fputc_unlocked(intc, FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefputc_unlocked
function is equivalent to thefputc
function except that it does not implicitly lock the stream.
wint_t
fputwc_unlocked(wchar_twc, FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefputwc_unlocked
function is equivalent to thefputwc
function except that it does not implicitly lock the stream.
This function is a GNU extension.
int
putc(intc, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
This is just likefputc
, except that it may be implemented asa macro and may evaluate thestream argument more than once.Therefore,stream should never be an expression with side-effects.
wint_t
putwc(wchar_twc, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
This is just likefputwc
, except that it may be implemented asa macro and may evaluate thestream argument more than once.Therefore,stream should never be an expression with side-effects.
int
putc_unlocked(intc, FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theputc_unlocked
function is equivalent to theputc
function except that it does not implicitly lock the stream.Likeputc
, it may be implemented as a macro and may evaluatethestream argument more than once. Therefore,streamshould not be an expression with side-effects.
wint_t
putwc_unlocked(wchar_twc, FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theputwc_unlocked
function is equivalent to theputwc
function except that it does not implicitly lock the stream.
This function is a GNU extension.
int
putchar(intc)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
Theputchar
function is equivalent toputc
withstdout
as the value of thestream argument.
wint_t
putwchar(wchar_twc)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
Theputwchar
function is equivalent toputwc
withstdout
as the value of thestream argument.
int
putchar_unlocked(intc)
¶Preliminary:| MT-Unsafe race:stdout| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theputchar_unlocked
function is equivalent to theputchar
function except that it does not implicitly lock the stream.
wint_t
putwchar_unlocked(wchar_twc)
¶Preliminary:| MT-Unsafe race:stdout| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theputwchar_unlocked
function is equivalent to theputwchar
function except that it does not implicitly lock the stream.
This function is a GNU extension.
int
fputs(const char *s, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
The functionfputs
writes the strings to the streamstream. The terminating null character is not written.This function doesnot add a newline character, either.It outputs only the characters in the string.
This function returnsEOF
if a write error occurs, and otherwisea non-negative value.
For example:
fputs ("Are ", stdout);fputs ("you ", stdout);fputs ("hungry?\n", stdout);
outputs the text ‘Are you hungry?’ followed by a newline.
int
fputws(const wchar_t *ws, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
The functionfputws
writes the wide character stringws tothe streamstream. The terminating null character is not written.This function doesnot add a newline character, either. Itoutputs only the characters in the string.
This function returnsWEOF
if a write error occurs, and otherwisea non-negative value.
int
fputs_unlocked(const char *s, FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefputs_unlocked
function is equivalent to thefputs
function except that it does not implicitly lock the stream.
This function is a GNU extension.
int
fputws_unlocked(const wchar_t *ws, FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefputws_unlocked
function is equivalent to thefputws
function except that it does not implicitly lock the stream.
This function is a GNU extension.
int
puts(const char *s)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Theputs
function writes the strings to the streamstdout
followed by a newline. The terminating null character ofthe string is not written. (Note thatfputs
doesnotwrite a newline as this function does.)
puts
is the most convenient function for printing simplemessages. For example:
puts ("This is a message.");
outputs the text ‘This is a message.’ followed by a newline.
int
putw(intw, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function writes the wordw (that is, anint
) tostream. It is provided for compatibility with SVID, but werecommend you usefwrite
instead (seeBlock Input/Output).
Next:Line-Oriented Input, Previous:Simple Output by Characters or Lines, Up:Input/Output on Streams [Contents][Index]
This section describes functions for performing character-orientedinput. These narrow stream functions are declared in the header filestdio.h and the wide character functions are declared inwchar.h.
These functions return anint
orwint_t
value (for narrowand wide stream functions respectively) that is either a character ofinput, or the special valueEOF
/WEOF
(usually -1). Forthe narrow stream functions it is important to store the result of thesefunctions in a variable of typeint
instead ofchar
, evenwhen you plan to use it only as a character. StoringEOF
in achar
variable truncates its value to the size of a character, sothat it is no longer distinguishable from the valid character‘(char) -1’. So always use anint
for the result ofgetc
and friends, and check forEOF
after the call; onceyou’ve verified that the result is notEOF
, you can be sure thatit will fit in a ‘char’ variable without loss of information.
int
fgetc(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function reads the next character as anunsigned char
fromthe streamstream and returns its value, converted to anint
. If an end-of-file condition or read error occurs,EOF
is returned instead.
wint_t
fgetwc(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function reads the next wide character from the streamstreamand returns its value. If an end-of-file condition or read erroroccurs,WEOF
is returned instead.
int
fgetc_unlocked(FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefgetc_unlocked
function is equivalent to thefgetc
function except that it does not implicitly lock the stream.
wint_t
fgetwc_unlocked(FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefgetwc_unlocked
function is equivalent to thefgetwc
function except that it does not implicitly lock the stream.
This function is a GNU extension.
int
getc(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This is just likefgetc
, except that it may be implemented asa macro and may evaluate thestream argument more than once.Therefore,stream should never be an expression with side-effects.
wint_t
getwc(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This is just likefgetwc
, except that it may be implemented asa macro and may evaluate thestream argument more than once.Therefore,stream should never be an expression with side-effects.
int
getc_unlocked(FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thegetc_unlocked
function is equivalent to thegetc
function except that it does not implicitly lock the stream.Likegetc
, it may be implemented as a macro and may evaluatethestream argument more than once. Therefore,streamshould not be an expression with side-effects.
wint_t
getwc_unlocked(FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thegetwc_unlocked
function is equivalent to thegetwc
function except that it does not implicitly lock the stream.
This function is a GNU extension.
int
getchar(void)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Thegetchar
function is equivalent togetc
withstdin
as the value of thestream argument.
wint_t
getwchar(void)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Thegetwchar
function is equivalent togetwc
withstdin
as the value of thestream argument.
int
getchar_unlocked(void)
¶Preliminary:| MT-Unsafe race:stdin| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thegetchar_unlocked
function is equivalent to thegetchar
function except that it does not implicitly lock the stream.
wint_t
getwchar_unlocked(void)
¶Preliminary:| MT-Unsafe race:stdin| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thegetwchar_unlocked
function is equivalent to thegetwchar
function except that it does not implicitly lock the stream.
This function is a GNU extension.
Here is an example of a function that does input usingfgetc
. Itwould work just as well usinggetc
instead, or usinggetchar ()
instead offgetc (stdin)
. The code wouldalso work the same for the wide character stream functions.
inty_or_n_p (const char *question){ fputs (question, stdout); while (1) { int c, answer; /*Write a space to separate answer from question. */ fputc (' ', stdout); /*Read the first character of the line.This should be the answer character, but might not be. */ c = tolower (fgetc (stdin)); answer = c; /*Discard rest of input line. */ while (c != '\n' && c != EOF)c = fgetc (stdin); /*Obey the answer if it was valid. */ if (answer == 'y')return 1; if (answer == 'n')return 0; /*Answer was invalid: ask for valid answer. */ fputs ("Please answer y or n:", stdout); }}
int
getw(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function reads a word (that is, anint
) fromstream.It’s provided for compatibility with SVID. We recommend you usefread
instead (seeBlock Input/Output). Unlikegetc
,anyint
value could be a valid result.getw
returnsEOF
when it encounters end-of-file or an error, but there is noway to distinguish this from an input word with value -1.
Next:Unreading, Previous:Character Input, Up:Input/Output on Streams [Contents][Index]
Since many programs interpret input on the basis of lines, it isconvenient to have functions to read a line of text from a stream.
Standard C has functions to do this, but they aren’t very safe: nullcharacters and even (forgets
) long lines can confuse them. Sothe GNU C Library provides thegetline
function that makes it easy toread lines reliably.
Thegetdelim
function is a generalized version ofgetline
.It reads a delimited record, defined as everything through the nextoccurrence of a specified delimiter character. These functions wereboth GNU extensions until standardized by POSIX.1-2008.
All these functions are declared instdio.h.
ssize_t
getline(char **restrictlineptr, size_t *restrictn, FILE *restrictstream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap| AC-Unsafe lock corrupt mem| SeePOSIX Safety Concepts.
This function reads an entire line fromstream, storing the text(including the newline and a terminating null character) in a bufferand storing the buffer address in*lineptr
.
Before callinggetline
, you should place in*lineptr
the address of a buffer*n
bytes long, allocated withmalloc
. If this buffer is long enough to hold the line,getline
stores the line in this buffer. Otherwise,getline
makes the buffer bigger usingrealloc
, storing thenew buffer address back in*lineptr
and the increased sizeback in*n
.SeeUnconstrained Allocation.
If you set*lineptr
to a null pointer, and*n
to zero, before the call, thengetline
allocates the initialbuffer for you by callingmalloc
. This buffer remains allocatedeven ifgetline
encounters errors and is unable to read any bytes.
In either case, whengetline
returns,*lineptr
isachar *
which points to the text of the line.
Whengetline
is successful, it returns the number of charactersread (including the newline, but not including the terminating null).This value enables you to distinguish null characters that are part ofthe line from the null character inserted as a terminator.
This function was originally a GNU extension, but was added inPOSIX.1-2008.
If an error occurs or end of file is reached without any bytes read,getline
returns-1
.
ssize_t
getdelim(char **restrictlineptr, size_t *restrictn, intdelimiter, FILE *restrictstream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap| AC-Unsafe lock corrupt mem| SeePOSIX Safety Concepts.
This function is likegetline
except that the character whichtells it to stop reading is not necessarily newline. The argumentdelimiter specifies the delimiter character;getdelim
keepsreading until it sees that character (or end of file).
The text is stored inlineptr, including the delimiter characterand a terminating null. Likegetline
,getdelim
makeslineptr bigger if it isn’t big enough.
This function was originally a GNU extension, but was added inPOSIX.1-2008.
getline
is in fact implemented in terms ofgetdelim
, justlike this:
ssize_tgetline (char **lineptr, size_t *n, FILE *stream){ return getdelim (lineptr, n, '\n', stream);}
char *
fgets(char *s, intcount, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Thefgets
function reads characters from the streamstreamup to and including a newline character and stores them in the strings, adding a null character to mark the end of the string. Youmust supplycount characters worth of space ins, but thenumber of characters read is at mostcount − 1. The extracharacter space is used to hold the null character at the end of thestring.
If the system is already at end of file when you callfgets
, thenthe contents of the arrays are unchanged and a null pointer isreturned. A null pointer is also returned if a read error occurs.Otherwise, the return value is the pointers.
Warning: If the input data has a null character, you can’t tell.So don’t usefgets
unless you know the data cannot contain a null.Don’t use it to read files edited by the user because, if the user insertsa null character, you should either handle it properly or print a clearerror message. We recommend usinggetline
instead offgets
.
wchar_t *
fgetws(wchar_t *ws, intcount, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Thefgetws
function reads wide characters from the streamstream up to and including a newline character and stores them inthe stringws, adding a null wide character to mark the end of thestring. You must supplycount wide characters worth of space inws, but the number of characters read is at mostcount− 1. The extra character space is used to hold the null widecharacter at the end of the string.
If the system is already at end of file when you callfgetws
, thenthe contents of the arrayws are unchanged and a null pointer isreturned. A null pointer is also returned if a read error occurs.Otherwise, the return value is the pointerws.
Warning: If the input data has a null wide character (which arenull bytes in the input stream), you can’t tell. So don’t usefgetws
unless you know the data cannot contain a null. Don’t useit to read files edited by the user because, if the user inserts a nullcharacter, you should either handle it properly or print a clear errormessage.
char *
fgets_unlocked(char *s, intcount, FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefgets_unlocked
function is equivalent to thefgets
function except that it does not implicitly lock the stream.
This function is a GNU extension.
wchar_t *
fgetws_unlocked(wchar_t *ws, intcount, FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefgetws_unlocked
function is equivalent to thefgetws
function except that it does not implicitly lock the stream.
This function is a GNU extension.
char *
gets(char *s)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
The functiongets
reads characters from the streamstdin
up to the next newline character, and stores them in the strings.The newline character is discarded (note that this differs from thebehavior offgets
, which copies the newline character into thestring). Ifgets
encounters a read error or end-of-file, itreturns a null pointer; otherwise it returnss.
Warning: Thegets
function isvery dangerousbecause it provides no protection against overflowing the strings. The GNU C Library includes it for compatibility only. Youshouldalways usefgets
orgetline
instead. Toremind you of this, the linker (if using GNUld
) will issue awarning whenever you usegets
.
Next:Block Input/Output, Previous:Line-Oriented Input, Up:Input/Output on Streams [Contents][Index]
In parser programs it is often useful to examine the next character inthe input stream without removing it from the stream. This is called“peeking ahead” at the input because your program gets a glimpse ofthe input it will read next.
Using stream I/O, you can peek ahead at input by first reading it andthenunreading it (also calledpushing it back on the stream).Unreading a character makes it available to be input again from the stream,by the next call tofgetc
or other input function on that stream.
Next:Usingungetc
To Do Unreading, Up:Unreading [Contents][Index]
Here is a pictorial explanation of unreading. Suppose you have astream reading a file that contains just six characters, the letters‘foobar’. Suppose you have read three characters so far. Thesituation looks like this:
f o o b a r ^
so the next input character will be ‘b’.
If instead of reading ‘b’ you unread the letter ‘o’, you get asituation like this:
f o o b a r | o-- ^
so that the next input characters will be ‘o’ and ‘b’.
If you unread ‘9’ instead of ‘o’, you get this situation:
f o o b a r | 9-- ^
so that the next input characters will be ‘9’ and ‘b’.
Previous:What Unreading Means, Up:Unreading [Contents][Index]
ungetc
To Do Unreading ¶The function to unread a character is calledungetc
, because itreverses the action ofgetc
.
int
ungetc(intc, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Theungetc
function pushes back the characterc onto theinput streamstream. So the next input fromstream willreadc before anything else.
Ifc isEOF
,ungetc
does nothing and just returnsEOF
. This lets you callungetc
with the return value ofgetc
without needing to check for an error fromgetc
.
The character that you push back doesn’t have to be the same as the lastcharacter that was actually read from the stream. In fact, it isn’tnecessary to actually read any characters from the stream beforeunreading them withungetc
! But that is a strange way to write aprogram; usuallyungetc
is used only to unread a character thatwas just read from the same stream. The GNU C Library supports thiseven on files opened in binary mode, but other systems might not.
The GNU C Library supports pushing back multiple characters; subsequentlyreading from the stream retrieves the characters in the reverse orderthat they were pushed.
Pushing back characters doesn’t alter the file; only the internalbuffering for the stream is affected. If a file positioning function(such asfseek
,fseeko
orrewind
; seeFile Positioning) is called, any pending pushed-back characters arediscarded.
Unreading a character on a stream that is at end of file clears theend-of-file indicator for the stream, because it makes the character ofinput available. After you read that character, trying to read againwill encounter end of file.
wint_t
ungetwc(wint_twc, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Theungetwc
function behaves just likeungetc
just that itpushes back a wide character.
Here is an example showing the use ofgetc
andungetc
toskip over whitespace characters. When this function reaches anon-whitespace character, it unreads that character to be seen again onthe next read operation on the stream.
#include <stdio.h>#include <ctype.h>voidskip_whitespace (FILE *stream){ int c; do /*No need to check forEOF
because it is notisspace
, andungetc
ignoresEOF
. */ c = getc (stream); while (isspace (c)); ungetc (c, stream);}
Next:Formatted Output, Previous:Unreading, Up:Input/Output on Streams [Contents][Index]
This section describes how to do input and output operations on blocksof data. You can use these functions to read and write binary data, aswell as to read and write text in fixed-size blocks instead of bycharacters or lines.
Binary files are typically used to read and write blocks of data in thesame format as is used to represent the data in a running program. Inother words, arbitrary blocks of memory—not just character or stringobjects—can be written to a binary file, and meaningfully read inagain by the same program.
Storing data in binary form is often considerably more efficient thanusing the formatted I/O functions. Also, for floating-point numbers,the binary form avoids possible loss of precision in the conversionprocess. On the other hand, binary files can’t be examined or modifiedeasily using many standard file utilities (such as text editors), andare not portable between different implementations of the language, ordifferent kinds of computers.
These functions are declared instdio.h.
size_t
fread(void *data, size_tsize, size_tcount, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function reads up tocount objects of sizesize intothe arraydata, from the streamstream. It returns thenumber of objects actually read, which might be less thancount ifa read error occurs or the end of the file is reached. This functionreturns a value of zero (and doesn’t read anything) if eithersizeorcount is zero.
Iffread
encounters end of file in the middle of an object, itreturns the number of complete objects read, and discards the partialobject. Therefore, the stream remains at the actual end of the file.
size_t
fread_unlocked(void *data, size_tsize, size_tcount, FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefread_unlocked
function is equivalent to thefread
function except that it does not implicitly lock the stream.
This function is a GNU extension.This function may be implemented as a macro and may evaluatestream more than once. Therefore,stream should not be anexpression with side-effects.
size_t
fwrite(const void *data, size_tsize, size_tcount, FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function writes up tocount objects of sizesize fromthe arraydata, to the streamstream. The return value isnormallycount, if the call succeeds. Any other value indicatessome sort of error, such as running out of space.
size_t
fwrite_unlocked(const void *data, size_tsize, size_tcount, FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefwrite_unlocked
function is equivalent to thefwrite
function except that it does not implicitly lock the stream.
This function is a GNU extension.This function may be implemented as a macro and may evaluatestream more than once. Therefore,stream should not be anexpression with side-effects.
Next:Customizingprintf
, Previous:Block Input/Output, Up:Input/Output on Streams [Contents][Index]
The functions described in this section (printf
and relatedfunctions) provide a convenient way to perform formatted output. Youcallprintf
with aformat string ortemplate stringthat specifies how to format the values of the remaining arguments.
Unless your program is a filter that specifically performs line- orcharacter-oriented processing, usingprintf
or one of the otherrelated functions described in this section is usually the easiest andmost concise way to perform output. These functions are especiallyuseful for printing error messages, tables of data, and the like.
Next:Output Conversion Syntax, Up:Formatted Output [Contents][Index]
Theprintf
function can be used to print any number of arguments.The template string argument you supply in a call providesinformation not only about the number of additional arguments, but alsoabout their types and what style should be used for printing them.
Ordinary characters in the template string are simply written to theoutput stream as-is, whileconversion specifications introduced bya ‘%’ character in the template cause subsequent arguments to beformatted and written to the output stream. For example,
int pct = 37;char filename[] = "foo.txt";printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",filename, pct);
produces output like
Processing of `foo.txt' is 37% finished.Please be patient.
This example shows the use of the ‘%d’ conversion to specify thatanint
argument should be printed in decimal notation, the‘%s’ conversion to specify printing of a string argument, andthe ‘%%’ conversion to print a literal ‘%’ character.
There are also conversions for printing an integer argument as anunsigned value in binary, octal, decimal, or hexadecimal radix(‘%b’, ‘%o’, ‘%u’, or ‘%x’, respectively); or as acharacter value (‘%c’).
Floating-point numbers can be printed in normal, fixed-point notationusing the ‘%f’ conversion or in exponential notation using the‘%e’ conversion. The ‘%g’ conversion uses either ‘%e’or ‘%f’ format, depending on what is more appropriate for themagnitude of the particular number.
You can control formatting more precisely by writingmodifiersbetween the ‘%’ and the character that indicates which conversionto apply. These slightly alter the ordinary behavior of the conversion.For example, most conversion specifications permit you to specify aminimum field width and a flag indicating whether you want the resultleft- or right-justified within the field.
The specific flags and modifiers that are permitted and theirinterpretation vary depending on the particular conversion. They’re alldescribed in more detail in the following sections. Don’t worry if thisall seems excessively complicated at first; you can almost always getreasonable free-format output without using any of the modifiers at all.The modifiers are mostly used to make the output look “prettier” intables.
Next:Table of Output Conversions, Previous:Formatted Output Basics, Up:Formatted Output [Contents][Index]
This section provides details about the precise syntax of conversionspecifications that can appear in aprintf
templatestring.
Characters in the template string that are not part of a conversionspecification are printed as-is to the output stream. Multibytecharacter sequences (seeCharacter Set Handling) are permitted in atemplate string.
The conversion specifications in aprintf
template string havethe general form:
%[param-no$]flagswidth[ .precision]typeconversion
or
%[param-no$]flagswidth .*[param-no$]typeconversion
For example, in the conversion specifier ‘%-10.8ld’, the ‘-’is a flag, ‘10’ specifies the field width, the precision is‘8’, the letter ‘l’ is a type modifier, and ‘d’ specifiesthe conversion style. (This particular type specifier says toprint along int
argument in decimal notation, with a minimum of8 digits left-justified in a field at least 10 characters wide.)
In more detail, output conversion specifications consist of aninitial ‘%’ character followed in sequence by:
printf
function are assigned to theformats in the order of appearance in the format string. But in somesituations (such as message translation) this is not desirable and thisextension allows an explicit parameter to be specified.Theparam-no parts of the format must be integers in the range of1 to the maximum number of arguments present to the function call. Someimplementations limit this number to a certain upper bound. The exactlimit can be retrieved by the following constant.
The value ofNL_ARGMAX
is the maximum value allowed for thespecification of a positional parameter in aprintf
call. Theactual value in effect at runtime can be retrieved by usingsysconf
using the_SC_NL_ARGMAX
parameter seeDefinition ofsysconf
.
Some systems have a quite low limit such as9 for System Vsystems. The GNU C Library has no real limit.
If any of the formats has a specification for the parameter position allof them in the format string shall have one. Otherwise the behavior isundefined.
You can also specify a field width of ‘*’. This means that thenext argument in the argument list (before the actual value to beprinted) is used as the field width. The value must be anint
.If the value is negative, this means to set the ‘-’ flag (seebelow) and to use the absolute value as the field width.
You can also specify a precision of ‘*’. This means that the nextargument in the argument list (before the actual value to be printed) isused as the precision. The value must be anint
, and is ignoredif it is negative. If you specify ‘*’ for both the field width andprecision, the field width argument precedes the precision argument.Other C library versions may not recognize this syntax.
int
,but you can specify ‘h’, ‘l’, or ‘L’ for other integertypes.)The exact options that are permitted and how they are interpreted varybetween the different conversion specifiers. See the descriptions of theindividual conversions for information about the particular options thatthey use.
With the ‘-Wformat’ option, the GNU C compiler checks calls toprintf
and related functions. It examines the format string andverifies that the correct number and types of arguments are supplied.There is also a GNU C syntax to tell the compiler that a function youwrite uses aprintf
-style format string.SeeDeclaring Attributes of Functions inUsing GNU CC, for more information.
Next:Integer Conversions, Previous:Output Conversion Syntax, Up:Formatted Output [Contents][Index]
Here is a table summarizing what all the different conversions do:
Print an integer as a signed decimal number. SeeInteger Conversions, for details. ‘%d’ and ‘%i’ are synonymous foroutput, but are different when used withscanf
for input(seeTable of Input Conversions).
Print an integer as an unsigned binary number. ‘%b’ useslower-case ‘b’ with the ‘#’ flag and ‘%B’ usesupper-case. ‘%b’ is an ISO C23 feature; ‘%B’ is anoptional ISO C23 feature. SeeInteger Conversions, fordetails.
Print an integer as an unsigned octal number. SeeInteger Conversions, for details.
Print an integer as an unsigned decimal number. SeeInteger Conversions, for details.
Print an integer as an unsigned hexadecimal number. ‘%x’ useslower-case letters and ‘%X’ uses upper-case. SeeInteger Conversions, for details.
Print a floating-point number in normal (fixed-point) notation.‘%f’ uses lower-case letters and ‘%F’ uses upper-case.SeeFloating-Point Conversions, for details.
Print a floating-point number in exponential notation. ‘%e’ useslower-case letters and ‘%E’ uses upper-case. SeeFloating-Point Conversions, for details.
Print a floating-point number in either normal or exponential notation,whichever is more appropriate for its magnitude. ‘%g’ useslower-case letters and ‘%G’ uses upper-case. SeeFloating-Point Conversions, for details.
Print a floating-point number in a hexadecimal fractional notation withthe exponent to base 2 represented in decimal digits. ‘%a’ useslower-case letters and ‘%A’ uses upper-case. SeeFloating-Point Conversions, for details.
Print a single character. SeeOther Output Conversions.
This is an alias for ‘%lc’ which is supported for compatibilitywith the Unix standard.
Print a string. SeeOther Output Conversions.
This is an alias for ‘%ls’ which is supported for compatibilitywith the Unix standard.
Print the value of a pointer. SeeOther Output Conversions.
Get the number of characters printed so far. SeeOther Output Conversions.Note that this conversion specification never produces any output.
Print the string corresponding to the value oferrno
.(This is a GNU extension.)SeeOther Output Conversions.
Print a literal ‘%’ character. SeeOther Output Conversions.
If the syntax of a conversion specification is invalid, unpredictablethings will happen, so don’t do this. If there aren’t enough functionarguments provided to supply values for all the conversionspecifications in the template string, or if the arguments are not ofthe correct types, the results are unpredictable. If you supply morearguments than conversion specifications, the extra argument values aresimply ignored; this is sometimes useful.
Next:Floating-Point Conversions, Previous:Table of Output Conversions, Up:Formatted Output [Contents][Index]
This section describes the options for the ‘%d’, ‘%i’,‘%b’, ‘%B’, ‘%o’, ‘%u’, ‘%x’, and ‘%X’ conversionspecifications. These conversions print integers in various formats.
The ‘%d’ and ‘%i’ conversion specifications both print anint
argument as a signed decimal number; while ‘%b’, ‘%o’,‘%u’, and ‘%x’ print the argument as an unsigned binary, octal,decimal, or hexadecimal number (respectively). The ‘%X’ conversionspecification is just like ‘%x’ except that it uses the characters‘ABCDEF’ as digits instead of ‘abcdef’. The ‘%B’conversion specification is just like ‘%b’ except that, with the‘#’ flag, the output starts with ‘0B’ instead of ‘0b’.
The following flags are meaningful:
Left-justify the result in the field (instead of the normalright-justification).
For the signed ‘%d’ and ‘%i’ conversions, print aplus sign if the value is positive.
For the signed ‘%d’ and ‘%i’ conversions, if the resultdoesn’t start with a plus or minus sign, prefix it with a spacecharacter instead. Since the ‘+’ flag ensures that the resultincludes a sign, this flag is ignored if you supply both of them.
For the ‘%o’ conversion, this forces the leading digit to be‘0’, as if by increasing the precision. For ‘%x’ or‘%X’, this prefixes a leading ‘0x’ or ‘0X’(respectively) to the result. For ‘%b’ or ‘%B’, thisprefixes a leading ‘0b’ or ‘0B’ (respectively)to the result. This doesn’t do anything useful for the ‘%d’,‘%i’, or ‘%u’ conversions. Using this flag produces outputwhich can be parsed by thestrtoul
function (seeParsing of Integers) andscanf
with the ‘%i’ conversion(seeNumeric Input Conversions).
For the ‘%m’ conversion, print an error constant or decimal errornumber, instead of a (possibly translated) error message.
Separate the digits into groups as specified by the locale specified fortheLC_NUMERIC
category; seeGeneric Numeric Formatting Parameters. This flag is aGNU extension.
Pad the field with zeros instead of spaces. The zeros are placed afterany indication of sign or base. This flag is ignored if the ‘-’flag is also specified, or if a precision is specified.
If a precision is supplied, it specifies the minimum number of digits toappear; leading zeros are produced if necessary. If you don’t specify aprecision, the number is printed with as many digits as it needs. Ifyou convert a value of zero with an explicit precision of zero, then nocharacters at all are produced.
Without a type modifier, the corresponding argument is treated as anint
(for the signed conversions ‘%i’ and ‘%d’) orunsigned int
(for the unsigned conversions ‘%b’,‘%B’, ‘%o’, ‘%u’,‘%x’, and ‘%X’). Recall that sinceprintf
and friendsare variadic, anychar
andshort
arguments areautomatically converted toint
by the default argumentpromotions. For arguments of other integer types, you can use thesemodifiers:
Specifies that the argument is asigned char
orunsignedchar
, as appropriate. Achar
argument is converted to anint
orunsigned int
by the default argument promotionsanyway, but the ‘hh’ modifier says to convert it back to achar
again.
This modifier was introduced in ISO C99.
Specifies that the argument is ashort int
orunsignedshort int
, as appropriate. Ashort
argument is converted to anint
orunsigned int
by the default argument promotionsanyway, but the ‘h’ modifier says to convert it back to ashort
again.
Specifies that the argument is aintmax_t
oruintmax_t
, asappropriate.
This modifier was introduced in ISO C99.
Specifies that the argument is along int
orunsigned longint
, as appropriate. Two ‘l’ characters are like the ‘L’modifier, below.
If used with ‘%c’ or ‘%s’ the corresponding parameter isconsidered as a wide character or wide character string respectively.This use of ‘l’ was introduced in Amendment 1 to ISO C90.
Specifies that the argument is along long int
. (This type isan extension supported by the GNU C compiler. On systems that don’tsupport extra-long integers, this is the same aslong int
.)
The ‘q’ modifier is another name for the same thing, which comesfrom 4.4 BSD; along long int
is sometimes called a “quad”int
.
Specifies that the argument is aptrdiff_t
.
This modifier was introduced in ISO C99.
Specifies that the argument is aintn_t
orint_leastn_t
(which are the same type), for conversionstaking signed integers, oruintn_t
oruint_leastn_t
(which are the same type), for conversionstaking unsigned integers. If the type is narrower thanint
,the promoted argument is converted back to the specified type.
This modifier was introduced in ISO C23.
Specifies that the argument is aint_fastn_t
oruint_fastn_t
, as appropriate. If the type is narrowerthanint
, the promoted argument is converted back to thespecified type.
This modifier was introduced in ISO C23.
Specifies that the argument is asize_t
.
‘z’ was introduced in ISO C99. ‘Z’ is a GNU extensionpredating this addition and should not be used in new code.
Here is an example. Using the template string:
"|%5d|%-5d|%+5d|%+-5d|% 5d|%05d|%5.0d|%5.2d|%d|\n"
to print numbers using the different options for the ‘%d’conversion gives results like:
| 0|0 | +0|+0 | 0|00000| | 00|0|| 1|1 | +1|+1 | 1|00001| 1| 01|1|| -1|-1 | -1|-1 | -1|-0001| -1| -01|-1||100000|100000|+100000|+100000| 100000|100000|100000|100000|100000|
In particular, notice what happens in the last case where the numberis too large to fit in the minimum field width specified.
Here are some more examples showing how unsigned integers print undervarious format options, using the template string:
"|%5u|%5o|%5x|%5X|%#5o|%#5x|%#5X|%#10.8x|\n"
| 0| 0| 0| 0| 0| 0| 0| 00000000|| 1| 1| 1| 1| 01| 0x1| 0X1|0x00000001||100000|303240|186a0|186A0|0303240|0x186a0|0X186A0|0x000186a0|
Next:Other Output Conversions, Previous:Integer Conversions, Up:Formatted Output [Contents][Index]
This section discusses the conversion specifications for floating-pointnumbers: the ‘%f’, ‘%F’, ‘%e’, ‘%E’, ‘%g’, and‘%G’ conversions.
The ‘%f’ and ‘%F’ conversions print their argument in fixed-pointnotation, producing output of the form[-
]ddd.
ddd,where the number of digits following the decimal point is controlledby the precision you specify.
The ‘%e’ conversion prints its argument in exponential notation,producing output of the form[-
]d.
ddde
[+
|-
]dd.Again, the number of digits following the decimal point is controlled bythe precision. The exponent always contains at least two digits. The‘%E’ conversion is similar but the exponent is marked with the letter‘E’ instead of ‘e’.
The ‘%g’ and ‘%G’ conversions print the argument in the styleof ‘%e’ or ‘%E’ (respectively) if the exponent would be lessthan -4 or greater than or equal to the precision; otherwise they usethe ‘%f’ or ‘%F’ style. A precision of0
, is taken as 1.Trailing zeros are removed from the fractional portion of the result anda decimal-point character appears only if it is followed by a digit.
The ‘%a’ and ‘%A’ conversions are meant for representingfloating-point numbers exactly in textual form so that they can beexchanged as texts between different programs and/or machines. Thenumbers are represented in the form[-
]0x
h.
hhhp
[+
|-
]dd.At the left of the decimal-point character exactly one digit is print.This character is only0
if the number is denormalized.Otherwise the value is unspecified; it is implementation dependent how manybits are used. The number of hexadecimal digits on the right side ofthe decimal-point character is equal to the precision. If the precisionis zero it is determined to be large enough to provide an exactrepresentation of the number (or it is large enough to distinguish twoadjacent values if theFLT_RADIX
is not a power of 2,seeFloating Point Parameters). For the ‘%a’ conversionlower-case characters are used to represent the hexadecimal number andthe prefix and exponent sign are printed as0x
andp
respectively. Otherwise upper-case characters are used and0X
andP
are used for the representation of prefix and exponentstring. The exponent to the base of two is printed as a decimal numberusing at least one digit but at most as many digits as necessary torepresent the value exactly.
If the value to be printed represents infinity or a NaN, the output is[-
]inf
ornan
respectively if the conversionspecifier is ‘%a’, ‘%e’, ‘%f’, or ‘%g’ and it is[-
]INF
orNAN
respectively if the conversion is‘%A’, ‘%E’, ‘%F’ or ‘%G’. On some implementations, a NaNmay result in longer output with information about the payload of theNaN; ISO C23 defines a macro_PRINTF_NAN_LEN_MAX
giving themaximum length of such output.
The following flags can be used to modify the behavior:
Left-justify the result in the field. Normally the result isright-justified.
Always include a plus or minus sign in the result.
If the result doesn’t start with a plus or minus sign, prefix it with aspace instead. Since the ‘+’ flag ensures that the result includesa sign, this flag is ignored if you supply both of them.
Specifies that the result should always include a decimal point, evenif no digits follow it. For the ‘%g’ and ‘%G’ conversions,this also forces trailing zeros after the decimal point to be leftin place where they would otherwise be removed.
Separate the digits of the integer part of the result into groups asspecified by the locale specified for theLC_NUMERIC
category;seeGeneric Numeric Formatting Parameters. This flag is a GNU extension.
Pad the field with zeros instead of spaces; the zeros are placedafter any sign. This flag is ignored if the ‘-’ flag is alsospecified.
The precision specifies how many digits follow the decimal-pointcharacter for the ‘%f’, ‘%F’, ‘%e’, and ‘%E’ conversions.For these conversions, the default precision is6
. If the precisionis explicitly0
, this suppresses the decimal point characterentirely. For the ‘%g’ and ‘%G’ conversions, the precisionspecifies how many significant digits to print. Significant digits arethe first digit before the decimal point, and all the digits after it.If the precision is0
or not specified for ‘%g’ or ‘%G’,it is treated like a value of1
. If the value being printedcannot be expressed accurately in the specified number of digits, thevalue is rounded to the nearest number that fits.
Without a type modifier, the floating-point conversions use an argumentof typedouble
. (By the default argument promotions, anyfloat
arguments are automatically converted todouble
.)The following type modifier is supported:
An uppercase ‘L’ specifies that the argument is alongdouble
.
Here are some examples showing how numbers print using the variousfloating-point conversions. All of the numbers were printed usingthis template string:
"|%13.4a|%13.4f|%13.4e|%13.4g|\n"
Here is the output:
| 0x0.0000p+0| 0.0000| 0.0000e+00| 0|| 0x1.0000p-1| 0.5000| 5.0000e-01| 0.5|| 0x1.0000p+0| 1.0000| 1.0000e+00| 1|| -0x1.0000p+0| -1.0000| -1.0000e+00| -1|| 0x1.9000p+6| 100.0000| 1.0000e+02| 100|| 0x1.f400p+9| 1000.0000| 1.0000e+03| 1000|| 0x1.3880p+13| 10000.0000| 1.0000e+04| 1e+04|| 0x1.81c8p+13| 12345.0000| 1.2345e+04| 1.234e+04|| 0x1.86a0p+16| 100000.0000| 1.0000e+05| 1e+05|| 0x1.e240p+16| 123456.0000| 1.2346e+05| 1.235e+05|
Notice how the ‘%g’ conversion drops trailing zeros.
Next:Formatted Output Functions, Previous:Floating-Point Conversions, Up:Formatted Output [Contents][Index]
This section describes miscellaneous conversions forprintf
.
The ‘%c’ conversion prints a single character. In case there is no‘l’ modifier theint
argument is first converted to anunsigned char
. Then, if used in a wide stream function, thecharacter is converted into the corresponding wide character. The‘-’ flag can be used to specify left-justification in the field,but no other flags are defined, and no precision or type modifier can begiven. For example:
printf ("%c%c%c%c%c", 'h', 'e', 'l', 'l', 'o');
prints ‘hello’.
If there is an ‘l’ modifier present the argument is expected to beof typewint_t
. If used in a multibyte function the widecharacter is converted into a multibyte character before being added tothe output. In this case more than one output byte can be produced.
The ‘%s’ conversion prints a string. If no ‘l’ modifier ispresent the corresponding argument must be of typechar *
(orconst char *
). If used in a wide stream function the string isfirst converted to a wide character string. A precision can bespecified to indicate the maximum number of characters to write;otherwise characters in the string up to but not including theterminating null character are written to the output stream. The‘-’ flag can be used to specify left-justification in the field,but no other flags or type modifiers are defined for this conversion.For example:
printf ("%3s%-6s", "no", "where");
prints ‘ nowhere’.
If there is an ‘l’ modifier present, the argument is expected tobe of typewchar_t
(orconst wchar_t *
).
If you accidentally pass a null pointer as the argument for a ‘%s’conversion, the GNU C Library prints it as ‘(null)’. We think thisis more useful than crashing. But it’s not good practice to pass a nullargument intentionally.
The ‘%m’ conversion prints the string corresponding to the errorcode inerrno
. SeeError Messages. Thus:
fprintf (stderr, "can't open `%s': %m\n", filename);
is equivalent to:
fprintf (stderr, "can't open `%s': %s\n", filename, strerror (errno));
The ‘%m’ conversion can be used with the ‘#’ flag to print anerror constant, as provided bystrerrorname_np
. Both ‘%m’and ‘%#m’ are GNU C Library extensions.
The ‘%p’ conversion prints a pointer value. The correspondingargument must be of typevoid *
. In practice, you can use anytype of pointer.
In the GNU C Library, non-null pointers are printed as unsigned integers,as if a ‘%#x’ conversion were used. Null pointers print as‘(nil)’. (Pointers might print differently in other systems.)
For example:
printf ("%p", "testing");
prints ‘0x’ followed by a hexadecimal number—the address of thestring constant"testing"
. It does not print the word‘testing’.
You can supply the ‘-’ flag with the ‘%p’ conversion tospecify left-justification, but no other flags, precision, or typemodifiers are defined.
The ‘%n’ conversion is unlike any of the other output conversions.It uses an argument which must be a pointer to anint
, butinstead of printing anything it stores the number of characters printedso far by this call at that location. The ‘h’ and ‘l’ typemodifiers are permitted to specify that the argument is of typeshort int *
orlong int *
instead ofint *
, but noflags, field width, or precision are permitted.
For example,
int nchar;printf ("%d %s%n\n", 3, "bears", &nchar);
prints:
3 bears
and setsnchar
to7
, because ‘3 bears’ is sevencharacters.
The ‘%%’ conversion prints a literal ‘%’ character. Thisconversion doesn’t use an argument, and no flags, field width,precision, or type modifiers are permitted.
Next:Dynamically Allocating Formatted Output, Previous:Other Output Conversions, Up:Formatted Output [Contents][Index]
This section describes how to callprintf
and related functions.Prototypes for these functions are in the header filestdio.h.Because these functions take a variable number of arguments, youmust declare prototypes for them before using them. Of course,the easiest way to make sure you have all the right prototypes is tojust includestdio.h.
Theprintf
family shares the error codes listed below.Individual functions may report additionalerrno
values if theyfail.
EOVERFLOW
The number of written bytes would have exceededINT_MAX
, and thuscould not be represented in the return typeint
.
ENOMEM
The function could not allocate memory during processing. Long argumentlists and certain floating point conversions may require memoryallocation, as does initialization of an output stream upon first use.
EILSEQ
POSIX specifies this error code should be used if a wide character isencountered that does not have a matching valid character. The GNU C Libraryalways performs transliteration, using a replacement character ifnecessary, so this error condition cannot occur on output. However,the GNU C Library usesEILSEQ
to indicate that an input charactersequence (wide or multi-byte) could not be converted successfully.
int
printf(const char *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
Theprintf
function prints the optional arguments under thecontrol of the template stringtemplate to the streamstdout
. It returns the number of characters printed, or anegative value if there was an output error.
int
wprintf(const wchar_t *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
Thewprintf
function prints the optional arguments under thecontrol of the wide template stringtemplate to the streamstdout
. It returns the number of wide characters printed, or anegative value if there was an output error.
int
fprintf(FILE *stream, const char *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This function is just likeprintf
, except that the output iswritten to the streamstream instead ofstdout
.
int
fwprintf(FILE *stream, const wchar_t *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This function is just likewprintf
, except that the output iswritten to the streamstream instead ofstdout
.
int
sprintf(char *s, const char *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is likeprintf
, except that the output is stored in the characterarrays instead of written to a stream. A null character is writtento mark the end of the string.
Thesprintf
function returns the number of characters stored inthe arrays, not including the terminating null character.
The behavior of this function is undefined if copying takes placebetween objects that overlap—for example, ifs is also givenas an argument to be printed under control of the ‘%s’ conversion.SeeCopying Strings and Arrays.
Warning: Thesprintf
function can bedangerousbecause it can potentially output more characters than can fit in theallocation size of the strings. Remember that the field widthgiven in a conversion specification is only aminimum value.
To avoid this problem, you can usesnprintf
orasprintf
,described below.
int
swprintf(wchar_t *ws, size_tsize, const wchar_t *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is likewprintf
, except that the output is stored in thewide character arrayws instead of written to a stream. A nullwide character is written to mark the end of the string. Thesizeargument specifies the maximum number of characters to produce. Thetrailing null character is counted towards this limit, so you shouldallocate at leastsize wide characters for the stringws.
The return value is the number of characters generated for the giveninput, excluding the trailing null. If not all output fits into theprovided buffer a negative value is returned, anderrno
is set toE2BIG
. (The setting oferrno
is a GNU extension.) Youshould try again with a bigger output string.Note: this isdifferent from howsnprintf
handles this situation.
Note that the corresponding narrow stream function takes fewerparameters.swprintf
in fact corresponds to thesnprintf
function. Since thesprintf
function can be dangerous and shouldbe avoided the ISO C committee refused to make the same mistakeagain and decided to not define a function exactly corresponding tosprintf
.
int
snprintf(char *s, size_tsize, const char *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thesnprintf
function is similar tosprintf
, except thatthesize argument specifies the maximum number of characters toproduce. The trailing null character is counted towards this limit, soyou should allocate at leastsize characters for the strings.Ifsize is zero, nothing, not even the null byte, shall be written ands may be a null pointer.
The return value is the number of characters which would be generatedfor the given input, excluding the trailing null. If this value isgreater than or equal tosize, not all characters from the result havebeen stored ins. If this happens, you should be wary of usingthe truncated result as that could lead to security, encoding, orother bugs in your program (seeTruncating Strings while Copying).Instead, you should try again with a bigger outputstring. Here is an example of doing this:
/*Construct a message describing the value of a variablewhose name isname and whose value isvalue. */char *make_message (char *name, char *value){ /*Guess we need no more than 100 bytes of space. */ size_t size = 100; char *buffer = xmalloc (size);
/*Try to print in the allocated space. */ int buflen = snprintf (buffer, size, "value of %s is %s", name, value); if (! (0 <= buflen && buflen < SIZE_MAX)) fatal ("integer overflow");
if (buflen >= size) { /*Reallocate buffer now that we know how much space is needed. */ size = buflen; size++; buffer = xrealloc (buffer, size); /*Try again. */ snprintf (buffer, size, "value of %s is %s",name, value); } /*The last call worked, return the string. */ return buffer;}
In practice, it is often easier just to useasprintf
, below.
Attention: In versions of the GNU C Library prior to 2.1 thereturn value is the number of characters stored, not including theterminating null; unless there was not enough space ins tostore the result in which case-1
is returned. This waschanged in order to comply with the ISO C99 standard.
int
dprintf(intfd,template, ...)
¶| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function formats its arguments according totemplate andwrites the result to the file descriptorfd, using thewrite
function. It returns the number of bytes written, or anegative value if there was an error. In the error case,errno
is set appropriately. The possibleerrno
values depend on thetype of the file descriptorfd, in addition to the generalprintf
error codes.
The number of calls towrite
is unspecified, and somewrite
calls may have happened even ifdprintf
returns with an error.
Portability Note: POSIX does not require that this function isasync-signal-safe, and the GNU C Library implementation is not. However, someother systems offer this function as an async-signal-safe alternative tofprintf
. SeePOSIX Safety Concepts.
Next:Variable Arguments Output Functions, Previous:Formatted Output Functions, Up:Formatted Output [Contents][Index]
The functions in this section do formatted output and place the resultsin dynamically allocated memory.
int
asprintf(char **ptr, const char *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function is similar tosprintf
, except that it dynamicallyallocates a string (as withmalloc
; seeUnconstrained Allocation) to hold the output, instead of putting the output in abuffer you allocate in advance. Theptr argument should be theaddress of achar *
object, and a successful call toasprintf
stores a pointer to the newly allocated string at thatlocation. Current and future versions of the GNU C Library write a nullpointer to ‘*ptr’ upon failure. To achieve similarbehavior with previous versions, initialize ‘*ptr’ to anull pointer before callingasprintf
. (Specifications forasprintf
only require a valid pointer value in‘*ptr’ ifasprintf
succeeds, but no implementationsare known which overwrite a null pointer with a pointer that cannot befreed on failure.)
The return value is the number of characters allocated for the buffer, orless than zero if an error occurred. Usually this means that the buffercould not be allocated.
Here is how to useasprintf
to get the same result as thesnprintf
example, but more easily:
/*Construct a message describing the value of a variablewhose name isname and whose value isvalue. */char *make_message (char *name, char *value){ char *result; if (asprintf (&result, "value of %s is %s", name, value) < 0) return NULL; return result;}
int
obstack_printf(struct obstack *obstack, const char *template, …)
¶Preliminary:| MT-Safe race:obstack locale| AS-Unsafe corrupt heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
This function is similar toasprintf
, except that it uses theobstackobstack to allocate the space. SeeObstacks.
The characters are written onto the end of the current object.To get at them, you must finish the object withobstack_finish
(seeGrowing Objects).
Next:Parsing a Template String, Previous:Dynamically Allocating Formatted Output, Up:Formatted Output [Contents][Index]
The functionsvprintf
and friends are provided so that you candefine your own variadicprintf
-like functions that make use ofthe same internals as the built-in formatted output functions.
The most natural way to define such functions would be to use a languageconstruct to say, “Callprintf
and pass this template plus allof my arguments after the first five.” But there is no way to do thisin C, and it would be hard to provide a way, since at the C languagelevel there is no way to tell how many arguments your function received.
Since that method is impossible, we provide alternative functions, thevprintf
series, which lets you pass ava_list
to describe“all of my arguments after the first five.”
When it is sufficient to define a macro rather than a real function,the GNU C compiler provides a way to do this much more easily with macros.For example:
#define myprintf(a, b, c, d, e, rest...) \ printf (mytemplate , ## rest)
SeeVariadic Macros inThe C preprocessor, for details.But this is limited to macros, and does not apply to real functions at all.
Before callingvprintf
or the other functions listed in thissection, youmust callva_start
(seeVariadic Functions) to initialize a pointer to the variable arguments. Then youcan callva_arg
to fetch the arguments that you want to handleyourself. This advances the pointer past those arguments.
Once yourva_list
pointer is pointing at the argument of yourchoice, you are ready to callvprintf
. That argument and allsubsequent arguments that were passed to your function are used byvprintf
along with the template that you specified separately.
Portability Note: The value of theva_list
pointer isundetermined after the call tovprintf
, so you must not useva_arg
after you callvprintf
. Instead, you should callva_end
to retire the pointer from service. You can callva_start
again and begin fetching the arguments from the start ofthe variable argument list. (Alternatively, you can useva_copy
to make a copy of theva_list
pointer before callingvfprintf
.) Callingvprintf
does not destroy the argumentlist of your function, merely the particular pointer that you passed toit.
Prototypes for these functions are declared instdio.h.
int
vprintf(const char *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This function is similar toprintf
except that, instead of takinga variable number of arguments directly, it takes an argument listpointerap.
int
vwprintf(const wchar_t *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This function is similar towprintf
except that, instead of takinga variable number of arguments directly, it takes an argument listpointerap.
int
vfprintf(FILE *stream, const char *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This is the equivalent offprintf
with the variable argument listspecified directly as forvprintf
.
int
vfwprintf(FILE *stream, const wchar_t *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This is the equivalent offwprintf
with the variable argument listspecified directly as forvwprintf
.
int
vsprintf(char *s, const char *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is the equivalent ofsprintf
with the variable argument listspecified directly as forvprintf
.
int
vswprintf(wchar_t *ws, size_tsize, const wchar_t *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is the equivalent ofswprintf
with the variable argument listspecified directly as forvwprintf
.
int
vsnprintf(char *s, size_tsize, const char *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is the equivalent ofsnprintf
with the variable argument listspecified directly as forvprintf
.
int
vasprintf(char **ptr, const char *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thevasprintf
function is the equivalent ofasprintf
with thevariable argument list specified directly as forvprintf
.
int
obstack_vprintf(struct obstack *obstack, const char *template, va_listap)
¶Preliminary:| MT-Safe race:obstack locale| AS-Unsafe corrupt heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Theobstack_vprintf
function is the equivalent ofobstack_printf
with the variable argument list specified directlyas forvprintf
.
int
vdprintf(intfd, const char *template, va_listap)
¶| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thevdprintf
is the equivalent ofdprintf
, but processesan argument list.
Here’s an example showing how you might usevfprintf
. This is afunction that prints error messages to the streamstderr
, alongwith a prefix indicating the name of the program(seeError Messages, for a description ofprogram_invocation_short_name
).
#include <stdio.h>#include <stdarg.h>voideprintf (const char *template, ...){ va_list ap; extern char *program_invocation_short_name; fprintf (stderr, "%s: ", program_invocation_short_name); va_start (ap, template); vfprintf (stderr, template, ap); va_end (ap);}
You could calleprintf
like this:
eprintf ("file `%s' does not exist\n", filename);
In GNU C, there is a special construct you can use to let the compilerknow that a function uses aprintf
-style format string. Then itcan check the number and types of arguments in each call to thefunction, and warn you when they do not match the format string.For example, take this declaration ofeprintf
:
void eprintf (const char *template, ...)__attribute__ ((format (printf, 1, 2)));
This tells the compiler thateprintf
uses a format string likeprintf
(as opposed toscanf
; seeFormatted Input);the format string appears as the first argument;and the arguments to satisfy the format begin with the second.SeeDeclaring Attributes of Functions inUsing GNU CC, for more information.
Next:Example of Parsing a Template String, Previous:Variable Arguments Output Functions, Up:Formatted Output [Contents][Index]
You can use the functionparse_printf_format
to obtaininformation about the number and types of arguments that are expected bya given template string. This function permits interpreters thatprovide interfaces toprintf
to avoid passing along invalidarguments from the user’s program, which could cause a crash.
All the symbols described in this section are declared in the headerfileprintf.h.
size_t
parse_printf_format(const char *template, size_tn, int *argtypes)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns information about the number and types ofarguments expected by theprintf
template stringtemplate.The information is stored in the arrayargtypes; each element ofthis array describes one argument. This information is encoded usingthe various ‘PA_’ macros, listed below.
The argumentn specifies the number of elements in the arrayargtypes. This is the maximum number of elements thatparse_printf_format
will try to write.
parse_printf_format
returns the total number of arguments requiredbytemplate. If this number is greater thann, then theinformation returned describes only the firstn arguments. If youwant information about additional arguments, allocate a biggerarray and callparse_printf_format
again.
The argument types are encoded as a combination of a basic type andmodifier flag bits.
int
PA_FLAG_MASK ¶This macro is a bitmask for the type modifier flag bits. You can writethe expression(argtypes[i] & PA_FLAG_MASK)
to extract just theflag bits for an argument, or(argtypes[i] & ~PA_FLAG_MASK)
toextract just the basic type code.
Here are symbolic constants that represent the basic types; they standfor integer values.
PA_INT
¶This specifies that the base type isint
.
PA_CHAR
¶This specifies that the base type isint
, cast tochar
.
PA_STRING
¶This specifies that the base type ischar *
, a null-terminated string.
PA_POINTER
¶This specifies that the base type isvoid *
, an arbitrary pointer.
PA_FLOAT
¶This specifies that the base type isfloat
.
PA_DOUBLE
¶This specifies that the base type isdouble
.
PA_LAST
¶You can define additional base types for your own programs as offsetsfromPA_LAST
. For example, if you have data types ‘foo’and ‘bar’ with their own specializedprintf
conversions,you could define encodings for these types as:
#define PA_FOO PA_LAST#define PA_BAR (PA_LAST + 1)
Here are the flag bits that modify a basic type. They are combined withthe code for the basic type using inclusive-or.
PA_FLAG_PTR
¶If this bit is set, it indicates that the encoded type is a pointer tothe base type, rather than an immediate value.For example, ‘PA_INT|PA_FLAG_PTR’ represents the type ‘int *’.
PA_FLAG_SHORT
¶If this bit is set, it indicates that the base type is modified withshort
. (This corresponds to the ‘h’ type modifier.)
PA_FLAG_LONG
¶If this bit is set, it indicates that the base type is modified withlong
. (This corresponds to the ‘l’ type modifier.)
PA_FLAG_LONG_LONG
¶If this bit is set, it indicates that the base type is modified withlong long
. (This corresponds to the ‘L’ type modifier.)
PA_FLAG_LONG_DOUBLE
¶This is a synonym forPA_FLAG_LONG_LONG
, used by convention witha base type ofPA_DOUBLE
to indicate a type oflong double
.
Previous:Parsing a Template String, Up:Formatted Output [Contents][Index]
Here is an example of decoding argument types for a format string. Weassume this is part of an interpreter which contains arguments of typeNUMBER
,CHAR
,STRING
andSTRUCTURE
(andperhaps others which are not valid here).
/*Test whether thenargs specified objectsin the vectorargs are validfor the format stringformat:if so, return 1.If not, return 0 after printing an error message. */intvalidate_args (char *format, int nargs, OBJECT *args){ int *argtypes; int nwanted; /*Get the information about the arguments.Each conversion specification must be at least two characterslong, so there cannot be more specifications than half thelength of the string. */ argtypes = (int *) alloca (strlen (format) / 2 * sizeof (int)); nwanted = parse_printf_format (format, nargs, argtypes); /*Check the number of arguments. */ if (nwanted > nargs) { error ("too few arguments (at least %d required)", nwanted); return 0; } /*Check the C type wanted for each argumentand see if the object given is suitable. */ for (i = 0; i < nwanted; i++) { int wanted; if (argtypes[i] & PA_FLAG_PTR)wanted = STRUCTURE; elseswitch (argtypes[i] & ~PA_FLAG_MASK) { case PA_INT: case PA_FLOAT: case PA_DOUBLE: wanted = NUMBER; break; case PA_CHAR: wanted = CHAR; break; case PA_STRING: wanted = STRING; break; case PA_POINTER: wanted = STRUCTURE; break; } if (TYPE (args[i]) != wanted){ error ("type mismatch for arg number %d", i); return 0;} } return 1;}
Next:Formatted Input, Previous:Formatted Output, Up:Input/Output on Streams [Contents][Index]
printf
¶The GNU C Library lets you define your own custom conversion specifiersforprintf
template strings, to teachprintf
clever waysto print the important data structures of your program.
The way you do this is by registering the conversion with the functionregister_printf_function
; seeRegistering New Conversions.One of the arguments you pass to this function is a pointer to a handlerfunction that produces the actual output; seeDefining the Output Handler, for information on how to write this function.
You can also install a function that just returns information about thenumber and type of arguments expected by the conversion specifier.SeeParsing a Template String, for information about this.
The facilities of this section are declared in the header fileprintf.h.
Portability Note: The ability to extend the syntax ofprintf
template strings is a GNU extension. ISO standard C hasnothing similar. When using the GNU C compiler or any other compilerthat interprets calls to standard I/O functions according to the rulesof the language standard it is necessary to disable such handling bythe appropriate compiler option. Otherwise the behavior of a programthat relies on the extension is undefined.
printf
Extension Exampleprintf
HandlersNext:Conversion Specifier Options, Up:Customizingprintf
[Contents][Index]
The function to register a new output conversion isregister_printf_function
, declared inprintf.h.
int
register_printf_function(intspec, printf_functionhandler-function, printf_arginfo_functionarginfo-function)
¶Preliminary:| MT-Unsafe const:printfext| AS-Unsafe heap lock| AC-Unsafe mem lock| SeePOSIX Safety Concepts.
This function defines the conversion specifier characterspec.Thus, ifspec is'Y'
, it defines the conversion ‘%Y’.You can redefine the built-in conversions like ‘%s’, but flagcharacters like ‘#’ and type modifiers like ‘l’ can never beused as conversions; callingregister_printf_function
for thosecharacters has no effect. It is advisable not to use lowercase letters,since the ISO C standard warns that additional lowercase letters may bestandardized in future editions of the standard.
Thehandler-function is the function called byprintf
andfriends when this conversion appears in a template string.SeeDefining the Output Handler, for information about how to definea function to pass as this argument. If you specify a null pointer, anyexisting handler function forspec is removed.
Thearginfo-function is the function called byparse_printf_format
when this conversion appears in atemplate string. SeeParsing a Template String, for informationabout this.
Attention: In the GNU C Library versions before 2.0 thearginfo-function function did not need to be installed unlessthe user used theparse_printf_format
function. This has changed.Now a call to any of theprintf
functions will call thisfunction when this format specifier appears in the format string.
The return value is0
on success, and-1
on failure(which occurs ifspec is out of range).
Portability Note: It is possible to redefine the standard outputconversions but doing so is strongly discouraged because it may interferewith the behavior of programs and compiler implementations that assumethe effects of the conversions conform to the relevant language standards.In addition, conforming compilers need not guarantee that the functionregistered for a standard conversion will be called for each suchconversion in every format string in a program.
Next:Defining the Output Handler, Previous:Registering New Conversions, Up:Customizingprintf
[Contents][Index]
If you define a meaning for ‘%A’, what if the template contains‘%+23A’ or ‘%-#A’? To implement a sensible meaning for these,the handler when called needs to be able to get the options specified inthe template.
Both thehandler-function andarginfo-function accept anargument that points to astruct printf_info
, which containsinformation about the options appearing in an instance of the conversionspecifier. This data type is declared in the header fileprintf.h.
This structure is used to pass information about the options appearingin an instance of a conversion specifier in aprintf
templatestring to the handler and arginfo functions for that specifier. Itcontains the following members:
int prec
This is the precision specified. The value is-1
if no precisionwas specified. If the precision was given as ‘*’, theprintf_info
structure passed to the handler function contains theactual value retrieved from the argument list. But the structure passedto the arginfo function contains a value ofINT_MIN
, since theactual value is not known.
int width
This is the minimum field width specified. The value is0
if nowidth was specified. If the field width was given as ‘*’, theprintf_info
structure passed to the handler function contains theactual value retrieved from the argument list. But the structure passedto the arginfo function contains a value ofINT_MIN
, since theactual value is not known.
wchar_t spec
This is the conversion specifier character specified. It’s stored inthe structure so that you can register the same handler function formultiple characters, but still have a way to tell them apart when thehandler function is called.
unsigned int is_long_double
This is a boolean that is true if the ‘L’, ‘ll’, or ‘q’type modifier was specified. For integer conversions, this indicateslong long int
, as opposed tolong double
for floatingpoint conversions.
unsigned int is_char
This is a boolean that is true if the ‘hh’ type modifier was specified.
unsigned int is_short
This is a boolean that is true if the ‘h’ type modifier was specified.
unsigned int is_long
This is a boolean that is true if the ‘l’ type modifier was specified.
unsigned int alt
This is a boolean that is true if the ‘#’ flag was specified.
unsigned int space
This is a boolean that is true if the ‘’ flag was specified.
unsigned int left
This is a boolean that is true if the ‘-’ flag was specified.
unsigned int showsign
This is a boolean that is true if the ‘+’ flag was specified.
unsigned int group
This is a boolean that is true if the ‘'’ flag was specified.
unsigned int extra
This flag has a special meaning depending on the context. It couldbe used freely by the user-defined handlers but when called fromtheprintf
function this variable always contains the value0
.
unsigned int wide
This flag is set if the stream is wide oriented.
wchar_t pad
This is the character to use for padding the output to the minimum fieldwidth. The value is'0'
if the ‘0’ flag was specified, and' '
otherwise.
Next:printf
Extension Example, Previous:Conversion Specifier Options, Up:Customizingprintf
[Contents][Index]
Now let’s look at how to define the handler and arginfo functionswhich are passed as arguments toregister_printf_function
.
Compatibility Note: The interface changed in the GNU C Libraryversion 2.0. Previously the third argument was of typeva_list *
.
You should define your handler functions with a prototype like:
intfunction (FILE *stream, const struct printf_info *info, const void *const *args)
Thestream argument passed to the handler function is the stream towhich it should write output.
Theinfo argument is a pointer to a structure that containsinformation about the various options that were included with theconversion in the template string. You should not modify this structureinside your handler function. SeeConversion Specifier Options, fora description of this data structure.
Theargs is a vector of pointers to the arguments data.The number of arguments was determined by calling the argumentinformation function provided by the user.
Your handler function should return a value just likeprintf
does: it should return the number of characters it has written, or anegative value to indicate an error.
This is the data type that a handler function should have.
If you are going to useparse_printf_format
in yourapplication, you must also define a function to pass as thearginfo-function argument for each new conversion you install withregister_printf_function
.
You have to define these functions with a prototype like:
intfunction (const struct printf_info *info, size_t n, int *argtypes)
The return value from the function should be the number of arguments theconversion expects. The function should also fill in no more thann elements of theargtypes array with information about thetypes of each of these arguments. This information is encoded using thevarious ‘PA_’ macros. (You will notice that this is the samecalling conventionparse_printf_format
itself uses.)
This type is used to describe functions that return information aboutthe number and type of arguments used by a conversion specifier.
Next:Predefinedprintf
Handlers, Previous:Defining the Output Handler, Up:Customizingprintf
[Contents][Index]
printf
Extension Example ¶Here is an example showing how to define aprintf
handler function.This program defines a data structure called aWidget
anddefines the ‘%W’ conversion to print information aboutWidget *
arguments, including the pointer value and the name stored in the datastructure. The ‘%W’ conversion supports the minimum field width andleft-justification options, but ignores everything else.
#include <stdio.h>#include <stdlib.h>#include <printf.h>
typedef struct{ char *name;}Widget;
intprint_widget (FILE *stream, const struct printf_info *info, const void *const *args){ const Widget *w; char *buffer; int len; /*Format the output into a string. */ w = *((const Widget **) (args[0])); len = asprintf (&buffer, "<Widget %p: %s>", w, w->name); if (len == -1) return -1; /*Pad to the minimum field width and print to the stream. */ len = fprintf (stream, "%*s", (info->left ? -info->width : info->width), buffer); /*Clean up and return. */ free (buffer); return len;}intprint_widget_arginfo (const struct printf_info *info, size_t n, int *argtypes){ /*We always take exactly one argument and this is a pointer to the structure.. */ if (n > 0) argtypes[0] = PA_POINTER; return 1;}intmain (void){ /*Make a widget to print. */ Widget mywidget; mywidget.name = "mywidget"; /*Register the print function for widgets. */ register_printf_function ('W', print_widget, print_widget_arginfo); /*Now print the widget. */ printf ("|%W|\n", &mywidget); printf ("|%35W|\n", &mywidget); printf ("|%-35W|\n", &mywidget); return 0;}
The output produced by this program looks like:
|<Widget 0xffeffb7c: mywidget>|| <Widget 0xffeffb7c: mywidget>||<Widget 0xffeffb7c: mywidget> |
Previous:printf
Extension Example, Up:Customizingprintf
[Contents][Index]
printf
Handlers ¶The GNU C Library also contains a concrete and useful application of theprintf
handler extension. There are two functions availablewhich implement a special way to print floating-point numbers.
int
printf_size(FILE *fp, const struct printf_info *info, const void *const *args)
¶Preliminary:| MT-Safe race:fp locale| AS-Unsafe corrupt heap| AC-Unsafe mem corrupt| SeePOSIX Safety Concepts.
Print a given floating point number as for the format%f
exceptthat there is a postfix character indicating the divisor for thenumber to make this less than 1000. There are two possible divisors:powers of 1024 or powers of 1000. Which one is used depends on theformat character specified while registered this handler. If thecharacter is of lower case, 1024 is used. For upper case characters,1000 is used.
The postfix tag corresponds to bytes, kilobytes, megabytes, gigabytes,etc. The full table is:
The default precision is 3, i.e., 1024 is printed with a lower-caseformat character as if it were%.3fk
and will yield1.000k
.
Due to the requirements ofregister_printf_function
we must alsoprovide the function which returns information about the arguments.
int
printf_size_info(const struct printf_info *info, size_tn, int *argtypes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function will return inargtypes the information about theused parameters in the way thevfprintf
implementation expectsit. The format always takes one argument.
To use these functions both functions must be registered with a call like
register_printf_function ('B', printf_size, printf_size_info);
Here we register the functions to print numbers as powers of 1000 sincethe format character'B'
is an upper-case character. If wewould additionally use'b'
in a line like
register_printf_function ('b', printf_size, printf_size_info);
we could also print using a power of 1024. Please note that all that isdifferent in these two lines is the format specifier. Theprintf_size
function knows about the difference between lower and uppercase format specifiers.
The use of'B'
and'b'
is no coincidence. Rather it isthe preferred way to use this functionality since it is available onsome other systems which also use format specifiers.
Next:End-Of-File and Errors, Previous:Customizingprintf
, Up:Input/Output on Streams [Contents][Index]
The functions described in this section (scanf
and relatedfunctions) provide facilities for formatted input analogous to theformatted output facilities. These functions provide a mechanism forreading arbitrary values under the control of aformat string ortemplate string.
Next:Input Conversion Syntax, Up:Formatted Input [Contents][Index]
Calls toscanf
are superficially similar to calls toprintf
in that arbitrary arguments are read under the control ofa template string. While the syntax of the conversion specifications inthe template is very similar to that forprintf
, theinterpretation of the template is oriented more towards free-formatinput and simple pattern matching, rather than fixed-field formatting.For example, mostscanf
conversions skip over any amount of“white space” (including spaces, tabs, and newlines) in the inputfile, and there is no concept of precision for the numeric inputconversions as there is for the corresponding output conversions.Ordinarily, non-whitespace characters in the template are expected tomatch characters in the input stream exactly, but a matching failure isdistinct from an input error on the stream.
Another area of difference betweenscanf
andprintf
isthat you must remember to supply pointers rather than immediate valuesas the optional arguments toscanf
; the values that are read arestored in the objects that the pointers point to. Even experiencedprogrammers tend to forget this occasionally, so if your program isgetting strange errors that seem to be related toscanf
, youmight want to double-check this.
When amatching failure occurs,scanf
returns immediately,leaving the first non-matching character as the next character to beread from the stream. The normal return value fromscanf
is thenumber of values that were assigned, so you can use this to determine ifa matching error happened before all the expected values were read.
Thescanf
function is typically used for things like reading inthe contents of tables. For example, here is a function that usesscanf
to initialize an array ofdouble
:
voidreadarray (double *array, int n){ int i; for (i=0; i<n; i++) if (scanf (" %lf", &(array[i])) != 1) invalid_input_error ();}
The formatted input functions are not used as frequently as theformatted output functions. Partly, this is because it takes some careto use them properly. Another reason is that it is difficult to recoverfrom a matching error.
If you are trying to read input that doesn’t match a single, fixedpattern, you may be better off using a tool such as Flex to generate alexical scanner, or Bison to generate a parser, rather than usingscanf
. For more information about these tools, seeFlex: The Lexical Scanner Generator, andTheBison Reference Manual.
Next:Table of Input Conversions, Previous:Formatted Input Basics, Up:Formatted Input [Contents][Index]
Ascanf
template string is a string that contains ordinarymultibyte characters interspersed with conversion specifications thatstart with ‘%’.
Any whitespace character (as defined by theisspace
function;seeClassification of Characters) in the template causes any numberof whitespace characters in the input stream to be read and discarded.The whitespace characters that are matched need not be exactly the samewhitespace characters that appear in the template string. For example,write ‘ ,’ in the template to recognize a comma with optionalwhitespace before and after.
Other characters in the template string that are not part of conversionspecifications must match characters in the input stream exactly; ifthis is not the case, a matching failure occurs.
The conversion specifications in ascanf
template stringhave the general form:
%flagswidthtypeconversion
In more detail, an input conversion specification consists of an initial‘%’ character followed in sequence by:
scanf
finds a conversionspecification that uses this flag, it reads input as directed by therest of the conversion specification, but it discards this input, doesnot use a pointer argument, and does not increment the count ofsuccessful assignments.long int
rather than a pointer to anint
.The exact options that are permitted and how they are interpreted varybetween the different conversion specifiers. See the descriptions of theindividual conversions for information about the particular options thatthey allow.
With the ‘-Wformat’ option, the GNU C compiler checks calls toscanf
and related functions. It examines the format string andverifies that the correct number and types of arguments are supplied.There is also a GNU C syntax to tell the compiler that a function youwrite uses ascanf
-style format string.SeeDeclaring Attributes of Functions inUsing GNU CC, for more information.
Next:Numeric Input Conversions, Previous:Input Conversion Syntax, Up:Formatted Input [Contents][Index]
Here is a table that summarizes the various conversion specifications:
Matches an optionally signed integer written in decimal. SeeNumeric Input Conversions.
Matches an optionally signed integer in any of the formats that the Clanguage defines for specifying an integer constant. SeeNumeric Input Conversions.
Matches an unsigned integer written in binary radix. This is an ISOC23 feature. SeeNumeric Input Conversions.
Matches an unsigned integer written in octal radix.SeeNumeric Input Conversions.
Matches an unsigned integer written in decimal radix.SeeNumeric Input Conversions.
Matches an unsigned integer written in hexadecimal radix.SeeNumeric Input Conversions.
Matches an optionally signed floating-point number. SeeNumeric Input Conversions.
Matches a string containing only non-whitespace characters.SeeString Input Conversions. The presence of the ‘l’ modifierdetermines whether the output is stored as a wide character string or amultibyte string. If ‘%s’ is used in a wide character function thestring is converted as with multiple calls towcrtomb
into amultibyte string. This means that the buffer must provide room forMB_CUR_MAX
bytes for each wide character read. In case‘%ls’ is used in a multibyte function the result is converted intowide characters as with multiple calls ofmbrtowc
before beingstored in the user provided buffer.
This is an alias for ‘%ls’ which is supported for compatibilitywith the Unix standard.
Matches a string of characters that belong to a specified set.SeeString Input Conversions. The presence of the ‘l’ modifierdetermines whether the output is stored as a wide character string or amultibyte string. If ‘%[’ is used in a wide character function thestring is converted as with multiple calls towcrtomb
into amultibyte string. This means that the buffer must provide room forMB_CUR_MAX
bytes for each wide character read. In case‘%l[’ is used in a multibyte function the result is converted intowide characters as with multiple calls ofmbrtowc
before beingstored in the user provided buffer.
Matches a string of one or more characters; the number of charactersread is controlled by the maximum field width given for the conversion.SeeString Input Conversions.
If ‘%c’ is used in a wide stream function the read value isconverted from a wide character to the corresponding multibyte characterbefore storing it. Note that this conversion can produce more than onebyte of output and therefore the provided buffer must be large enough for uptoMB_CUR_MAX
bytes for each character. If ‘%lc’ is used ina multibyte function the input is treated as a multibyte sequence (andnot bytes) and the result is converted as with calls tombrtowc
.
This is an alias for ‘%lc’ which is supported for compatibilitywith the Unix standard.
Matches a pointer value in the same implementation-defined format usedby the ‘%p’ output conversion forprintf
. SeeOther Input Conversions.
This conversion doesn’t read any characters; it records the number ofcharacters read so far by this call. SeeOther Input Conversions.
This matches a literal ‘%’ character in the input stream. Nocorresponding argument is used. SeeOther Input Conversions.
If the syntax of a conversion specification is invalid, the behavior isundefined. If there aren’t enough function arguments provided to supplyaddresses for all the conversion specifications in the template stringsthat perform assignments, or if the arguments are not of the correcttypes, the behavior is also undefined. On the other hand, extraarguments are simply ignored.
Next:String Input Conversions, Previous:Table of Input Conversions, Up:Formatted Input [Contents][Index]
This section describes thescanf
conversions for reading numericvalues.
The ‘%d’ conversion matches an optionally signed integer in decimalradix. The syntax that is recognized is the same as that for thestrtol
function (seeParsing of Integers) with the value10
for thebase argument.
The ‘%i’ conversion matches an optionally signed integer in any ofthe formats that the C language defines for specifying an integerconstant. The syntax that is recognized is the same as that for thestrtol
function (seeParsing of Integers) with the value0
for thebase argument. (You can print integers in thissyntax withprintf
by using the ‘#’ flag character with the‘%x’, ‘%o’, ‘%b’, or ‘%d’ conversion.SeeInteger Conversions.)
For example, any of the strings ‘10’, ‘0xa’, or ‘012’could be read in as integers under the ‘%i’ conversion. Each ofthese specifies a number with decimal value10
.
The ‘%b’, ‘%o’, ‘%u’, and ‘%x’ conversions match unsignedintegers in binary, octal, decimal, and hexadecimal radices, respectively. Thesyntax that is recognized is the same as that for thestrtoul
function (seeParsing of Integers) with the appropriate value(2
,8
,10
, or16
) for thebaseargument. The ‘%b’ conversion accepts an optional leading‘0b’ or ‘0B’ in all standards modes.
The ‘%X’ conversion is identical to the ‘%x’ conversion. Theyboth permit either uppercase or lowercase letters to be used as digits.
The default type of the corresponding argument for the%d
,%i
, and%n
conversions isint *
, andunsigned int *
for the other integer conversions. You can usethe following type modifiers to specify other sizes of integer:
Specifies that the argument is asigned char *
orunsignedchar *
.
This modifier was introduced in ISO C99.
Specifies that the argument is ashort int *
orunsignedshort int *
.
Specifies that the argument is aintmax_t *
oruintmax_t *
.
This modifier was introduced in ISO C99.
Specifies that the argument is along int *
orunsignedlong int *
. Two ‘l’ characters is like the ‘L’ modifier, below.
If used with ‘%c’ or ‘%s’ the corresponding parameter isconsidered as a pointer to a wide character or wide character stringrespectively. This use of ‘l’ was introduced in Amendment 1 toISO C90.
Specifies that the argument is along long int *
orunsigned long long int *
. (Thelong long
type is an extension supported by theGNU C compiler. For systems that don’t provide extra-long integers, thisis the same aslong int
.)
The ‘q’ modifier is another name for the same thing, which comesfrom 4.4 BSD; along long int
is sometimes called a “quad”int
.
Specifies that the argument is aptrdiff_t *
.
This modifier was introduced in ISO C99.
Specifies that the argument is anintn_t *
orint_leastn_t *
(which are the same type), oruintn_t *
oruint_leastn_t *
(which are thesame type).
This modifier was introduced in ISO C23.
Specifies that the argument is anint_fastn_t *
oruint_fastn_t *
.
This modifier was introduced in ISO C23.
Specifies that the argument is asize_t *
.
This modifier was introduced in ISO C99.
All of the ‘%e’, ‘%f’, ‘%g’, ‘%E’, ‘%F’ and ‘%G’input conversions are interchangeable. They all match an optionallysigned floating point number, in the same syntax as for thestrtod
function (seeParsing of Floats).
For the floating-point input conversions, the default argument type isfloat *
. (This is different from the corresponding outputconversions, where the default type isdouble
; remember thatfloat
arguments toprintf
are converted todouble
by the default argument promotions, butfloat *
arguments arenot promoted todouble *
.) You can specify other sizes of floatusing these type modifiers:
Specifies that the argument is of typedouble *
.
Specifies that the argument is of typelong double *
.
For all the above number parsing formats there is an additional optionalflag ‘'’. When this flag is given thescanf
functionexpects the number represented in the input string to be formattedaccording to the grouping rules of the currently selected locale(seeGeneric Numeric Formatting Parameters).
If the"C"
or"POSIX"
locale is selected there is nodifference. But for a locale which specifies values for the appropriatefields in the locale the input must have the correct form in the input.Otherwise the longest prefix with a correct form is processed.
Next:Dynamically Allocating String Conversions, Previous:Numeric Input Conversions, Up:Formatted Input [Contents][Index]
This section describes thescanf
input conversions for readingstring and character values: ‘%s’, ‘%S’, ‘%[’, ‘%c’,and ‘%C’.
You have two options for how to receive the input from theseconversions:
char *
orwchar_t *
(thelatter if the ‘l’ modifier is present).Warning: To make a robust program, you must make sure that theinput (plus its terminating null) cannot possibly exceed the size of thebuffer you provide. In general, the only way to do this is to specify amaximum field width one less than the buffer size.If youprovide the buffer, always specify a maximum field width to preventoverflow.
scanf
to allocate a big enough buffer, by specifying the‘a’ flag character. This is a GNU extension. You should providean argument of typechar **
for the buffer address to be storedin. SeeDynamically Allocating String Conversions.The ‘%c’ conversion is the simplest: it matches a fixed number ofcharacters, always. The maximum field width says how many characters toread; if you don’t specify the maximum, the default is 1. Thisconversion doesn’t append a null character to the end of the text itreads. It also does not skip over initial whitespace characters. Itreads precisely the nextn characters, and fails if it cannot getthat many. Since there is always a maximum field width with ‘%c’(whether specified, or 1 by default), you can always prevent overflow bymaking the buffer long enough.
If the format is ‘%lc’ or ‘%C’ the function stores widecharacters which are converted using the conversion determined at thetime the stream was opened from the external byte stream. The number ofbytes read from the medium is limited byMB_CUR_LEN *n
butat mostn wide characters get stored in the output string.
The ‘%s’ conversion matches a string of non-whitespace characters.It skips and discards initial whitespace, but stops when it encountersmore whitespace after having read something. It stores a null characterat the end of the text that it reads.
For example, reading the input:
hello, world
with the conversion ‘%10c’ produces" hello, wo"
, butreading the same input with the conversion ‘%10s’ produces"hello,"
.
Warning: If you do not specify a field width for ‘%s’,then the number of characters read is limited only by where the nextwhitespace character appears. This almost certainly means that invalidinput can make your program crash—which is a bug.
The ‘%ls’ and ‘%S’ format are handled just like ‘%s’except that the external byte sequence is converted using the conversionassociated with the stream to wide characters with their own encoding.A width or precision specified with the format do not directly determinehow many bytes are read from the stream since they measure widecharacters. But an upper limit can be computed by multiplying the valueof the width or precision byMB_CUR_MAX
.
To read in characters that belong to an arbitrary set of your choice,use the ‘%[’ conversion. You specify the set between the ‘[’character and a following ‘]’ character, using the same syntax usedin regular expressions for explicit sets of characters. As special cases:
The ‘%[’ conversion does not skip over initial whitespacecharacters.
Note that thecharacter class syntax available in character setsthat appear inside regular expressions (such as ‘[:alpha:]’) isnot available in the ‘%[’ conversion.
Here are some examples of ‘%[’ conversions and what they mean:
Matches a string of up to 25 digits.
Matches a string of up to 25 square brackets.
Matches a string up to 25 characters long that doesn’t contain any ofthe standard whitespace characters. This is slightly different from‘%s’, because if the input begins with a whitespace character,‘%[’ reports a matching failure while ‘%s’ simply discards theinitial whitespace.
Matches up to 25 lowercase characters.
As for ‘%c’ and ‘%s’ the ‘%[’ format is also modified toproduce wide characters if the ‘l’ modifier is present. All whatis said about ‘%ls’ above is true for ‘%l[’.
One more reminder: the ‘%s’ and ‘%[’ conversions aredangerous if you don’t specify a maximum width or use the‘a’ flag, because input too long would overflow whatever buffer youhave provided for it. No matter how long your buffer is, a user couldsupply input that is longer. A well-written program reports invalidinput with a comprehensible error message, not with a crash.
Next:Other Input Conversions, Previous:String Input Conversions, Up:Formatted Input [Contents][Index]
A GNU extension to formatted input lets you safely read a string with nomaximum size. Using this feature, you don’t supply a buffer; instead,scanf
allocates a buffer big enough to hold the data and givesyou its address. To use this feature, write ‘a’ as a flagcharacter, as in ‘%as’ or ‘%a[0-9a-z]’.
The pointer argument you supply for where to store the input should havetypechar **
. Thescanf
function allocates a buffer andstores its address in the word that the argument points to. You shouldfree the buffer withfree
when you no longer need it.
Here is an example of using the ‘a’ flag with the ‘%[…]’conversion specification to read a “variable assignment” of the form‘variable =value’.
{ char *variable, *value; if (2 > scanf ("%a[a-zA-Z0-9] = %a[^\n]\n", &variable, &value)) { invalid_input_error (); return 0; } ...}
Next:Formatted Input Functions, Previous:Dynamically Allocating String Conversions, Up:Formatted Input [Contents][Index]
This section describes the miscellaneous input conversions.
The ‘%p’ conversion is used to read a pointer value. It recognizesthe same syntax used by the ‘%p’ output conversion forprintf
(seeOther Output Conversions); that is, a hexadecimalnumber just as the ‘%x’ conversion accepts. The correspondingargument should be of typevoid **
; that is, the address of aplace to store a pointer.
The resulting pointer value is not guaranteed to be valid if it was notoriginally written during the same program execution that reads it in.
The ‘%n’ conversion produces the number of characters read so farby this call. The corresponding argument should be of typeint *
,unless a type modifier is in effect (seeNumeric Input Conversions).This conversion works in the same way as the ‘%n’ conversion forprintf
; seeOther Output Conversions, for an example.
The ‘%n’ conversion is the only mechanism for determining thesuccess of literal matches or conversions with suppressed assignments.If the ‘%n’ follows the locus of a matching failure, then no valueis stored for it sincescanf
returns before processing the‘%n’. If you store-1
in that argument slot before callingscanf
, the presence of-1
afterscanf
indicates anerror occurred before the ‘%n’ was reached.
Finally, the ‘%%’ conversion matches a literal ‘%’ characterin the input stream, without using an argument. This conversion doesnot permit any flags, field width, or type modifier to be specified.
Next:Variable Arguments Input Functions, Previous:Other Input Conversions, Up:Formatted Input [Contents][Index]
Here are the descriptions of the functions for performing formattedinput.Prototypes for these functions are in the header filestdio.h.
int
scanf(const char *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
Thescanf
function reads formatted input from the streamstdin
under the control of the template stringtemplate.The optional arguments are pointers to the places which receive theresulting values.
The return value is normally the number of successful assignments. Ifan end-of-file condition is detected before any matches are performed,including matches against whitespace and literal characters in thetemplate, thenEOF
is returned.
int
wscanf(const wchar_t *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
Thewscanf
function reads formatted input from the streamstdin
under the control of the template stringtemplate.The optional arguments are pointers to the places which receive theresulting values.
The return value is normally the number of successful assignments. Ifan end-of-file condition is detected before any matches are performed,including matches against whitespace and literal characters in thetemplate, thenWEOF
is returned.
int
fscanf(FILE *stream, const char *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This function is just likescanf
, except that the input is readfrom the streamstream instead ofstdin
.
int
fwscanf(FILE *stream, const wchar_t *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This function is just likewscanf
, except that the input is readfrom the streamstream instead ofstdin
.
int
sscanf(const char *s, const char *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is likescanf
, except that the characters are taken from thenull-terminated strings instead of from a stream. Reaching theend of the string is treated as an end-of-file condition.
The behavior of this function is undefined if copying takes placebetween objects that overlap—for example, ifs is also givenas an argument to receive a string read under control of the ‘%s’,‘%S’, or ‘%[’ conversion.
int
swscanf(const wchar_t *ws, const wchar_t *template, …)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is likewscanf
, except that the characters are taken from thenull-terminated stringws instead of from a stream. Reaching theend of the string is treated as an end-of-file condition.
The behavior of this function is undefined if copying takes placebetween objects that overlap—for example, ifws is also given asan argument to receive a string read under control of the ‘%s’,‘%S’, or ‘%[’ conversion.
Previous:Formatted Input Functions, Up:Formatted Input [Contents][Index]
The functionsvscanf
and friends are provided so that you candefine your own variadicscanf
-like functions that make use ofthe same internals as the built-in formatted output functions.These functions are analogous to thevprintf
series of outputfunctions. SeeVariable Arguments Output Functions, for importantinformation on how to use them.
Portability Note: The functions listed in this section wereintroduced in ISO C99 and were before available as GNU extensions.
int
vscanf(const char *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This function is similar toscanf
, but instead of takinga variable number of arguments directly, it takes an argument listpointerap of typeva_list
(seeVariadic Functions).
int
vwscanf(const wchar_t *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This function is similar towscanf
, but instead of takinga variable number of arguments directly, it takes an argument listpointerap of typeva_list
(seeVariadic Functions).
int
vfscanf(FILE *stream, const char *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This is the equivalent offscanf
with the variable argument listspecified directly as forvscanf
.
int
vfwscanf(FILE *stream, const wchar_t *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
This is the equivalent offwscanf
with the variable argument listspecified directly as forvwscanf
.
int
vsscanf(const char *s, const char *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is the equivalent ofsscanf
with the variable argument listspecified directly as forvscanf
.
int
vswscanf(const wchar_t *s, const wchar_t *template, va_listap)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is the equivalent ofswscanf
with the variable argument listspecified directly as forvwscanf
.
In GNU C, there is a special construct you can use to let the compilerknow that a function uses ascanf
-style format string. Then itcan check the number and types of arguments in each call to thefunction, and warn you when they do not match the format string.For details, seeDeclaring Attributes of Functions inUsing GNU CC.
Next:Recovering from errors, Previous:Formatted Input, Up:Input/Output on Streams [Contents][Index]
Many of the functions described in this chapter return the value of themacroEOF
to indicate unsuccessful completion of the operation.SinceEOF
is used to report both end of file and random errors,it’s often better to use thefeof
function to check explicitlyfor end of file andferror
to check for errors. These functionscheck indicators that are part of the internal state of the streamobject, indicators set if the appropriate condition was detected by aprevious I/O operation on that stream.
The end of file and error conditions are mutually exclusive. For anarrow oriented stream, end of file is not considered an error. Forwide oriented streams, reaching the end of the underlying file canresult an error if the underlying file ends with an incomplete multibytesequence. This is reported as an error byferror
, and not as anend of file byfeof
. End of file on wide oriented streams thatdoes not fall into the middle of a multibyte sequence is reported viafeof
.
int
EOF ¶This macro is an integer value that is returned by a number of narrowstream functions to indicate an end-of-file condition, or some othererror situation. With the GNU C Library,EOF
is-1
. Inother libraries, its value may be some other negative number.
This symbol is declared instdio.h.
int
WEOF ¶This macro is an integer value that is returned by a number of widestream functions to indicate an end-of-file condition, or some othererror situation. With the GNU C Library,WEOF
is-1
. Inother libraries, its value may be some other negative number.
This symbol is declared inwchar.h.
int
feof(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe lock| SeePOSIX Safety Concepts.
Thefeof
function returns nonzero if and only if the end-of-fileindicator for the streamstream is set.
This symbol is declared instdio.h.
int
feof_unlocked(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefeof_unlocked
function is equivalent to thefeof
function except that it does not implicitly lock the stream.
This function is a GNU extension.
This symbol is declared instdio.h.
int
ferror(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe lock| SeePOSIX Safety Concepts.
Theferror
function returns nonzero if and only if the errorindicator for the streamstream is set, indicating that an errorhas occurred on a previous operation on the stream.
This symbol is declared instdio.h.
int
ferror_unlocked(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theferror_unlocked
function is equivalent to theferror
function except that it does not implicitly lock the stream.
This function is a GNU extension.
This symbol is declared instdio.h.
In addition to setting the error indicator associated with the stream,the functions that operate on streams also seterrno
in the sameway as the corresponding low-level functions that operate on filedescriptors. For example, all of the functions that perform output to astream—such asfputc
,printf
, andfflush
—areimplemented in terms ofwrite
, and all of theerrno
errorconditions defined forwrite
are meaningful for these functions.For more information about the descriptor-level I/O functions, seeLow-Level Input/Output.
Next:Text and Binary Streams, Previous:End-Of-File and Errors, Up:Input/Output on Streams [Contents][Index]
You may explicitly clear the error and EOF flags with theclearerr
function.
void
clearerr(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe lock| SeePOSIX Safety Concepts.
This function clears the end-of-file and error indicators for thestreamstream.
The file positioning functions (seeFile Positioning) also clear theend-of-file indicator for the stream.
void
clearerr_unlocked(FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theclearerr_unlocked
function is equivalent to theclearerr
function except that it does not implicitly lock the stream.
This function is a GNU extension.
Note that it isnot correct to just clear the error flag and retrya failed stream operation. After a failed write, any number ofcharacters since the last buffer flush may have been committed to thefile, while some buffered data may have been discarded. Merely retryingcan thus cause lost or repeated data.
A failed read may leave the file pointer in an inappropriate position fora second try. In both cases, you should seek to a known position beforeretrying.
Most errors that can happen are not recoverable — a second try willalways fail again in the same way. So usually it is best to give up andreport the error to the user, rather than install complicated recoverylogic.
One important exception isEINTR
(seePrimitives Interrupted by Signals).Many stream I/O implementations will treat it as an ordinary error, whichcan be quite inconvenient. You can avoid this hassle by installing allsignals with theSA_RESTART
flag.
For similar reasons, setting nonblocking I/O on a stream’s filedescriptor is not usually advisable.
Next:File Positioning, Previous:Recovering from errors, Up:Input/Output on Streams [Contents][Index]
GNU systems and other POSIX-compatible operating systems organize allfiles as uniform sequences of characters. However, some other systemsmake a distinction between files containing text and files containingbinary data, and the input and output facilities of ISO C provide forthis distinction. This section tells you how to write programs portableto such systems.
When you open a stream, you can specify either atext stream or abinary stream. You indicate that you want a binary stream byspecifying the ‘b’ modifier in theopentype argument tofopen
; seeOpening Streams. Without thisoption,fopen
opens the file as a text stream.
Text and binary streams differ in several ways:
'\n'
) characters, while a binary stream issimply a long series of characters. A text stream might on some systemsfail to handle lines more than 254 characters long (including theterminating newline character).fflush
, for example) may produce a logical lineterminator even if no'\n'
character was written by the program.'\n'
characters that arenot treated as line terminators by the system. C programs cannot readsuch text files reliably using thestdio.h facilities.Since a binary stream is always more capable and more predictable than atext stream, you might wonder what purpose text streams serve. Why notsimply always use binary streams? The answer is that on these operatingsystems, text and binary streams use different file formats, and theonly way to read or write “an ordinary file of text” that can workwith other text-oriented programs is through a text stream.
In the GNU C Library, and on all POSIX systems, there is no differencebetween text streams and binary streams. When you open a stream, youget the same kind of stream regardless of whether you ask for binary.This stream can handle any file content, and has none of therestrictions that text streams sometimes have.
Next:Portable File-Position Functions, Previous:Text and Binary Streams, Up:Input/Output on Streams [Contents][Index]
Thefile position of a stream describes where in the file thestream is currently reading or writing. I/O on the stream advances thefile position through the file. On GNU systems, the file position isrepresented as an integer, which counts the number of bytes from thebeginning of the file. SeeFile Position.
During I/O to an ordinary disk file, you can change the file positionwhenever you wish, so as to read or write any portion of the file. Someother kinds of files may also permit this. Files which support changingthe file position are sometimes referred to asrandom-accessfiles.
You can use the functions in this section to examine or modify the fileposition indicator associated with a stream. The symbols listed beloware declared in the header filestdio.h.
long int
ftell(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function returns the current file position of the streamstream.
This function can fail if the stream doesn’t support file positioning,or if the file position can’t be represented in along int
, andpossibly for other reasons as well. If a failure occurs, a value of-1
is returned.
off_t
ftello(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Theftello
function is similar toftell
, except that itreturns a value of typeoff_t
. Systems which support this typeuse it to describe all file positions, unlike the POSIX specificationwhich uses a long int. The two are not necessarily the same size.Therefore, using ftell can lead to problems if the implementation iswritten on top of a POSIX compliant low-level I/O implementation, and usingftello
is preferable whenever it is available.
If this function fails it returns(off_t) -1
. This can happen dueto missing support for file positioning or internal errors. Otherwisethe return value is the current file position.
The function is an extension defined in the Unix Single Specificationversion 2.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32 bit system this function is in factftello64
. I.e., theLFS interface transparently replaces the old interface.
off64_t
ftello64(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function is similar toftello
with the only difference thatthe return value is of typeoff64_t
. This also requires that thestreamstream was opened using eitherfopen64
,freopen64
, ortmpfile64
since otherwise the underlyingfile operations to position the file pointer beyond the 2^31bytes limit might fail.
If the sources are compiled with_FILE_OFFSET_BITS == 64
on a 32bits machine this function is available under the nameftello
and so transparently replaces the old interface.
int
fseek(FILE *stream, long intoffset, intwhence)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Thefseek
function is used to change the file position of thestreamstream. The value ofwhence must be one of theconstantsSEEK_SET
,SEEK_CUR
, orSEEK_END
, toindicate whether theoffset is relative to the beginning of thefile, the current file position, or the end of the file, respectively.
This function returns a value of zero if the operation was successful,and a nonzero value to indicate failure. A successful call also clearsthe end-of-file indicator ofstream and discards any charactersthat were “pushed back” by the use ofungetc
.
fseek
either flushes any buffered output before setting the fileposition or else remembers it so it will be written later in its properplace in the file.
int
fseeko(FILE *stream, off_toffset, intwhence)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function is similar tofseek
but it corrects a problem withfseek
in a system with POSIX types. Using a value of typelong int
for the offset is not compatible with POSIX.fseeko
uses the correct typeoff_t
for theoffsetparameter.
For this reason it is a good idea to preferftello
whenever it isavailable since its functionality is (if different at all) closer theunderlying definition.
The functionality and return value are the same as forfseek
.
The function is an extension defined in the Unix Single Specificationversion 2.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32 bit system this function is in factfseeko64
. I.e., theLFS interface transparently replaces the old interface.
int
fseeko64(FILE *stream, off64_toffset, intwhence)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function is similar tofseeko
with the only difference thattheoffset parameter is of typeoff64_t
. This alsorequires that the streamstream was opened using eitherfopen64
,freopen64
, ortmpfile64
since otherwisethe underlying file operations to position the file pointer beyond the2^31 bytes limit might fail.
If the sources are compiled with_FILE_OFFSET_BITS == 64
on a 32bits machine this function is available under the namefseeko
and so transparently replaces the old interface.
Portability Note: In non-POSIX systems,ftell
,ftello
,fseek
andfseeko
might work reliably onlyon binary streams. SeeText and Binary Streams.
The following symbolic constants are defined for use as thewhenceargument tofseek
. They are also used with thelseek
function (seeInput and Output Primitives) and to specify offsets for file locks(seeControl Operations on Files).
int
SEEK_SET ¶This is an integer constant which, when used as thewhenceargument to thefseek
orfseeko
functions, specifies thatthe offset provided is relative to the beginning of the file.
int
SEEK_CUR ¶This is an integer constant which, when used as thewhenceargument to thefseek
orfseeko
functions, specifies thatthe offset provided is relative to the current file position.
int
SEEK_END ¶This is an integer constant which, when used as thewhenceargument to thefseek
orfseeko
functions, specifies thatthe offset provided is relative to the end of the file.
void
rewind(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Therewind
function positions the streamstream at thebeginning of the file. It is equivalent to callingfseek
orfseeko
on thestream with anoffset argument of0L
and awhence argument ofSEEK_SET
, except thatthe return value is discarded and the error indicator for the stream isreset.
These three aliases for the ‘SEEK_…’ constants exist for thesake of compatibility with older BSD systems. They are defined in twodifferent header files:fcntl.h andsys/file.h.
Next:Stream Buffering, Previous:File Positioning, Up:Input/Output on Streams [Contents][Index]
On GNU systems, the file position is truly a character count. Youcan specify any character count value as an argument tofseek
orfseeko
and get reliable results for any random access file.However, some ISO C systems do not represent file positions in thisway.
On some systems where text streams truly differ from binary streams, itis impossible to represent the file position of a text stream as a countof characters from the beginning of the file. For example, the fileposition on some systems must encode both a record offset within thefile, and a character offset within the record.
As a consequence, if you want your programs to be portable to thesesystems, you must observe certain rules:
ftell
on a text stream has no predictablerelationship to the number of characters you have read so far. The onlything you can rely on is that you can use it subsequently as theoffset argument tofseek
orfseeko
to move back tothe same file position.fseek
orfseeko
on a text stream, either theoffset must be zero, orwhence must beSEEK_SET
andtheoffset must be the result of an earlier call toftell
on the same stream.ungetc
that haven’t been read or discarded. SeeUnreading.But even if you observe these rules, you may still have trouble for longfiles, becauseftell
andfseek
use along int
valueto represent the file position. This type may not have room to encodeall the file positions in a large file. Using theftello
andfseeko
functions might help here since theoff_t
type isexpected to be able to hold all file position values but this still doesnot help to handle additional information which must be associated witha file position.
So if you do want to support systems with peculiar encodings for thefile positions, it is better to use the functionsfgetpos
andfsetpos
instead. These functions represent the file positionusing the data typefpos_t
, whose internal representation variesfrom system to system.
These symbols are declared in the header filestdio.h.
This is the type of an object that can encode information about thefile position of a stream, for use by the functionsfgetpos
andfsetpos
.
In the GNU C Library,fpos_t
is an opaque data structure thatcontains internal data to represent file offset and conversion stateinformation. In other systems, it might have a different internalrepresentation.
When compiling with_FILE_OFFSET_BITS == 64
on a 32 bit machinethis type is in fact equivalent tofpos64_t
since the LFSinterface transparently replaces the old interface.
This is the type of an object that can encode information about thefile position of a stream, for use by the functionsfgetpos64
andfsetpos64
.
In the GNU C Library,fpos64_t
is an opaque data structure thatcontains internal data to represent file offset and conversion stateinformation. In other systems, it might have a different internalrepresentation.
int
fgetpos(FILE *stream, fpos_t *position)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function stores the value of the file position indicator for thestreamstream in thefpos_t
object pointed to byposition. If successful,fgetpos
returns zero; otherwiseit returns a nonzero value and stores an implementation-defined positivevalue inerrno
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32 bit system the function is in factfgetpos64
. I.e., the LFSinterface transparently replaces the old interface.
int
fgetpos64(FILE *stream, fpos64_t *position)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function is similar tofgetpos
but the file position isreturned in a variable of typefpos64_t
to whichpositionpoints.
If the sources are compiled with_FILE_OFFSET_BITS == 64
on a 32bits machine this function is available under the namefgetpos
and so transparently replaces the old interface.
int
fsetpos(FILE *stream, const fpos_t *position)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function sets the file position indicator for the streamstreamto the positionposition, which must have been set by a previouscall tofgetpos
on the same stream. If successful,fsetpos
clears the end-of-file indicator on the stream, discards any charactersthat were “pushed back” by the use ofungetc
, and returns a valueof zero. Otherwise,fsetpos
returns a nonzero value and storesan implementation-defined positive value inerrno
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32 bit system the function is in factfsetpos64
. I.e., the LFSinterface transparently replaces the old interface.
int
fsetpos64(FILE *stream, const fpos64_t *position)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function is similar tofsetpos
but the file position usedfor positioning is provided in a variable of typefpos64_t
towhichposition points.
If the sources are compiled with_FILE_OFFSET_BITS == 64
on a 32bits machine this function is available under the namefsetpos
and so transparently replaces the old interface.
Next:Other Kinds of Streams, Previous:Portable File-Position Functions, Up:Input/Output on Streams [Contents][Index]
Characters that are written to a stream are normally accumulated andtransmitted asynchronously to the file in a block, instead of appearingas soon as they are output by the application program. Similarly,streams often retrieve input from the host environment in blocks ratherthan on a character-by-character basis. This is calledbuffering.
If you are writing programs that do interactive input and output usingstreams, you need to understand how buffering works when you design theuser interface to your program. Otherwise, you might find that output(such as progress or prompt messages) doesn’t appear when you intendedit to, or displays some other unexpected behavior.
This section deals only with controlling when characters are transmittedbetween the stream and the file or device, andnot with howthings like echoing, flow control, and the like are handled on specificclasses of devices. For information on common control operations onterminal devices, seeLow-Level Terminal Interface.
You can bypass the stream buffering facilities altogether by using thelow-level input and output functions that operate on file descriptorsinstead. SeeLow-Level Input/Output.
Next:Flushing Buffers, Up:Stream Buffering [Contents][Index]
There are three different kinds of buffering strategies:
Newly opened streams are normally fully buffered, with one exception: astream connected to an interactive device such as a terminal isinitially line buffered. SeeControlling Which Kind of Buffering, for informationon how to select a different kind of buffering. Usually the automaticselection gives you the most convenient kind of buffering for the fileor device you open.
The use of line buffering for interactive devices implies that outputmessages ending in a newline will appear immediately—which is usuallywhat you want. Output that doesn’t end in a newline might or might notshow up immediately, so if you want them to appear immediately, youshould flush buffered output explicitly withfflush
, as describedinFlushing Buffers.
Next:Controlling Which Kind of Buffering, Previous:Buffering Concepts, Up:Stream Buffering [Contents][Index]
Flushing output on a buffered stream means transmitting allaccumulated characters to the file. There are many circumstances whenbuffered output on a stream is flushed automatically:
exit
.SeeNormal Termination.If you want to flush the buffered output at another time, callfflush
, which is declared in the header filestdio.h.
int
fflush(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function causes any buffered output onstream to be deliveredto the file. Ifstream is a null pointer, thenfflush
causes buffered output onall open output streamsto be flushed.
This function returnsEOF
if a write error occurs, or zerootherwise.
int
fflush_unlocked(FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thefflush_unlocked
function is equivalent to thefflush
function except that it does not implicitly lock the stream.
Thefflush
function can be used to flush all streams currentlyopened. While this is useful in some situations it does often more thannecessary since it might be done in situations when terminal input isrequired and the program wants to be sure that all output is visible onthe terminal. But this means that only line buffered streams have to beflushed. Solaris introduced a function especially for this. It wasalways available in the GNU C Library in some form but never officiallyexported.
void
_flushlbf(void)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
The_flushlbf
function flushes all line buffered streamscurrently opened.
This function is declared in thestdio_ext.h header.
In some situations it might be useful to not flush the output pendingfor a stream but instead simply forget it. If transmission is costlyand the output is not needed anymore this is valid reasoning. In thissituation a non-standard function introduced in Solaris and available inthe GNU C Library can be used.
void
__fpurge(FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
The__fpurge
function causes the buffer of the streamstream to be emptied. If the stream is currently in read mode allinput in the buffer is lost. If the stream is in output mode thebuffered output is not written to the device (or whatever otherunderlying storage) and the buffer is cleared.
This function is declared instdio_ext.h.
Previous:Flushing Buffers, Up:Stream Buffering [Contents][Index]
After opening a stream (but before any other operations have beenperformed on it), you can explicitly specify what kind of buffering youwant it to have using thesetvbuf
function.
The facilities listed in this section are declared in the headerfilestdio.h.
int
setvbuf(FILE *stream, char *buf, intmode, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function is used to specify that the streamstream shouldhave the buffering modemode, which can be either_IOFBF
(for full buffering),_IOLBF
(for line buffering), or_IONBF
(for unbuffered input/output).
If you specify a null pointer as thebuf argument, thensetvbuf
allocates a buffer itself usingmalloc
. This buffer will be freedwhen you close the stream.
Otherwise,buf should be a character array that can hold at leastsize characters. You should not free the space for this array aslong as the stream remains open and this array remains its buffer. Youshould usually either allocate it statically, ormalloc
(seeUnconstrained Allocation) the buffer. Using an automatic arrayis not a good idea unless you close the file before exiting the blockthat declares the array.
While the array remains a stream buffer, the stream I/O functions willuse the buffer for their internal purposes. You shouldn’t try to accessthe values in the array directly while the stream is using it forbuffering.
Thesetvbuf
function returns zero on success, or a nonzero valueif the value ofmode is not valid or if the request could notbe honored.
int
_IOFBF ¶The value of this macro is an integer constant expression that can beused as themode argument to thesetvbuf
function tospecify that the stream should be fully buffered.
int
_IOLBF ¶The value of this macro is an integer constant expression that can beused as themode argument to thesetvbuf
function tospecify that the stream should be line buffered.
int
_IONBF ¶The value of this macro is an integer constant expression that can beused as themode argument to thesetvbuf
function tospecify that the stream should be unbuffered.
int
BUFSIZ ¶The value of this macro is an integer constant expression that is goodto use for thesize argument tosetvbuf
. This value isguaranteed to be at least256
.
The value ofBUFSIZ
is chosen on each system so as to make streamI/O efficient. So it is a good idea to useBUFSIZ
as the sizefor the buffer when you callsetvbuf
.
Actually, you can get an even better value to use for the buffer sizeby means of thefstat
system call: it is found in thest_blksize
field of the file attributes. SeeThe meaning of the File Attributes.
Sometimes people also useBUFSIZ
as the allocation size ofbuffers used for related purposes, such as strings used to receive aline of input withfgets
(seeCharacter Input). There is noparticular reason to useBUFSIZ
for this instead of any otherinteger, except that it might lead to doing I/O in chunks of anefficient size.
void
setbuf(FILE *stream, char *buf)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Ifbuf is a null pointer, the effect of this function isequivalent to callingsetvbuf
with amode argument of_IONBF
. Otherwise, it is equivalent to callingsetvbuf
withbuf, and amode of_IOFBF
and asizeargument ofBUFSIZ
.
Thesetbuf
function is provided for compatibility with old code;usesetvbuf
in all new programs.
void
setbuffer(FILE *stream, char *buf, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
Ifbuf is a null pointer, this function makesstream unbuffered.Otherwise, it makesstream fully buffered usingbuf as thebuffer. Thesize argument specifies the length ofbuf.
This function is provided for compatibility with old BSD code. Usesetvbuf
instead.
void
setlinebuf(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function makesstream be line buffered, and allocates thebuffer for you.
This function is provided for compatibility with old BSD code. Usesetvbuf
instead.
It is possible to query whether a given stream is line buffered or notusing a non-standard function introduced in Solaris and available inthe GNU C Library.
int
__flbf(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The__flbf
function will return a nonzero value in case thestreamstream is line buffered. Otherwise the return value iszero.
This function is declared in thestdio_ext.h header.
Two more extensions allow to determine the size of the buffer and howmuch of it is used. These functions were also introduced in Solaris.
size_t
__fbufsize(FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Safe | SeePOSIX Safety Concepts.
The__fbufsize
function return the size of the buffer in thestreamstream. This value can be used to optimize the use of thestream.
This function is declared in thestdio_ext.h header.
size_t
__fpending(FILE *stream)
¶Preliminary:| MT-Safe race:stream| AS-Unsafe corrupt| AC-Safe | SeePOSIX Safety Concepts.
The__fpending
function returns the number of bytes currently in the output buffer.For wide-oriented streams the measuring unit is wide characters. Thisfunction should not be used on buffers in read mode or opened read-only.
This function is declared in thestdio_ext.h header.
Next:Formatted Messages, Previous:Stream Buffering, Up:Input/Output on Streams [Contents][Index]
The GNU C Library provides ways for you to define additional kinds ofstreams that do not necessarily correspond to an open file.
One such type of stream takes input from or writes output to a string.These kinds of streams are used internally to implement thesprintf
andsscanf
functions. You can also create such astream explicitly, using the functions described inString Streams.
More generally, you can define streams that do input/output to arbitraryobjects using functions supplied by your program. This protocol isdiscussed inProgramming Your Own Custom Streams.
Portability Note: The facilities described in this section arespecific to GNU. Other systems or C implementations might or might notprovide equivalent functionality.
Thefmemopen
andopen_memstream
functions allow you to doI/O to a string or memory buffer. These facilities are declared instdio.h.
FILE *
fmemopen(void *buf, size_tsize, const char *opentype)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe mem lock| SeePOSIX Safety Concepts.
This function opens a stream that allows the access specified by theopentype argument, that reads from or writes to the buffer specifiedby the argumentbuf. This array must be at leastsize bytes long.
If you specify a null pointer as thebuf argument,fmemopen
dynamically allocates an arraysize bytes long (as withmalloc
;seeUnconstrained Allocation). This is really only usefulif you are going to write things to the buffer and then read them backin again, because you have no way of actually getting a pointer to thebuffer (for this, tryopen_memstream
, below). The buffer isfreed when the stream is closed.
The argumentopentype is the same as infopen
(seeOpening Streams). If theopentype specifiesappend mode, then the initial file position is set to the first nullcharacter in the buffer. Otherwise the initial file position is at thebeginning of the buffer.
When a stream open for writing is flushed or closed, a null character(zero byte) is written at the end of the buffer if it fits. Youshould add an extra byte to thesize argument to account for this.Attempts to write more thansize bytes to the buffer resultin an error.
For a stream open for reading, null characters (zero bytes) in thebuffer do not count as “end of file”. Read operations indicate end offile only when the file position advances pastsize bytes. So, ifyou want to read characters from a null-terminated string, you shouldsupply the length of the string as thesize argument.
Here is an example of usingfmemopen
to create a stream forreading from a string:
#include <stdio.h>static char buffer[] = "foobar";intmain (void){ int ch; FILE *stream; stream = fmemopen (buffer, strlen (buffer), "r"); while ((ch = fgetc (stream)) != EOF) printf ("Got %c\n", ch); fclose (stream); return 0;}
This program produces the following output:
Got fGot oGot oGot bGot aGot r
FILE *
open_memstream(char **ptr, size_t *sizeloc)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function opens a stream for writing to a buffer. The buffer isallocated dynamically and grown as necessary, usingmalloc
.After you’ve closed the stream, this buffer is your responsibility toclean up usingfree
orrealloc
. SeeUnconstrained Allocation.
When the stream is closed withfclose
or flushed withfflush
, the locationsptr andsizeloc are updated tocontain the pointer to the buffer and its size. The values thus storedremain valid only as long as no further output on the stream takesplace. If you do more output, you must flush the stream again to storenew values before you use them again.
A null character is written at the end of the buffer. This null characterisnot included in the size value stored atsizeloc.
You can move the stream’s file position withfseek
orfseeko
(seeFile Positioning). Moving the file position pastthe end of the data already written fills the intervening space withzeroes.
Here is an example of usingopen_memstream
:
#include <stdio.h>#include <stdlib.h>intmain (void){ char *bp; size_t size; FILE *stream; stream = open_memstream (&bp, &size); fprintf (stream, "hello"); fflush (stream); printf ("buf = `%s', size = %zu\n", bp, size); fprintf (stream, ", world"); fclose (stream); printf ("buf = `%s', size = %zu\n", bp, size); free (bp); return 0;}
This program produces the following output:
buf = `hello', size = 5buf = `hello, world', size = 12
Previous:String Streams, Up:Other Kinds of Streams [Contents][Index]
This section describes how you can make a stream that gets input from anarbitrary data source or writes output to an arbitrary data sinkprogrammed by you. We call thesecustom streams. The functionsand types described here are all GNU extensions.
Inside every custom stream is a special object called thecookie.This is an object supplied by you which records where to fetch or storethe data read or written. It is up to you to define a data type to usefor the cookie. The stream functions in the library never referdirectly to its contents, and they don’t even know what the type is;they record its address with typevoid *
.
To implement a custom stream, you must specifyhow to fetch orstore the data in the specified place. You do this by defininghook functions to read, write, change “file position”, and closethe stream. All four of these functions will be passed the stream’scookie so they can tell where to fetch or store the data. The libraryfunctions don’t know what’s inside the cookie, but your functions willknow.
When you create a custom stream, you must specify the cookie pointer,and also the four hook functions stored in a structure of typecookie_io_functions_t
.
These facilities are declared instdio.h.
This is a structure type that holds the functions that define thecommunications protocol between the stream and its cookie. It hasthe following members:
cookie_read_function_t *read
This is the function that reads data from the cookie. If the value is anull pointer instead of a function, then read operations on this streamalways returnEOF
.
cookie_write_function_t *write
This is the function that writes data to the cookie. If the value is anull pointer instead of a function, then data written to the stream isdiscarded.
cookie_seek_function_t *seek
This is the function that performs the equivalent of file positioning onthe cookie. If the value is a null pointer instead of a function, callstofseek
orfseeko
on this stream can only seek tolocations within the buffer; any attempt to seek outside the buffer willreturn anESPIPE
error.
cookie_close_function_t *close
This function performs any appropriate cleanup on the cookie whenclosing the stream. If the value is a null pointer instead of afunction, nothing special is done to close the cookie when the stream isclosed.
FILE *
fopencookie(void *cookie, const char *opentype, cookie_io_functions_tio-functions)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe mem lock| SeePOSIX Safety Concepts.
This function actually creates the stream for communicating with thecookie using the functions in theio-functions argument.Theopentype argument is interpreted as forfopen
;seeOpening Streams. (But note that the “truncate onopen” option is ignored.) The new stream is fully buffered.
Thefopencookie
function returns the newly created stream, or a nullpointer in case of an error.
Previous:Custom Streams and Cookies, Up:Programming Your Own Custom Streams [Contents][Index]
Here are more details on how you should define the four hook functionsthat a custom stream needs.
You should define the function to read data from the cookie as:
ssize_treader (void *cookie, char *buffer, size_tsize)
This is very similar to theread
function; seeInput and Output Primitives. Your function should transfer up tosize bytes intothebuffer, and return the number of bytes read, or zero toindicate end-of-file. You can return a value of-1
to indicatean error.
You should define the function to write data to the cookie as:
ssize_twriter (void *cookie, const char *buffer, size_tsize)
This is very similar to thewrite
function; seeInput and Output Primitives. Your function should transfer up tosize bytes fromthe buffer, and return the number of bytes written. You can return avalue of0
to indicate an error. You must not return anynegative value.
You should define the function to perform seek operations on the cookieas:
intseeker (void *cookie, off64_t *position, intwhence)
For this function, theposition andwhence arguments areinterpreted as forfgetpos
; seePortable File-Position Functions.
After doing the seek operation, your function should store the resultingfile position relative to the beginning of the file inposition.Your function should return a value of0
on success and-1
to indicate an error.
You should define the function to do cleanup operations on the cookieappropriate for closing the stream as:
intcleaner (void *cookie)
Your function should return-1
to indicate an error, and0
otherwise.
This is the data type that the read function for a custom stream should have.If you declare the function as shown above, this is the type it will have.
The data type of the write function for a custom stream.
The data type of the seek function for a custom stream.
The data type of the close function for a custom stream.
Previous:Other Kinds of Streams, Up:Input/Output on Streams [Contents][Index]
On systems which are based on System V messages of programs (especiallythe system tools) are printed in a strict form using thefmtmsg
function. The uniformity sometimes helps the user to interpret messagesand the strictness tests of thefmtmsg
function ensure that theprogrammer follows some minimal requirements.
Next:Adding Severity Classes, Up:Formatted Messages [Contents][Index]
Messages can be printed to standard error and/or to the console. Toselect the destination the programmer can use the following two values,bitwise OR combined if wanted, for theclassification parameter offmtmsg
:
MM_PRINT
¶Display the message in standard error.
MM_CONSOLE
¶Display the message on the system console.
The erroneous piece of the system can be signalled by exactly one of thefollowing values which also is bitwise ORed with theclassification parameter tofmtmsg
:
MM_HARD
¶The source of the condition is some hardware.
MM_SOFT
¶The source of the condition is some software.
MM_FIRM
¶The source of the condition is some firmware.
A third component of theclassification parameter tofmtmsg
can describe the part of the system which detects the problem. This isdone by using exactly one of the following values:
MM_APPL
¶The erroneous condition is detected by the application.
MM_UTIL
¶The erroneous condition is detected by a utility.
MM_OPSYS
¶The erroneous condition is detected by the operating system.
A last component ofclassification can signal the results of thismessage. Exactly one of the following values can be used:
int
fmtmsg(long intclassification, const char *label, intseverity, const char *text, const char *action, const char *tag)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Safe | SeePOSIX Safety Concepts.
Display a message described by its parameters on the device(s) specifiedin theclassification parameter. Thelabel parameteridentifies the source of the message. The string should consist of twocolon separated parts where the first part has not more than 10 and thesecond part not more than 14 characters. Thetext parameterdescribes the condition of the error, theaction parameter possiblesteps to recover from the error and thetag parameter is areference to the online documentation where more information can befound. It should contain thelabel value and a uniqueidentification number.
Each of the parameters can be a special value which means this valueis to be omitted. The symbolic names for these values are:
MM_NULLLBL
¶Ignorelabel parameter.
MM_NULLSEV
¶Ignoreseverity parameter.
MM_NULLMC
¶Ignoreclassification parameter. This implies that nothing isactually printed.
MM_NULLTXT
¶Ignoretext parameter.
MM_NULLACT
¶Ignoreaction parameter.
MM_NULLTAG
¶Ignoretag parameter.
There is another way certain fields can be omitted from the output tostandard error. This is described below in the description ofenvironment variables influencing the behavior.
Theseverity parameter can have one of the values in the followingtable:
MM_NOSEV
¶Nothing is printed, this value is the same asMM_NULLSEV
.
MM_HALT
¶This value is printed asHALT
.
MM_ERROR
¶This value is printed asERROR
.
MM_WARNING
¶This value is printed asWARNING
.
MM_INFO
¶This value is printed asINFO
.
The numeric value of these five macros are between0
and4
. Using the environment variableSEV_LEVEL
or using theaddseverity
function one can add more severity levels with theircorresponding string to print. This is described below(seeAdding Severity Classes).
If no parameter is ignored the output looks like this:
label:severity-string:textTO FIX:actiontag
The colons, new line characters and theTO FIX
string areinserted if necessary, i.e., if the corresponding parameter is notignored.
This function is specified in the X/Open Portability Guide. It is alsoavailable on all systems derived from System V.
The function returns the valueMM_OK
if no error occurred. Ifonly the printing to standard error failed, it returnsMM_NOMSG
.If printing to the console fails, it returnsMM_NOCON
. Ifnothing is printedMM_NOTOK
is returned. Among situations whereall outputs fail this last value is also returned if a parameter valueis incorrect.
There are two environment variables which influence the behavior offmtmsg
. The first isMSGVERB
. It is used to control theoutput actually happening on standard error (not the consoleoutput). Each of the five fields can explicitly be enabled. To dothis the user has to put theMSGVERB
variable with a format likethe following in the environment before calling thefmtmsg
functionthe first time:
MSGVERB=keyword[:keyword[:...]]
Validkeywords arelabel
,severity
,text
,action
, andtag
. If the environment variable is not givenor is the empty string, a not supported keyword is given or the value issomehow else invalid, no part of the message is masked out.
The second environment variable which influences the behavior offmtmsg
isSEV_LEVEL
. This variable and the change in thebehavior offmtmsg
is not specified in the X/Open PortabilityGuide. It is available in System V systems, though. It can be used tointroduce new severity levels. By default, only the five severity levelsdescribed above are available. Any other numeric value would makefmtmsg
print nothing.
If the user putsSEV_LEVEL
with a format like
SEV_LEVEL=[description[:description[:...]]]
in the environment of the process before the first call tofmtmsg
, wheredescription has a value of the form
severity-keyword,level,printstring
Theseverity-keyword part is not used byfmtmsg
but it hasto be present. Thelevel part is a string representation of anumber. The numeric value must be a number greater than 4. This valuemust be used in theseverity parameter offmtmsg
to selectthis class. It is not possible to overwrite any of the predefinedclasses. Theprintstring is the string printed when a message ofthis class is processed byfmtmsg
(see above,fmtsmg
doesnot print the numeric value but instead the string representation).
Next:How to usefmtmsg
andaddseverity
, Previous:Printing Formatted Messages, Up:Formatted Messages [Contents][Index]
There is another possibility to introduce severity classes besides usingthe environment variableSEV_LEVEL
. This simplifies the task ofintroducing new classes in a running program. One could use thesetenv
orputenv
function to set the environment variable,but this is toilsome.
int
addseverity(intseverity, const char *string)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
This function allows the introduction of new severity classes which can beaddressed by theseverity parameter of thefmtmsg
function.Theseverity parameter ofaddseverity
must match the valuefor the parameter with the same name offmtmsg
, andstringis the string printed in the actual messages instead of the numericvalue.
Ifstring isNULL
the severity class with the numeric valueaccording toseverity is removed.
It is not possible to overwrite or remove one of the default severityclasses. All calls toaddseverity
withseverity set to oneof the values for the default classes will fail.
The return value isMM_OK
if the task was successfully performed.If the return value isMM_NOTOK
something went wrong. This couldmean that no more memory is available or a class is not available whenit has to be removed.
This function is not specified in the X/Open Portability Guide althoughthefmtsmg
function is. It is available on System V systems.
Previous:Adding Severity Classes, Up:Formatted Messages [Contents][Index]
fmtmsg
andaddseverity
¶Here is a simple example program to illustrate the use of bothfunctions described in this section.
#include <fmtmsg.h>intmain (void){ addseverity (5, "NOTE2"); fmtmsg (MM_PRINT, "only1field", MM_INFO, "text2", "action2", "tag2"); fmtmsg (MM_PRINT, "UX:cat", 5, "invalid syntax", "refer to manual", "UX:cat:001"); fmtmsg (MM_PRINT, "label:foo", 6, "text", "action", "tag"); return 0;}
The second call tofmtmsg
illustrates a use of this function asit usually occurs on System V systems, which heavily use this function.It seems worthwhile to give a short explanation here of how this systemworks on System V. The value of thelabel field (UX:cat
) says that the error occurred in theUnix programcat
. The explanation of the error follows and thevalue for theaction parameter is"refer to manual"
. Onecould be more specific here, if necessary. Thetag field contains,as proposed above, the value of the string given for thelabelparameter, and additionally a unique ID (001
in this case). Fora GNU environment this string could contain a reference to thecorresponding node in the Info page for the program.
Running this program without specifying theMSGVERB
andSEV_LEVEL
function produces the following output:
UX:cat: NOTE2: invalid syntaxTO FIX: refer to manual UX:cat:001
We see the different fields of the message and how the extra glue (thecolons and theTO FIX
string) is printed. But only one of thethree calls tofmtmsg
produced output. The first call does notprint anything because thelabel parameter is not in the correctform. The string must contain two fields, separated by a colon(seePrinting Formatted Messages). The thirdfmtmsg
callproduced no output since the class with the numeric value6
isnot defined. Although a class with numeric value5
is also notdefined by default, the call toaddseverity
introduces it andthe second call tofmtmsg
produces the above output.
When we change the environment of the program to containSEV_LEVEL=XXX,6,NOTE
when running it we get a different result:
UX:cat: NOTE2: invalid syntaxTO FIX: refer to manual UX:cat:001label:foo: NOTE: textTO FIX: action tag
Now the third call tofmtmsg
produced some output and we see howthe stringNOTE
from the environment variable appears in themessage.
Now we can reduce the output by specifying which fields we areinterested in. If we additionally set the environment variableMSGVERB
to the valueseverity:label:action
we get thefollowing output:
UX:cat: NOTE2TO FIX: refer to manuallabel:foo: NOTETO FIX: action
I.e., the output produced by thetext and thetag parameterstofmtmsg
vanished. Please also note that now there is no colonafter theNOTE
andNOTE2
strings in the output. This isnot necessary since there is no more output on this line because the textis missing.
Next:File System Interface, Previous:Input/Output on Streams, Up:Main Menu [Contents][Index]
This chapter describes functions for performing low-level input/outputoperations on file descriptors. These functions include the primitivesfor the higher-level I/O functions described inInput/Output on Streams, aswell as functions for performing low-level control operations for whichthere are no equivalents on streams.
Stream-level I/O is more flexible and usually more convenient;therefore, programmers generally use the descriptor-level functions onlywhen necessary. These are some of the usual reasons:
fileno
to get the descriptorcorresponding to a stream.)This section describes the primitives for opening and closing filesusing file descriptors. Theopen
andcreat
functions aredeclared in the header filefcntl.h, whileclose
isdeclared inunistd.h.
int
open(const char *filename, intflags[, mode_tmode])
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
Theopen
function creates and returns a new file descriptor forthe file named byfilename. Initially, the file positionindicator for the file is at the beginning of the file. The argumentmode (seeThe Mode Bits for Access Permission) is used only when a file iscreated, but it doesn’t hurt to supply the argument in any case.
Theflags argument controls how the file is to be opened. This isa bit mask; you create the value by the bitwise OR of the appropriateparameters (using the ‘|’ operator in C).SeeFile Status Flags, for the parameters available.
The normal return value fromopen
is a non-negative integer filedescriptor. In the case of an error, a value of-1 is returnedinstead. In addition to the usual file name errors (seeFile Name Errors), the followingerrno
error conditions are definedfor this function:
EACCES
The file exists but is not readable/writable as requested by theflagsargument, or the file does not exist and the directory is unwritable soit cannot be created.
EEXIST
BothO_CREAT
andO_EXCL
are set, and the named file alreadyexists.
EINTR
Theopen
operation was interrupted by a signal.SeePrimitives Interrupted by Signals.
EISDIR
Theflags argument specified write access, and the file is a directory.
EMFILE
The process has too many files open.The maximum number of file descriptors is controlled by theRLIMIT_NOFILE
resource limit; seeLimiting Resource Usage.
ENFILE
The entire system, or perhaps the file system which contains thedirectory, cannot support any additional open files at the moment.(This problem cannot happen on GNU/Hurd systems.)
ENOENT
The named file does not exist, andO_CREAT
is not specified.
ENOSPC
The directory or file system that would contain the new file cannot beextended, because there is no disk space left.
ENXIO
O_NONBLOCK
andO_WRONLY
are both set in theflagsargument, the file named byfilename is a FIFO (seePipes and FIFOs), and no process has the file open for reading.
EROFS
The file resides on a read-only file system and any ofO_WRONLY
,O_RDWR
, andO_TRUNC
are set in theflags argument,orO_CREAT
is set and the file does not already exist.
If on a 32 bit machine the sources are translated with_FILE_OFFSET_BITS == 64
the functionopen
returns a filedescriptor opened in the large file mode which enables the file handlingfunctions to use files up to 2^63 bytes in size and offset from−2^63 to 2^63. This happens transparently for the usersince all of the low-level file handling functions are equally replaced.
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timeopen
iscalled. If the thread gets canceled these resources stay allocateduntil the program ends. To avoid this calls toopen
should beprotected using cancellation handlers.
Theopen
function is the underlying primitive for thefopen
andfreopen
functions, that create streams.
int
open64(const char *filename, intflags[, mode_tmode])
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
This function is similar toopen
. It returns a file descriptorwhich can be used to access the file named byfilename. The onlydifference is that on 32 bit systems the file is opened in thelarge file mode. I.e., file length and file offsets can exceed 31 bits.
When the sources are translated with_FILE_OFFSET_BITS == 64
thisfunction is actually available under the nameopen
. I.e., thenew, extended API using 64 bit file sizes and offsets transparentlyreplaces the old API.
int
openat(intfiledes, const char *filename, intflags[, mode_tmode])
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
This function is the descriptor-relative variant of theopen
function. SeeDescriptor-Relative Access.
Note that theflags argument ofopenat
does not acceptAT_…
flags, only the flags described for theopen
function above.
Theopenat
function can fail for additional reasons:
EBADF
Thefiledes argument is not a valid file descriptor.
ENOTDIR
The descriptorfiledes is not associated with a directory, andfilename is a relative file name.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is in factopenat64
since the LFS interface transparentlyreplaces the normal implementation.
int
openat64(intfiledes, const char *filename, intflags[, mode_tmode])
¶The large-file variant of theopenat
, similar to howopen64
is the large-file variant ofopen
.
When the sources are translated with_FILE_OFFSET_BITS == 64
thisfunction is actually available under the nameopenat
. I.e., thenew, extended API using 64 bit file sizes and offsets transparentlyreplaces the old API.
int
creat(const char *filename, mode_tmode)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
This function is obsolete. The call:
creat (filename,mode)
is equivalent to:
open (filename, O_WRONLY | O_CREAT | O_TRUNC,mode)
If on a 32 bit machine the sources are translated with_FILE_OFFSET_BITS == 64
the functioncreat
returns a filedescriptor opened in the large file mode which enables the file handlingfunctions to use files up to 2^63 in size and offset from−2^63 to 2^63. This happens transparently for the usersince all of the low-level file handling functions are equally replaced.
int
creat64(const char *filename, mode_tmode)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
This function is similar tocreat
. It returns a file descriptorwhich can be used to access the file named byfilename. The onlydifference is that on 32 bit systems the file is opened in thelarge file mode. I.e., file length and file offsets can exceed 31 bits.
To use this file descriptor one must not use the normal operations butinstead the counterparts named*64
, e.g.,read64
.
When the sources are translated with_FILE_OFFSET_BITS == 64
thisfunction is actually available under the nameopen
. I.e., thenew, extended API using 64 bit file sizes and offsets transparentlyreplaces the old API.
int
close(intfiledes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
The functionclose
closes the file descriptorfiledes.Closing a file has the following consequences:
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timeclose
iscalled. If the thread gets canceled these resources stay allocateduntil the program ends. To avoid this, calls toclose
should beprotected using cancellation handlers.
The normal return value fromclose
is0; a value of-1is returned in case of failure. The followingerrno
errorconditions are defined for this function:
EBADF
Thefiledes argument is not a valid file descriptor.
EINTR
Theclose
call was interrupted by a signal.SeePrimitives Interrupted by Signals.Here is an example of how to handleEINTR
properly:
TEMP_FAILURE_RETRY (close (desc));
ENOSPC
EIO
EDQUOT
When the file is accessed by NFS, these errors fromwrite
can sometimesnot be detected untilclose
. SeeInput and Output Primitives, for detailson their meaning.
Please note that there isno separateclose64
function.This is not necessary since this function does not determine nor dependon the mode of the file. The kernel which performs theclose
operation knows which mode the descriptor is used for and can handlethis situation.
To close a stream, callfclose
(seeClosing Streams) insteadof trying to close its underlying file descriptor withclose
.This flushes any buffered output and updates the stream object toindicate that it is closed.
int
close_range(unsigned intlowfd, unsigned intmaxfd, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
The functionclose_range
closes the file descriptor fromlowfdtomaxfd (inclusive). This function is similar to callclose
inspecified file descriptor range depending on theflags.
This is function is only supported on recent Linux versions and the GNU C Librarydoes not provide any fallback (the application will need to handle possibleENOSYS
).
Theflags add options on how the files are closes. Linux currentlysupports:
CLOSE_RANGE_UNSHARE
¶Unshare the file descriptor table before closing file descriptors.
CLOSE_RANGE_CLOEXEC
¶Set theFD_CLOEXEC
bit instead of closing the file descriptor.
The normal return value fromclose_range
is0; a valueof-1 is returned in case of failure. The followingerrno
errorconditions are defined for this function:
EINVAL
Thelowfd value is larger thanmaxfd or an unsupportedflagsis used.
ENOMEM
Either there is not enough memory for the operation, or the process isout of address space. It can only happen whenCLOSE_RANGE_UNSHARED
flag is used.
EMFILE
The process has too many files open and it can only happens whenCLOSE_RANGE_UNSHARED
flag is used.The maximum number of file descriptors is controlled by theRLIMIT_NOFILE
resource limit; seeLimiting Resource Usage.
ENOSYS
The kernel does not implement the required functionality.
void
closefrom(intlowfd)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
The functionclosefrom
closes all file descriptors greater than or equaltolowfd. This function is similar to callingclose
for all open file descriptors not less thanlowfd.
Already closed file descriptors are ignored.
Next:Setting the File Position of a Descriptor, Previous:Opening and Closing Files, Up:Low-Level Input/Output [Contents][Index]
This section describes the functions for performing primitive input andoutput operations on file descriptors:read
,write
, andlseek
. These functions are declared in the header fileunistd.h.
This data type is used to represent the sizes of blocks that can beread or written in a single operation. It is similar tosize_t
,but must be a signed type.
ssize_t
read(intfiledes, void *buffer, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theread
function reads up tosize bytes from the filewith descriptorfiledes, storing the results in thebuffer.(This is not necessarily a character string, and no terminating nullcharacter is added.)
The return value is the number of bytes actually read. This might beless thansize; for example, if there aren’t that many bytes leftin the file or if there aren’t that many bytes immediately available.The exact behavior depends on what kind of file it is. Note thatreading less thansize bytes is not an error.
A value of zero indicates end-of-file (except if the value of thesize argument is also zero). This is not considered an error.If you keep callingread
while at end-of-file, it will keepreturning zero and doing nothing else.
Ifread
returns at least one character, there is no way you cantell whether end-of-file was reached. But if you did reach the end, thenext read will return zero.
In case of an error,read
returns-1. The followingerrno
error conditions are defined for this function:
EAGAIN
Normally, when no input is immediately available,read
waits forsome input. But if theO_NONBLOCK
flag is set for the file(seeFile Status Flags),read
returns immediately withoutreading any data, and reports this error.
Compatibility Note: Most versions of BSD Unix use a differenterror code for this:EWOULDBLOCK
. In the GNU C Library,EWOULDBLOCK
is an alias forEAGAIN
, so it doesn’t matterwhich name you use.
On some systems, reading a large amount of data from a character specialfile can also fail withEAGAIN
if the kernel cannot find enoughphysical memory to lock down the user’s pages. This is limited todevices that transfer with direct memory access into the user’s memory,which means it does not include terminals, since they always useseparate buffers inside the kernel. This problem never happens onGNU/Hurd systems.
Any condition that could result inEAGAIN
can instead result in asuccessfulread
which returns fewer bytes than requested.Callingread
again immediately would result inEAGAIN
.
EBADF
Thefiledes argument is not a valid file descriptor,or is not open for reading.
EINTR
read
was interrupted by a signal while it was waiting for input.SeePrimitives Interrupted by Signals. A signal will not necessarily causeread
to returnEINTR
; it may instead result in asuccessfulread
which returns fewer bytes than requested.
EIO
For many devices, and for disk files, this error code indicatesa hardware error.
EIO
also occurs when a background process tries to read from thecontrolling terminal, and the normal action of stopping the process bysending it aSIGTTIN
signal isn’t working. This might happen ifthe signal is being blocked or ignored, or because the process group isorphaned. SeeJob Control, for more information about job control,andSignal Handling, for information about signals.
EINVAL
In some systems, when reading from a character or block device, positionand size offsets must be aligned to a particular block size. This errorindicates that the offsets were not properly aligned.
Please note that there is no function namedread64
. This is notnecessary since this function does not directly modify or handle thepossibly wide file offset. Since the kernel handles this stateinternally, theread
function can be used for all cases.
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timeread
iscalled. If the thread gets canceled these resources stay allocateduntil the program ends. To avoid this, calls toread
should beprotected using cancellation handlers.
Theread
function is the underlying primitive for all of thefunctions that read from streams, such asfgetc
.
ssize_t
pread(intfiledes, void *buffer, size_tsize, off_toffset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thepread
function is similar to theread
function. Thefirst three arguments are identical, and the return values and errorcodes also correspond.
The difference is the fourth argument and its handling. The data blockis not read from the current position of the file descriptorfiledes
. Instead the data is read from the file starting atpositionoffset. The position of the file descriptor itself isnot affected by the operation. The value is the same as before the call.
When the source file is compiled with_FILE_OFFSET_BITS == 64
thepread
function is in factpread64
and the typeoff_t
has 64 bits, which makes it possible to handle files up to2^63 bytes in length.
The return value ofpread
describes the number of bytes read.In the error case it returns-1 likeread
does and theerror codes are also the same, with these additions:
EINVAL
The value given foroffset is negative and therefore illegal.
ESPIPE
The file descriptorfiledes is associated with a pipe or a FIFO andthis device does not allow positioning of the file pointer.
The function is an extension defined in the Unix Single Specificationversion 2.
ssize_t
pread64(intfiledes, void *buffer, size_tsize, off64_toffset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thepread
function. The differenceis that theoffset parameter is of typeoff64_t
instead ofoff_t
which makes it possible on 32 bit machines to addressfiles larger than 2^31 bytes and up to 2^63 bytes. Thefile descriptorfiledes
must be opened usingopen64
sinceotherwise the large offsets possible withoff64_t
will lead toerrors with a descriptor in small file mode.
When the source file is compiled with_FILE_OFFSET_BITS == 64
on a32 bit machine this function is actually available under the namepread
and so transparently replaces the 32 bit interface.
ssize_t
write(intfiledes, const void *buffer, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewrite
function writes up tosize bytes frombuffer to the file with descriptorfiledes. The data inbuffer is not necessarily a character string and a null character isoutput like any other character.
The return value is the number of bytes actually written. This may besize, but can always be smaller. Your program should always callwrite
in a loop, iterating until all the data is written.
Oncewrite
returns, the data is enqueued to be written and can beread back right away, but it is not necessarily written out to permanentstorage immediately. You can usefsync
when you need to be sureyour data has been permanently stored before continuing. (It is moreefficient for the system to batch up consecutive writes and do them allat once when convenient. Normally they will always be written to diskwithin a minute or less.) Modern systems provide another functionfdatasync
which guarantees integrity only for the file data andis therefore faster.You can use theO_FSYNC
open mode to makewrite
alwaysstore the data to disk before returning; seeI/O Operating Modes.
In the case of an error,write
returns-1. The followingerrno
error conditions are defined for this function:
EAGAIN
Normally,write
blocks until the write operation is complete.But if theO_NONBLOCK
flag is set for the file (seeControl Operations on Files), it returns immediately without writing any data andreports this error. An example of a situation that might cause theprocess to block on output is writing to a terminal device that supportsflow control, where output has been suspended by receipt of a STOPcharacter.
Compatibility Note: Most versions of BSD Unix use a differenterror code for this:EWOULDBLOCK
. In the GNU C Library,EWOULDBLOCK
is an alias forEAGAIN
, so it doesn’t matterwhich name you use.
On some systems, writing a large amount of data from a character specialfile can also fail withEAGAIN
if the kernel cannot find enoughphysical memory to lock down the user’s pages. This is limited todevices that transfer with direct memory access into the user’s memory,which means it does not include terminals, since they always useseparate buffers inside the kernel. This problem does not arise onGNU/Hurd systems.
EBADF
Thefiledes argument is not a valid file descriptor,or is not open for writing.
EFBIG
The size of the file would become larger than the implementation can support.
EINTR
Thewrite
operation was interrupted by a signal while it wasblocked waiting for completion. A signal will not necessarily causewrite
to returnEINTR
; it may instead result in asuccessfulwrite
which writes fewer bytes than requested.SeePrimitives Interrupted by Signals.
EIO
For many devices, and for disk files, this error code indicatesa hardware error.
ENOSPC
The device containing the file is full.
EPIPE
This error is returned when you try to write to a pipe or FIFO thatisn’t open for reading by any process. When this happens, aSIGPIPE
signal is also sent to the process; seeSignal Handling.
EINVAL
In some systems, when writing to a character or block device, positionand size offsets must be aligned to a particular block size. This errorindicates that the offsets were not properly aligned.
Unless you have arranged to preventEINTR
failures, you shouldcheckerrno
after each failing call towrite
, and if theerror wasEINTR
, you should simply repeat the call.SeePrimitives Interrupted by Signals. The easy way to do this is with themacroTEMP_FAILURE_RETRY
, as follows:
nbytes = TEMP_FAILURE_RETRY (write (desc, buffer, count));
Please note that there is no function namedwrite64
. This is notnecessary since this function does not directly modify or handle thepossibly wide file offset. Since the kernel handles this stateinternally thewrite
function can be used for all cases.
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timewrite
iscalled. If the thread gets canceled these resources stay allocateduntil the program ends. To avoid this, calls towrite
should beprotected using cancellation handlers.
Thewrite
function is the underlying primitive for all of thefunctions that write to streams, such asfputc
.
ssize_t
pwrite(intfiledes, const void *buffer, size_tsize, off_toffset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thepwrite
function is similar to thewrite
function. Thefirst three arguments are identical, and the return values and error codesalso correspond.
The difference is the fourth argument and its handling. The data blockis not written to the current position of the file descriptorfiledes
. Instead the data is written to the file starting atpositionoffset. The position of the file descriptor itself isnot affected by the operation. The value is the same as before the call.
However, on Linux, if a file is opened withO_APPEND
,pwrite
appends data to the end of the file, regardless of the value ofoffset
.
When the source file is compiled with_FILE_OFFSET_BITS == 64
thepwrite
function is in factpwrite64
and the typeoff_t
has 64 bits, which makes it possible to handle files up to2^63 bytes in length.
The return value ofpwrite
describes the number of written bytes.In the error case it returns-1 likewrite
does and theerror codes are also the same, with these additions:
EINVAL
The value given foroffset is negative and therefore illegal.
ESPIPE
The file descriptorfiledes is associated with a pipe or a FIFO andthis device does not allow positioning of the file pointer.
The function is an extension defined in the Unix Single Specificationversion 2.
ssize_t
pwrite64(intfiledes, const void *buffer, size_tsize, off64_toffset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thepwrite
function. The differenceis that theoffset parameter is of typeoff64_t
instead ofoff_t
which makes it possible on 32 bit machines to addressfiles larger than 2^31 bytes and up to 2^63 bytes. Thefile descriptorfiledes
must be opened usingopen64
sinceotherwise the large offsets possible withoff64_t
will lead toerrors with a descriptor in small file mode.
When the source file is compiled using_FILE_OFFSET_BITS == 64
on a32 bit machine this function is actually available under the namepwrite
and so transparently replaces the 32 bit interface.
Next:Descriptors and Streams, Previous:Input and Output Primitives, Up:Low-Level Input/Output [Contents][Index]
Just as you can set the file position of a stream withfseek
, youcan set the file position of a descriptor withlseek
. Thisspecifies the position in the file for the nextread
orwrite
operation. SeeFile Positioning, for more informationon the file position and what it means.
To read the current file position value from a descriptor, uselseek (desc, 0, SEEK_CUR)
.
off_t
lseek(intfiledes, off_toffset, intwhence)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thelseek
function is used to change the file position of thefile with descriptorfiledes.
Thewhence argument specifies how theoffset should beinterpreted, in the same way as for thefseek
function, and it mustbe one of the symbolic constantsSEEK_SET
,SEEK_CUR
, orSEEK_END
.
SEEK_SET
¶Specifies thatoffset is a count of characters from the beginningof the file.
SEEK_CUR
¶Specifies thatoffset is a count of characters from the currentfile position. This count may be positive or negative.
SEEK_END
¶Specifies thatoffset is a count of characters from the end ofthe file. A negative count specifies a position within the currentextent of the file; a positive count specifies a position past thecurrent end. If you set the position past the current end, andactually write data, you will extend the file with zeros up to thatposition.
The return value fromlseek
is normally the resulting fileposition, measured in bytes from the beginning of the file.You can use this feature together withSEEK_CUR
to read thecurrent file position.
If you want to append to the file, setting the file position to thecurrent end of file withSEEK_END
is not sufficient. Anotherprocess may write more data after you seek but before you write,extending the file so the position you write onto clobbers their data.Instead, use theO_APPEND
operating mode; seeI/O Operating Modes.
You can set the file position past the current end of the file. Thisdoes not by itself make the file longer;lseek
never changes thefile. But subsequent output at that position will extend the file.Characters between the previous end of file and the new position arefilled with zeros. Extending the file in this way can create a“hole”: the blocks of zeros are not actually allocated on disk, so thefile takes up less space than it appears to; it is then called a“sparse file”.
If the file position cannot be changed, or the operation is in some wayinvalid,lseek
returns a value of-1. The followingerrno
error conditions are defined for this function:
EBADF
Thefiledes is not a valid file descriptor.
EINVAL
Thewhence argument value is not valid, or the resultingfile offset is not valid. A file offset is invalid.
ESPIPE
Thefiledes corresponds to an object that cannot be positioned,such as a pipe, FIFO or terminal device. (POSIX.1 specifies this erroronly for pipes and FIFOs, but on GNU systems, you always getESPIPE
if the object is not seekable.)
When the source file is compiled with_FILE_OFFSET_BITS == 64
thelseek
function is in factlseek64
and the typeoff_t
has 64 bits which makes it possible to handle files up to2^63 bytes in length.
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timelseek
iscalled. If the thread gets canceled these resources stay allocateduntil the program ends. To avoid this calls tolseek
should beprotected using cancellation handlers.
Thelseek
function is the underlying primitive for thefseek
,fseeko
,ftell
,ftello
andrewind
functions, which operate on streams instead of filedescriptors.
off64_t
lseek64(intfiledes, off64_toffset, intwhence)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thelseek
function. The differenceis that theoffset parameter is of typeoff64_t
instead ofoff_t
which makes it possible on 32 bit machines to addressfiles larger than 2^31 bytes and up to 2^63 bytes. Thefile descriptorfiledes
must be opened usingopen64
sinceotherwise the large offsets possible withoff64_t
will lead toerrors with a descriptor in small file mode.
When the source file is compiled with_FILE_OFFSET_BITS == 64
on a32 bits machine this function is actually available under the namelseek
and so transparently replaces the 32 bit interface.
You can have multiple descriptors for the same file if you open the filemore than once, or if you duplicate a descriptor withdup
.Descriptors that come from separate calls toopen
have independentfile positions; usinglseek
on one descriptor has no effect on theother. For example,
{ int d1, d2; char buf[4]; d1 = open ("foo", O_RDONLY); d2 = open ("foo", O_RDONLY); lseek (d1, 1024, SEEK_SET); read (d2, buf, 4);}
will read the first four characters of the filefoo. (Theerror-checking code necessary for a real program has been omitted herefor brevity.)
By contrast, descriptors made by duplication share a common fileposition with the original descriptor that was duplicated. Anythingwhich alters the file position of one of the duplicates, includingreading or writing data, affects all of them alike. Thus, for example,
{ int d1, d2, d3; char buf1[4], buf2[4]; d1 = open ("foo", O_RDONLY); d2 = dup (d1); d3 = dup (d2); lseek (d3, 1024, SEEK_SET); read (d1, buf1, 4); read (d2, buf2, 4);}
will read four characters starting with the 1024’th character offoo, and then four more characters starting with the 1028’thcharacter.
This is a signed integer type used to represent file sizes. Inthe GNU C Library, this type is no narrower thanint
.
If the source is compiled with_FILE_OFFSET_BITS == 64
this typeis transparently replaced byoff64_t
.
This type is used similar tooff_t
. The difference is that evenon 32 bit machines, where theoff_t
type would have 32 bits,off64_t
has 64 bits and so is able to address files up to2^63 bytes in length.
When compiling with_FILE_OFFSET_BITS == 64
this type isavailable under the nameoff_t
.
These aliases for the ‘SEEK_…’ constants exist for the sakeof compatibility with older BSD systems. They are defined in twodifferent header files:fcntl.h andsys/file.h.
Next:Dangers of Mixing Streams and Descriptors, Previous:Setting the File Position of a Descriptor, Up:Low-Level Input/Output [Contents][Index]
Given an open file descriptor, you can create a stream for it with thefdopen
function. You can get the underlying file descriptor foran existing stream with thefileno
function. These functions aredeclared in the header filestdio.h.
FILE *
fdopen(intfiledes, const char *opentype)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe mem lock| SeePOSIX Safety Concepts.
Thefdopen
function returns a new stream for the file descriptorfiledes.
Theopentype argument is interpreted in the same way as for thefopen
function (seeOpening Streams), except thatthe ‘b’ option is not permitted; this is because GNU systems make nodistinction between text and binary files. Also,"w"
and"w+"
do not cause truncation of the file; these have an effect onlywhen opening a file, and in this case the file has already been opened.You must make sure that theopentype argument matches the actualmode of the open file descriptor.
The return value is the new stream. If the stream cannot be created(for example, if the modes for the file indicated by the file descriptordo not permit the access specified by theopentype argument), anull pointer is returned instead.
In some other systems,fdopen
may fail to detect that the modesfor file descriptors do not permit the access specified byopentype
. The GNU C Library always checks for this.
For an example showing the use of thefdopen
function,seeCreating a Pipe.
int
fileno(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the file descriptor associated with the streamstream. If an error is detected (for example, if thestreamis not valid) or ifstream does not do I/O to a file,fileno
returns-1.
int
fileno_unlocked(FILE *stream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefileno_unlocked
function is equivalent to thefileno
function except that it does not implicitly lock the stream if the stateisFSETLOCKING_INTERNAL
.
This function is a GNU extension.
There are also symbolic constants defined inunistd.h for thefile descriptors belonging to the standard streamsstdin
,stdout
, andstderr
; seeStandard Streams.
STDIN_FILENO
¶This macro has value0
, which is the file descriptor forstandard input.
STDOUT_FILENO
¶This macro has value1
, which is the file descriptor forstandard output.
STDERR_FILENO
¶This macro has value2
, which is the file descriptor forstandard error output.
Next:Fast Scatter-Gather I/O, Previous:Descriptors and Streams, Up:Low-Level Input/Output [Contents][Index]
You can have multiple file descriptors and streams (let’s call bothstreams and descriptors “channels” for short) connected to the samefile, but you must take care to avoid confusion between channels. Thereare two cases to consider:linked channels that share a singlefile position value, andindependent channels that have their ownfile positions.
It’s best to use just one channel in your program for actual datatransfer to any given file, except when all the access is for input.For example, if you open a pipe (something you can only do at the filedescriptor level), either do all I/O with the descriptor, or construct astream from the descriptor withfdopen
and then do all I/O withthe stream.
Channels that come from a single opening share the same file position;we call themlinked channels. Linked channels result when youmake a stream from a descriptor usingfdopen
, when you get adescriptor from a stream withfileno
, when you copy a descriptorwithdup
ordup2
, and when descriptors are inheritedduringfork
. For files that don’t support random access, such asterminals and pipes,all channels are effectively linked. Onrandom-access files, all append-type output streams are effectivelylinked to each other.
If you have been using a stream for I/O (or have just opened the stream),and you want to do I/O usinganother channel (either a stream or a descriptor) that is linked to it,you must firstclean up the stream that you have been using.SeeCleaning Streams.
Terminating a process, or executing a new program in the process,destroys all the streams in the process. If descriptors linked to thesestreams persist in other processes, their file positions becomeundefined as a result. To prevent this, you must clean up the streamsbefore destroying them.
In addition to cleaning up a stream before doing I/O using anotherlinked channel, additional precautions are needed to ensure awell-defined file position indicator in some cases. If both thefollowing conditions hold, you must set the file position indicator onthe new channel (a stream) using a function such asfseek
.
fseek
.POSIX requires such precautions in more cases: if either the old orthe new linked channel is a stream (whether or not previously active)and the file position indicator was previously set on any channellinked to those channels with a function such asfseek
orlseek
.
Next:Cleaning Streams, Previous:Linked Channels, Up:Dangers of Mixing Streams and Descriptors [Contents][Index]
When you open channels (streams or descriptors) separately on a seekablefile, each channel has its own file position. These are calledindependent channels.
The system handles each channel independently. Most of the time, thisis quite predictable and natural (especially for input): each channelcan read or write sequentially at its own place in the file. However,if some of the channels are streams, you must take these precautions:
If you do output to one channel at the end of the file, this willcertainly leave the other independent channels positioned somewherebefore the new end. You cannot reliably set their file positions to thenew end of file before writing, because the file can always be extendedby another process between when you set the file position and when youwrite the data. Instead, use an append-type descriptor or stream; theyalways output at the current end of the file. In order to make theend-of-file position accurate, you must clean the output channel youwere using, if it is a stream.
It’s impossible for two channels to have separate file pointers for afile that doesn’t support random access. Thus, channels for reading orwriting such files are always linked, never independent. Append-typechannels are also always linked. For these channels, follow the rulesfor linked channels; seeLinked Channels.
Previous:Independent Channels, Up:Dangers of Mixing Streams and Descriptors [Contents][Index]
You can usefflush
to clean a stream in mostcases.
You can skip thefflush
if you know the streamis already clean. A stream is clean whenever its buffer is empty. Forexample, an unbuffered stream is always clean. An input stream that isat end-of-file is clean. A line-buffered stream is clean when the lastcharacter output was a newline. However, a just-opened input streammight not be clean, as its input buffer might not be empty.
There is one case in which cleaning a stream is impossible on mostsystems. This is when the stream is doing input from a file that is notrandom-access. Such streams typically read ahead, and when the file isnot random access, there is no way to give back the excess data alreadyread. When an input stream reads from a random-access file,fflush
does clean the stream, but leaves the file pointer at anunpredictable place; you must set the file pointer before doing anyfurther I/O.
Closing an output-only stream also doesfflush
, so this is avalid way of cleaning an output stream.
You need not clean a stream before using its descriptor for controloperations such as setting terminal modes; these operations don’t affectthe file position and are not affected by it. You can use anydescriptor for these operations, and all channels are affectedsimultaneously. However, text already “output” to a stream but stillbuffered by the stream will be subject to the new terminal modes whensubsequently flushed. To make sure “past” output is covered by theterminal settings that were in effect at the time, flush the outputstreams for that terminal before setting the modes. SeeTerminal Modes.
Next:Copying data between two files, Previous:Dangers of Mixing Streams and Descriptors, Up:Low-Level Input/Output [Contents][Index]
Some applications may need to read or write data to multiple buffers,which are separated in memory. Although this can be done easily enoughwith multiple calls toread
andwrite
, it is inefficientbecause there is overhead associated with each kernel call.
Instead, many platforms provide special high-speed primitives to performthesescatter-gather operations in a single kernel call. The GNU C Librarywill provide an emulation on any system that lacks theseprimitives, so they are not a portability threat. They are defined insys/uio.h
.
These functions are controlled with arrays ofiovec
structures,which describe the location and size of each buffer.
Theiovec
structure describes a buffer. It contains two fields:
void *iov_base
Contains the address of a buffer.
size_t iov_len
Contains the length of the buffer.
ssize_t
readv(intfiledes, const struct iovec *vector, intcount)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thereadv
function reads data fromfiledes and scatters itinto the buffers described invector, which is taken to becount structures long. As each buffer is filled, data is sent to thenext.
Note thatreadv
is not guaranteed to fill all the buffers.It may stop at any point, for the same reasonsread
would.
The return value is a count of bytes (not buffers) read,0indicating end-of-file, or-1 indicating an error. The possibleerrors are the same as inread
.
ssize_t
writev(intfiledes, const struct iovec *vector, intcount)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thewritev
function gathers data from the buffers described invector, which is taken to becount structures long, and writesthem tofiledes
. As each buffer is written, it moves on to thenext.
Likereadv
,writev
may stop midstream under the sameconditionswrite
would.
The return value is a count of bytes written, or-1 indicating anerror. The possible errors are the same as inwrite
.
ssize_t
preadv(intfd, const struct iovec *iov, intiovcnt, off_toffset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thereadv
function, with the differenceit adds an extraoffset parameter of typeoff_t
similar topread
. The data is read from the file starting at positionoffset. The position of the file descriptor itself is not affectedby the operation. The value is the same as before the call.
When the source file is compiled with_FILE_OFFSET_BITS == 64
thepreadv
function is in factpreadv64
and the typeoff_t
has 64 bits, which makes it possible to handle files up to2^63 bytes in length.
The return value is a count of bytes (not buffers) read,0indicating end-of-file, or-1 indicating an error. The possibleerrors are the same as inreadv
andpread
.
ssize_t
preadv64(intfd, const struct iovec *iov, intiovcnt, off64_toffset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thepreadv
function with the differenceis that theoffset parameter is of typeoff64_t
instead ofoff_t
. It makes it possible on 32 bit machines to addressfiles larger than 2^31 bytes and up to 2^63 bytes. Thefile descriptorfiledes
must be opened usingopen64
sinceotherwise the large offsets possible withoff64_t
will lead toerrors with a descriptor in small file mode.
When the source file is compiled using_FILE_OFFSET_BITS == 64
on a32 bit machine this function is actually available under the namepreadv
and so transparently replaces the 32 bit interface.
ssize_t
pwritev(intfd, const struct iovec *iov, intiovcnt, off_toffset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thewritev
function, with the differenceit adds an extraoffset parameter of typeoff_t
similar topwrite
. The data is written to the file starting at positionoffset. The position of the file descriptor itself is not affectedby the operation. The value is the same as before the call.
However, on Linux, if a file is opened withO_APPEND
,pwrite
appends data to the end of the file, regardless of the value ofoffset
.
When the source file is compiled with_FILE_OFFSET_BITS == 64
thepwritev
function is in factpwritev64
and the typeoff_t
has 64 bits, which makes it possible to handle files up to2^63 bytes in length.
The return value is a count of bytes (not buffers) written,0indicating end-of-file, or-1 indicating an error. The possibleerrors are the same as inwritev
andpwrite
.
ssize_t
pwritev64(intfd, const struct iovec *iov, intiovcnt, off64_toffset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thepwritev
function with the differenceis that theoffset parameter is of typeoff64_t
instead ofoff_t
. It makes it possible on 32 bit machines to addressfiles larger than 2^31 bytes and up to 2^63 bytes. Thefile descriptorfiledes
must be opened usingopen64
sinceotherwise the large offsets possible withoff64_t
will lead toerrors with a descriptor in small file mode.
When the source file is compiled using_FILE_OFFSET_BITS == 64
on a32 bit machine this function is actually available under the namepwritev
and so transparently replaces the 32 bit interface.
ssize_t
preadv2(intfd, const struct iovec *iov, intiovcnt, off_toffset, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thepreadv
function, with thedifference it adds an extraflags parameter of typeint
.Additionally, ifoffset is-1, the current file positionis used and updated (like thereadv
function).
The supportedflags are dependent of the underlying system. ForLinux it supports:
RWF_HIPRI
¶High priority request. This adds a flag that tells the file system thatthis is a high priority request for which it is worth to poll the hardware.The flag is purely advisory and can be ignored if not supported. Thefd must be opened usingO_DIRECT
.
RWF_DSYNC
¶Per-IO synchronization as if the file was opened withO_DSYNC
flag.
RWF_SYNC
¶Per-IO synchronization as if the file was opened withO_SYNC
flag.
RWF_NOWAIT
¶Use nonblocking mode for this operation; that is, this call topreadv2
will fail and seterrno
toEAGAIN
if the operation would block.
RWF_APPEND
¶Per-IO synchronization as if the file was opened withO_APPEND
flag.
RWF_NOAPPEND
¶This flag allows an offset to be honored, even if the file was opened withO_APPEND
flag.
RWF_ATOMIC
¶Indicate that the write is to be issued with torn-write prevention. Theinput buffer should follow some contraints: the total length should bepower-of-2 in size and also sizes betweenatomic_write_unit_min
andatomic_write_unit_max
, thestruct iovec
count should beup toatomic_write_segments_max
, and the offset should benaturally-aligned with regard to total write length.
Theatomic_*
values can be obtained withstatx
along withSTATX_WRITE_ATOMIC
flag.
This is a Linux-specific extension.
When the source file is compiled with_FILE_OFFSET_BITS == 64
thepreadv2
function is in factpreadv64v2
and the typeoff_t
has 64 bits, which makes it possible to handle files up to2^63 bytes in length.
The return value is a count of bytes (not buffers) read,0indicating end-of-file, or-1 indicating an error. The possibleerrors are the same as inpreadv
with the addition of:
EOPNOTSUPP
An unsupportedflags was used.
ssize_t
preadv64v2(intfd, const struct iovec *iov, intiovcnt, off64_toffset, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thepreadv2
function with the differenceis that theoffset parameter is of typeoff64_t
instead ofoff_t
. It makes it possible on 32 bit machines to addressfiles larger than 2^31 bytes and up to 2^63 bytes. Thefile descriptorfiledes
must be opened usingopen64
sinceotherwise the large offsets possible withoff64_t
will lead toerrors with a descriptor in small file mode.
When the source file is compiled using_FILE_OFFSET_BITS == 64
on a32 bit machine this function is actually available under the namepreadv2
and so transparently replaces the 32 bit interface.
ssize_t
pwritev2(intfd, const struct iovec *iov, intiovcnt, off_toffset, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thepwritev
function, with thedifference it adds an extraflags parameter of typeint
.Additionally, ifoffset is-1, the current file positionshould is used and updated (like thewritev
function).
The supportedflags are dependent of the underlying system. ForLinux, the supported flags are the same as those forpreadv2
.
When the source file is compiled with_FILE_OFFSET_BITS == 64
thepwritev2
function is in factpwritev64v2
and the typeoff_t
has 64 bits, which makes it possible to handle files up to2^63 bytes in length.
The return value is a count of bytes (not buffers) write,0indicating end-of-file, or-1 indicating an error. The possibleerrors are the same as inpreadv2
.
ssize_t
pwritev64v2(intfd, const struct iovec *iov, intiovcnt, off64_toffset, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thepwritev2
function with the differenceis that theoffset parameter is of typeoff64_t
instead ofoff_t
. It makes it possible on 32 bit machines to addressfiles larger than 2^31 bytes and up to 2^63 bytes. Thefile descriptorfiledes
must be opened usingopen64
sinceotherwise the large offsets possible withoff64_t
will lead toerrors with a descriptor in small file mode.
When the source file is compiled using_FILE_OFFSET_BITS == 64
on a32 bit machine this function is actually available under the namepwritev2
and so transparently replaces the 32 bit interface.
Next:Memory-mapped I/O, Previous:Fast Scatter-Gather I/O, Up:Low-Level Input/Output [Contents][Index]
A special function is provided to copy data between two files on thesame file system. The system can optimize such copy operations. Thisis particularly important on network file systems, where the data wouldotherwise have to be transferred twice over the network.
Note that this function only copies file data, but not metadata such asfile permissions or extended attributes.
ssize_t
copy_file_range(intinputfd, off64_t *inputpos, intoutputfd, off64_t *outputpos, ssize_tlength, unsigned intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function copies up tolength bytes from the file descriptorinputfd to the file descriptoroutputfd.
The function can operate on both the current file position (likeread
andwrite
) and an explicit offset (likepread
andpwrite
). If theinputpos pointer is null, the fileposition ofinputfd is used as the starting point of the copyoperation, and the file position is advanced during it. Ifinputpos is not null, then*inputpos
is used as thestarting point of the copy operation, and*inputpos
isincremented by the number of copied bytes, but the file position remainsunchanged. Similar rules apply tooutputfd andoutputposfor the output file position.
Theflags argument is currently reserved and must be zero.
Thecopy_file_range
function returns the number of bytes copied.This can be less than the specifiedlength in case the input filecontains fewer remaining bytes thanlength, or if a read or writefailure occurs. The return value is zero if the end of the input fileis encountered immediately.
If no bytes can be copied, to report an error,copy_file_range
returns the value-1 and setserrno
. The table belowlists some of the error conditions for this function.
ENOSYS
The kernel does not implement the required functionality.
EISDIR
At least one of the descriptorsinputfd oroutputfd refersto a directory.
EINVAL
At least one of the descriptorsinputfd oroutputfd refersto a non-regular, non-directory file (such as a socket or a FIFO).
The input or output positions before are after the copy operations areoutside of an implementation-defined limit.
Theflags argument is not zero.
EFBIG
The new file size would exceed the process file size limit.SeeLimiting Resource Usage.
The input or output positions before are after the copy operations areoutside of an implementation-defined limit. This can happen if the filewas not opened with large file support (LFS) on 32-bit machines, and thecopy operation would create a file which is larger than whatoff_t
could represent.
EBADF
The argumentinputfd is not a valid file descriptor open forreading.
The argumentoutputfd is not a valid file descriptor open forwriting, oroutputfd has been opened withO_APPEND
.
In addition,copy_file_range
can fail with the error codeswhich are used byread
,pread
,write
, andpwrite
.
Thecopy_file_range
function is a cancellation point. In case ofcancellation, the input location (the file position or the value at*inputpos
) is indeterminate.
Next:Waiting for Input or Output, Previous:Copying data between two files, Up:Low-Level Input/Output [Contents][Index]
On modern operating systems, it is possible tommap (pronounced“em-map”) a file to a region of memory. When this is done, the file canbe accessed just like an array in the program.
This is more efficient thanread
orwrite
, as only the regionsof the file that a program actually accesses are loaded. Accesses tonot-yet-loaded parts of the mmapped region are handled in the same way asswapped out pages.
Since mmapped pages can be stored back to their file when physicalmemory is low, it is possible to mmap files orders of magnitude largerthan both the physical memoryand swap space. The only limit isaddress space. The theoretical limit is 4GB on a 32-bit machine -however, the actual limit will be smaller since some areas will bereserved for other purposes. If the LFS interface is used the file sizeon 32-bit systems is not limited to 2GB (offsets are signed whichreduces the addressable area of 4GB by half); the full 64-bit areavailable.
Memory mapping only works on entire pages of memory. Thus, addressesfor mapping must be page-aligned, and length values will be rounded up.To determine the default size of a page the machine uses one should use:
size_t page_size = (size_t) sysconf (_SC_PAGESIZE);
On some systems, mappings can use larger page sizesfor certain files, and applications can request larger page sizes foranonymous mappings as well (see theMAP_HUGETLB
flag below).
The following functions are declared insys/mman.h:
void *
mmap(void *address, size_tlength, intprotect, intflags, intfiledes, off_toffset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Themmap
function creates a new mapping, connected to bytes(offset) to (offset +length - 1) in the file open onfiledes. A new reference for the file specified byfiledesis created, which is not removed by closing the file.
address gives a preferred starting address for the mapping.NULL
expresses no preference. Any previous mapping at thataddress is automatically removed. The address you give may still bechanged, unless you use theMAP_FIXED
flag.
protect contains flags that control what kind of access ispermitted. They includePROT_READ
,PROT_WRITE
, andPROT_EXEC
. The special flagPROT_NONE
reserves a regionof address space for future use. Themprotect
function can beused to change the protection flags. SeeMemory Protection.
Theflags parameter contains flags that control the nature ofthe map. One ofMAP_SHARED
,MAP_SHARED_VALIDATE
, orMAP_PRIVATE
must be specified. Additional flags may be bitwiseOR’d to further define the mapping.
Note that, aside fromMAP_PRIVATE
andMAP_SHARED
, notall flags are supported on all versions of all operating systems.Consult the kernel-specific documentation for details. The flagsinclude:
MAP_PRIVATE
¶This specifies that writes to the region should never be written backto the attached file. Instead, a copy is made for the process, and theregion will be swapped normally if memory runs low. No other process willsee the changes.
Since private mappings effectively revert to ordinary memorywhen written to, you must have enough virtual memory for a copy ofthe entire mmapped region if you use this mode withPROT_WRITE
.
MAP_SHARED
¶This specifies that writes to the region will be written back to thefile. Changes made will be shared immediately with other processesmmaping the same file.
Note that actual writing may take place at any time. You need to usemsync
, described below, if it is important that other processesusing conventional I/O get a consistent view of the file.
MAP_SHARED_VALIDATE
¶Similar toMAP_SHARED
except that additional flags will bevalidated by the kernel, and the call will fail if an unrecognizedflag is provided. WithMAP_SHARED
using a flag on a kernelthat doesn’t support it causes the flag to be ignored.MAP_SHARED_VALIDATE
should be used when the behavior of allflags is required.
MAP_FIXED
¶This forces the system to use the exact mapping address specified inaddress and fail if it can’t. Note that if the new mappingwould overlap an existing mapping, the overlapping portion of theexisting map is unmapped.
MAP_ANONYMOUS
¶MAP_ANON
¶This flag tells the system to create an anonymous mapping, not connectedto a file.filedes andoffset are ignored, and the region isinitialized with zeros.
Anonymous maps are used as the basic primitive to extend the heap on somesystems. They are also useful to share data between multiple taskswithout creating a file.
On some systems using private anonymous mmaps is more efficient than usingmalloc
for large blocks. This is not an issue with the GNU C Library,as the includedmalloc
automatically usesmmap
where appropriate.
MAP_HUGETLB
¶This requests that the system uses an alternative page size which islarger than the default page size for the mapping. For some workloads,increasing the page size for large mappings improves performance becausethe system needs to handle far fewer pages. For other workloads whichrequire frequent transfer of pages between storage or different nodes,the decreased page granularity may cause performance problems due to theincreased page size and larger transfers.
In order to create the mapping, the system needs physically contiguousmemory of the size of the increased page size. As a result,MAP_HUGETLB
mappings are affected by memory fragmentation, andtheir creation can fail even if plenty of memory is available in thesystem.
Not all file systems support mappings with an increased page size.
TheMAP_HUGETLB
flag is specific to Linux.
MAP_32BIT
¶Require addresses that can be accessed with a signed 32 bit pointer,i.e., within the first 2 GiB. Ignored if MAP_FIXED is specified.
MAP_DENYWRITE
¶MAP_EXECUTABLE
¶MAP_FILE
¶Provided for compatibility. Ignored by the Linux kernel.
MAP_FIXED_NOREPLACE
¶Similar toMAP_FIXED
except the call will fail withEEXIST
if the new mapping would overwrite an existing mapping.To test for support for this flag, specify MAP_FIXED_NOREPLACE withoutMAP_FIXED, and (if the call was successful) check the actual addressreturned. If it does not match the address passed, then this flag isnot supported.
MAP_GROWSDOWN
¶This flag is used to make stacks, and is typically only needed insidethe program loader to set up the main stack for the running process.The mapping is created according to the other flags, except anadditional page just prior to the mapping is marked as a “guardpage”. If a write is attempted inside this guard page, that page ismapped, the mapping is extended, and a new guard page is created.Thus, the mapping continues to grow towards lower addresses until itencounters some other mapping.
Note that accessing memory beyond the guard page will not trigger thisfeature. In gcc, use-fstack-clash-protection
to ensure theguard page is always touched.
MAP_LOCKED
¶A hint that requests that mapped pages are locked in memory (i.e. notpaged out). Note that this is a request and not a requirement; usemlock
if locking is required.
MAP_POPULATE
¶MAP_NONBLOCK
¶MAP_POPULATE
is a hint that requests that the kernel read-aheada file-backed mapping, causing pages to be mapped before they’reneeded.MAP_NONBLOCK
is a hint that requests that the kernelnot attempt such except for pages are already in memory. Notethat neither of these hints affects future paging activity, usemlock
if such needs to be controlled.
MAP_NORESERVE
¶Asks the kernel to not reserve physical backing (i.e. space in a swapdevice) for a mapping. This would be useful for, for example, a verylarge but sparsely used mapping which need not be limited in totallength by available RAM, but with very few mapped pages. Note thatwrites to such a mapping may cause aSIGSEGV
if the system isunable to map a page due to lack of resources.
On Linux, this flag’s behavior may be overwridden by/proc/sys/vm/overcommit_memory as documented in the proc(5) manpage.
MAP_STACK
¶Ensures that the resulting mapping is suitable for use as a programstack. For example, the use of huge pages might be precluded.
MAP_SYNC
¶This is a special flag for DAX devices, which tells the kernel towrite dirty metadata out whenever dirty data is written out. Unlikemost other flags, this one will fail unlessMAP_SHARED_VALIDATE
is also given.
MAP_DROPPABLE
¶Request the page to be never written out to swap, it will be zeroedunder memory pressure (so kernel can just drop the page), it is inheritedby fork, it is not counted againstmlock
budget, and if there isnot enough memory to service a page fault there is no fatal error (so nosignal is sent).
TheMAP_DROPPABLE
flag is specific to Linux.
mmap
returns the address of the new mapping, orMAP_FAILED
for an error.
Possible errors include:
EACCES
filedes was not open for the type of access specified inprotect.
EAGAIN
The system has temporarily run out of resources.
EBADF
Thefd passed is invalid, and a valid file descriptor isrequired (i.e. MAP_ANONYMOUS was not specified).
EEXIST
MAP_FIXED_NOREPLACE
was specified and an existing mapping wasfound overlapping the requested address range.
EINVAL
Eitheraddress was unusable (because it is not a multiple of theapplicable page size), or inconsistentflags were given.
IfMAP_HUGETLB
was specified, the file or system does not supportlarge page sizes.
ENODEV
This file is of a type that doesn’t support mapping, the process hasexceeded its data space limit, or the map request would exceed theprocess’s virtual address space.
ENOMEM
There is not enough memory for the operation, the process is out ofaddress space, or there are too many mappings. On Linux, the maximumnumber of mappings can be controlled via/proc/sys/vm/max_map_count or, if your OS supports it, viathevm.max_map_count
sysctl
setting.
ENOEXEC
The file is on a filesystem that doesn’t support mapping.
EPERM
PROT_EXEC
was requested but the file is on a filesystem thatwas mounted with execution denied, a file seal prevented the mapping,or the caller set MAP_HUDETLB but does not have the requiredpriviledges.
EOVERFLOW
Either the offset into the file plus the length of the mapping causesinternal page counts to overflow, or the offset requested exceeds thelength of the file.
void *
mmap64(void *address, size_tlength, intprotect, intflags, intfiledes, off64_toffset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Themmap64
function is equivalent to themmap
function buttheoffset parameter is of typeoff64_t
. On 32-bit systemsthis allows the file associated with thefiledes descriptor to belarger than 2GB.filedes must be a descriptor returned from acall toopen64
orfopen64
andfreopen64
where thedescriptor is retrieved withfileno
.
When the sources are translated with_FILE_OFFSET_BITS == 64
thisfunction is actually available under the namemmap
. I.e., thenew, extended API using 64 bit file sizes and offsets transparentlyreplaces the old API.
int
munmap(void *addr, size_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
munmap
removes any memory maps from (addr) to (addr +length).length should be the length of the mapping.
It is safe to unmap multiple mappings in one command, or include unmappedspace in the range. It is also possible to unmap only part of an existingmapping. However, only entire pages can be removed. Iflength is notan even number of pages, it will be rounded up.
It returns0 for success and-1 for an error.
One error is possible:
EINVAL
The memory range given was outside the user mmap range or wasn’t pagealigned.
int
msync(void *address, size_tlength, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
When using shared mappings, the kernel can write the file at any timebefore the mapping is removed. To be certain data has actually beenwritten to the file and will be accessible to non-memory-mapped I/O, itis necessary to use this function.
It operates on the regionaddress to (address +length).It may be used on part of a mapping or multiple mappings, however theregion given should not contain any unmapped space.
flags can contain some options:
MS_SYNC
¶This flag makes sure the data is actually writtento disk.Normallymsync
only makes sure that accesses to a file withconventional I/O reflect the recent changes.
MS_ASYNC
¶This tellsmsync
to begin the synchronization, but not to wait forit to complete.
msync
returns0 for success and-1 forerror. Errors include:
EINVAL
An invalid region was given, or theflags were invalid.
EFAULT
There is no existing mapping in at least part of the given region.
void *
mremap(void *address, size_tlength, size_tnew_length, intflag, ... /* void *new_address */)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function can be used to change the size of an existing memoryarea.address andlength must cover a region entirely mappedin the samemmap
statement. A new mapping with the samecharacteristics will be returned with the lengthnew_length.
Possible flags are
MREMAP_MAYMOVE
If it is given inflags, the system may remove the existing mappingand create a new one of the desired length in another location.
MREMAP_FIXED
If it is given inflags,mremap
accepts a fifth argument,void *new_address
, which specifies a page-aligned address towhich the mapping must be moved. Any previous mapping at the addressrange specified bynew_address andnew_size is unmapped.
MREMAP_FIXED
must be used together withMREMAP_MAYMOVE
.
MREMAP_DONTUNMAP
If it is given inflags,mremap
accepts a fifth argument,void *new_address
, which specifies a page-aligned address. Anyprevious mapping at the address range specified bynew_address andnew_size is unmapped. Ifnew_address isNULL
, thekernel chooses the page-aligned address at which to create the mapping.Otherwise, the kernel takes it as a hint about where to place the mapping.The mapping at the address range specified byold_address andold_size isn’t unmapped.
MREMAP_DONTUNMAP
must be used together withMREMAP_MAYMOVE
.old_size must be the same asnew_size. This flag bit isLinux-specific.
The address of the resulting mapping is returned, orMAP_FAILED
.Possible error codes include:
EFAULT
There is no existing mapping in at least part of the original region, orthe region covers two or more distinct mappings.
EINVAL
Any arguments are inappropriate, including unknownflags values.
EAGAIN
The region has pages locked, and if extended it would exceed theprocess’s resource limit for locked pages. SeeLimiting Resource Usage.
ENOMEM
The region is private writable, and insufficient virtual memory isavailable to extend it. Also, this error will occur ifMREMAP_MAYMOVE
is not given and the extension would collide withanother mapped region.
This function is only available on a few systems. Except for performingoptional optimizations one should not rely on this function.
Not all file descriptors may be mapped. Sockets, pipes, and most devicesonly allow sequential access and do not fit into the mapping abstraction.In addition, some regular files may not be mmapable, and older kernels maynot support mapping at all. Thus, programs usingmmap
shouldhave a fallback method to use should it fail. SeeMmap inGNUCoding Standards.
int
madvise(void *addr, size_tlength, intadvice)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function can be used to provide the system withadvice aboutthe intended usage patterns of the memory region starting ataddrand extendinglength bytes.
The valid BSD values foradvice are:
MADV_NORMAL
¶The region should receive no further special treatment.
MADV_RANDOM
¶The region will be accessed via random page references. The kernelshould page-in the minimal number of pages for each page fault.
MADV_SEQUENTIAL
¶The region will be accessed via sequential page references. Thismay cause the kernel to aggressively read-ahead, expecting furthersequential references after any page fault within this region.
MADV_WILLNEED
¶The region will be needed. The pages within this region maybe pre-faulted in by the kernel.
MADV_DONTNEED
¶The region is no longer needed. The kernel may free these pages,causing any changes to the pages to be lost, as well as swappedout pages to be discarded.
MADV_HUGEPAGE
¶Indicate that it is beneficial to increase the page size for thismapping. This can improve performance for larger mappings because thesystem needs to handle far fewer pages. However, if parts of themapping are frequently transferred between storage or different nodes,performance may suffer because individual transfers can becomesubstantially larger due to the increased page size.
This flag is specific to Linux.
MADV_NOHUGEPAGE
¶Undo the effect of a previousMADV_HUGEPAGE
advice. This flagis specific to Linux.
The POSIX names are slightly different, but with the same meanings:
POSIX_MADV_NORMAL
¶This corresponds with BSD’sMADV_NORMAL
.
POSIX_MADV_RANDOM
¶This corresponds with BSD’sMADV_RANDOM
.
POSIX_MADV_SEQUENTIAL
¶This corresponds with BSD’sMADV_SEQUENTIAL
.
POSIX_MADV_WILLNEED
¶This corresponds with BSD’sMADV_WILLNEED
.
POSIX_MADV_DONTNEED
¶This corresponds with BSD’sMADV_DONTNEED
.
madvise
returns0 for success and-1 forerror. Errors include:
EINVAL
An invalid region was given, or theadvice was invalid.
EFAULT
There is no existing mapping in at least part of the given region.
int
shm_open(const char *name, intoflag, mode_tmode)
¶Preliminary:| MT-Safe locale| AS-Unsafe init heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
This function returns a file descriptor that can be used to allocate sharedmemory via mmap. Unrelated processes can use samename to create oropen existing shared memory objects.
Aname argument specifies the shared memory object to be opened.In the GNU C Library it must be a string smaller thanNAME_MAX
bytes startingwith an optional slash but containing no other slashes.
The semantics ofoflag andmode arguments is same as inopen
.
shm_open
returns the file descriptor on success or-1 on error.On failureerrno
is set.
int
shm_unlink(const char *name)
¶Preliminary:| MT-Safe locale| AS-Unsafe init heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
This function is the inverse ofshm_open
and removes the object withthe givenname previously created byshm_open
.
shm_unlink
returns0 on success or-1 on error.On failureerrno
is set.
int
memfd_create(const char *name, unsigned intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
Thememfd_create
function returns a file descriptor which can beused to create memory mappings using themmap
function. It issimilar to theshm_open
function in the sense that these mappingsare not backed by actual files. However, the descriptor returned bymemfd_create
does not correspond to a named object; thename argument is used for debugging purposes only (e.g., willappear in/proc), and separate invocations ofmemfd_create
with the samename will not return descriptors for the same regionof memory. The descriptor can also be used to create alias mappingswithin the same process.
The descriptor initially refers to a zero-length file. Before mappingscan be created which are backed by memory, the file size needs to beincreased with theftruncate
function. SeeFile Size.
Theflags argument can be a combination of the following flags:
MFD_CLOEXEC
¶The descriptor is created with theO_CLOEXEC
flag.
MFD_ALLOW_SEALING
¶The descriptor supports the addition of seals using thefcntl
function.
MFD_HUGETLB
¶This requests that mappings created using the returned file descriptoruse a larger page size. SeeMAP_HUGETLB
above for details.
This flag is incompatible withMFD_ALLOW_SEALING
.
memfd_create
returns a file descriptor on success, and-1on failure.
The followingerrno
error conditions are defined for thisfunction:
EINVAL
An invalid combination is specified inflags, orname istoo long.
EFAULT
Thename argument does not point to a string.
EMFILE
The operation would exceed the file descriptor limit for this process.
ENFILE
The operation would exceed the system-wide file descriptor limit.
ENOMEM
There is not enough memory for the operation.
Next:Synchronizing I/O operations, Previous:Memory-mapped I/O, Up:Low-Level Input/Output [Contents][Index]
Sometimes a program needs to accept input on multiple input channelswhenever input arrives. For example, some workstations may have devicessuch as a digitizing tablet, function button box, or dial box that areconnected via normal asynchronous serial interfaces; good user interfacestyle requires responding immediately to input on any device. Anotherexample is a program that acts as a server to several other processesvia pipes or sockets.
You cannot normally useread
for this purpose, because thisblocks the program until input is available on one particular filedescriptor; input on other channels won’t wake it up. You could setnonblocking mode and poll each file descriptor in turn, but this is veryinefficient.
A better solution is to use theselect
function. This blocks theprogram until input or output is ready on a specified set of filedescriptors, or until a timer expires, whichever comes first. Thisfacility is declared in the header filesys/types.h.
In the case of a server socket (seeListening for Connections), we say that“input” is available when there are pending connections that could beaccepted (seeAccepting Connections).accept
for serversockets blocks and interacts withselect
just asread
doesfor normal input.
The file descriptor sets for theselect
function are specifiedasfd_set
objects. Here is the description of the data typeand some macros for manipulating these objects.
Thefd_set
data type represents file descriptor sets for theselect
function. It is actually a bit array.
int
FD_SETSIZE ¶The value of this macro is the maximum number of file descriptors that afd_set
object can hold information about. On systems with afixed maximum number,FD_SETSIZE
is at least that number. Onsome systems, including GNU, there is no absolute limit on the number ofdescriptors open, but this macro still has a constant value whichcontrols the number of bits in anfd_set
; if you get a filedescriptor with a value as high asFD_SETSIZE
, you cannot putthat descriptor into anfd_set
.
void
FD_ZERO(fd_set *set)
¶Preliminary:| MT-Safe race:set| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro initializes the file descriptor setset to be theempty set.
void
FD_SET(intfiledes, fd_set *set)
¶Preliminary:| MT-Safe race:set| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro addsfiledes to the file descriptor setset.
Thefiledes parameter must not have side effects since it isevaluated more than once.
void
FD_CLR(intfiledes, fd_set *set)
¶Preliminary:| MT-Safe race:set| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro removesfiledes from the file descriptor setset.
Thefiledes parameter must not have side effects since it isevaluated more than once.
int
FD_ISSET(intfiledes, const fd_set *set)
¶Preliminary:| MT-Safe race:set| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value (true) iffiledes is a memberof the file descriptor setset, and zero (false) otherwise.
Thefiledes parameter must not have side effects since it isevaluated more than once.
Next, here is the description of theselect
function itself.
int
select(intnfds, fd_set *read-fds, fd_set *write-fds, fd_set *except-fds, struct timeval *timeout)
¶Preliminary:| MT-Safe race:read-fds race:write-fds race:except-fds| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theselect
function blocks the calling process until there isactivity on any of the specified sets of file descriptors, or until thetimeout period has expired.
The file descriptors specified by theread-fds argument arechecked to see if they are ready for reading; thewrite-fds filedescriptors are checked to see if they are ready for writing; and theexcept-fds file descriptors are checked for exceptionalconditions. You can pass a null pointer for any of these arguments ifyou are not interested in checking for that kind of condition.
A file descriptor is considered ready for reading if aread
call will not block. This usually includes the read offset being atthe end of the file or there is an error to report. A server socketis considered ready for reading if there is a pending connection whichcan be accepted withaccept
; seeAccepting Connections. Aclient socket is ready for writing when its connection is fullyestablished; seeMaking a Connection.
“Exceptional conditions” does not mean errors—errors are reportedimmediately when an erroneous system call is executed, and do notconstitute a state of the descriptor. Rather, they include conditionssuch as the presence of an urgent message on a socket. (SeeSockets,for information on urgent messages.)
Theselect
function checks only the firstnfds filedescriptors. The usual thing is to passFD_SETSIZE
as the valueof this argument.
Thetimeout specifies the maximum time to wait. If you pass anull pointer for this argument, it means to block indefinitely untilone of the file descriptors is ready. Otherwise, you should providethe time instruct timeval
format; seeTime Types.Specify zero as the time (astruct timeval
containing allzeros) if you want to find out which descriptors are ready withoutwaiting if none are ready.
The normal return value fromselect
is the total number of ready filedescriptors in all of the sets. Each of the argument sets is overwrittenwith information about the descriptors that are ready for the correspondingoperation. Thus, to see if a particular descriptordesc has input,useFD_ISSET (desc,read-fds)
afterselect
returns.
Ifselect
returns because the timeout period expires, it returnsa value of zero.
Any signal will causeselect
to return immediately. So if yourprogram uses signals, you can’t rely onselect
to keep waitingfor the full time specified. If you want to be sure of waiting for aparticular amount of time, you must check forEINTR
and repeattheselect
with a newly calculated timeout based on the currenttime. See the example below. See alsoPrimitives Interrupted by Signals.
If an error occurs,select
returns-1
and does not modifythe argument file descriptor sets. The followingerrno
errorconditions are defined for this function:
EBADF
One of the file descriptor sets specified an invalid file descriptor.
EINTR
The operation was interrupted by a signal. SeePrimitives Interrupted by Signals.
EINVAL
Thetimeout argument is invalid; one of the components is negativeor too large.
Portability Note: Theselect
function is a BSD Unixfeature.
Here is an example showing how you can useselect
to establish atimeout period for reading from a file descriptor. Theinput_timeout
function blocks the calling process until input is available on thefile descriptor, or until the timeout period expires.
#include <errno.h>#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <sys/time.h>
intinput_timeout (int filedes, unsigned int seconds){ fd_set set; struct timeval timeout;
/*Initialize the file descriptor set. */ FD_ZERO (&set); FD_SET (filedes, &set); /*Initialize the timeout data structure. */ timeout.tv_sec = seconds; timeout.tv_usec = 0;
/*select
returns 0 if timeout, 1 if input available, -1 if error. */ return TEMP_FAILURE_RETRY (select (FD_SETSIZE, &set, NULL, NULL, &timeout));}
intmain (void){ fprintf (stderr, "select returned %d.\n", input_timeout (STDIN_FILENO, 5)); return 0;}
There is another example showing the use ofselect
to multiplexinput from multiple sockets inByte Stream Connection Server Example.
For an alternate interface to this functionality, seepoll
(seeOther low-level-I/O-related functions).
Next:Perform I/O Operations in Parallel, Previous:Waiting for Input or Output, Up:Low-Level Input/Output [Contents][Index]
In most modern operating systems, the normal I/O operations are notexecuted synchronously. I.e., even if awrite
system callreturns, this does not mean the data is actually written to the media,e.g., the disk.
In situations where synchronization points are necessary, you can usespecial functions which ensure that all operations finish beforethey return.
void
sync(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
A call to this function will not return as long as there is data whichhas not been written to the device. All dirty buffers in the kernel willbe written and so an overall consistent system can be achieved (if noother process in parallel writes data).
A prototype forsync
can be found inunistd.h.
Programs more often want to ensure that data written to a given file iscommitted, rather than all data in the system. For this,sync
is overkill.
int
fsync(intfildes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefsync
function can be used to make sure all data associated withthe open filefildes is written to the device associated with thedescriptor. The function call does not return unless all actions havefinished.
A prototype forfsync
can be found inunistd.h.
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timefsync
iscalled. If the thread gets canceled these resources stay allocateduntil the program ends. To avoid this, calls tofsync
should beprotected using cancellation handlers.
The return value of the function is zero if no error occurred. Otherwiseit is-1 and the global variableerrno
is set to thefollowing values:
EBADF
The descriptorfildes is not valid.
EINVAL
No synchronization is possible since the system does not implement this.
Sometimes it is not even necessary to write all data associated with afile descriptor. E.g., in database files which do not change in size itis enough to write all the file content data to the device.Meta-information, like the modification time etc., are not that importantand leaving such information uncommitted does not prevent a successfulrecovery of the file in case of a problem.
int
fdatasync(intfildes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
When a call to thefdatasync
function returns, it is ensuredthat all of the file data is written to the device. For all pending I/Ooperations, the parts guaranteeing data integrity finished.
Not all systems implement thefdatasync
operation. On systemsmissing this functionalityfdatasync
is emulated by a call tofsync
since the performed actions are a superset of thoserequired byfdatasync
.
The prototype forfdatasync
is inunistd.h.
The return value of the function is zero if no error occurred. Otherwiseit is-1 and the global variableerrno
is set to thefollowing values:
EBADF
The descriptorfildes is not valid.
EINVAL
No synchronization is possible since the system does not implement this.
Next:Control Operations on Files, Previous:Synchronizing I/O operations, Up:Low-Level Input/Output [Contents][Index]
The POSIX.1b standard defines a new set of I/O operations which cansignificantly reduce the time an application spends waiting for I/O. Thenew functions allow a program to initiate one or more I/O operations andthen immediately resume normal work while the I/O operations areexecuted in parallel. This functionality is available if theunistd.h file defines the symbol_POSIX_ASYNCHRONOUS_IO
.
These functions are part of the library with realtime functions namedlibrt. They are not actually part of thelibc binary.The implementation of these functions can be done using support in thekernel (if available) or using an implementation based on threads atuserlevel. In the latter case it might be necessary to link applicationswith the thread librarylibpthread in addition tolibrt.
All AIO operations operate on files which were opened previously. Theremight be arbitrarily many operations running for one file. Theasynchronous I/O operations are controlled using a data structure namedstruct aiocb
(AIO control block). It is defined inaio.h as follows.
The POSIX.1b standard mandates that thestruct aiocb
structurecontains at least the members described in the following table. Theremight be more elements which are used by the implementation, butdepending upon these elements is not portable and is highly deprecated.
int aio_fildes
This element specifies the file descriptor to be used for theoperation. It must be a legal descriptor, otherwise the operation willfail.
The device on which the file is opened must allow the seek operation.I.e., it is not possible to use any of the AIO operations on deviceslike terminals where anlseek
call would lead to an error.
off_t aio_offset
This element specifies the offset in the file at which the operation (inputor output) is performed. Since the operations are carried out in arbitraryorder and more than one operation for one file descriptor can bestarted, one cannot expect a current read/write position of the filedescriptor.
volatile void *aio_buf
This is a pointer to the buffer with the data to be written or the placewhere the read data is stored.
size_t aio_nbytes
This element specifies the length of the buffer pointed to byaio_buf
.
int aio_reqprio
If the platform has defined_POSIX_PRIORITIZED_IO
and_POSIX_PRIORITY_SCHEDULING
, the AIO requests areprocessed based on the current scheduling priority. Theaio_reqprio
element can then be used to lower the priority of theAIO operation.
struct sigevent aio_sigevent
This element specifies how the calling process is notified once theoperation terminates. If thesigev_notify
element isSIGEV_NONE
, no notification is sent. If it isSIGEV_SIGNAL
,the signal determined bysigev_signo
is sent. Otherwise,sigev_notify
must beSIGEV_THREAD
. In this case, a threadis created which starts executing the function pointed to bysigev_notify_function
.
int aio_lio_opcode
This element is only used by thelio_listio
andlio_listio64
functions. Since these functions allow anarbitrary number of operations to start at once, and each operation can beinput or output (or nothing), the information must be stored in thecontrol block. The possible values are:
LIO_READ
¶Start a read operation. Read from the file at positionaio_offset
and store the nextaio_nbytes
bytes in thebuffer pointed to byaio_buf
.
LIO_WRITE
¶Start a write operation. Writeaio_nbytes
bytes starting ataio_buf
into the file starting at positionaio_offset
.
LIO_NOP
¶Do nothing for this control block. This value is useful sometimes whenan array ofstruct aiocb
values contains holes, i.e., some of thevalues must not be handled although the whole array is presented to thelio_listio
function.
When the sources are compiled using_FILE_OFFSET_BITS == 64
on a32 bit machine, this type is in factstruct aiocb64
, since the LFSinterface transparently replaces thestruct aiocb
definition.
For use with the AIO functions defined in the LFS, there is a similar typedefined which replaces the types of the appropriate members with largertypes but otherwise is equivalent tostruct aiocb
. Particularly,all member names are the same.
int aio_fildes
This element specifies the file descriptor which is used for theoperation. It must be a legal descriptor since otherwise the operationfails for obvious reasons.
The device on which the file is opened must allow the seek operation.I.e., it is not possible to use any of the AIO operations on deviceslike terminals where anlseek
call would lead to an error.
off64_t aio_offset
This element specifies at which offset in the file the operation (inputor output) is performed. Since the operation are carried in arbitraryorder and more than one operation for one file descriptor can bestarted, one cannot expect a current read/write position of the filedescriptor.
volatile void *aio_buf
This is a pointer to the buffer with the data to be written or the placewhere the read data is stored.
size_t aio_nbytes
This element specifies the length of the buffer pointed to byaio_buf
.
int aio_reqprio
If for the platform_POSIX_PRIORITIZED_IO
and_POSIX_PRIORITY_SCHEDULING
are defined the AIO requests areprocessed based on the current scheduling priority. Theaio_reqprio
element can then be used to lower the priority of theAIO operation.
struct sigevent aio_sigevent
This element specifies how the calling process is notified once theoperation terminates. If thesigev_notify
element isSIGEV_NONE
no notification is sent. If it isSIGEV_SIGNAL
,the signal determined bysigev_signo
is sent. Otherwise,sigev_notify
must beSIGEV_THREAD
in which case a threadis created which starts executing the function pointed to bysigev_notify_function
.
int aio_lio_opcode
This element is only used by thelio_listio
andlio_listio64
functions. Since these functions allow anarbitrary number of operations to start at once, and since each operation can beinput or output (or nothing), the information must be stored in thecontrol block. See the description ofstruct aiocb
for a descriptionof the possible values.
When the sources are compiled using_FILE_OFFSET_BITS == 64
on a32 bit machine, this type is available under the namestructaiocb64
, since the LFS transparently replaces the old interface.
int
aio_read(struct aiocb *aiocbp)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
This function initiates an asynchronous read operation. Itimmediately returns after the operation was enqueued or when anerror was encountered.
The firstaiocbp->aio_nbytes
bytes of the file for whichaiocbp->aio_fildes
is a descriptor are written to the bufferstarting ataiocbp->aio_buf
. Reading starts at the absolutepositionaiocbp->aio_offset
in the file.
If prioritized I/O is supported by the platform theaiocbp->aio_reqprio
value is used to adjust the priority beforethe request is actually enqueued.
The calling process is notified about the termination of the readrequest according to theaiocbp->aio_sigevent
value.
Whenaio_read
returns, the return value is zero if no erroroccurred that can be found before the process is enqueued. If such anearly error is found, the function returns-1 and setserrno
to one of the following values:
EAGAIN
The request was not enqueued due to (temporarily) exceeded resourcelimitations.
ENOSYS
Theaio_read
function is not implemented.
EBADF
Theaiocbp->aio_fildes
descriptor is not valid. This conditionneed not be recognized before enqueueing the request and so this errormight also be signaled asynchronously.
EINVAL
Theaiocbp->aio_offset
oraiocbp->aio_reqpiro
value isinvalid. This condition need not be recognized before enqueueing therequest and so this error might also be signaled asynchronously.
Ifaio_read
returns zero, the current status of the requestcan be queried usingaio_error
andaio_return
functions.As long as the value returned byaio_error
isEINPROGRESS
the operation has not yet completed. Ifaio_error
returns zero,the operation successfully terminated, otherwise the value is to beinterpreted as an error code. If the function terminated, the result ofthe operation can be obtained using a call toaio_return
. Thereturned value is the same as an equivalent call toread
wouldhave returned. Possible error codes returned byaio_error
are:
EBADF
Theaiocbp->aio_fildes
descriptor is not valid.
ECANCELED
The operation was canceled before the operation was finished(seeCancellation of AIO Operations)
EINVAL
Theaiocbp->aio_offset
value is invalid.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is in factaio_read64
since the LFS interface transparentlyreplaces the normal implementation.
int
aio_read64(struct aiocb64 *aiocbp)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
This function is similar to theaio_read
function. The onlydifference is that on 32 bit machines, the file descriptor shouldbe opened in the large file mode. Internally,aio_read64
usesfunctionality equivalent tolseek64
(seeSetting the File Position of a Descriptor) to position the file descriptor correctly for the reading,as opposed to thelseek
functionality used inaio_read
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
, thisfunction is available under the nameaio_read
and so transparentlyreplaces the interface for small files on 32 bit machines.
To write data asynchronously to a file, there exists an equivalent pairof functions with a very similar interface.
int
aio_write(struct aiocb *aiocbp)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
This function initiates an asynchronous write operation. The functioncall immediately returns after the operation was enqueued or if beforethis happens an error was encountered.
The firstaiocbp->aio_nbytes
bytes from the buffer starting ataiocbp->aio_buf
are written to the file for whichaiocbp->aio_fildes
is a descriptor, starting at the absolutepositionaiocbp->aio_offset
in the file.
If prioritized I/O is supported by the platform, theaiocbp->aio_reqprio
value is used to adjust the priority beforethe request is actually enqueued.
The calling process is notified about the termination of the readrequest according to theaiocbp->aio_sigevent
value.
Whenaio_write
returns, the return value is zero if no erroroccurred that can be found before the process is enqueued. If such anearly error is found the function returns-1 and setserrno
to one of the following values.
EAGAIN
The request was not enqueued due to (temporarily) exceeded resourcelimitations.
ENOSYS
Theaio_write
function is not implemented.
EBADF
Theaiocbp->aio_fildes
descriptor is not valid. This conditionmay not be recognized before enqueueing the request, and so this errormight also be signaled asynchronously.
EINVAL
Theaiocbp->aio_offset
oraiocbp->aio_reqprio
value isinvalid. This condition may not be recognized before enqueueing therequest and so this error might also be signaled asynchronously.
In the caseaio_write
returns zero, the current status of therequest can be queried using theaio_error
andaio_return
functions. As long as the value returned byaio_error
isEINPROGRESS
the operation has not yet completed. Ifaio_error
returns zero, the operation successfully terminated,otherwise the value is to be interpreted as an error code. If thefunction terminated, the result of the operation can be obtained using a calltoaio_return
. The returned value is the same as an equivalentcall toread
would have returned. Possible error codes returnedbyaio_error
are:
EBADF
Theaiocbp->aio_fildes
descriptor is not valid.
ECANCELED
The operation was canceled before the operation was finished.(seeCancellation of AIO Operations)
EINVAL
Theaiocbp->aio_offset
value is invalid.
When the sources are compiled with_FILE_OFFSET_BITS == 64
, thisfunction is in factaio_write64
since the LFS interface transparentlyreplaces the normal implementation.
int
aio_write64(struct aiocb64 *aiocbp)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
This function is similar to theaio_write
function. The onlydifference is that on 32 bit machines the file descriptor shouldbe opened in the large file mode. Internallyaio_write64
usesfunctionality equivalent tolseek64
(seeSetting the File Position of a Descriptor) to position the file descriptor correctly for the writing,as opposed to thelseek
functionality used inaio_write
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
, thisfunction is available under the nameaio_write
and so transparentlyreplaces the interface for small files on 32 bit machines.
Besides these functions with the more or less traditional interface,POSIX.1b also defines a function which can initiate more than oneoperation at a time, and which can handle freely mixed read and writeoperations. It is therefore similar to a combination ofreadv
andwritev
.
int
lio_listio(intmode, struct aiocb *constlist[], intnent, struct sigevent *sig)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
Thelio_listio
function can be used to enqueue an arbitrarynumber of read and write requests at one time. The requests can all bemeant for the same file, all for different files or every solution inbetween.
lio_listio
gets thenent requests from the array pointed tobylist. The operation to be performed is determined by theaio_lio_opcode
member in each element oflist. If thisfield isLIO_READ
a read operation is enqueued, similar to a callofaio_read
for this element of the array (except that the waythe termination is signalled is different, as we will see below). Iftheaio_lio_opcode
member isLIO_WRITE
a write operationis enqueued. Otherwise theaio_lio_opcode
must beLIO_NOP
in which case this element oflist is simply ignored. This“operation” is useful in situations where one has a fixed array ofstruct aiocb
elements from which only a few need to be handled ata time. Another situation is where thelio_listio
call wascanceled before all requests are processed (seeCancellation of AIO Operations) and the remaining requests have to be reissued.
The other members of each element of the array pointed to bylist
must have values suitable for the operation as described inthe documentation foraio_read
andaio_write
above.
Themode argument determines howlio_listio
behaves afterhaving enqueued all the requests. Ifmode isLIO_WAIT
itwaits until all requests terminated. Otherwisemode must beLIO_NOWAIT
and in this case the function returns immediately afterhaving enqueued all the requests. In this case the caller gets anotification of the termination of all requests according to thesig parameter. Ifsig isNULL
no notification issent. Otherwise a signal is sent or a thread is started, just asdescribed in the description foraio_read
oraio_write
.
Ifmode isLIO_WAIT
, the return value oflio_listio
is0 when all requests completed successfully. Otherwise thefunction returns-1 anderrno
is set accordingly. To findout which request or requests failed one has to use theaio_error
function on all the elements of the arraylist.
In casemode isLIO_NOWAIT
, the function returns0 ifall requests were enqueued correctly. The current state of the requestscan be found usingaio_error
andaio_return
as describedabove. Iflio_listio
returns-1 in this mode, theglobal variableerrno
is set accordingly. If a request did notyet terminate, a call toaio_error
returnsEINPROGRESS
. Ifthe value is different, the request is finished and the error value (or0) is returned and the result of the operation can be retrievedusingaio_return
.
Possible values forerrno
are:
EAGAIN
The resources necessary to queue all the requests are not available atthe moment. The error status for each element oflist must bechecked to determine which request failed.
Another reason could be that the system wide limit of AIO requests isexceeded. This cannot be the case for the implementation on GNU systemssince no arbitrary limits exist.
EINVAL
Themode parameter is invalid ornent is larger thanAIO_LISTIO_MAX
.
EIO
One or more of the request’s I/O operations failed. The error status ofeach request should be checked to determine which one failed.
ENOSYS
Thelio_listio
function is not supported.
If themode parameter isLIO_NOWAIT
and the caller cancelsa request, the error status for this request returned byaio_error
isECANCELED
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
, thisfunction is in factlio_listio64
since the LFS interfacetransparently replaces the normal implementation.
int
lio_listio64(intmode, struct aiocb64 *constlist[], intnent, struct sigevent *sig)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
This function is similar to thelio_listio
function. The onlydifference is that on 32 bit machines, the file descriptor shouldbe opened in the large file mode. Internally,lio_listio64
usesfunctionality equivalent tolseek64
(seeSetting the File Position of a Descriptor) to position the file descriptor correctly for the reading orwriting, as opposed to thelseek
functionality used inlio_listio
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
, thisfunction is available under the namelio_listio
and sotransparently replaces the interface for small files on 32 bitmachines.
Next:Getting into a Consistent State, Previous:Asynchronous Read and Write Operations, Up:Perform I/O Operations in Parallel [Contents][Index]
As already described in the documentation of the functions in the lastsection, it must be possible to get information about the status of an I/Orequest. When the operation is performed truly asynchronously (as withaio_read
andaio_write
and withlio_listio
when themode isLIO_NOWAIT
), one sometimes needs to know whether aspecific request already terminated and if so, what the result was.The following two functions allow you to get this kind of information.
int
aio_error(const struct aiocb *aiocbp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function determines the error state of the request described by thestruct aiocb
variable pointed to byaiocbp. If therequest has not yet terminated the value returned is alwaysEINPROGRESS
. Once the request has terminated the valueaio_error
returns is either0 if the request completedsuccessfully or it returns the value which would be stored in theerrno
variable if the request would have been done usingread
,write
, orfsync
.
The function can returnENOSYS
if it is not implemented. Itcould also returnEINVAL
if theaiocbp parameter does notrefer to an asynchronous operation whose return status is not yet known.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is in factaio_error64
since the LFS interfacetransparently replaces the normal implementation.
int
aio_error64(const struct aiocb64 *aiocbp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar toaio_error
with the only differencethat the argument is a reference to a variable of typestructaiocb64
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is available under the nameaio_error
and sotransparently replaces the interface for small files on 32 bitmachines.
ssize_t
aio_return(struct aiocb *aiocbp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function can be used to retrieve the return status of the operationcarried out by the request described in the variable pointed to byaiocbp. As long as the error status of this request as returnedbyaio_error
isEINPROGRESS
the return value of this function isundefined.
Once the request is finished this function can be used exactly once toretrieve the return value. Following calls might lead to undefinedbehavior. The return value itself is the value which would have beenreturned by theread
,write
, orfsync
call.
The function can returnENOSYS
if it is not implemented. Itcould also returnEINVAL
if theaiocbp parameter does notrefer to an asynchronous operation whose return status is not yet known.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is in factaio_return64
since the LFS interfacetransparently replaces the normal implementation.
ssize_t
aio_return64(struct aiocb64 *aiocbp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar toaio_return
with the only differencethat the argument is a reference to a variable of typestructaiocb64
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is available under the nameaio_return
and sotransparently replaces the interface for small files on 32 bitmachines.
Next:Cancellation of AIO Operations, Previous:Getting the Status of AIO Operations, Up:Perform I/O Operations in Parallel [Contents][Index]
When dealing with asynchronous operations it is sometimes necessary toget into a consistent state. This would mean for AIO that one wants toknow whether a certain request or a group of requests were processed.This could be done by waiting for the notification sent by the systemafter the operation terminated, but this sometimes would mean wastingresources (mainly computation time). Instead POSIX.1b defines twofunctions which will help with most kinds of consistency.
Theaio_fsync
andaio_fsync64
functions are only availableif the symbol_POSIX_SYNCHRONIZED_IO
is defined inunistd.h.
int
aio_fsync(intop, struct aiocb *aiocbp)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
Calling this function forces all I/O operations queued at thetime of the function call operating on the file descriptoraiocbp->aio_fildes
into the synchronized I/O completion state(seeSynchronizing I/O operations). Theaio_fsync
function returnsimmediately but the notification through the method described inaiocbp->aio_sigevent
will happen only after all requests for thisfile descriptor have terminated and the file is synchronized. This alsomeans that requests for this very same file descriptor which are queuedafter the synchronization request are not affected.
Ifop isO_DSYNC
the synchronization happens as with a calltofdatasync
. Otherwiseop should beO_SYNC
andthe synchronization happens as withfsync
.
As long as the synchronization has not happened, a call toaio_error
with the reference to the object pointed to byaiocbp returnsEINPROGRESS
. Once the synchronization isdoneaio_error
return0 if the synchronization was notsuccessful. Otherwise the value returned is the value to which thefsync
orfdatasync
function would have set theerrno
variable. In this case nothing can be assumed about theconsistency of the data written to this file descriptor.
The return value of this function is0 if the request wassuccessfully enqueued. Otherwise the return value is-1 anderrno
is set to one of the following values:
EAGAIN
The request could not be enqueued due to temporary lack of resources.
EBADF
The file descriptoraiocbp->aio_fildes
is not valid.
EINVAL
The implementation does not support I/O synchronization or theopparameter is other thanO_DSYNC
andO_SYNC
.
ENOSYS
This function is not implemented.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is in factaio_fsync64
since the LFS interfacetransparently replaces the normal implementation.
int
aio_fsync64(intop, struct aiocb64 *aiocbp)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
This function is similar toaio_fsync
with the only differencethat the argument is a reference to a variable of typestructaiocb64
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is available under the nameaio_fsync
and sotransparently replaces the interface for small files on 32 bitmachines.
Another method of synchronization is to wait until one or more requests of aspecific set terminated. This could be achieved by theaio_*
functions to notify the initiating process about the termination but insome situations this is not the ideal solution. In a program whichconstantly updates clients somehow connected to the server it is notalways the best solution to go round robin since some connections mightbe slow. On the other hand letting theaio_*
functions notify thecaller might also be not the best solution since whenever the processworks on preparing data for a client it makes no sense to beinterrupted by a notification since the new client will not be handledbefore the current client is served. For situations like thisaio_suspend
should be used.
int
aio_suspend(const struct aiocb *constlist[], intnent, const struct timespec *timeout)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
When calling this function, the calling thread is suspended until atleast one of the requests pointed to by thenent elements of thearraylist has completed. If any of the requests has alreadycompleted at the timeaio_suspend
is called, the function returnsimmediately. Whether a request has terminated or not is determined bycomparing the error status of the request withEINPROGRESS
. Ifan element oflist isNULL
, the entry is simply ignored.
If no request has finished, the calling process is suspended. Iftimeout isNULL
, the process is not woken until a requesthas finished. Iftimeout is notNULL
, the process remainssuspended at least as long as specified intimeout. In this case,aio_suspend
returns with an error.
The return value of the function is0 if one or more requestsfrom thelist have terminated. Otherwise the function returns-1 anderrno
is set to one of the following values:
EAGAIN
None of the requests from thelist completed in the time specifiedbytimeout.
EINTR
A signal interrupted theaio_suspend
function. This signal mightalso be sent by the AIO implementation while signalling the terminationof one of the requests.
ENOSYS
Theaio_suspend
function is not implemented.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is in factaio_suspend64
since the LFS interfacetransparently replaces the normal implementation.
int
aio_suspend64(const struct aiocb64 *constlist[], intnent, const struct timespec *timeout)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function is similar toaio_suspend
with the only differencethat the argument is a reference to a variable of typestructaiocb64
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is available under the nameaio_suspend
and sotransparently replaces the interface for small files on 32 bitmachines.
Next:How to optimize the AIO implementation, Previous:Getting into a Consistent State, Up:Perform I/O Operations in Parallel [Contents][Index]
When one or more requests are asynchronously processed, it might beuseful in some situations to cancel a selected operation, e.g., if itbecomes obvious that the written data is no longer accurate and wouldhave to be overwritten soon. As an example, assume an application, whichwrites data in files in a situation where new incoming data would haveto be written in a file which will be updated by an enqueued request.The POSIX AIO implementation provides such a function, but this functionis not capable of forcing the cancellation of the request. It is up to theimplementation to decide whether it is possible to cancel the operationor not. Therefore using this function is merely a hint.
int
aio_cancel(intfildes, struct aiocb *aiocbp)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
Theaio_cancel
function can be used to cancel one or moreoutstanding requests. If theaiocbp parameter isNULL
, thefunction tries to cancel all of the outstanding requests which would processthe file descriptorfildes (i.e., whoseaio_fildes
memberisfildes). Ifaiocbp is notNULL
,aio_cancel
attempts to cancel the specific request pointed to byaiocbp.
For requests which were successfully canceled, the normal notificationabout the termination of the request should take place. I.e., dependingon thestruct sigevent
object which controls this, nothinghappens, a signal is sent or a thread is started. If the request cannotbe canceled, it terminates the usual way after performing the operation.
After a request is successfully canceled, a call toaio_error
witha reference to this request as the parameter will returnECANCELED
and a call toaio_return
will return-1.If the request wasn’t canceled and is still running the error status isstillEINPROGRESS
.
The return value of the function isAIO_CANCELED
if there wererequests which haven’t terminated and which were successfully canceled.If there is one or more requests left which couldn’t be canceled, thereturn value isAIO_NOTCANCELED
. In this caseaio_error
must be used to find out which of the, perhaps multiple, requests (ifaiocbp isNULL
) weren’t successfully canceled. If allrequests already terminated at the timeaio_cancel
is called thereturn value isAIO_ALLDONE
.
If an error occurred during the execution ofaio_cancel
thefunction returns-1 and setserrno
to one of the followingvalues.
EBADF
The file descriptorfildes is not valid.
ENOSYS
aio_cancel
is not implemented.
When the sources are compiled with_FILE_OFFSET_BITS == 64
, thisfunction is in factaio_cancel64
since the LFS interfacetransparently replaces the normal implementation.
int
aio_cancel64(intfildes, struct aiocb64 *aiocbp)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
This function is similar toaio_cancel
with the only differencethat the argument is a reference to a variable of typestructaiocb64
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
, thisfunction is available under the nameaio_cancel
and sotransparently replaces the interface for small files on 32 bitmachines.
The POSIX standard does not specify how the AIO functions areimplemented. They could be system calls, but it is also possible toemulate them at userlevel.
At the time of writing, the available implementation is a user-levelimplementation which uses threads for handling the enqueued requests.While this implementation requires making some decisions aboutlimitations, hard limitations are something best avoidedin the GNU C Library. Therefore, the GNU C Library provides a meansfor tuning the AIO implementation according to the individual use.
This data type is used to pass the configuration or tunable parametersto the implementation. The program has to initialize the members ofthis struct and pass it to the implementation using theaio_init
function.
int aio_threads
This member specifies the maximal number of threads which may be usedat any one time.
int aio_num
This number provides an estimate on the maximal number of simultaneouslyenqueued requests.
int aio_locks
Unused.
int aio_usedba
Unused.
int aio_debug
Unused.
int aio_numusers
Unused.
int aio_reserved[2]
Unused.
void
aio_init(const struct aioinit *init)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function must be called before any other AIO function. Calling itis completely voluntary, as it is only meant to help the AIOimplementation perform better.
Before callingaio_init
, the members of a variable oftypestruct aioinit
must be initialized. Then a reference tothis variable is passed as the parameter toaio_init
which itselfmay or may not pay attention to the hints.
The function has no return value and no error cases are defined. It isan extension which follows a proposal from the SGI implementation inIrix 6. It is not covered by POSIX.1b or Unix98.
Next:Duplicating Descriptors, Previous:Perform I/O Operations in Parallel, Up:Low-Level Input/Output [Contents][Index]
This section describes how you can perform various other operations onfile descriptors, such as inquiring about or setting flags describingthe status of the file descriptor, manipulating record locks, and thelike. All of these operations are performed by the functionfcntl
.
The second argument to thefcntl
function is a command thatspecifies which operation to perform. The function and macros that namevarious flags that are used with it are declared in the header filefcntl.h. Many of these flags are also used by theopen
function; seeOpening and Closing Files.
int
fcntl(intfiledes, intcommand, …)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefcntl
function performs the operation specified bycommand on the file descriptorfiledes. Some commandsrequire additional arguments to be supplied. These additional argumentsand the return value and error conditions are given in the detaileddescriptions of the individual commands.
Briefly, here is a list of what the various commands are. For anexhaustive list of kernel-specific options, please see SeeSystem Calls.
F_DUPFD
¶Duplicate the file descriptor (return another file descriptor pointingto the same open file). SeeDuplicating Descriptors.
F_GETFD
¶Get flags associated with the file descriptor. SeeFile Descriptor Flags.
F_SETFD
¶Set flags associated with the file descriptor. SeeFile Descriptor Flags.
F_GETFL
¶Get flags associated with the open file. SeeFile Status Flags.
F_SETFL
¶Set flags associated with the open file. SeeFile Status Flags.
F_GETLK
¶Test a file lock. SeeFile Locks.
F_SETLK
¶Set or clear a file lock. SeeFile Locks.
F_SETLKW
¶LikeF_SETLK
, but wait for completion. SeeFile Locks.
F_OFD_GETLK
¶Test an open file description lock. SeeOpen File Description Locks.Specific to Linux.
F_OFD_SETLK
¶Set or clear an open file description lock. SeeOpen File Description Locks.Specific to Linux.
F_OFD_SETLKW
¶LikeF_OFD_SETLK
, but block until lock is acquired.SeeOpen File Description Locks. Specific to Linux.
F_GETOWN
¶Get process or process group ID to receiveSIGIO
signals.SeeInterrupt-Driven Input.
F_SETOWN
¶Set process or process group ID to receiveSIGIO
signals.SeeInterrupt-Driven Input.
This function is a cancellation point in multi-threaded programs for thecommandsF_SETLKW
(and the LFS analogousF_SETLKW64
) andF_OFD_SETLKW
. This is a problem if the thread allocates someresources (like memory, file descriptors, semaphores or whatever) at the timefcntl
is called. If the thread gets canceled these resources stayallocated until the program ends. To avoid this calls tofcntl
shouldbe protected using cancellation handlers.
Next:File Descriptor Flags, Previous:Control Operations on Files, Up:Low-Level Input/Output [Contents][Index]
You canduplicate a file descriptor, or allocate another filedescriptor that refers to the same open file as the original. Duplicatedescriptors share one file position and one set of file status flags(seeFile Status Flags), but each has its own set of file descriptorflags (seeFile Descriptor Flags).
The major use of duplicating a file descriptor is to implementredirection of input or output: that is, to change thefile or pipe that a particular file descriptor corresponds to.
You can perform this operation using thefcntl
function with theF_DUPFD
command, but there are also convenient functionsdup
anddup2
for duplicating descriptors.
Thefcntl
function and flags are declared infcntl.h,while prototypes fordup
anddup2
are in the header fileunistd.h.
int
dup(intold)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function copies descriptorold to the first availabledescriptor number (the first number not currently open). It isequivalent tofcntl (old, F_DUPFD, 0)
.
int
dup2(intold, intnew)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function copies the descriptorold to descriptor numbernew.
Ifold is an invalid descriptor, thendup2
does nothing; itdoes not closenew. Otherwise, the new duplicate ofoldreplaces any previous meaning of descriptornew, as ifnewwere closed first.
Ifold andnew are different numbers, andold is avalid descriptor number, thendup2
is equivalent to:
close (new);fcntl (old, F_DUPFD,new)
However,dup2
does this atomically; there is no instant in themiddle of callingdup2
at whichnew is closed and not yet aduplicate ofold.
int
dup3(intold, intnew, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is the same asdup2
but creates the newdescriptor as if it had been opened with flagsflags. The onlyallowed flag isO_CLOEXEC
.
This function was originally a Linux extension, but was added inPOSIX.1-2024.
int
F_DUPFD ¶This macro is used as thecommand argument tofcntl
, tocopy the file descriptor given as the first argument.
The form of the call in this case is:
fcntl (old, F_DUPFD,next-filedes)
Thenext-filedes argument is of typeint
and specifies thatthe file descriptor returned should be the next available one greaterthan or equal to this value.
The return value fromfcntl
with this command is normally the valueof the new file descriptor. A return value of-1 indicates anerror. The followingerrno
error conditions are defined forthis command:
EBADF
Theold argument is invalid.
EINVAL
Thenext-filedes argument is invalid.
EMFILE
There are no more file descriptors available—your program is alreadyusing the maximum. In BSD and GNU, the maximum is controlled by aresource limit that can be changed; seeLimiting Resource Usage, formore information about theRLIMIT_NOFILE
limit.
ENFILE
is not a possible error code fordup2
becausedup2
does not create a new opening of a file; duplicatedescriptors do not count toward the limit whichENFILE
indicates.EMFILE
is possible because it refers to the limit ondistinct descriptor numbers in use in one process.
Here is an example showing how to usedup2
to do redirection.Typically, redirection of the standard streams (likestdin
) isdone by a shell or shell-like program before calling one of theexec
functions (seeExecuting a File) to execute a newprogram in a child process. When the new program is executed, itcreates and initializes the standard streams to point to thecorresponding file descriptors, before itsmain
function isinvoked.
So, to redirect standard input to a file, the shell could do somethinglike:
pid = fork ();if (pid == 0) { char *filename; char *program; int file; ... file = TEMP_FAILURE_RETRY (open (filename, O_RDONLY)); dup2 (file, STDIN_FILENO); TEMP_FAILURE_RETRY (close (file)); execv (program, NULL); }
There is also a more detailed example showing how to implement redirectionin the context of a pipeline of processes inLaunching Jobs.
Next:File Status Flags, Previous:Duplicating Descriptors, Up:Low-Level Input/Output [Contents][Index]
File descriptor flags are miscellaneous attributes of a filedescriptor. These flags are associated with particular filedescriptors, so that if you have created duplicate file descriptorsfrom a single opening of a file, each descriptor has its own set of flags.
Currently there is just one file descriptor flag:FD_CLOEXEC
,which causes the descriptor to be closed if you use any of theexec…
functions (seeExecuting a File).
The symbols in this section are defined in the header filefcntl.h.
int
F_GETFD ¶This macro is used as thecommand argument tofcntl
, tospecify that it should return the file descriptor flags associatedwith thefiledes argument.
The normal return value fromfcntl
with this command is anonnegative number which can be interpreted as the bitwise OR of theindividual flags (except that currently there is only one flag to use).
In case of an error,fcntl
returns-1. The followingerrno
error conditions are defined for this command:
EBADF
Thefiledes argument is invalid.
int
F_SETFD ¶This macro is used as thecommand argument tofcntl
, tospecify that it should set the file descriptor flags associated with thefiledes argument. This requires a thirdint
argument tospecify the new flags, so the form of the call is:
fcntl (filedes, F_SETFD,new-flags)
The normal return value fromfcntl
with this command is anunspecified value other than-1, which indicates an error.The flags and error conditions are the same as for theF_GETFD
command.
The following macro is defined for use as a file descriptor flag withthefcntl
function. The value is an integer constant usableas a bit mask value.
int
FD_CLOEXEC ¶This flag specifies that the file descriptor should be closed whenanexec
function is invoked; seeExecuting a File. Whena file descriptor is allocated (as withopen
ordup
),this bit is initially cleared on the new file descriptor, meaning thatdescriptor will survive into the new program afterexec
.
If you want to modify the file descriptor flags, you should get thecurrent flags withF_GETFD
and modify the value. Don’t assumethat the flags listed here are the only ones that are implemented; yourprogram may be run years from now and more flags may exist then. Forexample, here is a function to set or clear the flagFD_CLOEXEC
without altering any other flags:
/*Set theFD_CLOEXEC
flag ofdesc ifvalue is nonzero,or clear the flag ifvalue is 0.Return 0 on success, or -1 on error witherrno
set. */intset_cloexec_flag (int desc, int value){ int oldflags = fcntl (desc, F_GETFD, 0); /*If reading the flags failed, return error indication now. */ if (oldflags < 0) return oldflags; /*Set just the flag we want to set. */ if (value != 0) oldflags |= FD_CLOEXEC; else oldflags &= ~FD_CLOEXEC; /*Store modified flag word in the descriptor. */ return fcntl (desc, F_SETFD, oldflags);}
Next:File Locks, Previous:File Descriptor Flags, Up:Low-Level Input/Output [Contents][Index]
File status flags are used to specify attributes of the opening of afile. Unlike the file descriptor flags discussed inFile Descriptor Flags, the file status flags are shared by duplicated file descriptorsresulting from a single opening of the file. The file status flags arespecified with theflags argument toopen
;seeOpening and Closing Files.
File status flags fall into three categories, which are described in thefollowing sections.
open
and arereturned byfcntl
, but cannot be changed.open
will do.These flags are not preserved after theopen
call.read
andwrite
are done. They are set byopen
, and can be fetched orchanged withfcntl
.The symbols in this section are defined in the header filefcntl.h.
Next:Open-time Flags, Up:File Status Flags [Contents][Index]
The file access mode allows a file descriptor to be used for reading,writing, both, or neither. The access mode is determined when the fileis opened, and never change.
int
O_RDONLY ¶Open the file for read access.
int
O_WRONLY ¶Open the file for write access.
int
O_RDWR ¶Open the file for both reading and writing.
int
O_PATH ¶Obtain a file descriptor for the file, but do not open the file forreading or writing. Permission checks for the file itself are skippedwhen the file is opened (but permission to access the directory thatcontains it is still needed), and permissions are checked when thedescriptor is used later on.
For example, such descriptors can be used with thefexecve
function (seeExecuting a File). Other applications involve the‘*at’ function variants, along with theAT_EMPTY_PATH
flag.SeeDescriptor-Relative Access.
This access mode is specific to Linux. On GNU/Hurd systems, it ispossible to useO_EXEC
explicitly, or specify no access modesat all (see below).
The portable file access modesO_RDONLY
,O_WRONLY
, andO_RDWR
may not correspond to individual bits. To determine thefile access mode withfcntl
, you must extract the access modebits from the retrieved file status flags, using theO_ACCMODE
mask.
int
O_ACCMODE ¶This macro is a mask that can be bitwise-ANDed with the file status flagvalue to recover the file access mode, assuming that a standard fileaccess mode is in use.
If a non-standard file access mode is used (such asO_PATH
orO_EXEC
), masking withO_ACCMODE
may give incorrectresults. These non-standard access modes are identified by individualbits and have to be checked directly (without masking withO_ACCMODE
first).
On GNU/Hurd systems (but not on other systems),O_RDONLY
andO_WRONLY
are independent bits that can be bitwise-ORed together,and it is valid for either bit to be set or clear. This means thatO_RDWR
is the same asO_RDONLY|O_WRONLY
. A file accessmode of zero is permissible; it allows no operations that do input oroutput to the file, but does allow other operations such asfchmod
. On GNU/Hurd systems, since “read-only” or “write-only”is a misnomer,fcntl.h defines additional names for the fileaccess modes.
int
O_READ ¶Open the file for reading. Same asO_RDONLY
; only defined on GNU/Hurd.
int
O_WRITE ¶Open the file for writing. Same asO_WRONLY
; only defined on GNU/Hurd.
int
O_EXEC ¶Open the file for executing. Only defined on GNU/Hurd.
Next:I/O Operating Modes, Previous:File Access Modes, Up:File Status Flags [Contents][Index]
The open-time flags specify options affecting howopen
will behave.These options are not preserved once the file is open. The exception tothis isO_NONBLOCK
, which is also an I/O operating mode and so itis saved. SeeOpening and Closing Files, for how to callopen
.
There are two sorts of options specified by open-time flags.
open
looks up thefile name to locate the file, and whether the file can be created.open
willperform on the file once it is open.Here are the file name translation flags.
int
O_CREAT ¶If set, the file will be created if it doesn’t already exist.
int
O_EXCL ¶If bothO_CREAT
andO_EXCL
are set, thenopen
failsif the specified file already exists. This is guaranteed to neverclobber an existing file.
TheO_EXCL
flag has a special meaning in combination withO_TMPFILE
; see below.
int
O_DIRECTORY ¶If set, the open operation fails if the given name is not the name ofa directory. Theerrno
variable is set toENOTDIR
forthis error condition.
int
O_NOFOLLOW ¶If set, the open operation fails if the final component of the file namerefers to a symbolic link. Theerrno
variable is set toELOOP
for this error condition.
int
O_TMPFILE ¶If this flag is specified, functions in theopen
family create anunnamed temporary file. In this case, the pathname argument to theopen
family of functions (seeOpening and Closing Files) isinterpreted as the directory in which the temporary file is created(thus determining the file system which provides the storage for thefile). TheO_TMPFILE
flag must be combined withO_WRONLY
orO_RDWR
, and themode argument is required.
The temporary file can later be given a name usinglinkat
,turning it into a regular file. This allows the atomic creation of afile with the specific file attributes (mode and extended attributes)and file contents. If, for security reasons, it is not desirable that aname can be given to the file, theO_EXCL
flag can be specifiedalong withO_TMPFILE
.
Not all kernels support this open flag. If this flag is unsupported, anattempt to create an unnamed temporary file fails with an error ofEINVAL
. If the underlying file system does not support theO_TMPFILE
flag, anEOPNOTSUPP
error is the result.
TheO_TMPFILE
flag is a GNU extension.
int
O_NONBLOCK ¶This preventsopen
from blocking for a “long time” to open thefile. This is only meaningful for some kinds of files, usually devicessuch as serial ports; when it is not meaningful, it is harmless andignored. Often, opening a port to a modem blocks until the modem reportscarrier detection; ifO_NONBLOCK
is specified,open
willreturn immediately without a carrier.
Note that theO_NONBLOCK
flag is overloaded as both an I/O operatingmode and a file name translation flag. This means that specifyingO_NONBLOCK
inopen
also sets nonblocking I/O mode;seeI/O Operating Modes. To open the file without blocking but do normalI/O that blocks, you must callopen
withO_NONBLOCK
set andthen callfcntl
to turn the bit off.
int
O_NOCTTY ¶If the named file is a terminal device, don’t make it the controllingterminal for the process. SeeJob Control, for information aboutwhat it means to be the controlling terminal.
On GNU/Hurd systems and 4.4 BSD, opening a file never makes it thecontrolling terminal andO_NOCTTY
is zero. However, GNU/Linux systemsand some other systems use a nonzero value forO_NOCTTY
and set thecontrolling terminal when you open a file that is a terminal device; soto be portable, useO_NOCTTY
when it is important to avoid this.
The following three file name translation flags exist only onGNU/Hurd systems.
int
O_IGNORE_CTTY ¶Do not recognize the named file as the controlling terminal, even if itrefers to the process’s existing controlling terminal device. Operationson the new file descriptor will never induce job control signals.SeeJob Control.
int
O_NOLINK ¶If the named file is a symbolic link, open the link itself instead ofthe file it refers to. (fstat
on the new file descriptor willreturn the information returned bylstat
on the link’s name.)
int
O_NOTRANS ¶If the named file is specially translated, do not invoke the translator.Open the bare file the translator itself sees.
The open-time action flags tellopen
to do additional operationswhich are not really related to opening the file. The reason to do themas part ofopen
instead of in separate calls is thatopen
can do thematomically.
int
O_TRUNC ¶Truncate the file to zero length. This option is only useful forregular files, not special files such as directories or FIFOs. POSIX.1requires that you open the file for writing to useO_TRUNC
. InBSD and GNU you must have permission to write the file to truncate it,but you need not open for write access.
This is the only open-time action flag specified by POSIX.1. There isno good reason for truncation to be done byopen
, instead of bycallingftruncate
afterwards. TheO_TRUNC
flag existed inUnix beforeftruncate
was invented, and is retained for backwardcompatibility.
The remaining operating modes are BSD extensions. They exist onlyon some systems. On other systems, these macros are not defined.
int
O_SHLOCK ¶Acquire a shared lock on the file, as withflock
.SeeFile Locks.
IfO_CREAT
is specified, the locking is done atomically whencreating the file. You are guaranteed that no other process will getthe lock on the new file first.
int
O_EXLOCK ¶Acquire an exclusive lock on the file, as withflock
.SeeFile Locks. This is atomic likeO_SHLOCK
.
Next:Getting and Setting File Status Flags, Previous:Open-time Flags, Up:File Status Flags [Contents][Index]
The operating modes affect how input and output operations using a filedescriptor work. These flags are set byopen
and can be fetchedand changed withfcntl
.
int
O_APPEND ¶The bit that enables append mode for the file. If set, then allwrite
operations write the data at the end of the file, extendingit, regardless of the current file position. This is the only reliableway to append to a file. In append mode, you are guaranteed that thedata you write will always go to the current end of the file, regardlessof other processes writing to the file. Conversely, if you simply setthe file position to the end of file and write, then another process canextend the file after you set the file position but before you write,resulting in your data appearing someplace before the real end of file.
int
O_NONBLOCK ¶The bit that enables nonblocking mode for the file. If this bit is set,read
requests on the file can return immediately with a failurestatus if there is no input immediately available, instead of blocking.Likewise,write
requests can also return immediately with afailure status if the output can’t be written immediately.
Note that theO_NONBLOCK
flag is overloaded as both an I/Ooperating mode and a file name translation flag; seeOpen-time Flags.
int
O_NDELAY ¶This is an obsolete name forO_NONBLOCK
, provided forcompatibility with BSD. It is not defined by the POSIX.1 standard.
The remaining operating modes are BSD and GNU extensions. They exist onlyon some systems. On other systems, these macros are not defined.
int
O_ASYNC ¶The bit that enables asynchronous input mode. If set, thenSIGIO
signals will be generated when input is available. SeeInterrupt-Driven Input.
Asynchronous input mode is a BSD feature.
int
O_FSYNC ¶The bit that enables synchronous writing for the file. If set, eachwrite
call will make sure the data is reliably stored on disk beforereturning.
Synchronous writing is a BSD feature.
int
O_SYNC ¶This is another name forO_FSYNC
. They have the same value.
int
O_NOATIME ¶If this bit is set,read
will not update the access time of thefile. SeeFile Times. This is used by programs that do backups, sothat backing a file up does not count as reading it.Only the owner of the file or the superuser may use this bit.
This is a GNU extension.
Previous:I/O Operating Modes, Up:File Status Flags [Contents][Index]
Thefcntl
function can fetch or change file status flags.
int
F_GETFL ¶This macro is used as thecommand argument tofcntl
, toread the file status flags for the open file with descriptorfiledes.
The normal return value fromfcntl
with this command is anonnegative number which can be interpreted as the bitwise OR of theindividual flags. Since the file access modes are not single-bit values,you can mask off other bits in the returned flags withO_ACCMODE
to compare them.
In case of an error,fcntl
returns-1. The followingerrno
error conditions are defined for this command:
EBADF
Thefiledes argument is invalid.
int
F_SETFL ¶This macro is used as thecommand argument tofcntl
, to setthe file status flags for the open file corresponding to thefiledes argument. This command requires a thirdint
argument to specify the new flags, so the call looks like this:
fcntl (filedes, F_SETFL,new-flags)
You can’t change the access mode for the file in this way; that is,whether the file descriptor was opened for reading or writing.
The normal return value fromfcntl
with this command is anunspecified value other than-1, which indicates an error. Theerror conditions are the same as for theF_GETFL
command.
If you want to modify the file status flags, you should get the currentflags withF_GETFL
and modify the value. Don’t assume that theflags listed here are the only ones that are implemented; your programmay be run years from now and more flags may exist then. For example,here is a function to set or clear the flagO_NONBLOCK
withoutaltering any other flags:
/*Set theO_NONBLOCK
flag ofdesc ifvalue is nonzero,or clear the flag ifvalue is 0.Return 0 on success, or -1 on error witherrno
set. */intset_nonblock_flag (int desc, int value){ int oldflags = fcntl (desc, F_GETFL, 0); /*If reading the flags failed, return error indication now. */ if (oldflags == -1) return -1; /*Set just the flag we want to set. */ if (value != 0) oldflags |= O_NONBLOCK; else oldflags &= ~O_NONBLOCK; /*Store modified flag word in the descriptor. */ return fcntl (desc, F_SETFL, oldflags);}
Next:Open File Description Locks, Previous:File Status Flags, Up:Low-Level Input/Output [Contents][Index]
This section describes record locks that are associated with the process.There is also a different type of record lock that is associated with theopen file description instead of the process. SeeOpen File Description Locks.
The remainingfcntl
commands are used to supportrecordlocking, which permits multiple cooperating programs to prevent eachother from simultaneously accessing parts of a file in error-proneways.
Anexclusive orwrite lock gives a process exclusive accessfor writing to the specified part of the file. While a write lock is inplace, no other process can lock that part of the file.
Ashared orread lock prohibits any other process fromrequesting a write lock on the specified part of the file. However,other processes can request read locks.
Theread
andwrite
functions do not actually check to seewhether there are any locks in place. If you want to implement alocking protocol for a file shared by multiple processes, your applicationmust do explicitfcntl
calls to request and clear locks at theappropriate points.
Locks are associated with processes. A process can only have one kindof lock set for each byte of a given file. When any file descriptor forthat file is closed by the process, all of the locks that process holdson that file are released, even if the locks were made using otherdescriptors that remain open. Likewise, locks are released when aprocess exits, and are not inherited by child processes created usingfork
(seeCreating a Process).
When making a lock, use astruct flock
to specify what kind oflock and where. This data type and the associated macros for thefcntl
function are declared in the header filefcntl.h.
This structure is used with thefcntl
function to describe a filelock. It has these members:
short int l_type
Specifies the type of the lock; one ofF_RDLCK
,F_WRLCK
, orF_UNLCK
.
short int l_whence
This corresponds to thewhence argument tofseek
orlseek
, and specifies what the offset is relative to. Its valuecan be one ofSEEK_SET
,SEEK_CUR
, orSEEK_END
.
off_t l_start
This specifies the offset of the start of the region to which the lockapplies, and is given in bytes relative to the point specified by thel_whence
member.
off_t l_len
This specifies the length of the region to be locked. A value of0
is treated specially; it means the region extends to the end ofthe file.
pid_t l_pid
This field is the process ID (seeProcess Creation Concepts) of theprocess holding the lock. It is filled in by callingfcntl
withtheF_GETLK
command, but is ignored when making a lock. If theconflicting lock is an open file description lock(seeOpen File Description Locks), then this field will be set to-1.
int
F_GETLK ¶This macro is used as thecommand argument tofcntl
, tospecify that it should get information about a lock. This commandrequires a third argument of typestruct flock *
to be passedtofcntl
, so that the form of the call is:
fcntl (filedes, F_GETLK,lockp)
If there is a lock already in place that would block the lock describedby thelockp argument, information about that lock overwrites*lockp
. Existing locks are not reported if they arecompatible with making a new lock as specified. Thus, you shouldspecify a lock type ofF_WRLCK
if you want to find out about bothread and write locks, orF_RDLCK
if you want to find out aboutwrite locks only.
There might be more than one lock affecting the region specified by thelockp argument, butfcntl
only returns information aboutone of them. Thel_whence
member of thelockp structure isset toSEEK_SET
and thel_start
andl_len
fieldsset to identify the locked region.
If no lock applies, the only change to thelockp structure is toupdate thel_type
to a value ofF_UNLCK
.
The normal return value fromfcntl
with this command is anunspecified value other than-1, which is reserved to indicate anerror. The followingerrno
error conditions are defined forthis command:
EBADF
Thefiledes argument is invalid.
EINVAL
Either thelockp argument doesn’t specify valid lock information,or the file associated withfiledes doesn’t support locks.
int
F_SETLK ¶This macro is used as thecommand argument tofcntl
, tospecify that it should set or clear a lock. This command requires athird argument of typestruct flock *
to be passed tofcntl
, so that the form of the call is:
fcntl (filedes, F_SETLK,lockp)
If the process already has a lock on any part of the region, the old lockon that part is replaced with the new lock. You can remove a lockby specifying a lock type ofF_UNLCK
.
If the lock cannot be set,fcntl
returns immediately with a valueof-1. This function does not block while waiting for other processesto release locks. Iffcntl
succeeds, it returns a value otherthan-1.
The followingerrno
error conditions are defined for thisfunction:
EAGAIN
EACCES
The lock cannot be set because it is blocked by an existing lock on thefile. Some systems useEAGAIN
in this case, and other systemsuseEACCES
; your program should treat them alike, afterF_SETLK
. (GNU/Linux and GNU/Hurd systems always useEAGAIN
.)
EBADF
Either: thefiledes argument is invalid; you requested a read lockbut thefiledes is not open for read access; or, you requested awrite lock but thefiledes is not open for write access.
EINVAL
Either thelockp argument doesn’t specify valid lock information,or the file associated withfiledes doesn’t support locks.
ENOLCK
The system has run out of file lock resources; there are already toomany file locks in place.
Well-designed file systems never report this error, because they have nolimitation on the number of locks. However, you must still take accountof the possibility of this error, as it could result from network accessto a file system on another machine.
int
F_SETLKW ¶This macro is used as thecommand argument tofcntl
, tospecify that it should set or clear a lock. It is just like theF_SETLK
command, but causes the process to block (or wait)until the request can be specified.
This command requires a third argument of typestruct flock *
, asfor theF_SETLK
command.
Thefcntl
return values and errors are the same as for theF_SETLK
command, but these additionalerrno
error conditionsare defined for this command:
EINTR
The function was interrupted by a signal while it was waiting.SeePrimitives Interrupted by Signals.
EDEADLK
The specified region is being locked by another process. But thatprocess is waiting to lock a region which the current process haslocked, so waiting for the lock would result in deadlock. The systemdoes not guarantee that it will detect all such conditions, but it letsyou know if it notices one.
The following macros are defined for use as values for thel_type
member of theflock
structure. The values are integer constants.
F_RDLCK
¶This macro is used to specify a read (or shared) lock.
F_WRLCK
¶This macro is used to specify a write (or exclusive) lock.
F_UNLCK
¶This macro is used to specify that the region is unlocked.
As an example of a situation where file locking is useful, consider aprogram that can be run simultaneously by several different users, thatlogs status information to a common file. One example of such a programmight be a game that uses a file to keep track of high scores. Anotherexample might be a program that records usage or accounting informationfor billing purposes.
Having multiple copies of the program simultaneously writing to thefile could cause the contents of the file to become mixed up. Butyou can prevent this kind of problem by setting a write lock on thefile before actually writing to the file.
If the program also needs to read the file and wants to make sure thatthe contents of the file are in a consistent state, then it can also usea read lock. While the read lock is set, no other process can lockthat part of the file for writing.
Remember that file locks are only anadvisory protocol forcontrolling access to a file. There is still potential for access tothe file by programs that don’t use the lock protocol.
Next:Open File Description Locks Example, Previous:File Locks, Up:Low-Level Input/Output [Contents][Index]
In contrast to process-associated record locks (seeFile Locks),open file description record locks are associated with an open filedescription rather than a process.
Usingfcntl
to apply an open file description lock on a region thatalready has an existing open file description lock that was created via thesame file descriptor will never cause a lock conflict.
Open file description locks are also inherited by child processes acrossfork
, orclone
withCLONE_FILES
set(seeCreating a Process), along with the file descriptor.
It is important to distinguish between the open filedescription (aninstance of an open file, usually created by a call toopen
) andan open filedescriptor, which is a numeric value that refers to theopen file description. The locks described here are associated with theopen filedescription and not the open filedescriptor.
Usingdup
(seeDuplicating Descriptors) to copy a filedescriptor does not give you a new open file description, but rather copies areference to an existing open file description and assigns it to a newfile descriptor. Thus, open file description locks set on a filedescriptor cloned bydup
will never conflict with open filedescription locks set on the original descriptor since they refer to thesame open file description. Depending on the range and type of lockinvolved, the original lock may be modified by aF_OFD_SETLK
orF_OFD_SETLKW
command in this situation however.
Open file description locks always conflict with process-associated locks,even if acquired by the same process or on the same open filedescriptor.
Open file description locks use the samestruct flock
asprocess-associated locks as an argument (seeFile Locks) and themacros for thecommand
values are also declared in the header filefcntl.h. To use them, the macro_GNU_SOURCE
must bedefined prior to including any header file.
In contrast to process-associated locks, anystruct flock
used asan argument to open file description lock commands must have thel_pid
value set to0. Also, when returning information about anopen file description lock in aF_GETLK
orF_OFD_GETLK
request,thel_pid
field instruct flock
will be set to-1to indicate that the lock is not associated with a process.
When the samestruct flock
is reused as an argument to aF_OFD_SETLK
orF_OFD_SETLKW
request after being used for anF_OFD_GETLK
request, it is necessary to inspect and reset thel_pid
field to0.
int
F_OFD_GETLK ¶This macro is used as thecommand argument tofcntl
, tospecify that it should get information about a lock. This commandrequires a third argument of typestruct flock *
to be passedtofcntl
, so that the form of the call is:
fcntl (filedes, F_OFD_GETLK,lockp)
If there is a lock already in place that would block the lock describedby thelockp argument, information about that lock is written to*lockp
. Existing locks are not reported if they arecompatible with making a new lock as specified. Thus, you shouldspecify a lock type ofF_WRLCK
if you want to find out about bothread and write locks, orF_RDLCK
if you want to find out aboutwrite locks only.
There might be more than one lock affecting the region specified by thelockp argument, butfcntl
only returns information aboutone of them. Which lock is returned in this situation is undefined.
Thel_whence
member of thelockp structure are set toSEEK_SET
and thel_start
andl_len
fields are setto identify the locked region.
If no conflicting lock exists, the only change to thelockp structureis to update thel_type
field to the valueF_UNLCK
.
The normal return value fromfcntl
with this command is either0on success or-1, which indicates an error. The followingerrno
error conditions are defined for this command:
EBADF
Thefiledes argument is invalid.
EINVAL
Either thelockp argument doesn’t specify valid lock information,the operating system kernel doesn’t support open file description locks, or the fileassociated withfiledes doesn’t support locks.
int
F_OFD_SETLK ¶This macro is used as thecommand argument tofcntl
, tospecify that it should set or clear a lock. This command requires athird argument of typestruct flock *
to be passed tofcntl
, so that the form of the call is:
fcntl (filedes, F_OFD_SETLK,lockp)
If the open file already has a lock on any part of theregion, the old lock on that part is replaced with the new lock. Youcan remove a lock by specifying a lock type ofF_UNLCK
.
If the lock cannot be set,fcntl
returns immediately with a valueof-1. This command does not wait for other tasksto release locks. Iffcntl
succeeds, it returns0.
The followingerrno
error conditions are defined for thiscommand:
EAGAIN
The lock cannot be set because it is blocked by an existing lock on thefile.
EBADF
Either: thefiledes argument is invalid; you requested a read lockbut thefiledes is not open for read access; or, you requested awrite lock but thefiledes is not open for write access.
EINVAL
Either thelockp argument doesn’t specify valid lock information,the operating system kernel doesn’t support open file description locks, or thefile associated withfiledes doesn’t support locks.
ENOLCK
The system has run out of file lock resources; there are already toomany file locks in place.
Well-designed file systems never report this error, because they have nolimitation on the number of locks. However, you must still take accountof the possibility of this error, as it could result from network accessto a file system on another machine.
int
F_OFD_SETLKW ¶This macro is used as thecommand argument tofcntl
, tospecify that it should set or clear a lock. It is just like theF_OFD_SETLK
command, but causes the process to wait until the requestcan be completed.
This command requires a third argument of typestruct flock *
, asfor theF_OFD_SETLK
command.
Thefcntl
return values and errors are the same as for theF_OFD_SETLK
command, but these additionalerrno
error conditionsare defined for this command:
EINTR
The function was interrupted by a signal while it was waiting.SeePrimitives Interrupted by Signals.
Open file description locks are useful in the same sorts of situations asprocess-associated locks. They can also be used to synchronize fileaccess between threads within the same process by having each thread performits ownopen
of the file, to obtain its own open file description.
Because open file description locks are automatically freed only uponclosing the last file descriptor that refers to the open filedescription, this locking mechanism avoids the possibility that locksare inadvertently released due to a library routine opening and closinga file without the application being aware.
As with process-associated locks, open file description locks are advisory.
Next:Interrupt-Driven Input, Previous:Open File Description Locks, Up:Low-Level Input/Output [Contents][Index]
Here is an example of using open file description locks in a threadedprogram. If this program used process-associated locks, then it would besubject to data corruption because process-associated locks are sharedby the threads inside a process, and thus cannot be used by one threadto lock out another thread in the same process.
Proper error handling has been omitted in the following program forbrevity.
#define _GNU_SOURCE#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <fcntl.h>#include <pthread.h>#define FILENAME "/tmp/foo"#define NUM_THREADS 3#define ITERATIONS 5void *thread_start (void *arg){ int i, fd, len; long tid = (long) arg; char buf[256]; struct flock lck = { .l_whence = SEEK_SET, .l_start = 0, .l_len = 1, }; fd = open ("/tmp/foo", O_RDWR | O_CREAT, 0666); for (i = 0; i < ITERATIONS; i++) { lck.l_type = F_WRLCK; fcntl (fd, F_OFD_SETLKW, &lck); len = sprintf (buf, "%d: tid=%ld fd=%d\n", i, tid, fd); lseek (fd, 0, SEEK_END); write (fd, buf, len); fsync (fd); lck.l_type = F_UNLCK; fcntl (fd, F_OFD_SETLK, &lck); /*sleep to ensure lock is yielded to another thread */ usleep (1); } pthread_exit (NULL);}intmain (int argc, char **argv){ long i; pthread_t threads[NUM_THREADS]; truncate (FILENAME, 0); for (i = 0; i < NUM_THREADS; i++) pthread_create (&threads[i], NULL, thread_start, (void *) i); pthread_exit (NULL); return 0;}
This example creates three threads each of which loops five times,appending to the file. Access to the file is serialized via open filedescription locks. If we compile and run the above program, we’ll end upwith /tmp/foo that has 15 lines in it.
If we, however, were to replace theF_OFD_SETLK
andF_OFD_SETLKW
commands with their process-associated lockequivalents, the locking essentially becomes a noop since it is all donewithin the context of the same process. That leads to data corruption(typically manifested as missing lines) as some threads race in andoverwrite the data written by others.
Next:Generic I/O Control operations, Previous:Open File Description Locks Example, Up:Low-Level Input/Output [Contents][Index]
If you set theO_ASYNC
status flag on a file descriptor(seeFile Status Flags), aSIGIO
signal is sent wheneverinput or output becomes possible on that file descriptor. The processor process group to receive the signal can be selected by using theF_SETOWN
command to thefcntl
function. If the filedescriptor is a socket, this also selects the recipient ofSIGURG
signals that are delivered when out-of-band data arrives on that socket;seeOut-of-Band Data. (SIGURG
is sent in any situationwhereselect
would report the socket as having an “exceptionalcondition”. SeeWaiting for Input or Output.)
If the file descriptor corresponds to a terminal device, thenSIGIO
signals are sent to the foreground process group of the terminal.SeeJob Control.
The symbols in this section are defined in the header filefcntl.h.
int
F_GETOWN ¶This macro is used as thecommand argument tofcntl
, tospecify that it should get information about the process or processgroup to whichSIGIO
signals are sent. (For a terminal, this isactually the foreground process group ID, which you can get usingtcgetpgrp
; seeFunctions for Controlling Terminal Access.)
The return value is interpreted as a process ID; if negative, itsabsolute value is the process group ID.
The followingerrno
error condition is defined for this command:
EBADF
Thefiledes argument is invalid.
int
F_SETOWN ¶This macro is used as thecommand argument tofcntl
, tospecify that it should set the process or process group to whichSIGIO
signals are sent. This command requires a third argumentof typepid_t
to be passed tofcntl
, so that the form ofthe call is:
fcntl (filedes, F_SETOWN,pid)
Thepid argument should be a process ID. You can also pass anegative number whose absolute value is a process group ID.
The return value fromfcntl
with this command is-1in case of error and some other value if successful. The followingerrno
error conditions are defined for this command:
EBADF
Thefiledes argument is invalid.
ESRCH
There is no process or process group corresponding topid.
Next:Other low-level-I/O-related functions, Previous:Interrupt-Driven Input, Up:Low-Level Input/Output [Contents][Index]
GNU systems can handle most input/output operations on many differentdevices and objects in terms of a few file primitives -read
,write
andlseek
. However, most devices also have a fewpeculiar operations which do not fit into this model. Such as:
lseek
is inapplicable).Although some such objects such as sockets and terminals3 have special functions of their own, it wouldnot be practical to create functions for all these cases.
Instead these minor operations, known asIOCTLs, are assigned codenumbers and multiplexed through theioctl
function, defined insys/ioctl.h
. The code numbers themselves are defined in manydifferent headers.
int
ioctl(intfiledes, intcommand, …)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theioctl
function performs the generic I/O operationcommand onfiledes.
A third argument is usually present, either a single number or a pointerto a structure. The meaning of this argument, the returned value, andany error codes depends upon the command used. Often-1 isreturned for a failure.
On some systems, IOCTLs used by different devices share the same numbers.Thus, although use of an inappropriate IOCTLusually only producesan error, you should not attempt to use device-specific IOCTLs on anunknown device.
Most IOCTLs are OS-specific and/or only used in special system utilities,and are thus beyond the scope of this document. For an example of the useof an IOCTL, seeOut-of-Band Data.
Previous:Generic I/O Control operations, Up:Low-Level Input/Output [Contents][Index]
int
poll(struct pollfd *fds, nfds_tnfds, inttimeout)
¶This documentation is a stub. For additional information on thisfunction, consult the manual pagepoll(2)SeeLinux (The Linux Kernel).
int
epoll_create(intsize)
¶This documentation is a stub. For additional information on thisfunction, consult the manual pageepoll_create(2)SeeLinux (The Linux Kernel).
int
epoll_wait(intepfd, struct epoll_event *events, intmaxevents, inttimeout)
¶This documentation is a stub. For additional information on thisfunction, consult the manual pageepoll_wait(2)SeeLinux (The Linux Kernel).
Next:Pipes and FIFOs, Previous:Low-Level Input/Output, Up:Main Menu [Contents][Index]
This chapter describes the GNU C Library’s functions for manipulatingfiles. Unlike the input and output functions (seeInput/Output on Streams;seeLow-Level Input/Output), these functions are concerned with operatingon the files themselves rather than on their contents.
Among the facilities described in this chapter are functions forexamining or modifying directories, functions for renaming and deletingfiles, and functions for examining and setting file attributes such asaccess permissions and modification times.
Next:Descriptor-Relative Access, Up:File System Interface [Contents][Index]
Each process has associated with it a directory, called itscurrentworking directory or simplyworking directory, that is used inthe resolution of relative file names (seeFile Name Resolution).
When you log in and begin a new session, your working directory isinitially set to the home directory associated with your login accountin the system user database. You can find any user’s home directoryusing thegetpwuid
orgetpwnam
functions; seeUser Database.
Users can change the working directory using shell commands likecd
. The functions described in this section are the primitivesused by those commands and by other programs for examining and changingthe working directory.
Prototypes for these functions are declared in the header fileunistd.h.
char *
getcwd(char *buffer, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Thegetcwd
function returns an absolute file name representingthe current working directory, storing it in the character arraybuffer that you provide. Thesize argument is how you tellthe system the allocation size ofbuffer.
The GNU C Library version of this function also permits you to specify anull pointer for thebuffer argument. Thengetcwd
allocates a buffer automatically, as withmalloc
(seeUnconstrained Allocation). If thesize is greater thanzero, then the buffer is that large; otherwise, the buffer is as largeas necessary to hold the result.
The return value isbuffer on success and a null pointer on failure.The followingerrno
error conditions are defined for this function:
EINVAL
Thesize argument is zero andbuffer is not a null pointer.
ERANGE
Thesize argument is less than the length of the working directoryname. You need to allocate a bigger array and try again.
EACCES
Permission to read or search a component of the file name was denied.
You could implement the behavior of GNU’sgetcwd (NULL, 0)
using only the standard behavior ofgetcwd
:
char *gnu_getcwd (){ size_t size = 100; while (1) { char *buffer = (char *) xmalloc (size); if (getcwd (buffer, size) == buffer) return buffer; free (buffer); if (errno != ERANGE) return 0; size *= 2; }}
SeeExamples ofmalloc
, for information aboutxmalloc
, which isnot a library function but is a customary name used in most GNUsoftware.
char *
getwd(char *buffer)
¶Preliminary:| MT-Safe | AS-Unsafe heap i18n| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
This is similar togetcwd
, but has no way to specify the size ofthe buffer. The GNU C Library providesgetwd
onlyfor backwards compatibility with BSD.
Thebuffer argument should be a pointer to an array at leastPATH_MAX
bytes long (seeLimits on File System Capacity). On GNU/Hurd systemsthere is no limit to the size of a file name, so this is notnecessarily enough space to contain the directory name. That is whythis function is deprecated.
char *
get_current_dir_name(void)
¶Preliminary:| MT-Safe env| AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Theget_current_dir_name
function is basically equivalent togetcwd (NULL, 0)
, except the value of thePWD
environment variable is first examined, and if it does in factcorrespond to the current directory, that value is returned. This isa subtle difference which is visible if the path described by thevalue inPWD
is using one or more symbolic links, in which casethe value returned bygetcwd
would resolve the symbolic linksand therefore yield a different result.
This function is a GNU extension.
int
chdir(const char *filename)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is used to set the process’s working directory tofilename.
The normal, successful return value fromchdir
is0
. Avalue of-1
is returned to indicate an error. Theerrno
error conditions defined for this function are the usual file namesyntax errors (seeFile Name Errors), plusENOTDIR
if thefilefilename is not a directory.
int
fchdir(intfiledes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is used to set the process’s working directory todirectory associated with the file descriptorfiledes.
The normal, successful return value fromfchdir
is0
. Avalue of-1
is returned to indicate an error. The followingerrno
error conditions are defined for this function:
EACCES
Read permission is denied for the directory named bydirname
.
EBADF
Thefiledes argument is not a valid file descriptor.
ENOTDIR
The file descriptorfiledes is not associated with a directory.
EINTR
The function call was interrupt by a signal.
EIO
An I/O error occurred.
Next:Accessing Directories, Previous:Working Directory, Up:File System Interface [Contents][Index]
Many functions that accept file names have…at
variantswhich accept a file descriptor and a file name argument instead of justa file name argument. For example,fstatat
is thedescriptor-based variant of thefstat
function. Most suchfunctions also accept an additional flags argument which changes thebehavior of the file name lookup based on the passedAT_…
flags.
There are several reasons to use descriptor-relative access:
O_NOFOLLOW
flag(seeOpen-time Flags) or theAT_SYMLINK_FOLLOW
flag(described below). Without directory-relative access, it is necessaryto use thefchdir
function to change the working directory(seeWorking Directory), which is not thread-safe.readdir
orreaddir64
functions (seeReading and Closing a Directory Stream) does not provide full filename paths. Using…at
functions, it is possible to use thefile names directly, without having to construct such full paths.…at
functionsprovide access to functionality which is not available otherwise.The file descriptor used by these…at
functions has thefollowing uses:
open
function and theO_RDONLY
file access mode, with or without theO_DIRECTORY
flag. SeeOpening and Closing Files. Or it can be createdimplicitly byopendir
and retrieved using thedirfd
function. SeeOpening a Directory Stream.If a directory descriptor is used with one of the…at
functions, a relative file name argument is resolved relative todirectory referred to by the file descriptor, just as if that directorywere the current working directory. Absolute file name arguments(starting with ‘/’) are resolved against the file system root, andthe descriptor argument is effectively ignored.
This means that file name lookup is not constrained to the directory ofthe descriptor. For example, it is possible to access a fileexample in the descriptor’s parent directory using a file nameargument"../example"
, or in the root directory using"/example"
.
If the file descriptor refers to a directory, the empty string""
is not a valid file name argument. It is possible to use"."
torefer to the directory itself. Also seeAT_EMPTY_PATH
below.
AT_FDCWD
. This means that the current workingdirectory is used for the lookup if the file name is a relative. For…at
functions with anAT_…
flags argument,this provides a shortcut to use those flags with regular (notdescriptor-based) file name lookups.IfAT_FDCWD
is used, the empty string""
is not a validfile name argument.
""
asthe file name argument, and theAT_EMPTY_PATH
flag. In thiscase, the operation uses the file descriptor directly, without furtherfile name resolution. On Linux, this allows operations on descriptorsopened with theO_PATH
flag. For regular descriptors (openedwithoutO_PATH
), the same functionality is also available throughthe plain descriptor-based functions (for example,fstat
insteadoffstatat
).This is a GNU extension.
The flags argument in…at
functions can be a combination ofthe following flags, defined infcntl.h. Not all such functionssupport all flags, and some (such asopenat
) do not accept aflags argument at all. Although the flags specific to each function havedistinct values from each other, some flags (relevant to differentfunctions) might share the same value and therefore are not guaranteed tohave unique values.
A non-exhaustive list of common flags and their descriptions follows. Flagsspecific to a function are described alongside the function itself. Inthese flag descriptions, theeffective final path component refers tothe final component (basename) of the full path constructed from thedescriptor and file name arguments, using file name lookup, as describedabove.
AT_EMPTY_PATH
¶This flag is used with an empty file name""
and a descriptorwhich does not necessarily refer to a directory. It is most useful withO_PATH
descriptors, as described above. This flag is a GNUextension.
AT_NO_AUTOMOUNT
¶If the effective final path component refers to a potential file systemmount point controlled by an auto-mounting service, the operation doesnot trigger auto-mounting and refers to the unmounted mount pointinstead. SeeMount, Unmount, Remount. If a file system has alreadybeen mounted at the effective final path component, the operationapplies to the file or directory in the mounted file system, not theunderlying file system that was mounted over. This flag is a GNUextension.
AT_SYMLINK_FOLLOW
¶If the effective final path component is a symbolic link, theoperation follows the symbolic link and operates on its target. (Formost functions, this is the default behavior.)
AT_SYMLINK_NOFOLLOW
¶If the effective final path component is a symbolic link, theoperation operates on the symbolic link, without following it. Thedifference in behavior enabled by this flag is similar to the differencebetween thelstat
andstat
functions, or the behavioractivated by theO_NOFOLLOW
argument to theopen
function.Even with theAT_SYMLINK_NOFOLLOW
flag present, symbolic links ina non-final component of the file name are still followed.
Note: There is no relationship between these flags and the typeargument to thegetauxval
function (withAT_…
constants defined inelf.h). SeeAuxiliary Vector.
The…at
functions have some common error conditions due to thenature of descriptor-relative access. A list of common errors and theirdescriptions follows. Errors specific to a function are described alongsidethe function itself.
EBADF
The file name argument is a relative path but the descriptor argumentis neitherAT_FDCWD
nor a valid file descriptor.
EINVAL
If the function accepts aflags argument, the flag combination passedis not valid for the function.
ENOTDIR
The file name argument is a relative file name but the descriptorargument is associated with a file that is not a directory.
Next:Working with Directory Trees, Previous:Descriptor-Relative Access, Up:File System Interface [Contents][Index]
The facilities described in this section let you read the contents of adirectory file. This is useful if you want your program to list all thefiles in a directory, perhaps as part of a menu.
Theopendir
function opens adirectory stream whoseelements are directory entries. Alternativelyfdopendir
can beused which can have advantages if the program needs to have morecontrol over the way the directory is opened for reading. Thisallows, for instance, to pass theO_NOATIME
flag toopen
.
You use thereaddir
function on the directory stream toretrieve these entries, represented asstruct dirent
objects. The name of the file for each entry is stored in thed_name
member of this structure. There are obvious parallelshere to the stream facilities for ordinary files, described inInput/Output on Streams.
Next:Opening a Directory Stream, Up:Accessing Directories [Contents][Index]
This section describes what you find in a single directory entry, as youmight obtain it from a directory stream. All the symbols are declaredin the header filedirent.h.
This is a structure type used to return information about directoryentries. It contains the following fields:
char d_name[]
This is the null-terminated file name component. This is the onlyfield you can count on in all POSIX systems.
While this field is defined with a specified length, functions such asreaddir
may return a pointer to astruct dirent
where thed_name
extends beyond the end of the struct.
ino_t d_fileno
This is the file serial number. For BSD compatibility, you can alsorefer to this member asd_ino
. On GNU/Linux and GNU/Hurd systems and most POSIXsystems, for most files this the same as thest_ino
member thatstat
will return for the file. SeeFile Attributes.
off_t d_off
This value contains the offset of the next directory entry (after thisentry) in the directory stream. The value may not be compatible withlseek
orseekdir
, especially if the width ofd_off
is less than 64 bits. Directory entries are not ordered by offset, andthed_off
andd_reclen
values are unrelated. Seeking ondirectory streams is not recommended. The symbol_DIRENT_HAVE_D_OFF
is defined if thed_ino
member isavailable.
unsigned char d_namlen
This is the length of the file name, not including the terminatingnull character. Its type isunsigned char
because that is theinteger type of the appropriate size. This member is a BSD extension.The symbol_DIRENT_HAVE_D_NAMLEN
is defined if this member isavailable. (It is not available on Linux.)
unsigned short int d_reclen
This is the length of the entire directory record. When iteratingthrough a buffer filled bygetdents64
(seeLow-level Directory Access), this value needs to be added to the offset of the currentdirectory entry to obtain the offset of the next entry. When usingreaddir
and related functions, the value ofd_reclen
isundefined and should not be accessed. The symbol_DIRENT_HAVE_D_RECLEN
is defined if this member is available.
unsigned char d_type
This is the type of the file, possibly unknown. The following constantsare defined for its value:
DT_UNKNOWN
¶The type is unknown. Only some filesystems have full support toreturn the type of the file, others might always return this value.
DT_REG
¶A regular file.
DT_DIR
¶A directory.
DT_FIFO
¶A named pipe, or FIFO. SeeFIFO Special Files.
DT_SOCK
¶A local-domain socket.
DT_CHR
¶A character device.
DT_BLK
¶A block device.
DT_LNK
¶A symbolic link.
This member is a BSD extension. The symbol_DIRENT_HAVE_D_TYPE
is defined if this member is available. On systems where it is used, itcorresponds to the file type bits in thest_mode
member ofstruct stat
. If the value cannot be determined the membervalue isDT_UNKNOWN
. These two macros convert betweend_type
values andst_mode
values:
int
IFTODT(mode_tmode)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This returns thed_type
value corresponding tomode.
mode_t
DTTOIF(intdtype)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This returns thest_mode
value corresponding todtype.
This structure may contain additional members in the future. Theiravailability is always announced in the compilation environment by amacro named_DIRENT_HAVE_D_xxx
wherexxx is replacedby the name of the new member. For instance, the memberd_reclen
available on some systems is announced through the macro_DIRENT_HAVE_D_RECLEN
.
When a file has multiple names, each name has its own directory entry.The only way you can tell that the directory entries belong to asingle file is that they have the same value for thed_fileno
field.
File attributes such as size, modification times etc., are part of thefile itself, not of any particular directory entry. SeeFile Attributes.
Next:Reading and Closing a Directory Stream, Previous:Format of a Directory Entry, Up:Accessing Directories [Contents][Index]
This section describes how to open a directory stream. All the symbolsare declared in the header filedirent.h.
TheDIR
data type represents a directory stream.
You shouldn’t ever allocate objects of thestruct dirent
orDIR
data types, since the directory access functions do that foryou. Instead, you refer to these objects using the pointers returned bythe following functions.
Directory streams are a high-level interface. On Linux, alternativeinterfaces for accessing directories using file descriptors areavailable. SeeLow-level Directory Access.
DIR *
opendir(const char *dirname)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Theopendir
function opens and returns a directory stream forreading the directory whose file name isdirname. The stream hastypeDIR *
.
If unsuccessful,opendir
returns a null pointer. In addition tothe usual file name errors (seeFile Name Errors), thefollowingerrno
error conditions are defined for this function:
EACCES
Read permission is denied for the directory named bydirname
.
EMFILE
The process has too many files open.
ENFILE
The entire system, or perhaps the file system which contains thedirectory, cannot support any additional open files at the moment.(This problem cannot happen on GNU/Hurd systems.)
ENOMEM
Not enough memory available.
TheDIR
type is typically implemented using a file descriptor,and theopendir
function in terms of theopen
function.SeeLow-Level Input/Output. Directory streams and the underlyingfile descriptors are closed onexec
(seeExecuting a File).
The directory which is opened for reading byopendir
isidentified by the name. In some situations this is not sufficient.Or the wayopendir
implicitly creates a file descriptor for thedirectory is not the way a program might want it. In these cases analternative interface can be used.
DIR *
fdopendir(intfd)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Thefdopendir
function works just likeopendir
butinstead of taking a file name and opening a file descriptor for thedirectory the caller is required to provide a file descriptor. Thisfile descriptor is then used in subsequent uses of the returneddirectory stream object.
The caller must make sure the file descriptor is associated with adirectory and it allows reading.
If thefdopendir
call returns successfully the file descriptoris now under the control of the system. It can be used in the sameway the descriptor implicitly created byopendir
can be usedbut the program must not close the descriptor.
In case the function is unsuccessful it returns a null pointer and thefile descriptor remains to be usable by the program. The followingerrno
error conditions are defined for this function:
EBADF
The file descriptor is not valid.
ENOTDIR
The file descriptor is not associated with a directory.
EINVAL
The descriptor does not allow reading the directory content.
ENOMEM
Not enough memory available.
In some situations it can be desirable to get hold of the filedescriptor which is created by theopendir
call. For instance,to switch the current working directory to the directory just read thefchdir
function could be used. Historically theDIR
typewas exposed and programs could access the fields. This does not happenin the GNU C Library. Instead a separate function is provided to allowaccess.
int
dirfd(DIR *dirstream)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functiondirfd
returns the file descriptor associated withthe directory streamdirstream. This descriptor can be used untilthe directory is closed withclosedir
. If the directory streamimplementation is not using file descriptors the return value is-1
.
Next:Simple Program to List a Directory, Previous:Opening a Directory Stream, Up:Accessing Directories [Contents][Index]
This section describes how to read directory entries from a directorystream, and how to close the stream when you are done with it. All thesymbols are declared in the header filedirent.h.
struct dirent *
readdir(DIR *dirstream)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function reads the next entry from the directory. It normallyreturns a pointer to a structure containing information about thefile. This structure is associated with thedirstream handleand can be rewritten by a subsequent call.
Portability Note: On some systemsreaddir
may notreturn entries for. and.., even though these are alwaysvalid file names in any directory. SeeFile Name Resolution.
If a directory is modified between a call toreaddir
and afterthe directory stream was created orrewinddir
was last called onit, it is unspecified according to POSIX whether newly created orremoved entries appear among the entries returned by repeatedreaddir
calls before the end of the directory is reached.However, due to practical implementation constraints, it is possiblethat entries (including unrelated, unmodified entries) appear multipletimes or do not appear at all if the directory is modified while listingit. If the application intends to create files in the directory, it maybe necessary to complete the iteration first and create a copy of theinformation obtained before creating any new files. (See below forinstructions regarding copying ofd_name
.) The iteration can berestarted usingrewinddir
. SeeRandom Access in a Directory Stream.
If there are no more entries in the directory or an error is detected,readdir
returns a null pointer. The followingerrno
errorconditions are defined for this function:
EBADF
Thedirstream argument is not valid.
To distinguish between an end-of-directory condition or an error, youmust seterrno
to zero before callingreaddir
. To avoidentering an infinite loop, you should stop reading from the directoryafter the first error.
Caution: The pointer returned byreaddir
points toa buffer within theDIR
object. The data in that buffer willbe overwritten by the next call toreaddir
. You must take care,for instance, to copy thed_name
string if you need it later.
Because of this, it is not safe to share aDIR
object amongmultiple threads, unless you use your own locking to ensure thatno thread callsreaddir
while another thread is still using thedata from the previous call. In the GNU C Library, it is safe to callreaddir
from multiple threads as long as each thread usesits ownDIR
object. POSIX.1-2008 does not require this tobe safe, but we are not aware of any operating systems where itdoes not work.
readdir_r
allows you to provide your own buffer for thestruct dirent
, but it is less portable thanreaddir
, andhas problems with very long filenames (see below). We recommendyou usereaddir
, but do not shareDIR
objects.
int
readdir_r(DIR *dirstream, struct dirent *entry, struct dirent **result)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function is a version ofreaddir
which performs internallocking. Likereaddir
it returns the next entry from thedirectory. To prevent conflicts between simultaneously runningthreads the result is stored inside theentry object.
Portability Note:readdir_r
is deprecated. It isrecommended to usereaddir
instead ofreaddir_r
for thefollowing reasons:
NAME_MAX
, it may not be possibleto usereaddir_r
safely because the caller does not specify thelength of the buffer for the directory entry.readdir_r
cannot read directory entries withvery long names. If such a name is encountered, the GNU C Libraryimplementation ofreaddir_r
returns with an error code ofENAMETOOLONG
after the final directory entry has been read. Onother systems,readdir_r
may return successfully, but thed_name
member may not be NUL-terminated or may be truncated.readdir
is thread-safe,even when access to the samedirstream is serialized. But incurrent implementations (including the GNU C Library), it is safe to callreaddir
concurrently on differentdirstreams, so there isno need to usereaddir_r
in most multi-threaded programs. Inthe rare case that multiple threads need to read from the samedirstream, it is still better to usereaddir
and externalsynchronization.readdir_r
and mandate the level of thread safety forreaddir
which is provided by the GNU C Library and otherimplementations today.Normallyreaddir_r
returns zero and sets*result
toentry. If there are no more entries in the directory or anerror is detected,readdir_r
sets*result
to anull pointer and returns a nonzero error code, also stored inerrno
, as described forreaddir
.
It is also important to look at the definition of thestructdirent
type. Simply passing a pointer to an object of this type forthe second parameter ofreaddir_r
might not be enough. Somesystems don’t define thed_name
element sufficiently long. Inthis case the user has to provide additional space. There must be roomfor at leastNAME_MAX + 1
characters in thed_name
array.Code to callreaddir_r
could look like this:
union { struct dirent d; char b[offsetof (struct dirent, d_name) + NAME_MAX + 1]; } u; if (readdir_r (dir, &u.d, &res) == 0) ...
To support large filesystems on 32-bit machines there are LFS variantsof the last two functions.
struct dirent64 *
readdir64(DIR *dirstream)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Thereaddir64
function is just like thereaddir
functionexcept that it returns a pointer to a record of typestructdirent64
. Some of the members of this data type (notablyd_ino
)might have a different size to allow large filesystems.
In all other aspects this function is equivalent toreaddir
.
int
readdir64_r(DIR *dirstream, struct dirent64 *entry, struct dirent64 **result)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
The deprecatedreaddir64_r
function is equivalent to thereaddir_r
function except that it takes parameters of base typestruct dirent64
instead ofstruct dirent
in the second andthird position. The same precautions mentioned in the documentation ofreaddir_r
also apply here.
int
closedir(DIR *dirstream)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock/hurd| AC-Unsafe mem fd lock/hurd| SeePOSIX Safety Concepts.
This function closes the directory streamdirstream. It returns0
on success and-1
on failure.
The followingerrno
error conditions are defined for thisfunction:
EBADF
Thedirstream argument is not valid.
Next:Random Access in a Directory Stream, Previous:Reading and Closing a Directory Stream, Up:Accessing Directories [Contents][Index]
Here’s a simple program that prints the names of the files inthe current working directory:
#include <stdio.h>#include <sys/types.h>#include <dirent.h>
intmain (void){ DIR *dp; struct dirent *ep; dp = opendir ("./"); if (dp != NULL) { while (ep = readdir (dp)) puts (ep->d_name); (void) closedir (dp); } else perror ("Couldn't open the directory"); return 0;}
The order in which files appear in a directory tends to be fairlyrandom. A more useful program would sort the entries (perhaps byalphabetizing them) before printing them; seeScanning the Content of a Directory, andArray Sort Function.
Next:Scanning the Content of a Directory, Previous:Simple Program to List a Directory, Up:Accessing Directories [Contents][Index]
This section describes how to reread parts of a directory that you havealready read from an open directory stream. All the symbols aredeclared in the header filedirent.h.
void
rewinddir(DIR *dirstream)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Therewinddir
function is used to reinitialize the directorystreamdirstream, so that if you callreaddir
itreturns information about the first entry in the directory again. Thisfunction also notices if files have been added or removed to thedirectory since it was opened withopendir
. (Entries for thesefiles might or might not be returned byreaddir
if they wereadded or removed since you last calledopendir
orrewinddir
.)
For example, it is recommended to callrewinddir
followed byreaddir
to check if a directory is empty after listing it withreaddir
and deleting all encountered files from it.
long int
telldir(DIR *dirstream)
¶Preliminary:| MT-Safe | AS-Unsafe heap/bsd lock/bsd| AC-Unsafe mem/bsd lock/bsd| SeePOSIX Safety Concepts.
Thetelldir
function returns the file position of the directorystreamdirstream. You can use this value withseekdir
torestore the directory stream to that position.
Using the thetelldir
function is not recommended.
The value returned bytelldir
may not be compatible with thed_off
field instruct dirent
, and cannot be used with thelseek
function. The returned value may not unambiguouslyidentify the position in the directory stream.
void
seekdir(DIR *dirstream, long intpos)
¶Preliminary:| MT-Safe | AS-Unsafe heap/bsd lock/bsd| AC-Unsafe mem/bsd lock/bsd| SeePOSIX Safety Concepts.
Theseekdir
function sets the file position of the directorystreamdirstream topos. The valuepos must be theresult of a previous call totelldir
on this particular stream;closing and reopening the directory can invalidate values returned bytelldir
.
Using the theseekdir
function is not recommended. To seek tothe beginning of the directory stream, userewinddir
.
Next:Simple Program to List a Directory, Mark II, Previous:Random Access in a Directory Stream, Up:Accessing Directories [Contents][Index]
A higher-level interface to the directory handling functions is thescandir
function. With its help one can select a subset of theentries in a directory, possibly sort them and get a list of names asthe result.
int
scandir(const char *dir, struct dirent ***namelist, int (*selector) (const struct dirent *), int (*cmp) (const struct dirent **, const struct dirent **))
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Thescandir
function scans the contents of the directory selectedbydir. The result in *namelist is an array of pointers tostructures of typestruct dirent
which describe all selecteddirectory entries and which is allocated usingmalloc
. Insteadof always getting all directory entries returned, the user suppliedfunctionselector can be used to decide which entries are in theresult. Only the entries for whichselector returns a non-zerovalue are selected.
Finally the entries in *namelist are sorted using theuser-supplied functioncmp. The arguments passed to thecmpfunction are of typestruct dirent **
, therefore one cannotdirectly use thestrcmp
orstrcoll
functions; instead seethe functionsalphasort
andversionsort
below.
The return value of the function is the number of entries placed in*namelist. If it is-1
an error occurred (either thedirectory could not be opened for reading or memory allocation failed) andthe global variableerrno
contains more information on the error.
As described above, the fourth argument to thescandir
functionmust be a pointer to a sorting function. For the convenience of theprogrammer the GNU C Library contains implementations of functions whichare very helpful for this purpose.
int
alphasort(const struct dirent **a, const struct dirent **b)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thealphasort
function behaves like thestrcoll
function(seeString/Array Comparison). The difference is that the argumentsare not string pointers but instead they are of typestruct dirent **
.
The return value ofalphasort
is less than, equal to, or greaterthan zero depending on the order of the two entriesa andb.
int
versionsort(const struct dirent **a, const struct dirent **b)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theversionsort
function is likealphasort
except that ituses thestrverscmp
function internally.
If the filesystem supports large files we cannot use thescandir
anymore since thedirent
structure might not able to contain allthe information. The LFS provides the new typestruct dirent64
. To use this we need a new function.
int
scandir64(const char *dir, struct dirent64 ***namelist, int (*selector) (const struct dirent64 *), int (*cmp) (const struct dirent64 **, const struct dirent64 **))
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Thescandir64
function works like thescandir
functionexcept that the directory entries it returns are described by elementsof typestruct dirent64
. The function pointed to byselector is again used to select the desired entries, except thatselector now must point to a function which takes astruct dirent64 *
parameter.
Similarly thecmp function should expect its two arguments to beof typestruct dirent64 **
.
Ascmp is now a function of a different type, the functionsalphasort
andversionsort
cannot be supplied for thatargument. Instead we provide the two replacement functions below.
int
alphasort64(const struct dirent64 **a, const struct dirent **b)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Thealphasort64
function behaves like thestrcoll
function(seeString/Array Comparison). The difference is that the argumentsare not string pointers but instead they are of typestruct dirent64 **
.
Return value ofalphasort64
is less than, equal to, or greaterthan zero depending on the order of the two entriesa andb.
int
versionsort64(const struct dirent64 **a, const struct dirent64 **b)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theversionsort64
function is likealphasort64
, excepted that ituses thestrverscmp
function internally.
It is important not to mix the use ofscandir
and the 64-bitcomparison functions or vice versa. There are systems on which thisworks but on others it will fail miserably.
Next:Low-level Directory Access, Previous:Scanning the Content of a Directory, Up:Accessing Directories [Contents][Index]
Here is a revised version of the directory lister found above(seeSimple Program to List a Directory). Using thescandir
function wecan avoid the functions which work directly with the directory contents.After the call the returned entries are available for direct use.
#include <stdio.h>#include <dirent.h>
static intone (const struct dirent *unused){ return 1;}intmain (void){ struct dirent **eps; int n; n = scandir ("./", &eps, one, alphasort); if (n >= 0) { int cnt; for (cnt = 0; cnt < n; ++cnt) puts (eps[cnt]->d_name); } else perror ("Couldn't open the directory"); return 0;}
Note the simple selector function in this example. Since we want to seeall directory entries we always return1
.
The stream-based directory functions are not AS-Safe and cannot beused aftervfork
. SeePOSIX Safety Concepts. The functionsbelow provide an alternative that can be used in these contexts.
Directory data is obtained from a file descriptor, as created by theopen
function, with or without theO_DIRECTORY
flag.SeeOpening and Closing Files.
ssize_t
getdents64(intfd, void *buffer, size_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetdents64
function reads at mostlength bytes ofdirectory entry data from the file descriptorfd and stores itinto the byte array starting atbuffer.
On success, the function returns the number of bytes written to thebuffer. This number is zero iffd is already at the end of thedirectory stream. On error, the function returns-1
and setserrno
to the appropriate error code.
The data is stored as a sequence ofstruct dirent64
records,which can be traversed using thed_reclen
member. The buffershould be large enough to hold the largest possible directory entry.Note that some file systems support file names longer thanNAME_MAX
bytes (e.g., because they support up to 255 Unicodecharacters), so a buffer size of at least 1024 is recommended.
If the directory has been modified since the first call togetdents64
on the directory (opening the descriptor or seeking tooffset zero), it is possible that the buffer contains entries that havebeen encountered before. Likewise, it is possible that files that arestill present are not reported before the end of the directory isencountered (andgetdents64
returns zero).
This function is specific to Linux.
Systems that supportgetdents64
support seeking on directorystreams. SeeSetting the File Position of a Descriptor. However, the only offset thatworks reliably is offset zero, indicating that reading the directoryshould start from the beginning.
Next:Hard Links, Previous:Accessing Directories, Up:File System Interface [Contents][Index]
The functions described so far for handling the files in a directoryhave allowed you to either retrieve the information bit by bit, or toprocess all the files as a group (seescandir
). Sometimes it isuseful to process whole hierarchies of directories and their containedfiles. The X/Open specification defines two functions to do this. Thesimpler form is derived from an early definition in System V systemsand therefore this function is available on SVID-derived systems. Theprototypes and required definitions can be found in theftw.hheader.
There are four functions in this family:ftw
,nftw
andtheir 64-bit counterpartsftw64
andnftw64
. Thesefunctions take as one of their arguments a pointer to a callbackfunction of the appropriate type.
int (*) (const char *, const struct stat *, int)
The type of callback functions given to theftw
function. Thefirst parameter points to the file name, the second parameter to anobject of typestruct stat
which is filled in for the file namedin the first parameter.
The last parameter is a flag giving more information about the currentfile. It can have the following values:
FTW_F
¶The item is either a normal file or a file which does not fit into oneof the following categories. This could be special files, sockets etc.
FTW_D
¶The item is a directory.
FTW_NS
¶Thestat
call failed and so the information pointed to by thesecond parameter is invalid.
FTW_DNR
¶The item is a directory which cannot be read.
FTW_SL
¶The item is a symbolic link. Since symbolic links are normally followedseeing this value in aftw
callback function means the referencedfile does not exist. The situation fornftw
is different.
This value is only available if the program is compiled with_XOPEN_EXTENDED
defined before includingthe first header. The original SVID systems do not have symbolic links.
If the sources are compiled with_FILE_OFFSET_BITS == 64
thistype is in fact__ftw64_func_t
since this mode changesstruct stat
to bestruct stat64
.
For the LFS interface and for use in the functionftw64
, theheaderftw.h defines another function type.
int (*) (const char *, const struct stat64 *, int)
This type is used just like__ftw_func_t
for the callbackfunction, but this time is called fromftw64
. The secondparameter to the function is a pointer to a variable of typestruct stat64
which is able to represent the larger values.
int (*) (const char *, const struct stat *, int, struct FTW *)
The first three arguments are the same as for the__ftw_func_t
type. However for the third argument some additional values are definedto allow finer differentiation:
FTW_DP
¶The current item is a directory and all subdirectories have already beenvisited and reported. This flag is returned instead ofFTW_D
iftheFTW_DEPTH
flag is passed tonftw
(see below).
FTW_SLN
¶The current item is a stale symbolic link. The file it points to doesnot exist.
The last parameter of the callback function is a pointer to a structurewith some extra information as described below.
If the sources are compiled with_FILE_OFFSET_BITS == 64
thistype is in fact__nftw64_func_t
since this mode changesstruct stat
to bestruct stat64
.
For the LFS interface there is also a variant of this data typeavailable which has to be used with thenftw64
function.
int (*) (const char *, const struct stat64 *, int, struct FTW *)
This type is used just like__nftw_func_t
for the callbackfunction, but this time is called fromnftw64
. The secondparameter to the function is this time a pointer to a variable of typestruct stat64
which is able to represent the larger values.
The information contained in this structure helps in interpreting thename parameter and gives some information about the current state of thetraversal of the directory hierarchy.
int base
The value is the offset into the string passed in the first parameter tothe callback function of the beginning of the file name. The rest ofthe string is the path of the file. This information is especiallyimportant if theFTW_CHDIR
flag was set in callingnftw
since then the current directory is the one the current item is foundin.
int level
Whilst processing, the code tracks how many directories down it has goneto find the current file. This nesting level starts at0 forfiles in the initial directory (or is zero for the initial file if afile was passed).
int
ftw(const char *filename, __ftw_func_tfunc, intdescriptors)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Theftw
function calls the callback function given in theparameterfunc for every item which is found in the directoryspecified byfilename and all directories below. The functionfollows symbolic links if necessary but does not process an item twice.Iffilename is not a directory then it itself is the only objectreturned to the callback function.
The file name passed to the callback function is constructed by takingthefilename parameter and appending the names of all passeddirectories and then the local file name. So the callback function canuse this parameter to access the file.ftw
also callsstat
for the file and passes that information on to the callbackfunction. If thisstat
call is not successful the failure isindicated by setting the third argument of the callback function toFTW_NS
. Otherwise it is set according to the description givenin the account of__ftw_func_t
above.
The callback function is expected to return0 to indicate that noerror occurred and that processing should continue. If an erroroccurred in the callback function or it wantsftw
to returnimmediately, the callback function can return a value other than0. This is the only correct way to stop the function. Theprogram must not usesetjmp
or similar techniques to continuefrom another place. This would leave resources allocated by theftw
function unfreed.
Thedescriptors parameter toftw
specifies how many filedescriptors it is allowed to consume. The function runs faster the moredescriptors it can use. For each level in the directory hierarchy atmost one descriptor is used, but for very deep ones any limit on openfile descriptors for the process or the system may be exceeded.Moreover, file descriptor limits in a multi-threaded program apply toall the threads as a group, and therefore it is a good idea to supply areasonable limit to the number of open descriptors.
The return value of theftw
function is0 if all callbackfunction calls returned0 and all actions performed by theftw
succeeded. If a function call failed (other than callingstat
on an item) the function returns-1. If a callbackfunction returns a value other than0 this value is returned asthe return value offtw
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32-bit system this function is in factftw64
, i.e., the LFSinterface transparently replaces the old interface.
int
ftw64(const char *filename, __ftw64_func_tfunc, intdescriptors)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
This function is similar toftw
but it can work on filesystemswith large files. File information is reported using a variable of typestruct stat64
which is passed by reference to the callbackfunction.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32-bit system this function is available under the nameftw
andtransparently replaces the old implementation.
int
nftw(const char *filename, __nftw_func_tfunc, intdescriptors, intflag)
¶Preliminary:| MT-Safe cwd| AS-Unsafe heap| AC-Unsafe mem fd cwd| SeePOSIX Safety Concepts.
Thenftw
function works like theftw
functions. They callthe callback functionfunc for all items found in the directoryfilename and below. At mostdescriptors file descriptorsare consumed during thenftw
call.
One difference is that the callback function is of a different type. Itis of typestruct FTW *
and provides the callback functionwith the extra information described above.
A second difference is thatnftw
takes a fourth argument, whichis0 or a bitwise-OR combination of any of the following values.
FTW_PHYS
¶While traversing the directory symbolic links are not followed. Insteadsymbolic links are reported using theFTW_SL
value for the typeparameter to the callback function. If the file referenced by asymbolic link does not existFTW_SLN
is returned instead.
FTW_MOUNT
¶The callback function is only called for items which are on the samemounted filesystem as the directory given by thefilenameparameter tonftw
.
FTW_CHDIR
¶If this flag is given the current working directory is changed to thedirectory of the reported object before the callback function is called.Whenntfw
finally returns the current directory is restored toits original value.
FTW_DEPTH
¶If this option is specified then all subdirectories and files withinthem are processed before processing the top directory itself(depth-first processing). This also means the type flag given to thecallback function isFTW_DP
and notFTW_D
.
FTW_ACTIONRETVAL
¶If this option is specified then return values from callbacksare handled differently. If the callback returnsFTW_CONTINUE
,walking continues normally.FTW_STOP
means walking stopsandFTW_STOP
is returned to the caller. IfFTW_SKIP_SUBTREE
is returned by the callback withFTW_D
argument, the subtreeis skipped and walking continues with next sibling of the directory.IfFTW_SKIP_SIBLINGS
is returned by the callback, all siblingsof the current entry are skipped and walking continues in its parent.No other return values should be returned from the callbacks ifthis option is set. This option is a GNU extension.
The return value is computed in the same way as forftw
.nftw
returns0 if no failures occurred and all callbackfunctions returned0. In case of internal errors, such as memoryproblems, the return value is-1 anderrno
is setaccordingly. If the return value of a callback invocation was non-zerothen that value is returned.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32-bit system this function is in factnftw64
, i.e., the LFSinterface transparently replaces the old interface.
int
nftw64(const char *filename, __nftw64_func_tfunc, intdescriptors, intflag)
¶Preliminary:| MT-Safe cwd| AS-Unsafe heap| AC-Unsafe mem fd cwd| SeePOSIX Safety Concepts.
This function is similar tonftw
but it can work on filesystemswith large files. File information is reported using a variable of typestruct stat64
which is passed by reference to the callbackfunction.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32-bit system this function is available under the namenftw
andtransparently replaces the old implementation.
Next:Symbolic Links, Previous:Working with Directory Trees, Up:File System Interface [Contents][Index]
In POSIX systems, one file can have many names at the same time. All ofthe names are equally real, and no one of them is preferred to theothers.
To add a name to a file, use thelink
function. (The new name isalso called ahard link to the file.) Creating a new link to afile does not copy the contents of the file; it simply makes a new nameby which the file can be known, in addition to the file’s existing nameor names.
One file can have names in several directories, so the organizationof the file system is not a strict hierarchy or tree.
In most implementations, it is not possible to have hard links to thesame file in multiple file systems.link
reports an error if youtry to make a hard link to the file from another file system when thiscannot be done.
The prototype for thelink
function is declared in the headerfileunistd.h.
int
link(const char *oldname, const char *newname)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thelink
function makes a new link to the existing file named byoldname, under the new namenewname.
This function returns a value of0
if it is successful and-1
on failure. In addition to the usual file name errors(seeFile Name Errors) for botholdname andnewname, thefollowingerrno
error conditions are defined for this function:
EACCES
You are not allowed to write to the directory in which the new link isto be written.
EEXIST
There is already a file namednewname. If you want to replacethis link with a new link, you must remove the old link explicitly first.
EMLINK
There are already too many links to the file named byoldname.(The maximum number of links to a file isLINK_MAX
; seeLimits on File System Capacity.)
ENOENT
The file named byoldname doesn’t exist. You can’t make a link toa file that doesn’t exist.
ENOSPC
The directory or file system that would contain the new link is fulland cannot be extended.
EPERM
On GNU/Linux and GNU/Hurd systems and some others, you cannot make links todirectories.Many systems allow only privileged users to do so. This erroris used to report the problem.
EROFS
The directory containing the new link can’t be modified because it’s ona read-only file system.
EXDEV
The directory specified innewname is on a different file systemthan the existing file.
EIO
A hardware error occurred while trying to read or write the to filesystem.
int
linkat(int oldfd, const char *oldname, int newfd, const char *newname, int flags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thelinkat
function is analogous to thelink
function,except that it identifies its source and target using a combination of afile descriptor (referring to a directory) and a file name.SeeDescriptor-Relative Access. Forlinkat
, if a file name isnot absolute, it is resolved relative to the corresponding filedescriptor. As usual, the special valueAT_FDCWD
denotes thecurrent directory.
Theflags argument is a combination of the following flags:
AT_SYMLINK_FOLLOW
If the source path identified byoldfd andoldname is asymbolic link,linkat
follows the symbolic link and creates alink to its target. If the flag is not set, a link for the symboliclink itself is created; this is not supported by all file systems andlinkat
can fail in this case.
AT_EMPTY_PATH
If this flag is specified,oldname can be an empty string. Inthis case, a new link to the file denoted by the descriptoroldfdis created, which may have been opened withO_PATH
orO_TMPFILE
. This flag is a GNU extension.
Next:Deleting Files, Previous:Hard Links, Up:File System Interface [Contents][Index]
GNU systems supportsoft links orsymbolic links. Thisis a kind of “file” that is essentially a pointer to another filename. Unlike hard links, symbolic links can be made to directories oracross file systems with no restrictions. You can also make a symboliclink to a name which is not the name of any file. (Opening this linkwill fail until a file by that name is created.) Likewise, if thesymbolic link points to an existing file which is later deleted, thesymbolic link continues to point to the same file name even though thename no longer names any file.
The reason symbolic links work the way they do is that special thingshappen when you try to open the link. Theopen
function realizesyou have specified the name of a link, reads the file name contained inthe link, and opens that file name instead. Thestat
functionlikewise operates on the file that the symbolic link points to, insteadof on the link itself.
By contrast, other operations such as deleting or renaming the fileoperate on the link itself. The functionsreadlink
andlstat
also refrain from following symbolic links, because theirpurpose is to obtain information about the link.link
, thefunction that makes a hard link, does too. It makes a hard link to thesymbolic link, which one rarely wants.
Some systems have, for some functions operating on files, a limit onhow many symbolic links are followed when resolving a path name. Thelimit if it exists is published in thesys/param.h header file.
int
MAXSYMLINKS ¶The macroMAXSYMLINKS
specifies how many symlinks some functionwill follow before returningELOOP
. Not all functions behave thesame and this value is not the same as that returned for_SC_SYMLOOP
bysysconf
. In fact, thesysconf
result can indicate that there is no fixed limit althoughMAXSYMLINKS
exists and has a finite value.
Prototypes for most of the functions listed in this section are inunistd.h.
int
symlink(const char *oldname, const char *newname)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thesymlink
function makes a symbolic link tooldname namednewname.
The normal return value fromsymlink
is0
. A return valueof-1
indicates an error. In addition to the usual file namesyntax errors (seeFile Name Errors), the followingerrno
error conditions are defined for this function:
EEXIST
There is already an existing file namednewname.
EROFS
The filenewname would exist on a read-only file system.
ENOSPC
The directory or file system cannot be extended to make the new link.
EIO
A hardware error occurred while reading or writing data on the disk.
ssize_t
readlink(const char *filename, char *buffer, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thereadlink
function gets the value of the symbolic linkfilename. The file name that the link points to is copied intobuffer. This file name string isnot null-terminated;readlink
normally returns the number of characters copied. Thesize argument specifies the maximum number of characters to copy,usually the allocation size ofbuffer.
If the return value equalssize, you cannot tell whether or notthere was room to return the entire name. So make a bigger buffer andcallreadlink
again. Here is an example:
char *readlink_malloc (const char *filename){ size_t size = 50; char *buffer = NULL; while (1) { buffer = xreallocarray (buffer, size, 2); size *= 2; ssize_t nchars = readlink (filename, buffer, size); if (nchars < 0) { free (buffer); return NULL; } if (nchars < size) return buffer; }}
A value of-1
is returned in case of error. In addition to theusual file name errors (seeFile Name Errors), the followingerrno
error conditions are defined for this function:
EINVAL
The named file is not a symbolic link.
EIO
A hardware error occurred while reading or writing data on the disk.
In some situations it is desirable to resolve all thesymbolic links to get the realname of a file where no prefix names a symbolic link which is followedand no filename in the path is.
or..
. This is forinstance desirable if files have to be compared in which case differentnames can refer to the same inode.
char *
canonicalize_file_name(const char *name)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Thecanonicalize_file_name
function returns the absolute name ofthe file named byname which contains no.
,..
components nor any repeated path separators (/
) or symlinks. Theresult is passed back as the return value of the function in a block ofmemory allocated withmalloc
. If the result is not used anymorethe memory should be freed with a call tofree
.
If any of the path components are missing the function returns a NULLpointer. This is also what is returned if the length of the pathreaches or exceedsPATH_MAX
characters. In any caseerrno
is set accordingly.
ENAMETOOLONG
The resulting path is too long. This error only occurs on systems whichhave a limit on the file name length.
EACCES
At least one of the path components is not readable.
ENOENT
The input file name is empty.
ENOENT
At least one of the path components does not exist.
ELOOP
More thanMAXSYMLINKS
many symlinks have been followed.
This function is a GNU extension and is declared instdlib.h.
The Unix standard includes a similar function which differs fromcanonicalize_file_name
in that the user has to provide the bufferwhere the result is placed in.
char *
realpath(const char *restrictname, char *restrictresolved)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
A call torealpath
where theresolved parameter isNULL
behaves exactly likecanonicalize_file_name
. Thefunction allocates a buffer for the file name and returns a pointer toit. Ifresolved is notNULL
it points to a buffer intowhich the result is copied. It is the callers responsibility toallocate a buffer which is large enough. On systems which definePATH_MAX
this means the buffer must be large enough for apathname of this size. For systems without limitations on the pathnamelength the requirement cannot be met and programs should not callrealpath
with anything butNULL
for the second parameter.
One other difference is that the bufferresolved (if nonzero) willcontain the part of the path component which does not exist or is notreadable if the function returnsNULL
anderrno
is set toEACCES
orENOENT
.
This function is declared instdlib.h.
The advantage of using this function is that it is more widelyavailable. The drawback is that it reports failures for long paths onsystems which have no limits on the file name length.
Next:Renaming Files, Previous:Symbolic Links, Up:File System Interface [Contents][Index]
You can delete a file withunlink
orremove
.
Deletion actually deletes a file name. If this is the file’s only name,then the file is deleted as well. If the file has other remaining names(seeHard Links), it remains accessible under those names.
int
unlink(const char *filename)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theunlink
function deletes the file namefilename. Ifthis is a file’s sole name, the file itself is also deleted. (Actually,if any process has the file open when this happens, deletion ispostponed until all processes have closed the file.)
The functionunlink
is declared in the header fileunistd.h.
This function returns0
on successful completion, and-1
on error. In addition to the usual file name errors(seeFile Name Errors), the followingerrno
error conditions aredefined for this function:
EACCES
Write permission is denied for the directory from which the file is to beremoved, or the directory has the sticky bit set and you do not own the file.
EBUSY
This error indicates that the file is being used by the system in such away that it can’t be unlinked. For example, you might see this error ifthe file name specifies the root directory or a mount point for a filesystem.
ENOENT
The file name to be deleted doesn’t exist.
EPERM
On some systemsunlink
cannot be used to delete the name of adirectory, or at least can only be used this way by a privileged user.To avoid such problems, usermdir
to delete directories. (OnGNU/Linux and GNU/Hurd systemsunlink
can never delete the name of a directory.)
EROFS
The directory containing the file name to be deleted is on a read-onlyfile system and can’t be modified.
int
unlinkat(intfiledes, const char *filename, intflags)
¶| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is a descriptor-relative version of theunlink
function above. SeeDescriptor-Relative Access. Theflagsargument may either be0
or contain the flagAT_REMOVEDIR
:
AT_REMOVEDIR
This flag causesunlinkat
to perform anrmdir
operation onfilename
instead of performing the equivalent ofunlink
.
Compared tounlink
, some additional error conditions can occur due todescriptor-relative access. SeeDescriptor-Relative Access. Inaddition to this, the following other errors can also occur:
EISDIR
The effective final path derived fromfilename andfiledes is adirectory butAT_REMOVEDIR
was not passed inflags
.
int
rmdir(const char *filename)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thermdir
function deletes a directory. The directory must beempty before it can be removed; in other words, it can only containentries for. and...
In most other respects,rmdir
behaves likeunlink
. Thereare two additionalerrno
error conditions defined forrmdir
:
ENOTEMPTY
EEXIST
The directory to be deleted is not empty.
These two error codes are synonymous; some systems use one, and some usethe other. GNU/Linux and GNU/Hurd systems always useENOTEMPTY
.
The prototype for this function is declared in the header fileunistd.h.
int
remove(const char *filename)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is the ISO C function to remove a file. It works likeunlink
for files and likermdir
for directories.remove
is declared instdio.h.
Next:Creating Directories, Previous:Deleting Files, Up:File System Interface [Contents][Index]
Therename
function is used to change a file’s name.
int
rename(const char *oldname, const char *newname)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Therename
function renames the fileoldname tonewname. The file formerly accessible under the nameoldname is afterwards accessible asnewname instead. (Ifthe file had any other names aside fromoldname, it continues tohave those names.)
The directory containing the namenewname must be on the same filesystem as the directory containing the nameoldname.
One special case forrename
is whenoldname andnewname are two names for the same file. The consistent way tohandle this case is to deleteoldname. However, in this casePOSIX requires thatrename
do nothing and report success—whichis inconsistent. We don’t know what your operating system will do.
Ifoldname is not a directory, then any existing file namednewname is removed during the renaming operation. However, ifnewname is the name of a directory,rename
fails in thiscase.
Ifoldname is a directory, then eithernewname must notexist or it must name a directory that is empty. In the latter case,the existing directory namednewname is deleted first. The namenewname must not specify a subdirectory of the directoryoldname
which is being renamed.
One useful feature ofrename
is that the meaning ofnewnamechanges “atomically” from any previously existing file by that name toits new meaning (i.e., the file that was calledoldname). There isno instant at whichnewname is non-existent “in between” the oldmeaning and the new meaning. If there is a system crash during theoperation, it is possible for both names to still exist; butnewname will always be intact if it exists at all.
Ifrename
fails, it returns-1
. In addition to the usualfile name errors (seeFile Name Errors), the followingerrno
error conditions are defined for this function:
EACCES
One of the directories containingnewname oroldnamerefuses write permission; ornewname andoldname aredirectories and write permission is refused for one of them.
EBUSY
A directory named byoldname ornewname is being used bythe system in a way that prevents the renaming from working. This includesdirectories that are mount points for filesystems, and directoriesthat are the current working directories of processes.
ENOTEMPTY
EEXIST
The directorynewname isn’t empty. GNU/Linux and GNU/Hurd systems always returnENOTEMPTY
for this, but some other systems returnEEXIST
.
EINVAL
oldname is a directory that containsnewname.
EISDIR
newname is a directory but theoldname isn’t.
EMLINK
The parent directory ofnewname would have too many links(entries).
ENOENT
The fileoldname doesn’t exist.
ENOSPC
The directory that would containnewname has no room for anotherentry, and there is no space left in the file system to expand it.
EROFS
The operation would involve writing to a directory on a read-only filesystem.
EXDEV
The two file namesnewname andoldname are on differentfile systems.
int
renameat(intoldfiledes, const char *oldname, intnewfiledes, const char *newname)
¶| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is a descriptor-relative version of therename
function above. SeeDescriptor-Relative Access. Ifoldname ornewname is a relative path, it is interpreted relative to thedirectory associated witholdfiledes ornewfiledes,respectively. Absolute paths are interpreted in the usual way.
Compared torename
, some additional error conditions can occur.SeeDescriptor-Relative Access.
Next:File Attributes, Previous:Renaming Files, Up:File System Interface [Contents][Index]
Directories are created with themkdir
function. (There is alsoa shell commandmkdir
which does the same thing.)
int
mkdir(const char *filename, mode_tmode)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Themkdir
function creates a new, empty directory with namefilename.
The argumentmode specifies the file permissions for the newdirectory file. SeeThe Mode Bits for Access Permission, for more information aboutthis.
A return value of0
indicates successful completion, and-1
indicates failure. In addition to the usual file name syntaxerrors (seeFile Name Errors), the followingerrno
errorconditions are defined for this function:
EACCES
Write permission is denied for the parent directory in which the newdirectory is to be added.
EEXIST
A file namedfilename already exists.
EMLINK
The parent directory has too many links (entries).
Well-designed file systems never report this error, because they permitmore links than your disk could possibly hold. However, you must stilltake account of the possibility of this error, as it could result fromnetwork access to a file system on another machine.
ENOSPC
The file system doesn’t have enough room to create the new directory.
EROFS
The parent directory of the directory being created is on a read-onlyfile system and cannot be modified.
To use this function, your program should include the header filesys/stat.h.
int
mkdirat(intfiledes, const char *filename, mode_tmode)
¶| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is a descriptor-relative version of themkdir
function above. SeeDescriptor-Relative Access.
Compared tomkdir
, some additional error conditions can occur.SeeDescriptor-Relative Access.
Next:Making Special Files, Previous:Creating Directories, Up:File System Interface [Contents][Index]
When you issue an ‘ls -l’ shell command on a file, it gives youinformation about the size of the file, who owns it, when it was lastmodified, etc. These are called thefile attributes, and areassociated with the file itself and not a particular one of its names.
This section contains information about how you can inquire about andmodify the attributes of a file.
Next:Reading the Attributes of a File, Up:File Attributes [Contents][Index]
When you read the attributes of a file, they come back in a structurecalledstruct stat
. This section describes the names of theattributes, their data types, and what they mean. For the functionsto read the attributes of a file, seeReading the Attributes of a File.
The header filesys/stat.h declares all the symbols definedin this section.
Thestat
structure type is used to return information about theattributes of a file. It contains at least the following members:
mode_t st_mode
Specifies the mode of the file. This includes file type information(seeTesting the Type of a File) and the file permission bits(seeThe Mode Bits for Access Permission).
ino_t st_ino
The file serial number, which distinguishes this file from all otherfiles on the same device.
dev_t st_dev
Identifies the device containing the file. Thest_ino
andst_dev
, taken together, uniquely identify the file. Thest_dev
value is not necessarily consistent across reboots orsystem crashes, however.
nlink_t st_nlink
The number of hard links to the file. This count keeps track of howmany directories have entries for this file. If the count is everdecremented to zero, then the file itself is discarded as soon as noprocess still holds it open. Symbolic links are not counted in thetotal.
uid_t st_uid
The user ID of the file’s owner. SeeFile Owner.
gid_t st_gid
The group ID of the file. SeeFile Owner.
off_t st_size
This specifies the size of a regular file in bytes. For files that arereally devices this field isn’t usually meaningful. For symbolic linksthis specifies the length of the file name the link refers to.
time_t st_atime
This is the last access time for the file. SeeFile Times.
unsigned long int st_atime_usec
This is the fractional part of the last access time for the file.SeeFile Times.
time_t st_mtime
This is the time of the last modification to the contents of the file.SeeFile Times.
unsigned long int st_mtime_usec
This is the fractional part of the time of the last modification to thecontents of the file. SeeFile Times.
time_t st_ctime
This is the time of the last modification to the attributes of the file.SeeFile Times.
unsigned long int st_ctime_usec
This is the fractional part of the time of the last modification to theattributes of the file. SeeFile Times.
blkcnt_t st_blocks
This is the amount of disk space that the file occupies, measured inunits of 512-byte blocks.
The number of disk blocks is not strictly proportional to the size ofthe file, for two reasons: the file system may use some blocks forinternal record keeping; and the file may be sparse—it may have“holes” which contain zeros but do not actually take up space on thedisk.
You can tell (approximately) whether a file is sparse by comparing thisvalue withst_size
, like this:
(st.st_blocks * 512 < st.st_size)
This test is not perfect because a file that is just slightly sparsemight not be detected as sparse at all. For practical applications,this is not a problem.
unsigned int st_blksize
The optimal block size for reading or writing this file, in bytes. Youmight use this size for allocating the buffer space for reading orwriting the file. (This is unrelated tost_blocks
.)
The extensions for the Large File Support (LFS) require, even on 32-bitmachines, types which can handle file sizes up to 2^63.Therefore a new definition ofstruct stat
is necessary.
The members of this type are the same and have the same names as thoseinstruct stat
. The only difference is that the membersst_ino
,st_size
, andst_blocks
have a differenttype to support larger values.
mode_t st_mode
Specifies the mode of the file. This includes file type information(seeTesting the Type of a File) and the file permission bits(seeThe Mode Bits for Access Permission).
ino64_t st_ino
The file serial number, which distinguishes this file from all otherfiles on the same device.
dev_t st_dev
Identifies the device containing the file. Thest_ino
andst_dev
, taken together, uniquely identify the file. Thest_dev
value is not necessarily consistent across reboots orsystem crashes, however.
nlink_t st_nlink
The number of hard links to the file. This count keeps track of howmany directories have entries for this file. If the count is everdecremented to zero, then the file itself is discarded as soon as noprocess still holds it open. Symbolic links are not counted in thetotal.
uid_t st_uid
The user ID of the file’s owner. SeeFile Owner.
gid_t st_gid
The group ID of the file. SeeFile Owner.
off64_t st_size
This specifies the size of a regular file in bytes. For files that arereally devices this field isn’t usually meaningful. For symbolic linksthis specifies the length of the file name the link refers to.
time_t st_atime
This is the last access time for the file. SeeFile Times.
unsigned long int st_atime_usec
This is the fractional part of the last access time for the file.SeeFile Times.
time_t st_mtime
This is the time of the last modification to the contents of the file.SeeFile Times.
unsigned long int st_mtime_usec
This is the fractional part of the time of the last modification to thecontents of the file. SeeFile Times.
time_t st_ctime
This is the time of the last modification to the attributes of the file.SeeFile Times.
unsigned long int st_ctime_usec
This is the fractional part of the time of the last modification to theattributes of the file. SeeFile Times.
blkcnt64_t st_blocks
This is the amount of disk space that the file occupies, measured inunits of 512-byte blocks.
unsigned int st_blksize
The optimal block size for reading of writing this file, in bytes. Youmight use this size for allocating the buffer space for reading ofwriting the file. (This is unrelated tost_blocks
.)
Some of the file attributes have special data type names which existspecifically for those attributes. (They are all aliases for well-knowninteger types that you know and love.) These typedef names are definedin the header filesys/types.h as well as insys/stat.h.Here is a list of them.
This is an integer data type used to represent file modes. Inthe GNU C Library, this is an unsigned type no narrower thanunsignedint
.
This is an unsigned integer type used to represent file serial numbers.(In Unix jargon, these are sometimes calledinode numbers.)In the GNU C Library, this type is no narrower thanunsigned int
.
If the source is compiled with_FILE_OFFSET_BITS == 64
this typeis transparently replaced byino64_t
.
This is an unsigned integer type used to represent file serial numbersfor the use in LFS. In the GNU C Library, this type is no narrower thanunsigned int
.
When compiling with_FILE_OFFSET_BITS == 64
this type isavailable under the nameino_t
.
This is an arithmetic data type used to represent file device numbers.In the GNU C Library, this is an integer type no narrower thanint
.
This is an integer type used to represent file link counts.
This is a signed integer type used to represent block counts.In the GNU C Library, this type is no narrower thanint
.
If the source is compiled with_FILE_OFFSET_BITS == 64
this typeis transparently replaced byblkcnt64_t
.
This is a signed integer type used to represent block counts for theuse in LFS. In the GNU C Library, this type is no narrower thanint
.
When compiling with_FILE_OFFSET_BITS == 64
this type isavailable under the nameblkcnt_t
.
Next:Testing the Type of a File, Previous:The meaning of the File Attributes, Up:File Attributes [Contents][Index]
To examine the attributes of files, use the functionsstat
,fstat
andlstat
. They return the attribute information inastruct stat
object. All three functions are declared in theheader filesys/stat.h.
int
stat(const char *filename, struct stat *buf)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestat
function returns information about the attributes of thefile named byfilename in the structure pointed to bybuf.
Iffilename is the name of a symbolic link, the attributes you getdescribe the file that the link points to. If the link points to anonexistent file name, thenstat
fails reporting a nonexistentfile.
The return value is0
if the operation is successful, or-1
on failure. In addition to the usual file name errors(seeFile Name Errors, the followingerrno
error conditionsare defined for this function:
ENOENT
The file named byfilename doesn’t exist.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is in factstat64
since the LFS interface transparentlyreplaces the normal implementation.
int
stat64(const char *filename, struct stat64 *buf)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar tostat
but it is also able to work onfiles larger than 2^31 bytes on 32-bit systems. To be able to dothis the result is stored in a variable of typestruct stat64
towhichbuf must point.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is available under the namestat
and so transparentlyreplaces the interface for small files on 32-bit machines.
int
fstat(intfiledes, struct stat *buf)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefstat
function is likestat
, except that it takes anopen file descriptor as an argument instead of a file name.SeeLow-Level Input/Output.
Likestat
,fstat
returns0
on success and-1
on failure. The followingerrno
error conditions are defined forfstat
:
EBADF
Thefiledes argument is not a valid file descriptor.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is in factfstat64
since the LFS interface transparentlyreplaces the normal implementation.
int
fstat64(intfiledes, struct stat64 *buf)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar tofstat
but is able to work on largefiles on 32-bit platforms. For large files the file descriptorfiledes should be obtained byopen64
orcreat64
.Thebuf pointer points to a variable of typestruct stat64
which is able to represent the larger values.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is available under the namefstat
and so transparentlyreplaces the interface for small files on 32-bit machines.
int
fstatat(intfiledes, const char *filename, struct stat *buf, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is a descriptor-relative version of thefstat
function above. SeeDescriptor-Relative Access. Theflagsargument can contain a combination of the flagsAT_EMPTY_PATH
,AT_NO_AUTOMOUNT
,AT_SYMLINK_NOFOLLOW
.
Compared tofstat
, the following additional error conditions canoccur:
EBADF
Thefiledes argument is not a valid file descriptor.
EINVAL
Theflags argument is not valid for this function.
ENOTDIR
The descriptorfiledes is not associated with a directory, andfilename is a relative file name.
ENOENT
The file named byfilename does not exist, it’s a dangling symbolic linkandflags does not containAT_SYMLINK_NOFOLLOW
, orfilenameis an empty string andflags does not containAT_EMPTY_PATH
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is in factfstatat64
since the LFS interface transparentlyreplaces the normal implementation.
int
fstatat64(intfiledes, const char *filename, struct stat64 *buf, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is the large-file variant offstatat
, similar tohowfstat64
is the variant offstat
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is available under the namefstatat
and so transparentlyreplaces the interface for small files on 32-bit machines.
int
lstat(const char *filename, struct stat *buf)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thelstat
function is likestat
, except that it does notfollow symbolic links. Iffilename is the name of a symboliclink,lstat
returns information about the link itself; otherwiselstat
works likestat
. SeeSymbolic Links.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is in factlstat64
since the LFS interface transparentlyreplaces the normal implementation.
int
lstat64(const char *filename, struct stat64 *buf)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar tolstat
but it is also able to work onfiles larger than 2^31 bytes on 32-bit systems. To be able to dothis the result is stored in a variable of typestruct stat64
towhichbuf must point.
When the sources are compiled with_FILE_OFFSET_BITS == 64
thisfunction is available under the namelstat
and so transparentlyreplaces the interface for small files on 32-bit machines.
Next:File Owner, Previous:Reading the Attributes of a File, Up:File Attributes [Contents][Index]
Thefile mode, stored in thest_mode
field of the fileattributes, contains two kinds of information: the file type code, andthe access permission bits. This section discusses only the type code,which you can use to tell whether the file is a directory, socket,symbolic link, and so on. For details about access permissions seeThe Mode Bits for Access Permission.
There are two ways you can access the file type information in a filemode. Firstly, for each file type there is apredicate macrowhich examines a given file mode and returns whether it is of that typeor not. Secondly, you can mask out the rest of the file mode to leavejust the file type code, and compare this against constants for each ofthe supported file types.
All of the symbols listed in this section are defined in the header filesys/stat.h.
The following predicate macros test the type of a file, given the valuem which is thest_mode
field returned bystat
onthat file:
int
S_ISDIR(mode_tm)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns non-zero if the file is a directory.
int
S_ISCHR(mode_tm)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns non-zero if the file is a character special file (adevice like a terminal).
int
S_ISBLK(mode_tm)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns non-zero if the file is a block special file (a devicelike a disk).
int
S_ISREG(mode_tm)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns non-zero if the file is a regular file.
int
S_ISFIFO(mode_tm)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns non-zero if the file is a FIFO special file, or apipe. SeePipes and FIFOs.
int
S_ISLNK(mode_tm)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns non-zero if the file is a symbolic link.SeeSymbolic Links.
int
S_ISSOCK(mode_tm)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns non-zero if the file is a socket. SeeSockets.
An alternate non-POSIX method of testing the file type is supported forcompatibility with BSD. The mode can be bitwise AND-ed withS_IFMT
to extract the file type code, and compared to theappropriate constant. For example,
S_ISCHR (mode)
is equivalent to:
((mode & S_IFMT) == S_IFCHR)
int
S_IFMT ¶This is a bit mask used to extract the file type code from a mode value.
These are the symbolic names for the different file type codes:
S_IFDIR
¶This is the file type constant of a directory file.
S_IFCHR
¶This is the file type constant of a character-oriented device file.
S_IFBLK
¶This is the file type constant of a block-oriented device file.
S_IFREG
¶This is the file type constant of a regular file.
S_IFLNK
¶This is the file type constant of a symbolic link.
S_IFSOCK
¶This is the file type constant of a socket.
S_IFIFO
¶This is the file type constant of a FIFO or pipe.
The POSIX.1b standard introduced a few more objects which possibly canbe implemented as objects in the filesystem. These are message queues,semaphores, and shared memory objects. To allow differentiating theseobjects from other files the POSIX standard introduced three new testmacros. But unlike the other macros they do not take the value of thest_mode
field as the parameter. Instead they expect a pointer tothe wholestruct stat
structure.
int
S_TYPEISMQ(struct stat *s)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
If the system implements POSIX message queues as distinct objects and thefile is a message queue object, this macro returns a non-zero value.In all other cases the result is zero.
int
S_TYPEISSEM(struct stat *s)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
If the system implements POSIX semaphores as distinct objects and thefile is a semaphore object, this macro returns a non-zero value.In all other cases the result is zero.
int
S_TYPEISSHM(struct stat *s)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
If the system implements POSIX shared memory objects as distinct objectsand the file is a shared memory object, this macro returns a non-zerovalue. In all other cases the result is zero.
Next:The Mode Bits for Access Permission, Previous:Testing the Type of a File, Up:File Attributes [Contents][Index]
Every file has anowner which is one of the registered user namesdefined on the system. Each file also has agroup which is one ofthe defined groups. The file owner can often be useful for showing youwho edited the file (especially when you edit with GNU Emacs), but itsmain purpose is for access control.
The file owner and group play a role in determining access because thefile has one set of access permission bits for the owner, another setthat applies to users who belong to the file’s group, and a third set ofbits that applies to everyone else. SeeHow Your Access to a File is Decided, for thedetails of how access is decided based on this data.
When a file is created, its owner is set to the effective user ID of theprocess that creates it (seeThe Persona of a Process). The file’s group IDmay be set to either the effective group ID of the process, or the groupID of the directory that contains the file, depending on the systemwhere the file is stored. When you access a remote file system, itbehaves according to its own rules, not according to the system yourprogram is running on. Thus, your program must be prepared to encountereither kind of behavior no matter what kind of system you run it on.
You can change the owner and/or group owner of an existing file usingthechown
function. This is the primitive for thechown
andchgrp
shell commands.
The prototype for this function is declared inunistd.h.
int
chown(const char *filename, uid_towner, gid_tgroup)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thechown
function changes the owner of the filefilename toowner, and its group owner togroup.
Changing the owner of the file on certain systems clears the set-user-IDand set-group-ID permission bits. (This is because those bits may notbe appropriate for the new owner.) Other file permission bits are notchanged.
The return value is0
on success and-1
on failure.In addition to the usual file name errors (seeFile Name Errors),the followingerrno
error conditions are defined for this function:
EPERM
This process lacks permission to make the requested change.
Only privileged users or the file’s owner can change the file’s group.On most file systems, only privileged users can change the file owner;some file systems allow you to change the owner if you are currently theowner. When you access a remote file system, the behavior you encounteris determined by the system that actually holds the file, not by thesystem your program is running on.
SeeOptional Features in File Support, for information about the_POSIX_CHOWN_RESTRICTED
macro.
EROFS
The file is on a read-only file system.
int
fchown(intfiledes, uid_towner, gid_tgroup)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is likechown
, except that it changes the owner of the openfile with descriptorfiledes.
The return value fromfchown
is0
on success and-1
on failure. The followingerrno
error codes are defined for thisfunction:
EBADF
Thefiledes argument is not a valid file descriptor.
EINVAL
Thefiledes argument corresponds to a pipe or socket, not an ordinaryfile.
EPERM
This process lacks permission to make the requested change. For detailsseechmod
above.
EROFS
The file resides on a read-only file system.
Next:How Your Access to a File is Decided, Previous:File Owner, Up:File Attributes [Contents][Index]
Thefile mode, stored in thest_mode
field of the fileattributes, contains two kinds of information: the file type code, andthe access permission bits. This section discusses only the accesspermission bits, which control who can read or write the file.SeeTesting the Type of a File, for information about the file type code.
All of the symbols listed in this section are defined in the header filesys/stat.h.
These symbolic constants are defined for the file mode bits that controlaccess permission for the file:
S_IRUSR
¶S_IREAD
¶Read permission bit for the owner of the file. On many systems this bitis 0400.S_IREAD
is an obsolete synonym provided for BSDcompatibility.
S_IWUSR
¶S_IWRITE
¶Write permission bit for the owner of the file. Usually 0200.S_IWRITE
is an obsolete synonym provided for BSD compatibility.
S_IXUSR
¶S_IEXEC
¶Execute (for ordinary files) or search (for directories) permission bitfor the owner of the file. Usually 0100.S_IEXEC
is an obsoletesynonym provided for BSD compatibility.
S_IRWXU
¶This is equivalent to ‘(S_IRUSR | S_IWUSR | S_IXUSR)’.
S_IRGRP
¶Read permission bit for the group owner of the file. Usually 040.
S_IWGRP
¶Write permission bit for the group owner of the file. Usually 020.
S_IXGRP
¶Execute or search permission bit for the group owner of the file.Usually 010.
S_IRWXG
¶This is equivalent to ‘(S_IRGRP | S_IWGRP | S_IXGRP)’.
S_IROTH
¶Read permission bit for other users. Usually 04.
S_IWOTH
¶Write permission bit for other users. Usually 02.
S_IXOTH
¶Execute or search permission bit for other users. Usually 01.
S_IRWXO
¶This is equivalent to ‘(S_IROTH | S_IWOTH | S_IXOTH)’.
S_ISUID
¶This is the set-user-ID on execute bit, usually 04000.SeeHow an Application Can Change Persona.
S_ISGID
¶This is the set-group-ID on execute bit, usually 02000.SeeHow an Application Can Change Persona.
S_ISVTX
¶This is thesticky bit, usually 01000.
For a directory it gives permission to delete a file in that directoryonly if you own that file. Ordinarily, a user can either delete all thefiles in a directory or cannot delete any of them (based on whether theuser has write permission for the directory). The same restrictionapplies—you must have both write permission for the directory and ownthe file you want to delete. The one exception is that the owner of thedirectory can delete any file in the directory, no matter who owns it(provided the owner has given himself write permission for thedirectory). This is commonly used for the/tmp directory, whereanyone may create files but not delete files created by other users.
Originally the sticky bit on an executable file modified the swappingpolicies of the system. Normally, when a program terminated, its pagesin core were immediately freed and reused. If the sticky bit was set onthe executable file, the system kept the pages in core for a while as ifthe program were still running. This was advantageous for a programlikely to be run many times in succession. This usage is obsolete inmodern systems. When a program terminates, its pages always remain incore as long as there is no shortage of memory in the system. When theprogram is next run, its pages will still be in core if no shortagearose since the last run.
On some modern systems where the sticky bit has no useful meaning for anexecutable file, you cannot set the bit at all for a non-directory.If you try,chmod
fails withEFTYPE
;seeAssigning File Permissions.
Some systems (particularly SunOS) have yet another use for the stickybit. If the sticky bit is set on a file that isnot executable,it means the opposite: never cache the pages of this file at all. Themain use of this is for the files on an NFS server machine which areused as the swap area of diskless client machines. The idea is that thepages of the file will be cached in the client’s memory, so it is awaste of the server’s memory to cache them a second time. With thisusage the sticky bit also implies that the filesystem may fail to recordthe file’s modification time onto disk reliably (the idea being thatno-one cares for a swap file).
This bit is only available on BSD systems (and those derived fromthem). Therefore one has to use the_GNU_SOURCE
feature selectmacro, or not define any feature test macros, to get the definition(seeFeature Test Macros).
The actual bit values of the symbols are listed in the table aboveso you can decode file mode values when debugging your programs.These bit values are correct for most systems, but they are notguaranteed.
Warning: Writing explicit numbers for file permissions is badpractice. Not only is it not portable, it also requires everyone whoreads your program to remember what the bits mean. To make your programclean use the symbolic names.
Next:Assigning File Permissions, Previous:The Mode Bits for Access Permission, Up:File Attributes [Contents][Index]
Recall that the operating system normally decides access permission fora file based on the effective user and group IDs of the process and itssupplementary group IDs, together with the file’s owner, group andpermission bits. These concepts are discussed in detail inThe Persona of a Process.
If the effective user ID of the process matches the owner user ID of thefile, then permissions for read, write, and execute/search arecontrolled by the corresponding “user” (or “owner”) bits. Likewise,if any of the effective group ID or supplementary group IDs of theprocess matches the group owner ID of the file, then permissions arecontrolled by the “group” bits. Otherwise, permissions are controlledby the “other” bits.
Privileged users, like ‘root’, can access any file regardless ofits permission bits. As a special case, for a file to be executableeven by a privileged user, at least one of its execute bits must be set.
Next:Testing Permission to Access a File, Previous:How Your Access to a File is Decided, Up:File Attributes [Contents][Index]
The primitive functions for creating files (for example,open
ormkdir
) take amode argument, which specifies the filepermissions to give the newly created file. This mode is modified bythe process’sfile creation mask, orumask, before it isused.
The bits that are set in the file creation mask identify permissionsthat are always to be disabled for newly created files. For example, ifyou set all the “other” access bits in the mask, then newly createdfiles are not accessible at all to processes in the “other” category,even if themode argument passed to the create function wouldpermit such access. In other words, the file creation mask is thecomplement of the ordinary access permissions you want to grant.
Programs that create files typically specify amode argument thatincludes all the permissions that make sense for the particular file.For an ordinary file, this is typically read and write permission forall classes of users. These permissions are then restricted asspecified by the individual user’s own file creation mask.
To change the permission of an existing file given its name, callchmod
. This function uses the specified permission bits andignores the file creation mask.
In normal use, the file creation mask is initialized by the user’s loginshell (using theumask
shell command), and inherited by allsubprocesses. Application programs normally don’t need to worry aboutthe file creation mask. It will automatically do what it is supposed todo.
When your program needs to create a file and bypass the umask for itsaccess permissions, the easiest way to do this is to usefchmod
after opening the file, rather than changing the umask. In fact,changing the umask is usually done only by shells. They use theumask
function.
The functions in this section are declared insys/stat.h.
mode_t
umask(mode_tmask)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theumask
function sets the file creation mask of the currentprocess tomask, and returns the previous value of the filecreation mask.
Here is an example showing how to read the mask withumask
without changing it permanently:
mode_tread_umask (void){ mode_t mask = umask (0); umask (mask); return mask;}
However, on GNU/Hurd systems it is better to usegetumask
ifyou just want to read the mask value, because it is reentrant.
mode_t
getumask(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Return the current value of the file creation mask for the currentprocess. This function is a GNU extension and is only available onGNU/Hurd systems.
int
chmod(const char *filename, mode_tmode)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thechmod
function sets the access permission bits for the filenamed byfilename tomode.
Iffilename is a symbolic link,chmod
changes thepermissions of the file pointed to by the link, not those of the linkitself.
This function returns0
if successful and-1
if not. Inaddition to the usual file name errors (seeFile Name Errors), the followingerrno
error conditions are defined forthis function:
ENOENT
The named file doesn’t exist.
EPERM
This process does not have permission to change the access permissionsof this file. Only the file’s owner (as judged by the effective user IDof the process) or a privileged user can change them.
EROFS
The file resides on a read-only file system.
EFTYPE
mode has theS_ISVTX
bit (the “sticky bit”) set,and the named file is not a directory. Some systems do not allow setting thesticky bit on non-directory files, and some do (and only some of thoseassign a useful meaning to the bit for non-directory files).
You only getEFTYPE
on systems where the sticky bit has no usefulmeaning for non-directory files, so it is always safe to just clear thebit inmode and callchmod
again. SeeThe Mode Bits for Access Permission,for full details on the sticky bit.
int
fchmod(intfiledes, mode_tmode)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is likechmod
, except that it changes the permissions of thecurrently open file given byfiledes.
The return value fromfchmod
is0
on success and-1
on failure. The followingerrno
error codes are defined for thisfunction:
EBADF
Thefiledes argument is not a valid file descriptor.
EINVAL
Thefiledes argument corresponds to a pipe or socket, or somethingelse that doesn’t really have access permissions.
EPERM
This process does not have permission to change the access permissionsof this file. Only the file’s owner (as judged by the effective user IDof the process) or a privileged user can change them.
EROFS
The file resides on a read-only file system.
Next:File Times, Previous:Assigning File Permissions, Up:File Attributes [Contents][Index]
In some situations it is desirable to allow programs to access files ordevices even if this is not possible with the permissions granted to theuser. One possible solution is to set the setuid-bit of the programfile. If such a program is started theeffective user ID of theprocess is changed to that of the owner of the program file. So toallow write access to files like/etc/passwd, which normally canbe written only by the super-user, the modifying program will have to beowned byroot
and the setuid-bit must be set.
But besides the files the program is intended to change the user shouldnot be allowed to access any file to which s/he would not have accessanyway. The program therefore must explicitly check whethertheuser would have the necessary access to a file, before it reads orwrites the file.
To do this, use the functionaccess
, which checks for accesspermission based on the process’sreal user ID rather than theeffective user ID. (The setuid feature does not alter the real user ID,so it reflects the user who actually ran the program.)
There is another way you could check this access, which is easy todescribe, but very hard to use. This is to examine the file mode bitsand mimic the system’s own access computation. This method isundesirable because many systems have additional access controlfeatures; your program cannot portably mimic them, and you would notwant to try to keep track of the diverse features that different systemshave. Usingaccess
is simple and automatically does whatever isappropriate for the system you are using.
access
isonly appropriate to use in setuid programs.A non-setuid program will always use the effective ID rather than thereal ID.
The symbols in this section are declared inunistd.h.
int
access(const char *filename, inthow)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theaccess
function checks to see whether the file named byfilename can be accessed in the way specified by thehowargument. Thehow argument either can be the bitwise OR of theflagsR_OK
,W_OK
,X_OK
, or the existence testF_OK
.
This function uses thereal user and group IDs of the callingprocess, rather than theeffective IDs, to check for accesspermission. As a result, if you use the function from asetuid
orsetgid
program (seeHow an Application Can Change Persona), it givesinformation relative to the user who actually ran the program.
The return value is0
if the access is permitted, and-1
otherwise. (In other words, treated as a predicate function,access
returns true if the requested access isdenied.)
In addition to the usual file name errors (seeFile Name Errors), the followingerrno
error conditions are defined forthis function:
EACCES
The access specified byhow is denied.
ENOENT
The file doesn’t exist.
EROFS
Write permission was requested for a file on a read-only file system.
These macros are defined in the header fileunistd.h for useas thehow argument to theaccess
function. The valuesare integer constants.
int
R_OK ¶Flag meaning test for read permission.
int
W_OK ¶Flag meaning test for write permission.
int
X_OK ¶Flag meaning test for execute/search permission.
int
F_OK ¶Flag meaning test for existence of the file.
int
faccessat(intfiledes, const char *filename, inthow, intflags)
¶| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is a descriptor-relative version of theaccess
function above. SeeDescriptor-Relative Access. Theflagsargument can contain a combination of the flagsAT_EACCESS
describedbelow,AT_EMPTY_PATH
, andAT_SYMLINK_NOFOLLOW
.
AT_EACCESS
¶This flag when passed to thefaccessat
function causes it to performaccess checks using effective user and group IDs instead of real IDs, whichis the default and matches theaccess
function.
Compared toaccess
, some additional error conditions can occur.SeeDescriptor-Relative Access.
This function may not work correctly on older kernels missing thefaccessat2
system call.
Next:File Size, Previous:Testing Permission to Access a File, Up:File Attributes [Contents][Index]
Each file has three time stamps associated with it: its access time,its modification time, and its attribute modification time. Thesecorrespond to thest_atime
,st_mtime
, andst_ctime
members of thestat
structure; seeFile Attributes.
All of these times are represented in calendar time format, astime_t
objects. This data type is defined intime.h.For more information about representation and manipulation of timevalues, seeCalendar Time.
Reading from a file updates its access time attribute, and writingupdates its modification time. When a file is created, all threetime stamps for that file are set to the current time. In addition, theattribute change time and modification time fields of the directory thatcontains the new entry are updated.
Adding a new name for a file with thelink
function updates theattribute change time field of the file being linked, and both theattribute change time and modification time fields of the directorycontaining the new name. These same fields are affected if a file nameis deleted withunlink
,remove
orrmdir
. Renaminga file withrename
affects only the attribute change time andmodification time fields of the two parent directories involved, and notthe times for the file being renamed.
Changing the attributes of a file (for example, withchmod
)updates its attribute change time field.
You can also change some of the time stamps of a file explicitly usingtheutime
function—all except the attribute change time. Youneed to include the header fileutime.h to use this facility.
Theutimbuf
structure is used with theutime
function tospecify new access and modification times for a file. It contains thefollowing members:
time_t actime
This is the access time for the file.
time_t modtime
This is the modification time for the file.
int
utime(const char *filename, const struct utimbuf *times)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is used to modify the file times associated with the filenamedfilename.
Iftimes is a null pointer, then the access and modification timesof the file are set to the current time. Otherwise, they are set to thevalues from theactime
andmodtime
members (respectively)of theutimbuf
structure pointed to bytimes.
The attribute modification time for the file is set to the current timein either case (since changing the time stamps is itself a modificationof the file attributes).
Theutime
function returns0
if successful and-1
on failure. In addition to the usual file name errors(seeFile Name Errors), the followingerrno
error conditionsare defined for this function:
EACCES
There is a permission problem in the case where a null pointer waspassed as thetimes argument. In order to update the time stamp onthe file, you must either be the owner of the file, have writepermission for the file, or be a privileged user.
ENOENT
The file doesn’t exist.
EPERM
If thetimes argument is not a null pointer, you must either bethe owner of the file or be a privileged user.
EROFS
The file lives on a read-only file system.
Each of the three time stamps has a corresponding microsecond part,which extends its resolution. These fields are calledst_atime_usec
,st_mtime_usec
, andst_ctime_usec
;each has a value between 0 and 999,999, which indicates the time inmicroseconds. They correspond to thetv_usec
field of atimeval
structure; seeTime Types.
Theutimes
function is likeutime
, but also lets you specifythe fractional part of the file times. The prototype for this function isin the header filesys/time.h.
int
utimes(const char *filename, const struct timevaltvp[2]
)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function sets the file access and modification times of the filefilename. The new file access time is specified bytvp[0]
, and the new modification time bytvp[1]
. Similar toutime
, iftvp is a nullpointer then the access and modification times of the file are set tothe current time. This function comes from BSD.
The return values and error conditions are the same as for theutime
function.
int
lutimes(const char *filename, const struct timevaltvp[2]
)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likeutimes
, except that it does not followsymbolic links. Iffilename is the name of a symbolic link,lutimes
sets the file access and modification times of thesymbolic link special file itself (as seen bylstat
;seeSymbolic Links) whileutimes
sets the file access andmodification times of the file the symbolic link refers to. Thisfunction comes from FreeBSD, and is not available on all platforms (ifnot available, it will fail withENOSYS
).
The return values and error conditions are the same as for theutime
function.
int
futimes(intfd, const struct timevaltvp[2]
)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likeutimes
, except that it takes an open filedescriptor as an argument instead of a file name. SeeLow-Level Input/Output. This function comes from FreeBSD, and is not available on allplatforms (if not available, it will fail withENOSYS
).
Likeutimes
,futimes
returns0
on success and-1
on failure. The followingerrno
error conditions are defined forfutimes
:
EACCES
There is a permission problem in the case where a null pointer waspassed as thetimes argument. In order to update the time stamp onthe file, you must either be the owner of the file, have writepermission for the file, or be a privileged user.
EBADF
Thefiledes argument is not a valid file descriptor.
EINVAL
At least one of the fields in thetvp
array passed has an invalidvalue.
EPERM
If thetimes argument is not a null pointer, you must either bethe owner of the file or be a privileged user.
EROFS
The file lives on a read-only file system.
int
futimens(intfiledes, const struct timespectsp[2]
)
¶| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is likefutimes
, except that it sets the file accessand modification timestamps with nanosecond precision. The argumenttsp
is used similarly tofutimes
’tvp
, but has aconst struct timespec
type that can express calendar time withnanosecond precision. SeeTime Types.
int
utimensat(intfiledes, const char *filename, const struct timespectsp[2]
, intflags)
¶| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is a descriptor-relative version of thefutimens
function above. SeeDescriptor-Relative Access. Theflagsargument can contain a combination of the flagsAT_EMPTY_PATH
, andAT_SYMLINK_NOFOLLOW
. The call:
futimens (filedes,tsp)
is equivalent to:
utimensat (filedes,NULL
,tsp, 0)
Compared tofutimens
, some additional error conditions can occur dueto descriptor-relative access. SeeDescriptor-Relative Access. Inaddition to this, the following other errors can also occur:
EINVAL
Thefilename argument is NULL,filedes is notAT_FDCWD
,andflags is not0
.
ELOOP
There are too many levels of indirection. This can be the result ofcircular symbolic links to directories.
ENAMETOOLONG
The resulting path is too long. This error only occurs on systems whichhave a limit on the file name length.
ENOENT
Thefilename argument is an empty string andflags does notcontainAT_EMPTY_PATH
, orfilename does not refer to anexisting file.
ESRCH
Search permission was denied for one of the prefix components of the thefilename argument.
Next:Storage Allocation, Previous:File Times, Up:File Attributes [Contents][Index]
Normally file sizes are maintained automatically. A file begins with asize of0 and is automatically extended when data is written pastits end. It is also possible to empty a file completely by anopen
orfopen
call.
However, sometimes it is necessary toreduce the size of a file.This can be done with thetruncate
andftruncate
functions.They were introduced in BSD Unix.ftruncate
was later added toPOSIX.1.
Some systems allow you to extend a file (creating holes) with thesefunctions. This is useful when using memory-mapped I/O(seeMemory-mapped I/O), where files are not automatically extended.However, it is not portable but must be implemented ifmmap
allows mapping of files (i.e.,_POSIX_MAPPED_FILES
is defined).
Using these functions on anything other than a regular file givesundefined results. On many systems, such a call will appear tosucceed, without actually accomplishing anything.
int
truncate(const char *filename, off_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thetruncate
function changes the size offilename tolength. Iflength is shorter than the previous length, dataat the end will be lost. The file must be writable by the user toperform this operation.
Iflength is longer, holes will be added to the end. However, somesystems do not support this feature and will leave the file unchanged.
When the source file is compiled with_FILE_OFFSET_BITS == 64
thetruncate
function is in facttruncate64
and the typeoff_t
has 64 bits which makes it possible to handle files up to2^63 bytes in length.
The return value is0 for success, or-1 for an error. Inaddition to the usual file name errors, the following errors may occur:
EACCES
The file is a directory or not writable.
EINVAL
length is negative.
EFBIG
The operation would extend the file beyond the limits of the operating system.
EIO
A hardware I/O error occurred.
EPERM
The file is "append-only" or "immutable".
EINTR
The operation was interrupted by a signal.
int
truncate64(const char *name, off64_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thetruncate
function. Thedifference is that thelength argument is 64 bits wide even on 32bits machines, which allows the handling of files with sizes up to2^63 bytes.
When the source file is compiled with_FILE_OFFSET_BITS == 64
on a32 bits machine this function is actually available under the nametruncate
and so transparently replaces the 32 bits interface.
int
ftruncate(intfd, off_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is liketruncate
, but it works on a file descriptorfdfor an opened file instead of a file name to identify the object. Thefile must be opened for writing to successfully carry out the operation.
The POSIX standard leaves it implementation defined what happens if thespecified newlength of the file is bigger than the original size.Theftruncate
function might simply leave the file alone and donothing or it can increase the size to the desired size. In this latercase the extended area should be zero-filled. So usingftruncate
is no reliable way to increase the file size but if it is possible it isprobably the fastest way. The function also operates on POSIX sharedmemory segments if these are implemented by the system.
ftruncate
is especially useful in combination withmmap
.Since the mapped region must have a fixed size one cannot enlarge thefile by writing something beyond the last mapped page. Instead one hasto enlarge the file itself and then remap the file with the new size.The example below shows how this works.
When the source file is compiled with_FILE_OFFSET_BITS == 64
theftruncate
function is in factftruncate64
and the typeoff_t
has 64 bits which makes it possible to handle files up to2^63 bytes in length.
The return value is0 for success, or-1 for an error. Thefollowing errors may occur:
EBADF
fd does not correspond to an open file.
EACCES
fd is a directory or not open for writing.
EINVAL
length is negative.
EFBIG
The operation would extend the file beyond the limits of the operating system.
EIO
A hardware I/O error occurred.
EPERM
The file is "append-only" or "immutable".
EINTR
The operation was interrupted by a signal.
int
ftruncate64(intid, off64_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to theftruncate
function. Thedifference is that thelength argument is 64 bits wide even on 32bits machines which allows the handling of files with sizes up to2^63 bytes.
When the source file is compiled with_FILE_OFFSET_BITS == 64
on a32 bits machine this function is actually available under the nameftruncate
and so transparently replaces the 32 bits interface.
As announced here is a little example of how to useftruncate
incombination withmmap
:
int fd;void *start;size_t len;intadd (off_t at, void *block, size_t size){ if (at + size > len) { /* Resize the file and remap. */ size_t ps = sysconf (_SC_PAGESIZE); size_t ns = (at + size + ps - 1) & ~(ps - 1); void *np; if (ftruncate (fd, ns) < 0) return -1; np = mmap (NULL, ns, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (np == MAP_FAILED) return -1; start = np; len = ns; } memcpy ((char *) start + at, block, size); return 0;}
The functionadd
writes a block of memory at an arbitraryposition in the file. If the current size of the file is too small itis extended. Note that it is extended by a whole number of pages. Thisis a requirement ofmmap
. The program has to keep track of thereal size, and when it has finished a finalftruncate
call shouldset the real size of the file.
Previous:File Size, Up:File Attributes [Contents][Index]
Most file systems support allocating large files in a non-contiguousfashion: the file is split intofragments which are allocatedsequentially, but the fragments themselves can be scattered across thedisk. File systems generally try to avoid such fragmentation because itdecreases performance, but if a file gradually increases in size, theremight be no other option than to fragment it. In addition, many filesystems supportsparse files withholes: regions of nullbytes for which no backing storage has been allocated by the filesystem. When the holes are finally overwritten with data, fragmentationcan occur as well.
Explicit allocation of storage for yet-unwritten parts of the file canhelp the system to avoid fragmentation. Additionally, if storagepre-allocation fails, it is possible to report the out-of-disk errorearly, often without filling up the entire disk. However, due todeduplication, copy-on-write semantics, and file compression, suchpre-allocation may not reliably prevent the out-of-disk-space error fromoccurring later. Checking for write errors is still required, andwrites to memory-mapped regions created withmmap
can stillresult inSIGBUS
.
int
posix_fallocate(intfd, off_toffset, off_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Allocate backing store for the region oflength bytes starting atbyteoffset in the file for the descriptorfd. The filelength is increased to ‘length +offset’ if necessary.
fd must be a regular file opened for writing, orEBADF
isreturned. If there is insufficient disk space to fulfill the allocationrequest,ENOSPC
is returned.
Note: Iffallocate
is not available (because the filesystem does not support it),posix_fallocate
is emulated, whichhas the following drawbacks:
fallocate
support (see below), the file system can examine the internal fileallocation data structures and eliminate holes directly, maybe evenusing unwritten extents (which are pre-allocated but uninitialized ondisk).O_WRONLY
flag, the functionwill fail with anerrno
value ofEBADF
.O_APPEND
flag, the functionwill fail with anerrno
value ofEBADF
.ftruncate
is used to increase the filesize as requested, without allocating file system blocks. There is arace condition which means thatftruncate
can accidentallytruncate the file if it has been extended concurrently.On Linux, if an application does not benefit from emulation or if theemulation is harmful due to its inherent race conditions, theapplication can use the Linux-specificfallocate
function, with azero flag argument. For thefallocate
function, the GNU C Library doesnot perform allocation emulation if the file system does not supportallocation. Instead, anEOPNOTSUPP
is returned to the caller.
int
posix_fallocate64(intfd, off64_toffset, off64_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is a variant ofposix_fallocate64
which accepts64-bit file offsets on all platforms.
Next:Temporary Files, Previous:File Attributes, Up:File System Interface [Contents][Index]
Themknod
function is the primitive for making special files,such as files that correspond to devices. The GNU C Library includesthis function for compatibility with BSD.
The prototype formknod
is declared insys/stat.h.
int
mknod(const char *filename, mode_tmode, dev_tdev)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Themknod
function makes a special file with namefilename.Themode specifies the mode of the file, and may include the variousspecial file bits, such asS_IFCHR
(for a character special file)orS_IFBLK
(for a block special file). SeeTesting the Type of a File.
Thedev argument specifies which device the special file refers to.Its exact interpretation depends on the kind of special file being created.
The return value is0
on success and-1
on error. In additionto the usual file name errors (seeFile Name Errors), thefollowingerrno
error conditions are defined for this function:
EPERM
The calling process is not privileged. Only the superuser can createspecial files.
ENOSPC
The directory or file system that would contain the new file is fulland cannot be extended.
EROFS
The directory containing the new file can’t be modified because it’s ona read-only file system.
EEXIST
There is already a file namedfilename. If you want to replacethis file, you must remove the old file explicitly first.
Previous:Making Special Files, Up:File System Interface [Contents][Index]
If you need to use a temporary file in your program, you can use thetmpfile
function to open it. Or you can use thetmpnam
(better:tmpnam_r
) function to provide a name for a temporaryfile and then you can open it in the usual way withfopen
.
Thetempnam
function is liketmpnam
but lets you choosewhat directory temporary files will go in, and something about whattheir file names will look like. Important for multi-threaded programsis thattempnam
is reentrant, whiletmpnam
is not since itreturns a pointer to a static buffer.
These facilities are declared in the header filestdio.h.
FILE *
tmpfile(void)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe mem fd lock| SeePOSIX Safety Concepts.
This function creates a temporary binary file for update mode, as if bycallingfopen
with mode"wb+"
. The file is deletedautomatically when it is closed or when the program terminates. (Onsome other ISO C systems the file may fail to be deleted if the programterminates abnormally).
This function is reentrant.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32-bit system this function is in facttmpfile64
, i.e., the LFSinterface transparently replaces the old interface.
FILE *
tmpfile64(void)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe mem fd lock| SeePOSIX Safety Concepts.
This function is similar totmpfile
, but the stream it returns apointer to was opened usingtmpfile64
. Therefore this stream canbe used for files larger than 2^31 bytes on 32-bit machines.
Please note that the return type is stillFILE *
. There is nospecialFILE
type for the LFS interface.
If the sources are compiled with_FILE_OFFSET_BITS == 64
on a 32bits machine this function is available under the nametmpfile
and so transparently replaces the old interface.
char *
tmpnam(char *result)
¶Preliminary:| MT-Unsafe race:tmpnam/!result| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
This function constructs and returns a valid file name that does notrefer to any existing file. If theresult argument is a nullpointer, the return value is a pointer to an internal static string,which might be modified by subsequent calls and therefore makes thisfunction non-reentrant. Otherwise, theresult argument should bea pointer to an array of at leastL_tmpnam
characters, and theresult is written into that array.
It is possible fortmpnam
to fail if you call it too many timeswithout removing previously-created files. This is because the limitedlength of the temporary file names gives room for only a finite numberof different names. Iftmpnam
fails it returns a null pointer.
Warning: Between the time the pathname is constructed and thefile is created another process might have created a file with the samename usingtmpnam
, leading to a possible security hole. Theimplementation generates names which can hardly be predicted, but whenopening the file you should use theO_EXCL
flag. Usingtmpfile
ormkstemp
is a safe way to avoid this problem.
char *
tmpnam_r(char *result)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is nearly identical to thetmpnam
function, exceptthat ifresult is a null pointer it returns a null pointer.
This guarantees reentrancy because the non-reentrant situation oftmpnam
cannot happen here.
Warning: This function has the same security problems astmpnam
.
int
L_tmpnam ¶The value of this macro is an integer constant expression thatrepresents the minimum size of a string large enough to hold a file namegenerated by thetmpnam
function.
int
TMP_MAX ¶The macroTMP_MAX
is a lower bound for how many temporary namesyou can create withtmpnam
. You can rely on being able to calltmpnam
at least this many times before it might fail saying youhave made too many temporary file names.
With the GNU C Library, you can create a very large number of temporaryfile names. If you actually created the files, you would probably runout of disk space before you ran out of names. Some other systems havea fixed, small limit on the number of temporary files. The limit isnever less than25
.
char *
tempnam(const char *dir, const char *prefix)
¶Preliminary:| MT-Safe env| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function generates a unique temporary file name. Ifprefixis not a null pointer, up to five characters of this string are used asa prefix for the file name. The return value is a string newlyallocated withmalloc
, so you should release its storage withfree
when it is no longer needed.
Because the string is dynamically allocated this function is reentrant.
The directory prefix for the temporary file name is determined bytesting each of the following in sequence. The directory must exist andbe writable.
TMPDIR
, if it is defined. For securityreasons this only happens if the program is not SUID or SGID enabled.P_tmpdir
macro.This function is defined for SVID compatibility.
Warning: Between the time the pathname is constructed and thefile is created another process might have created a file with the samename usingtempnam
, leading to a possible security hole. Theimplementation generates names which can hardly be predicted, but whenopening the file you should use theO_EXCL
flag. Usingtmpfile
ormkstemp
is a safe way to avoid this problem.
char *
P_tmpdir ¶This macro is the name of the default directory for temporary files.
Older Unix systems did not have the functions just described. Insteadthey usedmktemp
andmkstemp
. Both of these functionswork by modifying a file name template string you pass. The last sixcharacters of this string must be ‘XXXXXX’. These six ‘X’sare replaced with six characters which make the whole string a uniquefile name. Usually the template string is something like‘/tmp/prefixXXXXXX’, and each program uses a uniqueprefix.
NB: Becausemktemp
andmkstemp
modify thetemplate string, youmust not pass string constants to them.String constants are normally in read-only storage, so your programwould crash whenmktemp
ormkstemp
tried to modify thestring. These functions are declared in the header filestdlib.h.
char *
mktemp(char *template)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Themktemp
function generates a unique file name by modifyingtemplate as described above. If successful, it returnstemplate as modified. Ifmktemp
cannot find a unique filename, it makestemplate an empty string and returns that. Iftemplate does not end with ‘XXXXXX’,mktemp
returns anull pointer.
Warning: Between the time the pathname is constructed and thefile is created another process might have created a file with the samename usingmktemp
, leading to a possible security hole. Theimplementation generates names which can hardly be predicted, but whenopening the file you should use theO_EXCL
flag. Usingmkstemp
is a safe way to avoid this problem.
int
mkstemp(char *template)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
Themkstemp
function generates a unique file name just asmktemp
does, but it also opens the file for you withopen
(seeOpening and Closing Files). If successful, it modifiestemplate in place and returns a file descriptor for that file openfor reading and writing. Ifmkstemp
cannot create auniquely-named file, it returns-1
. Iftemplate does notend with ‘XXXXXX’,mkstemp
returns-1
and does notmodifytemplate.
The file is opened using mode0600
. If the file is meant to beused by other users this mode must be changed explicitly.
Unlikemktemp
,mkstemp
is actually guaranteed to create aunique file that cannot possibly clash with any other program trying tocreate a temporary file. This is because it works by callingopen
with theO_EXCL
flag, which says you want to create anew file and get an error if the file already exists.
char *
mkdtemp(char *template)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Themkdtemp
function creates a directory with a unique name. Ifit succeeds, it overwritestemplate with the name of thedirectory, and returnstemplate. As withmktemp
andmkstemp
,template should be a string ending with‘XXXXXX’.
Ifmkdtemp
cannot create an uniquely named directory, it returnsNULL
and setserrno
appropriately. Iftemplate doesnot end with ‘XXXXXX’,mkdtemp
returnsNULL
and doesnot modifytemplate.errno
will be set toEINVAL
inthis case.
The directory is created using mode0700
.
The directory created bymkdtemp
cannot clash with temporaryfiles or directories created by other users. This is because directorycreation always works likeopen
withO_EXCL
.SeeCreating Directories.
Themkdtemp
function comes from OpenBSD.
Next:Sockets, Previous:File System Interface, Up:Main Menu [Contents][Index]
Apipe is a mechanism for interprocess communication; data writtento the pipe by one process can be read by another process. The data ishandled in a first-in, first-out (FIFO) order. The pipe has no name; itis created for one use and both ends must be inherited from the singleprocess which created the pipe.
AFIFO special file is similar to a pipe, but instead of being ananonymous, temporary connection, a FIFO has a name or names like anyother file. Processes open the FIFO by name in order to communicatethrough it.
A pipe or FIFO has to be open at both ends simultaneously. If you readfrom a pipe or FIFO file that doesn’t have any processes writing to it(perhaps because they have all closed the file, or exited), the readreturns end-of-file. Writing to a pipe or FIFO that doesn’t have areading process is treated as an error condition; it generates aSIGPIPE
signal, and fails with error codeEPIPE
if thesignal is handled or blocked.
Neither pipes nor FIFO special files allow file positioning. Bothreading and writing operations happen sequentially; reading from thebeginning of the file and writing at the end.
Next:Pipe to a Subprocess, Up:Pipes and FIFOs [Contents][Index]
The primitive for creating a pipe is thepipe
function. Thiscreates both the reading and writing ends of the pipe. It is not veryuseful for a single process to use a pipe to talk to itself. In typicaluse, a process creates a pipe just before it forks one or more childprocesses (seeCreating a Process). The pipe is then used forcommunication either between the parent or child processes, or betweentwo sibling processes.
Thepipe
function is declared in the header fileunistd.h.
int
pipe(intfiledes[2]
)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
Thepipe
function creates a pipe and puts the file descriptorsfor the reading and writing ends of the pipe (respectively) intofiledes[0]
andfiledes[1]
.
An easy way to remember that the input end comes first is that filedescriptor0
is standard input, and file descriptor1
isstandard output.
If successful,pipe
returns a value of0
. On failure,-1
is returned. The followingerrno
error conditions aredefined for this function:
EMFILE
The process has too many files open.
ENFILE
There are too many open files in the entire system. SeeError Codes,for more information aboutENFILE
. This error never occurs onGNU/Hurd systems.
Here is an example of a simple program that creates a pipe. This programuses thefork
function (seeCreating a Process) to createa child process. The parent process writes data to the pipe, which isread by the child process.
#include <sys/types.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>/*Read characters from the pipe and echo them tostdout
. */voidread_from_pipe (int file){ FILE *stream; int c; stream = fdopen (file, "r"); while ((c = fgetc (stream)) != EOF) putchar (c); fclose (stream);}/*Write some random text to the pipe. */voidwrite_to_pipe (int file){ FILE *stream; stream = fdopen (file, "w"); fprintf (stream, "hello, world!\n"); fprintf (stream, "goodbye, world!\n"); fclose (stream);}intmain (void){ pid_t pid; int mypipe[2];
/*Create the pipe. */ if (pipe (mypipe)) { fprintf (stderr, "Pipe failed.\n"); return EXIT_FAILURE; }
/*Create the child process. */ pid = fork (); if (pid == (pid_t) 0) { /*This is the child process. Close other end first. */ close (mypipe[1]); read_from_pipe (mypipe[0]); return EXIT_SUCCESS; } else if (pid < (pid_t) 0) { /*The fork failed. */ fprintf (stderr, "Fork failed.\n"); return EXIT_FAILURE; } else { /*This is the parent process. Close other end first. */ close (mypipe[0]); write_to_pipe (mypipe[1]); return EXIT_SUCCESS; }}
Next:FIFO Special Files, Previous:Creating a Pipe, Up:Pipes and FIFOs [Contents][Index]
A common use of pipes is to send data to or receive data from a programbeing run as a subprocess. One way of doing this is by using a combination ofpipe
(to create the pipe),fork
(to create the subprocess),dup2
(to force the subprocess to use the pipe as its standard inputor output channel), andexec
(to execute the new program). Or,you can usepopen
andpclose
.
The advantage of usingpopen
andpclose
is that theinterface is much simpler and easier to use. But it doesn’t offer asmuch flexibility as using the low-level functions directly.
FILE *
popen(const char *command, const char *mode)
¶Preliminary:| MT-Safe | AS-Unsafe heap corrupt| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thepopen
function is closely related to thesystem
function; seeRunning a Command. It executes the shell commandcommand as a subprocess. However, instead of waiting for thecommand to complete, it creates a pipe to the subprocess and returns astream that corresponds to that pipe.
If you specify amode argument of"r"
, you can read from thestream to retrieve data from the standard output channel of the subprocess.The subprocess inherits its standard input channel from the parent process.
Similarly, if you specify amode argument of"w"
, you canwrite to the stream to send data to the standard input channel of thesubprocess. The subprocess inherits its standard output channel fromthe parent process.
In the event of an errorpopen
returns a null pointer. Thismight happen if the pipe or stream cannot be created, if the subprocesscannot be forked, or if the program cannot be executed.
int
pclose(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe heap plugin corrupt lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thepclose
function is used to close a stream created bypopen
.It waits for the child process to terminate and returns its status value,as for thesystem
function.
Here is an example showing how to usepopen
andpclose
tofilter output through another program, in this case the paging programmore
.
#include <stdio.h>#include <stdlib.h>voidwrite_data (FILE * stream){ int i; for (i = 0; i < 100; i++) fprintf (stream, "%d\n", i); if (ferror (stream)) { fprintf (stderr, "Output to stream failed.\n"); exit (EXIT_FAILURE); }}
intmain (void){ FILE *output; output = popen ("more", "w"); if (!output) { fprintf (stderr, "incorrect parameters or too many files.\n"); return EXIT_FAILURE; } write_data (output); if (pclose (output) != 0) { fprintf (stderr, "Could not run more or other error.\n"); } return EXIT_SUCCESS;}
Next:Atomicity of Pipe I/O, Previous:Pipe to a Subprocess, Up:Pipes and FIFOs [Contents][Index]
A FIFO special file is similar to a pipe, except that it is created in adifferent way. Instead of being an anonymous communications channel, aFIFO special file is entered into the file system by callingmkfifo
.
Once you have created a FIFO special file in this way, any process canopen it for reading or writing, in the same way as an ordinary file.However, it has to be open at both ends simultaneously before you canproceed to do any input or output operations on it. Opening a FIFO forreading normally blocks until some other process opens the same FIFO forwriting, and vice versa.
Themkfifo
function is declared in the header filesys/stat.h.
int
mkfifo(const char *filename, mode_tmode)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Themkfifo
function makes a FIFO special file with namefilename. Themode argument is used to set the file’spermissions; seeAssigning File Permissions.
The normal, successful return value frommkfifo
is0
. Inthe case of an error,-1
is returned. In addition to the usualfile name errors (seeFile Name Errors), the followingerrno
error conditions are defined for this function:
EEXIST
The named file already exists.
ENOSPC
The directory or file system cannot be extended.
EROFS
The directory that would contain the file resides on a read-only filesystem.
Previous:FIFO Special Files, Up:Pipes and FIFOs [Contents][Index]
Reading or writing pipe data isatomic if the size of data writtenis not greater thanPIPE_BUF
. This means that the data transferseems to be an instantaneous unit, in that nothing else in the systemcan observe a state in which it is partially complete. Atomic I/O maynot begin right away (it may need to wait for buffer space or for data),but once it does begin it finishes immediately.
Reading or writing a larger amount of data may not be atomic; forexample, output data from other processes sharing the descriptor may beinterspersed. Also, oncePIPE_BUF
characters have been written,further writes will block until some characters are read.
SeeLimits on File System Capacity, for information about thePIPE_BUF
parameter.
Next:Low-Level Terminal Interface, Previous:Pipes and FIFOs, Up:Main Menu [Contents][Index]
This chapter describes the GNU facilities for interprocesscommunication using sockets.
Asocket is a generalized interprocess communication channel.Like a pipe, a socket is represented as a file descriptor. Unlike pipessockets support communication between unrelated processes, and evenbetween processes running on different machines that communicate over anetwork. Sockets are the primary means of communicating with othermachines;telnet
,rlogin
,ftp
,talk
and theother familiar network programs use sockets.
Not all operating systems support sockets. In the GNU C Library, theheader filesys/socket.h exists regardless of the operatingsystem, and the socket functions always exist, but if the system doesnot really support sockets these functions always fail.
Incomplete: We do not currently document the facilities forbroadcast messages or for configuring Internet interfaces. Thereentrant functions and some newer functions that are related to IPv6aren’t documented either so far.
inetd
DaemonNext:Communication Styles, Up:Sockets [Contents][Index]
When you create a socket, you must specify the style of communicationyou want to use and the type of protocol that should implement it.Thecommunication style of a socket defines the user-levelsemantics of sending and receiving data on the socket. Choosing acommunication style specifies the answers to questions such as these:
Designing a program to use unreliable communication styles usuallyinvolves taking precautions to detect lost or misordered packets andto retransmit data as needed.
You must also choose anamespace for naming the socket. A socketname (“address”) is meaningful only in the context of a particularnamespace. In fact, even the data type to use for a socket name maydepend on the namespace. Namespaces are also called “domains”, but weavoid that word as it can be confused with other usage of the sameterm. Each namespace has a symbolic name that starts with ‘PF_’.A corresponding symbolic name starting with ‘AF_’ designates theaddress format for that namespace.
Finally you must choose theprotocol to carry out thecommunication. The protocol determines what low-level mechanism is usedto transmit and receive data. Each protocol is valid for a particularnamespace and communication style; a namespace is sometimes called aprotocol family because of this, which is why the namespace namesstart with ‘PF_’.
The rules of a protocol apply to the data passing between two programs,perhaps on different computers; most of these rules are handled by theoperating system and you need not know about them. What you do need toknow about protocols is this:
Throughout the following description at various placesvariables/parameters to denote sizes are required. And here the troublestarts. In the first implementations the type of these variables wassimplyint
. On most machines at that time anint
was 32bits wide, which created ade facto standard requiring 32-bitvariables. This is important since references to variables of this typeare passed to the kernel.
Then the POSIX people came and unified the interface with the words "allsize values are of typesize_t
". On 64-bit machinessize_t
is 64 bits wide, so pointers to variables were no longerpossible.
The Unix98 specification provides a solution by introducing a typesocklen_t
. This type is used in all of the cases that POSIXchanged to usesize_t
. The only requirement of this type is thatit be an unsigned type of at least 32 bits. Therefore, implementationswhich require that references to 32-bit variables be passed can be ashappy as implementations which use 64-bit values.
Next:Socket Addresses, Previous:Socket Concepts, Up:Sockets [Contents][Index]
The GNU C Library includes support for several different kinds of sockets,each with different characteristics. This section describes thesupported socket types. The symbolic constants listed here aredefined insys/socket.h.
int
SOCK_STREAM ¶TheSOCK_STREAM
style is like a pipe (seePipes and FIFOs).It operates over a connection with a particular remote socket andtransmits data reliably as a stream of bytes.
Use of this style is covered in detail inUsing Sockets with Connections.
int
SOCK_DGRAM ¶TheSOCK_DGRAM
style is used for sendingindividually-addressed packets unreliably.It is the diametrical opposite ofSOCK_STREAM
.
Each time you write data to a socket of this kind, that data becomesone packet. SinceSOCK_DGRAM
sockets do not have connections,you must specify the recipient address with each packet.
The only guarantee that the system makes about your requests totransmit data is that it will try its best to deliver each packet yousend. It may succeed with the sixth packet after failing with thefourth and fifth packets; the seventh packet may arrive before thesixth, and may arrive a second time after the sixth.
The typical use forSOCK_DGRAM
is in situations where it isacceptable to simply re-send a packet if no response is seen in areasonable amount of time.
SeeDatagram Socket Operations, for detailed information about how to use datagramsockets.
int
SOCK_RAW ¶This style provides access to low-level network protocols andinterfaces. Ordinary user programs usually have no need to use thisstyle.
Next:Interface Naming, Previous:Communication Styles, Up:Sockets [Contents][Index]
The name of a socket is normally called anaddress. Thefunctions and symbols for dealing with socket addresses were namedinconsistently, sometimes using the term “name” and sometimes using“address”. You can regard these terms as synonymous where socketsare concerned.
A socket newly created with thesocket
function has noaddress. Other processes can find it for communication only if yougive it an address. We call thisbinding the address to thesocket, and the way to do it is with thebind
function.
You need only be concerned with the address of a socket if other processesare to find it and start communicating with it. You can specify anaddress for other sockets, but this is usually pointless; the first timeyou send data from a socket, or use it to initiate a connection, thesystem assigns an address automatically if you have not specified one.
Occasionally a client needs to specify an address because the serverdiscriminates based on address; for example, the rsh and rloginprotocols look at the client’s socket address and only bypass passphrasechecking if it is less thanIPPORT_RESERVED
(seeInternet Ports).
The details of socket addresses vary depending on what namespace you areusing. SeeThe Local Namespace, orThe Internet Namespace, for specificinformation.
Regardless of the namespace, you use the same functionsbind
andgetsockname
to set and examine a socket’s address. Thesefunctions use a phony data type,struct sockaddr *
, to accept theaddress. In practice, the address lives in a structure of some otherdata type appropriate to the address format you are using, but you castits address tostruct sockaddr *
when you pass it tobind
.
Next:Setting the Address of a Socket, Up:Socket Addresses [Contents][Index]
The functionsbind
andgetsockname
use the generic datatypestruct sockaddr *
to represent a pointer to a socketaddress. You can’t use this data type effectively to interpret anaddress or construct one; for that, you must use the proper data typefor the socket’s namespace.
Thus, the usual practice is to construct an address of the propernamespace-specific type, then cast a pointer tostruct sockaddr *
when you callbind
orgetsockname
.
The one piece of information that you can get from thestructsockaddr
data type is theaddress format designator. This tellsyou which data type to use to understand the address fully.
The symbols in this section are defined in the header filesys/socket.h.
Thestruct sockaddr
type itself has the following members:
short int sa_family
This is the code for the address format of this address. Itidentifies the format of the data which follows.
char sa_data[14]
This is the actual socket address data, which is format-dependent. Itslength also depends on the format, and may well be more than 14. Thelength 14 ofsa_data
is essentially arbitrary.
Each address format has a symbolic name which starts with ‘AF_’.Each of them corresponds to a ‘PF_’ symbol which designates thecorresponding namespace. Here is a list of address format names:
AF_LOCAL
¶This designates the address format that goes with the local namespace.(PF_LOCAL
is the name of that namespace.) SeeDetails of Local Namespace, for information about this address format.
AF_UNIX
¶This is a synonym forAF_LOCAL
. AlthoughAF_LOCAL
ismandated by POSIX.1g,AF_UNIX
is portable to more systems.AF_UNIX
was the traditional name stemming from BSD, so even mostPOSIX systems support it. It is also the name of choice in the Unix98specification. (The same is true forPF_UNIX
vs.PF_LOCAL
).
AF_FILE
¶This is another synonym forAF_LOCAL
, for compatibility.(PF_FILE
is likewise a synonym forPF_LOCAL
.)
AF_INET
¶This designates the address format that goes with the Internetnamespace. (PF_INET
is the name of that namespace.)SeeInternet Socket Address Formats.
AF_INET6
¶This is similar toAF_INET
, but refers to the IPv6 protocol.(PF_INET6
is the name of the corresponding namespace.)
AF_UNSPEC
¶This designates no particular address format. It is used only in rarecases, such as to clear out the default destination address of a“connected” datagram socket. SeeSending Datagrams.
The corresponding namespace designator symbolPF_UNSPEC
existsfor completeness, but there is no reason to use it in a program.
sys/socket.h defines symbols starting with ‘AF_’ for manydifferent kinds of networks, most or all of which are not actuallyimplemented. We will document those that really work as we receiveinformation about how to use them.
Next:Reading the Address of a Socket, Previous:Address Formats, Up:Socket Addresses [Contents][Index]
Use thebind
function to assign an address to a socket. Theprototype forbind
is in the header filesys/socket.h.For examples of use, seeExample of Local-Namespace Sockets, or seeInternet Socket Example.
int
bind(intsocket, struct sockaddr *addr, socklen_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thebind
function assigns an address to the socketsocket. Theaddr andlength arguments specify theaddress; the detailed format of the address depends on the namespace.The first part of the address is always the format designator, whichspecifies a namespace, and says that the address is in the format ofthat namespace.
The return value is0
on success and-1
on failure. Thefollowingerrno
error conditions are defined for this function:
EBADF
Thesocket argument is not a valid file descriptor.
ENOTSOCK
The descriptorsocket is not a socket.
EADDRNOTAVAIL
The specified address is not available on this machine.
EADDRINUSE
Some other socket is already using the specified address.
EINVAL
The socketsocket already has an address.
EACCES
You do not have permission to access the requested address. (In theInternet domain, only the super-user is allowed to specify a port numberin the range 0 throughIPPORT_RESERVED
minus one; seeInternet Ports.)
Additional conditions may be possible depending on the particular namespaceof the socket.
Previous:Setting the Address of a Socket, Up:Socket Addresses [Contents][Index]
Use the functiongetsockname
to examine the address of anInternet socket. The prototype for this function is in the header filesys/socket.h.
int
getsockname(intsocket, struct sockaddr *addr, socklen_t *length-ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe mem/hurd| SeePOSIX Safety Concepts.
Thegetsockname
function returns information about theaddress of the socketsocket in the locations specified by theaddr andlength-ptr arguments. Note that thelength-ptr is a pointer; you should initialize it to be theallocation size ofaddr, and on return it contains the actualsize of the address data.
The format of the address data depends on the socket namespace. Thelength of the information is usually fixed for a given namespace, sonormally you can know exactly how much space is needed and can providethat much. The usual practice is to allocate a place for the valueusing the proper data type for the socket’s namespace, then cast itsaddress tostruct sockaddr *
to pass it togetsockname
.
The return value is0
on success and-1
on error. Thefollowingerrno
error conditions are defined for this function:
EBADF
Thesocket argument is not a valid file descriptor.
ENOTSOCK
The descriptorsocket is not a socket.
ENOBUFS
There are not enough internal buffers available for the operation.
You can’t read the address of a socket in the file namespace. This isconsistent with the rest of the system; in general, there’s no way tofind a file’s name from a descriptor for that file.
Next:The Local Namespace, Previous:Socket Addresses, Up:Sockets [Contents][Index]
Each network interface has a name. This usually consists of a fewletters that relate to the type of interface, which may be followed by anumber if there is more than one interface of that type. Examplesmight belo
(the loopback interface) andeth0
(the firstEthernet interface).
Although such names are convenient for humans, it would be clumsy tohave to use them whenever a program needs to refer to an interface. Insuch situations an interface is referred to by itsindex, which isan arbitrarily-assigned small positive integer.
The following functions, constants and data types are declared in theheader filenet/if.h.
size_t
IFNAMSIZ ¶This constant defines the maximum buffer size needed to hold aninterface name, including its terminating zero byte.
unsigned int
if_nametoindex(const char *ifname)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
This function yields the interface index corresponding to a particularname specified withifname.
The return value is the interface index on success. On failure, thefunction’s return value is zero anderrno
is set accordingly.The followingerrno
values are specific to this function:
ENODEV
There is no interface by the name requested.
Additionally, sinceif_nametoindex
invokessocket
internally,errno
may also be set to a value listed for thesocket
function (seeCreating a Socket).
char *
if_indextoname(unsigned intifindex, char *ifname)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
This function maps an interface indexifindex to its correspondingname. The returned name is placed in the buffer pointed to byifname,which must be at leastIFNAMSIZ
bytes in length.
The return value isifname on success. On failure, the function’sreturn value is a null pointer anderrno
is set accordingly. Thefollowingerrno
values are specific to this function:
ENXIO
There is no interface at the index requested.
Additionally, sinceif_indextoname
invokessocket
internally,errno
may also be set to a value listed for thesocket
function (seeCreating a Socket).
This data type is used to hold the information about a singleinterface. It has the following members:
unsigned int if_index;
This is the interface index.
char *if_name
This is the null-terminated index name.
struct if_nameindex *
if_nameindex(void)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock/hurd| AC-Unsafe lock/hurd fd mem| SeePOSIX Safety Concepts.
This function returns an array ofif_nameindex
structures, onefor every interface that is present. The end of the list is indicatedby a structure with an interface of 0 and a null name pointer. If anerror occurs, this function returns a null pointer.
The returned structure must be freed withif_freenameindex
afteruse.
void
if_freenameindex(struct if_nameindex *ptr)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function frees the structure returned by an earlier call toif_nameindex
.
Next:The Internet Namespace, Previous:Interface Naming, Up:Sockets [Contents][Index]
This section describes the details of the local namespace, whosesymbolic name (required when you create a socket) isPF_LOCAL
.The local namespace is also known as “Unix domain sockets”. Anothername is file namespace since socket addresses are normally implementedas file names.
Next:Details of Local Namespace, Up:The Local Namespace [Contents][Index]
In the local namespace socket addresses are file names. You can specifyany file name you want as the address of the socket, but you must havewrite permission on the directory containing it.It’s common to put these files in the/tmp directory.
One peculiarity of the local namespace is that the name is only usedwhen opening the connection; once open the address is not meaningful andmay not exist.
Another peculiarity is that you cannot connect to such a socket fromanother machine–not even if the other machine shares the file systemwhich contains the name of the socket. You can see the socket in adirectory listing, but connecting to it never succeeds. Some programstake advantage of this, such as by asking the client to send its ownprocess ID, and using the process IDs to distinguish between clients.However, we recommend you not use this method in protocols you design,as we might someday permit connections from other machines that mountthe same file systems. Instead, send each new client an identifyingnumber if you want it to have one.
After you close a socket in the local namespace, you should delete thefile name from the file system. Useunlink
orremove
todo this; seeDeleting Files.
The local namespace supports just one protocol for any communicationstyle; it is protocol number0
.
Next:Example of Local-Namespace Sockets, Previous:Local Namespace Concepts, Up:The Local Namespace [Contents][Index]
To create a socket in the local namespace, use the constantPF_LOCAL
as thenamespace argument tosocket
orsocketpair
. This constant is defined insys/socket.h.
int
PF_LOCAL ¶This designates the local namespace, in which socket addresses are localnames, and its associated family of protocols.PF_LOCAL
is themacro used by POSIX.1g.
int
PF_UNIX ¶This is a synonym forPF_LOCAL
, for compatibility’s sake.
int
PF_FILE ¶This is a synonym forPF_LOCAL
, for compatibility’s sake.
The structure for specifying socket names in the local namespace isdefined in the header filesys/un.h:
This structure is used to specify local namespace socket addresses. It hasthe following members:
short int sun_family
This identifies the address family or format of the socket address.You should store the valueAF_LOCAL
to designate the localnamespace. SeeSocket Addresses.
char sun_path[108]
This is the file name to use.
Incomplete: Why is 108 a magic number? RMS suggests makingthis a zero-length array and tweaking the following example to usealloca
to allocate an appropriate amount of storage based onthe length of the filename.
You should compute thelength parameter for a socket address inthe local namespace as the sum of the size of thesun_family
component and the string length (not the allocation size!) ofthe file name string. This can be done using the macroSUN_LEN
:
int
SUN_LEN(struct sockaddr_un *ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro computes the length of the socket address in the local namespace.
Previous:Details of Local Namespace, Up:The Local Namespace [Contents][Index]
Here is an example showing how to create and name a socket in the localnamespace.
#include <stddef.h>#include <stdio.h>#include <errno.h>#include <stdlib.h>#include <string.h>#include <sys/socket.h>#include <sys/un.h>intmake_named_socket (const char *filename){ struct sockaddr_un name; int sock; size_t size; /*Create the socket. */ sock = socket (PF_LOCAL, SOCK_DGRAM, 0); if (sock < 0) { perror ("socket"); exit (EXIT_FAILURE); } /*Bind a name to the socket. */ name.sun_family = AF_LOCAL; strncpy (name.sun_path, filename, sizeof (name.sun_path)); name.sun_path[sizeof (name.sun_path) - 1] = '\0'; /*The size of the address is the offset of the start of the filename, plus its length (not including the terminating null byte). Alternatively you can just do: size = SUN_LEN (&name); */ size = (offsetof (struct sockaddr_un, sun_path) + strlen (name.sun_path)); if (bind (sock, (struct sockaddr *) &name, size) < 0) { perror ("bind"); exit (EXIT_FAILURE); } return sock;}
Next:Other Namespaces, Previous:The Local Namespace, Up:Sockets [Contents][Index]
This section describes the details of the protocols and socket namingconventions used in the Internet namespace.
Originally the Internet namespace used only IP version 4 (IPv4). Withthe growing number of hosts on the Internet, a new protocol with alarger address space was necessary: IP version 6 (IPv6). IPv6introduces 128-bit addresses (IPv4 has 32-bit addresses) and otherfeatures, and will eventually replace IPv4.
To create a socket in the IPv4 Internet namespace, use the symbolic namePF_INET
of this namespace as thenamespace argument tosocket
orsocketpair
. For IPv6 addresses you need themacroPF_INET6
. These macros are defined insys/socket.h.
int
PF_INET ¶This designates the IPv4 Internet namespace and associated family ofprotocols.
int
PF_INET6 ¶This designates the IPv6 Internet namespace and associated family ofprotocols.
A socket address for the Internet namespace includes the following components:
You must ensure that the address and port number are represented in acanonical format callednetwork byte order. SeeByte Order Conversion,for information about this.
Next:Host Addresses, Up:The Internet Namespace [Contents][Index]
In the Internet namespace, for both IPv4 (AF_INET
) and IPv6(AF_INET6
), a socket address consists of a host addressand a port on that host. In addition, the protocol you choose serveseffectively as a part of the address because local port numbers aremeaningful only within a particular protocol.
The data types for representing socket addresses in the Internet namespaceare defined in the header filenetinet/in.h.
This is the data type used to represent socket addresses in theInternet namespace. It has the following members:
sa_family_t sin_family
This identifies the address family or format of the socket address.You should store the valueAF_INET
in this member. The addressfamily is stored in host byte order. SeeSocket Addresses.
struct in_addr sin_addr
This is the IPv4 address. SeeHost Addresses, andHost Names, for how to get a value to store here. The IPv4 address isstored in network byte order.
unsigned short int sin_port
This is the port number. SeeInternet Ports. The port number is stored innetwork byte order.
When you callbind
orgetsockname
, you should specifysizeof (struct sockaddr_in)
as thelength parameter ifyou are using an IPv4 Internet namespace socket address.
This is the data type used to represent socket addresses in the IPv6namespace. It has the following members:
sa_family_t sin6_family
This identifies the address family or format of the socket address.You should store the value ofAF_INET6
in this member.SeeSocket Addresses. The address family is stored in host byteorder.
struct in6_addr sin6_addr
This is the IPv6 address of the host machine. SeeHost Addresses, andHost Names, for how to get a value to storehere. The address is stored in network byte order.
uint32_t sin6_flowinfo
¶This combines the IPv6 traffic class and flow label values, as foundin the IPv6 header. This field is stored in network byte order. Onlythe 28 lower bits (of the number in network byte order) are used; theremaining bits must be zero. The lower 20 bits are the flow label, andbits 20 to 27 are the the traffic class. Typically, this field iszero.
uint32_t sin6_scope_id
¶For link-local addresses, this identifies the interface on which thisaddress is valid. The scope ID is stored in host byte order.Typically, this field is zero.
uint16_t sin6_port
This is the port number. SeeInternet Ports. The port number is stored innetwork byte order.
Next:Internet Ports, Previous:Internet Socket Address Formats, Up:The Internet Namespace [Contents][Index]
Each computer on the Internet has one or moreInternet addresses,numbers which identify that computer among all those on the Internet.Users typically write IPv4 numeric host addresses as sequences of fournumbers, separated by periods, as in ‘128.52.46.32’, and IPv6numeric host addresses as sequences of up to eight numbers separated bycolons, as in ‘5f03:1200:836f:c100::1’.
Each computer also has one or morehost names, which are stringsof words separated by periods, as in ‘www.gnu.org’.
Programs that let the user specify a host typically accept both numericaddresses and host names. To open a connection a program needs anumeric address, and so must convert a host name to the numeric addressit stands for.
Next:Host Address Data Type, Up:Host Addresses [Contents][Index]
An IPv4 Internet host address is a number containing four bytes of data.Historically these are divided into two parts, anetwork number and alocal network address number within that network. In themid-1990s classless addresses were introduced which changed thisbehavior. Since some functions implicitly expect the old definitions,we first describe the class-based network and will then describeclassless addresses. IPv6 uses only classless addresses and thereforethe following paragraphs don’t apply.
The class-based IPv4 network number consists of the first one, two orthree bytes; the rest of the bytes are the local address.
IPv4 network numbers are registered with the Network Information Center(NIC), and are divided into three classes—A, B and C. The localnetwork address numbers of individual machines are registered with theadministrator of the particular network.
Class A networks have single-byte numbers in the range 0 to 127. Thereare only a small number of Class A networks, but they can each support avery large number of hosts. Medium-sized Class B networks have two-bytenetwork numbers, with the first byte in the range 128 to 191. Class Cnetworks are the smallest; they have three-byte network numbers, withthe first byte in the range 192-255. Thus, the first 1, 2, or 3 bytesof an Internet address specify a network. The remaining bytes of theInternet address specify the address within that network.
The Class A network 0 is reserved for broadcast to all networks. Inaddition, the host number 0 within each network is reserved for broadcastto all hosts in that network. These uses are obsolete now but forcompatibility reasons you shouldn’t use network 0 and host number 0.
The Class A network 127 is reserved for loopback; you can always usethe Internet address ‘127.0.0.1’ to refer to the host machine.
Since a single machine can be a member of multiple networks, it canhave multiple Internet host addresses. However, there is neversupposed to be more than one machine with the same host address.
There are four forms of thestandard numbers-and-dots notationfor Internet addresses:
a.b.c.d
This specifies all four bytes of the address individually and is thecommonly used representation.
a.b.c
The last part of the address,c, is interpreted as a 2-byte quantity.This is useful for specifying host addresses in a Class B network withnetwork address numbera.b
.
a.b
The last part of the address,b, is interpreted as a 3-byte quantity.This is useful for specifying host addresses in a Class A network withnetwork address numbera.
a
If only one part is given, this corresponds directly to the host addressnumber.
Within each part of the address, the usual C conventions for specifyingthe radix apply. In other words, a leading ‘0x’ or ‘0X’ implieshexadecimal radix; a leading ‘0’ implies octal; and otherwise decimalradix is assumed.
IPv4 addresses (and IPv6 addresses also) are now considered classless;the distinction between classes A, B and C can be ignored. Instead anIPv4 host address consists of a 32-bit address and a 32-bit mask. Themask contains set bits for the network part and cleared bits for thehost part. The network part is contiguous from the left, with theremaining bits representing the host. As a consequence, the netmask cansimply be specified as the number of set bits. Classes A, B and C arejust special cases of this general rule. For example, class A addresseshave a netmask of ‘255.0.0.0’ or a prefix length of 8.
Classless IPv4 network addresses are written in numbers-and-dotsnotation with the prefix length appended and a slash as separator. Forexample the class A network 10 is written as ‘10.0.0.0/8’.
IPv6 addresses contain 128 bits (IPv4 has 32 bits) of data. A hostaddress is usually written as eight 16-bit hexadecimal numbers that areseparated by colons. Two colons are used to abbreviate strings ofconsecutive zeros. For example, the IPv6 loopback address‘0:0:0:0:0:0:0:1’ can just be written as ‘::1’.
Next:Host Address Functions, Previous:Internet Host Addresses, Up:Host Addresses [Contents][Index]
IPv4 Internet host addresses are represented in some contexts as integers(typeuint32_t
). In other contexts, the integer ispackaged inside a structure of typestruct in_addr
. It wouldbe better if the usage were made consistent, but it is not hard to extractthe integer from the structure or put the integer into a structure.
You will find older code that usesunsigned long int
forIPv4 Internet host addresses instead ofuint32_t
orstructin_addr
. Historicallyunsigned long int
was a 32-bit number butwith 64-bit machines this has changed. Usingunsigned long int
might break the code if it is used on machines where this type doesn’thave 32 bits.uint32_t
is specified by Unix98 and guaranteed to have32 bits.
IPv6 Internet host addresses have 128 bits and are packaged inside astructure of typestruct in6_addr
.
The following basic definitions for Internet addresses are declared inthe header filenetinet/in.h:
This data type is used in certain contexts to contain an IPv4 Internethost address. It has just one field, nameds_addr
, which recordsthe host address number as anuint32_t
.
uint32_t
INADDR_LOOPBACK ¶You can use this constant to stand for “the address of this machine,”instead of finding its actual address. It is the IPv4 Internet address‘127.0.0.1’, which is usually called ‘localhost’. Thisspecial constant saves you the trouble of looking up the address of yourown machine. Also, the system usually implementsINADDR_LOOPBACK
specially, avoiding any network traffic for the case of one machinetalking to itself.
uint32_t
INADDR_ANY ¶You can use this constant to stand for “any incoming address” whenbinding to an address. SeeSetting the Address of a Socket. This is the usualaddress to give in thesin_addr
member ofstruct sockaddr_in
when you want to accept Internet connections.
uint32_t
INADDR_BROADCAST ¶This constant is the address you use to send a broadcast message.
uint32_t
INADDR_NONE ¶This constant is returned by some functions to indicate an error.
This data type is used to store an IPv6 address. It stores 128 bits ofdata, which can be accessed (via a union) in a variety of ways.
struct in6_addr
in6addr_loopback ¶This constant is the IPv6 address ‘::1’, the loopback address. Seeabove for a description of what this means. The macroIN6ADDR_LOOPBACK_INIT
is provided to allow you to initialize yourown variables to this value.
struct in6_addr
in6addr_any ¶This constant is the IPv6 address ‘::’, the unspecified address. Seeabove for a description of what this means. The macroIN6ADDR_ANY_INIT
is provided to allow you to initialize yourown variables to this value.
Next:Host Names, Previous:Host Address Data Type, Up:Host Addresses [Contents][Index]
These additional functions for manipulating Internet addresses aredeclared in the header filearpa/inet.h. They represent Internetaddresses in network byte order, and network numbers andlocal-address-within-network numbers in host byte order. SeeByte Order Conversion, for an explanation of network and host byte order.
int
inet_aton(const char *name, struct in_addr *addr)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function converts the IPv4 Internet host addressnamefrom the standard numbers-and-dots notation into binary data and storesit in thestruct in_addr
thataddr points to.inet_aton
returns nonzero if the address is valid, zero if not.
uint32_t
inet_addr(const char *name)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function converts the IPv4 Internet host addressname from thestandard numbers-and-dots notation into binary data. If the input isnot valid,inet_addr
returnsINADDR_NONE
. This is anobsolete interface toinet_aton
, described immediately above. Itis obsolete becauseINADDR_NONE
is a valid address(255.255.255.255), andinet_aton
provides a cleaner way toindicate error return.
uint32_t
inet_network(const char *name)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function extracts the network number from the addressname,given in the standard numbers-and-dots notation. The returned address isin host order. If the input is not valid,inet_network
returns-1
.
The function works only with traditional IPv4 class A, B and C networktypes. It doesn’t work with classless addresses and shouldn’t be usedanymore.
char *
inet_ntoa(struct in_addraddr)
¶Preliminary:| MT-Safe locale| AS-Unsafe race| AC-Safe | SeePOSIX Safety Concepts.
This function converts the IPv4 Internet host addressaddr to astring in the standard numbers-and-dots notation. The return value isa pointer into a statically-allocated buffer. Subsequent calls willoverwrite the same buffer, so you should copy the string if you needto save it.
In multi-threaded programs each thread has its own statically-allocatedbuffer. But still subsequent calls ofinet_ntoa
in the samethread will overwrite the result of the last call.
Instead ofinet_ntoa
the newer functioninet_ntop
which isdescribed below should be used since it handles both IPv4 and IPv6addresses.
struct in_addr
inet_makeaddr(uint32_tnet, uint32_tlocal)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function makes an IPv4 Internet host address by combining the networknumbernet with the local-address-within-network numberlocal.
uint32_t
inet_lnaof(struct in_addraddr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the local-address-within-network part of theInternet host addressaddr.
The function works only with traditional IPv4 class A, B and C networktypes. It doesn’t work with classless addresses and shouldn’t be usedanymore.
uint32_t
inet_netof(struct in_addraddr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the network number part of the Internet hostaddressaddr.
The function works only with traditional IPv4 class A, B and C networktypes. It doesn’t work with classless addresses and shouldn’t be usedanymore.
int
inet_pton(intaf, const char *cp, void *buf)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function converts an Internet address (either IPv4 or IPv6) frompresentation (textual) to network (binary) format.af should beeitherAF_INET
orAF_INET6
, as appropriate for the type ofaddress being converted.cp is a pointer to the input string, andbuf is a pointer to a buffer for the result. It is the caller’sresponsibility to make sure the buffer is large enough.
The return value is1
on success and0
ifcp does notpoint to a valid address string for the address familyaf requested.On failure, the function’s return value is-1
anderrno
isset accordingly. The followingerrno
values are specific to thisfunction:
EAFNOSUPPORT
The address family requested is neitherAF_INET
norAF_INET6
.
const char *
inet_ntop(intaf, const void *cp, char *buf, socklen_tlen)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function converts an Internet address (either IPv4 or IPv6) fromnetwork (binary) to presentation (textual) form.af should beeitherAF_INET
orAF_INET6
, as appropriate.cp is apointer to the address to be converted.buf should be a pointerto a buffer to hold the result, andlen is the length of thisbuffer.
The return value isbuf on success. On failure, the function’sreturn value is a null pointer anderrno
is set accordingly.The followingerrno
values are specific to this function:
EAFNOSUPPORT
The address family requested is neitherAF_INET
norAF_INET6
.
ENOSPC
Insufficient space available for the result in the buffer provided.
Previous:Host Address Functions, Up:Host Addresses [Contents][Index]
Besides the standard numbers-and-dots notation for Internet addresses,you can also refer to a host by a symbolic name. The advantage of asymbolic name is that it is usually easier to remember. For example,the machine with Internet address ‘158.121.106.19’ is also known as‘alpha.gnu.org’; and other machines in the ‘gnu.org’domain can refer to it simply as ‘alpha’.
Internally, the system uses a database to keep track of the mappingbetween host names and host numbers. This database is usually eitherthe file/etc/hosts or an equivalent provided by a name server.The functions and other symbols for accessing this database are declaredinnetdb.h. They are BSD features, defined unconditionally ifyou includenetdb.h.
This data type is used to represent an entry in the hosts database. Ithas the following members:
char *h_name
This is the “official” name of the host.
char **h_aliases
These are alternative names for the host, represented as a null-terminatedvector of strings.
int h_addrtype
This is the host address type; in practice, its value is always eitherAF_INET
orAF_INET6
, with the latter being used for IPv6hosts. In principle other kinds of addresses could be represented inthe database as well as Internet addresses; if this were done, youmight find a value in this field other thanAF_INET
orAF_INET6
. SeeSocket Addresses.
int h_length
This is the length, in bytes, of each address.
char **h_addr_list
This is the vector of addresses for the host. (Recall that the hostmight be connected to multiple networks and have different addresses oneach one.) The vector is terminated by a null pointer.
char *h_addr
This is a synonym forh_addr_list[0]
; in other words, it is thefirst host address.
As far as the host database is concerned, each address is just a blockof memoryh_length
bytes long. But in other contexts there is animplicit assumption that you can convert IPv4 addresses to astruct in_addr
or anuint32_t
. Host addresses inastruct hostent
structure are always given in network byteorder; seeByte Order Conversion.
You can usegethostbyname
,gethostbyname2
orgethostbyaddr
to search the hosts database for information abouta particular host. The information is returned in astatically-allocated structure; you must copy the information if youneed to save it across calls. You can also usegetaddrinfo
andgetnameinfo
to obtain this information.
struct hostent *
gethostbyname(const char *name)
¶Preliminary:| MT-Unsafe race:hostbyname env locale| AS-Unsafe dlopen plugin corrupt heap lock| AC-Unsafe lock corrupt mem fd| SeePOSIX Safety Concepts.
Thegethostbyname
function returns information about the hostnamedname. If the lookup fails, it returns a null pointer.
struct hostent *
gethostbyname2(const char *name, intaf)
¶Preliminary:| MT-Unsafe race:hostbyname2 env locale| AS-Unsafe dlopen plugin corrupt heap lock| AC-Unsafe lock corrupt mem fd| SeePOSIX Safety Concepts.
Thegethostbyname2
function is likegethostbyname
, butallows the caller to specify the desired address family (e.g.AF_INET
orAF_INET6
) of the result.
struct hostent *
gethostbyaddr(const void *addr, socklen_tlength, intformat)
¶Preliminary:| MT-Unsafe race:hostbyaddr env locale| AS-Unsafe dlopen plugin corrupt heap lock| AC-Unsafe lock corrupt mem fd| SeePOSIX Safety Concepts.
Thegethostbyaddr
function returns information about the hostwith Internet addressaddr. The parameteraddr is notreally a pointer to char - it can be a pointer to an IPv4 or an IPv6address. Thelength argument is the size (in bytes) of the addressataddr.format specifies the address format; for an IPv4Internet address, specify a value ofAF_INET
; for an IPv6Internet address, useAF_INET6
.
If the lookup fails,gethostbyaddr
returns a null pointer.
If the name lookup bygethostbyname
orgethostbyaddr
fails, you can find out the reason by looking at the value of thevariableh_errno
. (It would be cleaner design for thesefunctions to seterrno
, but use ofh_errno
is compatiblewith other systems.)
Here are the error codes that you may find inh_errno
:
HOST_NOT_FOUND
¶No such host is known in the database.
TRY_AGAIN
¶This condition happens when the name server could not be contacted. Ifyou try again later, you may succeed then.
NO_RECOVERY
¶A non-recoverable error occurred.
NO_ADDRESS
¶The host database contains an entry for the name, but it doesn’t have anassociated Internet address.
The lookup functions above all have one thing in common: they are notreentrant and therefore unusable in multi-threaded applications.Therefore provides the GNU C Library a new set of functions which can beused in this context.
int
gethostbyname_r(const char *restrictname, struct hostent *restrictresult_buf, char *restrictbuf, size_tbuflen, struct hostent **restrictresult, int *restricth_errnop)
¶Preliminary:| MT-Safe env locale| AS-Unsafe dlopen plugin corrupt heap lock| AC-Unsafe lock corrupt mem fd| SeePOSIX Safety Concepts.
Thegethostbyname_r
function returns information about the hostnamedname. The caller must pass a pointer to an object of typestruct hostent
in theresult_buf parameter. In additionthe function may need extra buffer space and the caller must pass apointer and the size of the buffer in thebuf andbuflenparameters.
A pointer to the buffer, in which the result is stored, is available in*result
after the function call successfully returned. Thebuffer passed as thebuf parameter can be freed only once the callerhas finished with the result hostent struct, or has copied it including allthe other memory that it points to. If an error occurs or if no entry isfound, the pointer*result
is a null pointer. Success issignalled by a zero return value. If the function failed the return valueis an error number. In addition to the errors defined forgethostbyname
it can also beERANGE
. In this case the callshould be repeated with a larger buffer. Additional error information isnot stored in the global variableh_errno
but instead in the objectpointed to byh_errnop.
Here’s a small example:
struct hostent *gethostname (char *host){ struct hostent *hostbuf, *hp; size_t hstbuflen; char *tmphstbuf; int res; int herr; hostbuf = malloc (sizeof (struct hostent)); hstbuflen = 1024; tmphstbuf = malloc (hstbuflen); while ((res = gethostbyname_r (host, hostbuf, tmphstbuf, hstbuflen, &hp, &herr)) == ERANGE) { /* Enlarge the buffer. */ tmphstbuf = reallocarray (tmphstbuf, hstbuflen, 2); hstbuflen *= 2; } free (tmphstbuf); /* Check for errors. */ if (res || hp == NULL) return NULL; return hp;}
int
gethostbyname2_r(const char *name, intaf, struct hostent *restrictresult_buf, char *restrictbuf, size_tbuflen, struct hostent **restrictresult, int *restricth_errnop)
¶Preliminary:| MT-Safe env locale| AS-Unsafe dlopen plugin corrupt heap lock| AC-Unsafe lock corrupt mem fd| SeePOSIX Safety Concepts.
Thegethostbyname2_r
function is likegethostbyname_r
, butallows the caller to specify the desired address family (e.g.AF_INET
orAF_INET6
) for the result.
int
gethostbyaddr_r(const void *addr, socklen_tlength, intformat, struct hostent *restrictresult_buf, char *restrictbuf, size_tbuflen, struct hostent **restrictresult, int *restricth_errnop)
¶Preliminary:| MT-Safe env locale| AS-Unsafe dlopen plugin corrupt heap lock| AC-Unsafe lock corrupt mem fd| SeePOSIX Safety Concepts.
Thegethostbyaddr_r
function returns information about the hostwith Internet addressaddr. The parameteraddr is notreally a pointer to char - it can be a pointer to an IPv4 or an IPv6address. Thelength argument is the size (in bytes) of the addressataddr.format specifies the address format; for an IPv4Internet address, specify a value ofAF_INET
; for an IPv6Internet address, useAF_INET6
.
Similar to thegethostbyname_r
function, the caller must providebuffers for the result and memory used internally. In case of successthe function returns zero. Otherwise the value is an error number whereERANGE
has the special meaning that the caller-provided buffer istoo small.
You can also scan the entire hosts database one entry at a time usingsethostent
,gethostent
andendhostent
. Be carefulwhen using these functions because they are not reentrant.
void
sethostent(intstayopen)
¶Preliminary:| MT-Unsafe race:hostent env locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function opens the hosts database to begin scanning it. You canthen callgethostent
to read the entries.
If thestayopen argument is nonzero, this sets a flag so thatsubsequent calls togethostbyname
orgethostbyaddr
willnot close the database (as they usually would). This makes for moreefficiency if you call those functions several times, by avoidingreopening the database for each call.
struct hostent *
gethostent(void)
¶Preliminary:| MT-Unsafe race:hostent race:hostentbuf env locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function returns the next entry in the hosts database. Itreturns a null pointer if there are no more entries.
void
endhostent(void)
¶Preliminary:| MT-Unsafe race:hostent env locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function closes the hosts database.
Next:The Services Database, Previous:Host Addresses, Up:The Internet Namespace [Contents][Index]
A socket address in the Internet namespace consists of a machine’sInternet address plus aport number which distinguishes thesockets on a given machine (for a given protocol). Port numbers rangefrom 0 to 65,535.
Port numbers less thanIPPORT_RESERVED
are reserved for standardservers, such asfinger
andtelnet
. There is a databasethat keeps track of these, and you can use thegetservbyname
function to map a service name onto a port number; seeThe Services Database.
If you write a server that is not one of the standard ones defined inthe database, you must choose a port number for it. Use a numbergreater thanIPPORT_USERRESERVED
; such numbers are reserved forservers and won’t ever be generated automatically by the system.Avoiding conflicts with servers being run by other users is up to you.
When you use a socket without specifying its address, the systemgenerates a port number for it. This number is betweenIPPORT_RESERVED
andIPPORT_USERRESERVED
.
On the Internet, it is actually legitimate to have two differentsockets with the same port number, as long as they never both try tocommunicate with the same socket address (host address plus portnumber). You shouldn’t duplicate a port number except in specialcircumstances where a higher-level protocol requires it. Normally,the system won’t let you do it;bind
normally insists ondistinct port numbers. To reuse a port number, you must set thesocket optionSO_REUSEADDR
. SeeSocket-Level Options.
These macros are defined in the header filenetinet/in.h.
int
IPPORT_RESERVED ¶Port numbers less thanIPPORT_RESERVED
are reserved forsuperuser use.
int
IPPORT_USERRESERVED ¶Port numbers greater than or equal toIPPORT_USERRESERVED
arereserved for explicit use; they will never be allocated automatically.
Next:Byte Order Conversion, Previous:Internet Ports, Up:The Internet Namespace [Contents][Index]
The database that keeps track of “well-known” services is usuallyeither the file/etc/services or an equivalent from a name server.You can use these utilities, declared innetdb.h, to accessthe services database.
This data type holds information about entries from the services database.It has the following members:
char *s_name
This is the “official” name of the service.
char **s_aliases
These are alternate names for the service, represented as an array ofstrings. A null pointer terminates the array.
int s_port
This is the port number for the service. Port numbers are given innetwork byte order; seeByte Order Conversion.
char *s_proto
This is the name of the protocol to use with this service.SeeProtocols Database.
To get information about a particular service, use thegetservbyname
orgetservbyport
functions. The informationis returned in a statically-allocated structure; you must copy theinformation if you need to save it across calls.
struct servent *
getservbyname(const char *name, const char *proto)
¶Preliminary:| MT-Unsafe race:servbyname locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegetservbyname
function returns information about theservice namedname using protocolproto. If it can’t findsuch a service, it returns a null pointer.
This function is useful for servers as well as for clients; serversuse it to determine which port they should listen on (seeListening for Connections).
struct servent *
getservbyport(intport, const char *proto)
¶Preliminary:| MT-Unsafe race:servbyport locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegetservbyport
function returns information about theservice at portport using protocolproto. If it can’tfind such a service, it returns a null pointer.
You can also scan the services database usingsetservent
,getservent
andendservent
. Be careful when using thesefunctions because they are not reentrant.
void
setservent(intstayopen)
¶Preliminary:| MT-Unsafe race:servent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function opens the services database to begin scanning it.
If thestayopen argument is nonzero, this sets a flag so thatsubsequent calls togetservbyname
orgetservbyport
willnot close the database (as they usually would). This makes for moreefficiency if you call those functions several times, by avoidingreopening the database for each call.
struct servent *
getservent(void)
¶Preliminary:| MT-Unsafe race:servent race:serventbuf locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function returns the next entry in the services database. Ifthere are no more entries, it returns a null pointer.
void
endservent(void)
¶Preliminary:| MT-Unsafe race:servent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function closes the services database.
Next:Protocols Database, Previous:The Services Database, Up:The Internet Namespace [Contents][Index]
Different kinds of computers use different conventions for theordering of bytes within a word. Some computers put the mostsignificant byte within a word first (this is called “big-endian”order), and others put it last (“little-endian” order).
So that machines with different byte order conventions cancommunicate, the Internet protocols specify a canonical byte orderconvention for data transmitted over the network. This is knownasnetwork byte order.
When establishing an Internet socket connection, you must make sure thatthe data in thesin_port
andsin_addr
members of thesockaddr_in
structure are represented in network byte order.If you are encoding integer data in the messages sent through thesocket, you should convert this to network byte order too. If you don’tdo this, your program may fail when running on or talking to other kindsof machines.
If you usegetservbyname
andgethostbyname
orinet_addr
to get the port number and host address, the values arealready in network byte order, and you can copy them directly intothesockaddr_in
structure.
Otherwise, you have to convert the values explicitly. Usehtons
andntohs
to convert values for thesin_port
member. Usehtonl
andntohl
to convert IPv4 addresses for thesin_addr
member. (Remember,struct in_addr
is equivalenttouint32_t
.) These functions are declared innetinet/in.h.
uint16_t
htons(uint16_thostshort)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function converts theuint16_t
integerhostshort fromhost byte order to network byte order.
uint16_t
ntohs(uint16_tnetshort)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function converts theuint16_t
integernetshort fromnetwork byte order to host byte order.
uint32_t
htonl(uint32_thostlong)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function converts theuint32_t
integerhostlong fromhost byte order to network byte order.
This is used for IPv4 Internet addresses.
uint32_t
ntohl(uint32_tnetlong)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function converts theuint32_t
integernetlong fromnetwork byte order to host byte order.
This is used for IPv4 Internet addresses.
Next:Internet Socket Example, Previous:Byte Order Conversion, Up:The Internet Namespace [Contents][Index]
The communications protocol used with a socket controls low-leveldetails of how data are exchanged. For example, the protocol implementsthings like checksums to detect errors in transmissions, and routinginstructions for messages. Normal user programs have little reason tomess with these details directly.
The default communications protocol for the Internet namespace depends onthe communication style. For stream communication, the default is TCP(“transmission control protocol”). For datagram communication, thedefault is UDP (“user datagram protocol”). For reliable datagramcommunication, the default is RDP (“reliable datagram protocol”).You should nearly always use the default.
Internet protocols are generally specified by a name instead of anumber. The network protocols that a host knows about are stored in adatabase. This is usually either derived from the file/etc/protocols, or it may be an equivalent provided by a nameserver. You look up the protocol number associated with a namedprotocol in the database using thegetprotobyname
function.
Here are detailed descriptions of the utilities for accessing theprotocols database. These are declared innetdb.h.
This data type is used to represent entries in the network protocolsdatabase. It has the following members:
char *p_name
This is the official name of the protocol.
char **p_aliases
These are alternate names for the protocol, specified as an array ofstrings. The last element of the array is a null pointer.
int p_proto
This is the protocol number (in host byte order); use this member as theprotocol argument tosocket
.
You can usegetprotobyname
andgetprotobynumber
to searchthe protocols database for a specific protocol. The information isreturned in a statically-allocated structure; you must copy theinformation if you need to save it across calls.
struct protoent *
getprotobyname(const char *name)
¶Preliminary:| MT-Unsafe race:protobyname locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegetprotobyname
function returns information about thenetwork protocol namedname. If there is no such protocol, itreturns a null pointer.
struct protoent *
getprotobynumber(intprotocol)
¶Preliminary:| MT-Unsafe race:protobynumber locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegetprotobynumber
function returns information about thenetwork protocol with numberprotocol. If there is no suchprotocol, it returns a null pointer.
You can also scan the whole protocols database one protocol at a time byusingsetprotoent
,getprotoent
andendprotoent
.Be careful when using these functions because they are not reentrant.
void
setprotoent(intstayopen)
¶Preliminary:| MT-Unsafe race:protoent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function opens the protocols database to begin scanning it.
If thestayopen argument is nonzero, this sets a flag so thatsubsequent calls togetprotobyname
orgetprotobynumber
willnot close the database (as they usually would). This makes for moreefficiency if you call those functions several times, by avoidingreopening the database for each call.
struct protoent *
getprotoent(void)
¶Preliminary:| MT-Unsafe race:protoent race:protoentbuf locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function returns the next entry in the protocols database. Itreturns a null pointer if there are no more entries.
void
endprotoent(void)
¶Preliminary:| MT-Unsafe race:protoent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function closes the protocols database.
Previous:Protocols Database, Up:The Internet Namespace [Contents][Index]
Here is an example showing how to create and name a socket in theInternet namespace. The newly created socket exists on the machine thatthe program is running on. Rather than finding and using the machine’sInternet address, this example specifiesINADDR_ANY
as the hostaddress; the system replaces that with the machine’s actual address.
#include <stdio.h>#include <stdlib.h>#include <sys/socket.h>#include <netinet/in.h>intmake_socket (uint16_t port){ int sock; struct sockaddr_in name; /*Create the socket. */ sock = socket (PF_INET, SOCK_STREAM, 0); if (sock < 0) { perror ("socket"); exit (EXIT_FAILURE); } /*Give the socket a name. */ name.sin_family = AF_INET; name.sin_port = htons (port); name.sin_addr.s_addr = htonl (INADDR_ANY); if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) { perror ("bind"); exit (EXIT_FAILURE); } return sock;}
Here is another example, showing how you can fill in asockaddr_in
structure, given a host name string and a port number:
#include <stdio.h>#include <stdlib.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>voidinit_sockaddr (struct sockaddr_in *name, const char *hostname, uint16_t port){ struct hostent *hostinfo; name->sin_family = AF_INET; name->sin_port = htons (port); hostinfo = gethostbyname (hostname); if (hostinfo == NULL) { fprintf (stderr, "Unknown host %s.\n", hostname); exit (EXIT_FAILURE); } name->sin_addr = *(struct in_addr *) hostinfo->h_addr;}
Next:Opening and Closing Sockets, Previous:The Internet Namespace, Up:Sockets [Contents][Index]
Certain other namespaces and associated protocol families are supportedbut not documented yet because they are not often used.PF_NS
refers to the Xerox Network Software protocols.PF_ISO
standsfor Open Systems Interconnect.PF_CCITT
refers to protocols fromCCITT.socket.h defines these symbols and others naming protocolsnot actually implemented.
PF_IMPLINK
is used for communicating between hosts and InternetMessage Processors. For information on this andPF_ROUTE
, anoccasionally-used local area routing protocol, see the GNU Hurd Manual(to appear in the future).
Next:Using Sockets with Connections, Previous:Other Namespaces, Up:Sockets [Contents][Index]
This section describes the actual library functions for opening andclosing sockets. The same functions work for all namespaces andconnection styles.
Next:Closing a Socket, Up:Opening and Closing Sockets [Contents][Index]
The primitive for creating a socket is thesocket
function,declared insys/socket.h.
int
socket(intnamespace, intstyle, intprotocol)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
This function creates a socket and specifies communication stylestyle, which should be one of the socket styles listed inCommunication Styles. Thenamespace argument specifiesthe namespace; it must bePF_LOCAL
(seeThe Local Namespace) orPF_INET
(seeThe Internet Namespace).protocoldesignates the specific protocol (seeSocket Concepts); zero isusually right forprotocol.
The return value fromsocket
is the file descriptor for the newsocket, or-1
in case of error. The followingerrno
errorconditions are defined for this function:
EAFNOSUPPORT
Thenamespace requested is not supported.
ESOCKTNOSUPPORT
EPROTONOSUPPORT
EPROTOTYPE
Thestyle is not supported by thenamespace specified.
EPROTONOSUPPORT
Theprotocol is not supported by thenamespace specified.
EINVAL
Thestyle orprotocol requested is not valid.
EMFILE
The process already has too many file descriptors open.
ENFILE
The system already has too many file descriptors open.
EACCES
EPERM
The process does not have the privilege to create a socket of the specifiedstyle orprotocol.
ENOBUFS
ENOMEM
Insufficient memory was available.
The file descriptor returned by thesocket
function supports bothread and write operations. However, like pipes, sockets do not support filepositioning operations.
For examples of how to call thesocket
function,seeExample of Local-Namespace Sockets, orInternet Socket Example.
Next:Socket Pairs, Previous:Creating a Socket, Up:Opening and Closing Sockets [Contents][Index]
When you have finished using a socket, you can simply close itsfile descriptor withclose
; seeOpening and Closing Files.If there is still data waiting to be transmitted over the connection,normallyclose
tries to complete this transmission. Youcan control this behavior using theSO_LINGER
socket option tospecify a timeout period; seeSocket Options.
You can also shut down only reception or transmission on aconnection by callingshutdown
, which is declared insys/socket.h.
int
shutdown(intsocket, inthow)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theshutdown
function shuts down the connection of socketsocket. The argumenthow specifies what action toperform:
0
Stop receiving data for this socket. If further data arrives,reject it.
1
Stop trying to transmit data from this socket. Discard any datawaiting to be sent. Stop looking for acknowledgement of data alreadysent; don’t retransmit it if it is lost.
2
Stop both reception and transmission.
The return value is0
on success and-1
on failure. Thefollowingerrno
error conditions are defined for this function:
EBADF
socket is not a valid file descriptor.
ENOTSOCK
socket is not a socket.
ENOTCONN
socket is not connected.
Previous:Closing a Socket, Up:Opening and Closing Sockets [Contents][Index]
Asocket pair consists of a pair of connected (but unnamed)sockets. It is very similar to a pipe and is used in much the sameway. Socket pairs are created with thesocketpair
function,declared insys/socket.h. A socket pair is much like a pipe; themain difference is that the socket pair is bidirectional, whereas thepipe has one input-only end and one output-only end (seePipes and FIFOs).
int
socketpair(intnamespace, intstyle, intprotocol, intfiledes[2]
)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
This function creates a socket pair, returning the file descriptors infiledes[0]
andfiledes[1]
. The socket pairis a full-duplex communications channel, so that both reading and writingmay be performed at either end.
Thenamespace,style andprotocol arguments areinterpreted as for thesocket
function.style should beone of the communication styles listed inCommunication Styles.Thenamespace argument specifies the namespace, which must beAF_LOCAL
(seeThe Local Namespace);protocol specifies thecommunications protocol, but zero is the only meaningful value.
Ifstyle specifies a connectionless communication style, thenthe two sockets you get are notconnected, strictly speaking,but each of them knows the other as the default destination address,so they can send packets to each other.
Thesocketpair
function returns0
on success and-1
on failure. The followingerrno
error conditions are definedfor this function:
EMFILE
The process has too many file descriptors open.
EAFNOSUPPORT
The specified namespace is not supported.
EPROTONOSUPPORT
The specified protocol is not supported.
EOPNOTSUPP
The specified protocol does not support the creation of socket pairs.
Next:Datagram Socket Operations, Previous:Opening and Closing Sockets, Up:Sockets [Contents][Index]
The most common communication styles involve making a connection to aparticular other socket, and then exchanging data with that socketover and over. Making a connection is asymmetric; one side (theclient) acts to request a connection, while the other side (theserver) makes a socket and waits for the connection request.
In making a connection, the client makes a connection while the serverwaits for and accepts the connection. Here we discuss what the clientprogram must do with theconnect
function, which is declared insys/socket.h.
int
connect(intsocket, struct sockaddr *addr, socklen_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theconnect
function initiates a connection from the socketwith file descriptorsocket to the socket whose address isspecified by theaddr andlength arguments. (This socketis typically on another machine, and it must be already set up as aserver.) SeeSocket Addresses, for information about how thesearguments are interpreted.
Normally,connect
waits until the server responds to the requestbefore it returns. You can set nonblocking mode on the socketsocket to makeconnect
return immediately without waitingfor the response. SeeFile Status Flags, for information aboutnonblocking mode.
The normal return value fromconnect
is0
. If an erroroccurs,connect
returns-1
. The followingerrno
error conditions are defined for this function:
EBADF
The socketsocket is not a valid file descriptor.
ENOTSOCK
File descriptorsocket is not a socket.
EADDRNOTAVAIL
The specified address is not available on the remote machine.
EAFNOSUPPORT
The namespace of theaddr is not supported by this socket.
EISCONN
The socketsocket is already connected.
ETIMEDOUT
The attempt to establish the connection timed out.
ECONNREFUSED
The server has actively refused to establish the connection.
ENETUNREACH
The network of the givenaddr isn’t reachable from this host.
EADDRINUSE
The socket address of the givenaddr is already in use.
EINPROGRESS
The socketsocket is non-blocking and the connection could not beestablished immediately. You can determine when the connection iscompletely established withselect
; seeWaiting for Input or Output.Anotherconnect
call on the same socket, before the connection iscompletely established, will fail withEALREADY
.
EALREADY
The socketsocket is non-blocking and already has a pendingconnection in progress (seeEINPROGRESS
above).
This function is defined as a cancellation point in multi-threadedprograms, so one has to be prepared for this and make sure thatallocated resources (like memory, file descriptors, semaphores orwhatever) are freed even if the thread is canceled.
Next:Accepting Connections, Previous:Making a Connection, Up:Using Sockets with Connections [Contents][Index]
Now let us consider what the server process must do to acceptconnections on a socket. First it must use thelisten
functionto enable connection requests on the socket, and then accept eachincoming connection with a call toaccept
(seeAccepting Connections). Once connection requests are enabled on a server socket,theselect
function reports when the socket has a connectionready to be accepted (seeWaiting for Input or Output).
Thelisten
function is not allowed for sockets usingconnectionless communication styles.
You can write a network server that does not even start running until aconnection to it is requested. Seeinetd
Servers.
In the Internet namespace, there are no special protection mechanismsfor controlling access to a port; any process on any machinecan make a connection to your server. If you want to restrict access toyour server, make it examine the addresses associated with connectionrequests or implement some other handshaking or identificationprotocol.
In the local namespace, the ordinary file protection bits control who hasaccess to connect to the socket.
int
listen(intsocket, intn)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
Thelisten
function enables the socketsocket to acceptconnections, thus making it a server socket.
The argumentn specifies the length of the queue for pendingconnections. When the queue fills, new clients attempting to connectfail withECONNREFUSED
until the server callsaccept
toaccept a connection from the queue.
Thelisten
function returns0
on success and-1
on failure. The followingerrno
error conditions are definedfor this function:
EBADF
The argumentsocket is not a valid file descriptor.
ENOTSOCK
The argumentsocket is not a socket.
EOPNOTSUPP
The socketsocket does not support this operation.
Next:Who is Connected to Me?, Previous:Listening for Connections, Up:Using Sockets with Connections [Contents][Index]
When a server receives a connection request, it can complete theconnection by accepting the request. Use the functionaccept
to do this.
A socket that has been established as a server can accept connectionrequests from multiple clients. The server’s original socketdoes not become part of the connection; instead,accept
makes a new socket which participates in the connection.accept
returns the descriptor for this socket. The server’soriginal socket remains available for listening for further connectionrequests.
The number of pending connection requests on a server socket is finite.If connection requests arrive from clients faster than the server canact upon them, the queue can fill up and additional requests are refusedwith anECONNREFUSED
error. You can specify the maximum length ofthis queue as an argument to thelisten
function, although thesystem may also impose its own internal limit on the length of thisqueue.
int
accept(intsocket, struct sockaddr *addr, socklen_t *length_ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
This function is used to accept a connection request on the serversocketsocket.
Theaccept
function waits if there are no connections pending,unless the socketsocket has nonblocking mode set. (You can useselect
to wait for a pending connection, with a nonblockingsocket.) SeeFile Status Flags, for information about nonblockingmode.
Theaddr andlength-ptr arguments are used to returninformation about the name of the client socket that initiated theconnection. SeeSocket Addresses, for information about the formatof the information.
Accepting a connection does not makesocket part of theconnection. Instead, it creates a new socket which becomesconnected. The normal return value ofaccept
is the filedescriptor for the new socket.
Afteraccept
, the original socketsocket remains open andunconnected, and continues listening until you close it. You canaccept further connections withsocket by callingaccept
again.
If an error occurs,accept
returns-1
. The followingerrno
error conditions are defined for this function:
EBADF
Thesocket argument is not a valid file descriptor.
ENOTSOCK
The descriptorsocket argument is not a socket.
EOPNOTSUPP
The descriptorsocket does not support this operation.
EWOULDBLOCK
socket has nonblocking mode set, and there are no pendingconnections immediately available.
This function is defined as a cancellation point in multi-threadedprograms, so one has to be prepared for this and make sure thatallocated resources (like memory, file descriptors, semaphores orwhatever) are freed even if the thread is canceled.
Theaccept
function is not allowed for sockets usingconnectionless communication styles.
Next:Transferring Data, Previous:Accepting Connections, Up:Using Sockets with Connections [Contents][Index]
int
getpeername(intsocket, struct sockaddr *addr, socklen_t *length-ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetpeername
function returns the address of the socket thatsocket is connected to; it stores the address in the memory spacespecified byaddr andlength-ptr. It stores the length ofthe address in*length-ptr
.
SeeSocket Addresses, for information about the format of theaddress. In some operating systems,getpeername
works only forsockets in the Internet domain.
The return value is0
on success and-1
on error. Thefollowingerrno
error conditions are defined for this function:
EBADF
The argumentsocket is not a valid file descriptor.
ENOTSOCK
The descriptorsocket is not a socket.
ENOTCONN
The socketsocket is not connected.
ENOBUFS
There are not enough internal buffers available.
Next:Byte Stream Socket Example, Previous:Who is Connected to Me?, Up:Using Sockets with Connections [Contents][Index]
Once a socket has been connected to a peer, you can use the ordinaryread
andwrite
operations (seeInput and Output Primitives) totransfer data. A socket is a two-way communications channel, so readand write operations can be performed at either end.
There are also some I/O modes that are specific to socket operations.In order to specify these modes, you must use therecv
andsend
functions instead of the more genericread
andwrite
functions. Therecv
andsend
functions takean additional argument which you can use to specify various flags tocontrol special I/O modes. For example, you can specify theMSG_OOB
flag to read or write out-of-band data, theMSG_PEEK
flag to peek at input, or theMSG_DONTROUTE
flagto control inclusion of routing information on output.
Next:Receiving Data, Up:Transferring Data [Contents][Index]
Thesend
function is declared in the header filesys/socket.h. If yourflags argument is zero, you can justas well usewrite
instead ofsend
; seeInput and Output Primitives. If the socket was connected but the connection has broken,you get aSIGPIPE
signal for any use ofsend
orwrite
(seeMiscellaneous Signals).
ssize_t
send(intsocket, const void *buffer, size_tsize, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thesend
function is likewrite
, but with the additionalflagsflags. The possible values offlags are describedinSocket Data Options.
This function returns the number of bytes transmitted, or-1
onfailure. If the socket is nonblocking, thensend
(likewrite
) can return after sending just part of the data.SeeFile Status Flags, for information about nonblocking mode.
Note, however, that a successful return value merely indicates thatthe message has been sent without error, not necessarily that it hasbeen received without error.
The followingerrno
error conditions are defined for this function:
EBADF
Thesocket argument is not a valid file descriptor.
EINTR
The operation was interrupted by a signal before any data was sent.SeePrimitives Interrupted by Signals.
ENOTSOCK
The descriptorsocket is not a socket.
EMSGSIZE
The socket type requires that the message be sent atomically, but themessage is too large for this to be possible.
EWOULDBLOCK
Nonblocking mode has been set on the socket, and the write operationwould block. (Normallysend
blocks until the operation can becompleted.)
ENOBUFS
There is not enough internal buffer space available.
ENOTCONN
You never connected this socket.
EPIPE
This socket was connected but the connection is now broken. In thiscase,send
generates aSIGPIPE
signal first; if thatsignal is ignored or blocked, or if its handler returns, thensend
fails withEPIPE
.
This function is defined as a cancellation point in multi-threadedprograms, so one has to be prepared for this and make sure thatallocated resources (like memory, file descriptors, semaphores orwhatever) are freed even if the thread is canceled.
Next:Socket Data Options, Previous:Sending Data, Up:Transferring Data [Contents][Index]
Therecv
function is declared in the header filesys/socket.h. If yourflags argument is zero, you canjust as well useread
instead ofrecv
; seeInput and Output Primitives.
ssize_t
recv(intsocket, void *buffer, size_tsize, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Therecv
function is likeread
, but with the additionalflagsflags. The possible values offlags are describedinSocket Data Options.
If nonblocking mode is set forsocket, and no data are available tobe read,recv
fails immediately rather than waiting. SeeFile Status Flags, for information about nonblocking mode.
This function returns the number of bytes received, or-1
on failure.The followingerrno
error conditions are defined for this function:
EBADF
Thesocket argument is not a valid file descriptor.
ENOTSOCK
The descriptorsocket is not a socket.
EWOULDBLOCK
Nonblocking mode has been set on the socket, and the read operationwould block. (Normally,recv
blocks until there is inputavailable to be read.)
EINTR
The operation was interrupted by a signal before any data was read.SeePrimitives Interrupted by Signals.
ENOTCONN
You never connected this socket.
This function is defined as a cancellation point in multi-threadedprograms, so one has to be prepared for this and make sure thatallocated resources (like memory, file descriptors, semaphores orwhatever) are freed even if the thread is canceled.
Previous:Receiving Data, Up:Transferring Data [Contents][Index]
Theflags argument tosend
andrecv
is a bitmask. You can bitwise-OR the values of the following macros togetherto obtain a value for this argument. All are defined in the headerfilesys/socket.h.
int
MSG_OOB ¶Send or receive out-of-band data. SeeOut-of-Band Data.
int
MSG_PEEK ¶Look at the data but don’t remove it from the input queue. This isonly meaningful with input functions such asrecv
, not withsend
.
int
MSG_DONTROUTE ¶Don’t include routing information in the message. This is onlymeaningful with output operations, and is usually only of interest fordiagnostic or routing programs. We don’t try to explain it here.
Next:Byte Stream Connection Server Example, Previous:Transferring Data, Up:Using Sockets with Connections [Contents][Index]
Here is an example client program that makes a connection for a bytestream socket in the Internet namespace. It doesn’t do anythingparticularly interesting once it has connected to the server; it justsends a text string to the server and exits.
This program usesinit_sockaddr
to set up the socket address; seeInternet Socket Example.
#include <stdio.h>#include <errno.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>#define PORT 5555#define MESSAGE "Yow!!! Are we having fun yet?!?"#define SERVERHOST "www.gnu.org"voidwrite_to_server (int filedes){ int nbytes; nbytes = write (filedes, MESSAGE, strlen (MESSAGE) + 1); if (nbytes < 0) { perror ("write"); exit (EXIT_FAILURE); }}intmain (void){ extern void init_sockaddr (struct sockaddr_in *name, const char *hostname, uint16_t port); int sock; struct sockaddr_in servername; /*Create the socket. */ sock = socket (PF_INET, SOCK_STREAM, 0); if (sock < 0) { perror ("socket (client)"); exit (EXIT_FAILURE); } /*Connect to the server. */ init_sockaddr (&servername, SERVERHOST, PORT); if (0 > connect (sock, (struct sockaddr *) &servername, sizeof (servername))) { perror ("connect (client)"); exit (EXIT_FAILURE); } /*Send data to the server. */ write_to_server (sock); close (sock); exit (EXIT_SUCCESS);}
Next:Out-of-Band Data, Previous:Byte Stream Socket Example, Up:Using Sockets with Connections [Contents][Index]
The server end is much more complicated. Since we want to allowmultiple clients to be connected to the server at the same time, itwould be incorrect to wait for input from a single client by simplycallingread
orrecv
. Instead, the right thing to do isto useselect
(seeWaiting for Input or Output) to wait for input onall of the open sockets. This also allows the server to deal withadditional connection requests.
This particular server doesn’t do anything interesting once it hasgotten a message from a client. It does close the socket for thatclient when it detects an end-of-file condition (resulting from theclient shutting down its end of the connection).
This program usesmake_socket
to set up the socket address; seeInternet Socket Example.
#include <stdio.h>#include <errno.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>#define PORT 5555#define MAXMSG 512intread_from_client (int filedes){ char buffer[MAXMSG]; int nbytes; nbytes = read (filedes, buffer, MAXMSG); if (nbytes < 0) { /*Read error. */ perror ("read"); exit (EXIT_FAILURE); } else if (nbytes == 0) /*End-of-file. */ return -1; else { /*Data read. */ fprintf (stderr, "Server: got message: `%s'\n", buffer); return 0; }}intmain (void){ extern int make_socket (uint16_t port); int sock; fd_set active_fd_set, read_fd_set; int i; struct sockaddr_in clientname; size_t size; /*Create the socket and set it up to accept connections. */ sock = make_socket (PORT); if (listen (sock, 1) < 0) { perror ("listen"); exit (EXIT_FAILURE); } /*Initialize the set of active sockets. */ FD_ZERO (&active_fd_set); FD_SET (sock, &active_fd_set); while (1) { /*Block until input arrives on one or more active sockets. */ read_fd_set = active_fd_set; if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0) { perror ("select"); exit (EXIT_FAILURE); } /*Service all the sockets with input pending. */ for (i = 0; i < FD_SETSIZE; ++i) if (FD_ISSET (i, &read_fd_set)) { if (i == sock) { /*Connection request on original socket. */ int new; size = sizeof (clientname); new = accept (sock, (struct sockaddr *) &clientname, &size); if (new < 0) { perror ("accept"); exit (EXIT_FAILURE); } fprintf (stderr, "Server: connect from host %s, port %hd.\n", inet_ntoa (clientname.sin_addr), ntohs (clientname.sin_port)); FD_SET (new, &active_fd_set); } else { /*Data arriving on an already-connected socket. */ if (read_from_client (i) < 0) { close (i); FD_CLR (i, &active_fd_set); } } } }}
Streams with connections permitout-of-band data that isdelivered with higher priority than ordinary data. Typically thereason for sending out-of-band data is to send notice of anexceptional condition. To send out-of-band data usesend
, specifying the flagMSG_OOB
(seeSending Data).
Out-of-band data are received with higher priority because thereceiving process need not read it in sequence; to read the nextavailable out-of-band data, userecv
with theMSG_OOB
flag (seeReceiving Data). Ordinary read operations do not readout-of-band data; they read only ordinary data.
When a socket finds that out-of-band data are on their way, it sends aSIGURG
signal to the owner process or process group of thesocket. You can specify the owner using theF_SETOWN
commandto thefcntl
function; seeInterrupt-Driven Input. You mustalso establish a handler for this signal, as described inSignal Handling, in order to take appropriate action such as reading theout-of-band data.
Alternatively, you can test for pending out-of-band data, or waituntil there is out-of-band data, using theselect
function; itcan wait for an exceptional condition on the socket. SeeWaiting for Input or Output, for more information aboutselect
.
Notification of out-of-band data (whether withSIGURG
or withselect
) indicates that out-of-band data are on the way; the datamay not actually arrive until later. If you try to read theout-of-band data before it arrives,recv
fails with anEWOULDBLOCK
error.
Sending out-of-band data automatically places a “mark” in the streamof ordinary data, showing where in the sequence the out-of-band data“would have been”. This is useful when the meaning of out-of-banddata is “cancel everything sent so far”. Here is how you can test,in the receiving process, whether any ordinary data was sent beforethe mark:
success = ioctl (socket, SIOCATMARK, &atmark);
Theinteger
variableatmark is set to a nonzero value ifthe socket’s read pointer has reached the “mark”.
Here’s a function to discard any ordinary data preceding theout-of-band mark:
intdiscard_until_mark (int socket){ while (1) { /*This is not an arbitrary limit; any size will do. */ char buffer[1024]; int atmark, success; /*If we have reached the mark, return. */ success = ioctl (socket, SIOCATMARK, &atmark); if (success < 0) perror ("ioctl"); if (result) return; /*Otherwise, read a bunch of ordinary data and discard it.This is guaranteed not to read past the markif it starts before the mark. */ success = read (socket, buffer, sizeof buffer); if (success < 0) perror ("read"); }}
If you don’t want to discard the ordinary data preceding the mark, youmay need to read some of it anyway, to make room in internal systembuffers for the out-of-band data. If you try to read out-of-band dataand get anEWOULDBLOCK
error, try reading some ordinary data(saving it so that you can use it when you want it) and see if thatmakes room. Here is an example:
struct buffer{ char *buf; int size; struct buffer *next;};/*Read the out-of-band data from SOCKET and return itas a ‘struct buffer’, which records the address of the dataand its size.It may be necessary to read some ordinary datain order to make room for the out-of-band data.If so, the ordinary data are saved as a chain of buffersfound in the ‘next’ field of the value. */struct buffer *read_oob (int socket){ struct buffer *tail = 0; struct buffer *list = 0; while (1) { /*This is an arbitrary limit.Does anyone know how to do this without a limit? */#define BUF_SZ 1024 char *buf = (char *) xmalloc (BUF_SZ); int success; int atmark; /*Try again to read the out-of-band data. */ success = recv (socket, buf, BUF_SZ, MSG_OOB); if (success >= 0) { /*We got it, so return it. */ struct buffer *link = (struct buffer *) xmalloc (sizeof (struct buffer)); link->buf = buf; link->size = success; link->next = list; return link; } /*If we fail, see if we are at the mark. */ success = ioctl (socket, SIOCATMARK, &atmark); if (success < 0) perror ("ioctl"); if (atmark) { /*At the mark; skipping past more ordinary data cannot help.So just wait a while. */ sleep (1); continue; } /*Otherwise, read a bunch of ordinary data and save it.This is guaranteed not to read past the markif it starts before the mark. */ success = read (socket, buf, BUF_SZ); if (success < 0) perror ("read"); /*Save this data in the buffer list. */ { struct buffer *link = (struct buffer *) xmalloc (sizeof (struct buffer)); link->buf = buf; link->size = success; /*Add the new link to the end of the list. */ if (tail) tail->next = link; else list = link; tail = link; } }}
Next:Theinetd
Daemon, Previous:Using Sockets with Connections, Up:Sockets [Contents][Index]
This section describes how to use communication styles that don’t useconnections (stylesSOCK_DGRAM
andSOCK_RDM
). Usingthese styles, you group data into packets and each packet is anindependent communication. You specify the destination for eachpacket individually.
Datagram packets are like letters: you send each one independentlywith its own destination address, and they may arrive in the wrongorder or not at all.
Thelisten
andaccept
functions are not allowed forsockets using connectionless communication styles.
Next:Receiving Datagrams, Up:Datagram Socket Operations [Contents][Index]
The normal way of sending data on a datagram socket is by using thesendto
function, declared insys/socket.h.
You can callconnect
on a datagram socket, but this onlyspecifies a default destination for further data transmission on thesocket. When a socket has a default destination you can usesend
(seeSending Data) or evenwrite
(seeInput and Output Primitives) to send a packet there. You can cancel the defaultdestination by callingconnect
using an address format ofAF_UNSPEC
in theaddr argument. SeeMaking a Connection, formore information about theconnect
function.
ssize_t
sendto(intsocket, const void *buffer, size_tsize, intflags, struct sockaddr *addr, socklen_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thesendto
function transmits the data in thebufferthrough the socketsocket to the destination address specifiedby theaddr andlength arguments. Thesize argumentspecifies the number of bytes to be transmitted.
Theflags are interpreted the same way as forsend
; seeSocket Data Options.
The return value and error conditions are also the same as forsend
, but you cannot rely on the system to detect errors andreport them; the most common error is that the packet is lost or thereis no-one at the specified address to receive it, and the operatingsystem on your machine usually does not know this.
It is also possible for one call tosendto
to report an errorowing to a problem related to a previous call.
This function is defined as a cancellation point in multi-threadedprograms, so one has to be prepared for this and make sure thatallocated resources (like memory, file descriptors, semaphores orwhatever) are freed even if the thread is canceled.
Next:Datagram Socket Example, Previous:Sending Datagrams, Up:Datagram Socket Operations [Contents][Index]
Therecvfrom
function reads a packet from a datagram socket andalso tells you where it was sent from. This function is declared insys/socket.h.
ssize_t
recvfrom(intsocket, void *buffer, size_tsize, intflags, struct sockaddr *addr, socklen_t *length-ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Therecvfrom
function reads one packet from the socketsocket into the bufferbuffer. Thesize argumentspecifies the maximum number of bytes to be read.
If the packet is longer thansize bytes, then you get the firstsize bytes of the packet and the rest of the packet is lost.There’s no way to read the rest of the packet. Thus, when you use apacket protocol, you must always know how long a packet to expect.
Theaddr andlength-ptr arguments are used to return theaddress where the packet came from. SeeSocket Addresses. For asocket in the local domain the address information won’t be meaningful,since you can’t read the address of such a socket (seeThe Local Namespace). You can specify a null pointer as theaddr argumentif you are not interested in this information.
Theflags are interpreted the same way as forrecv
(seeSocket Data Options). The return value and error conditionsare also the same as forrecv
.
This function is defined as a cancellation point in multi-threadedprograms, so one has to be prepared for this and make sure thatallocated resources (like memory, file descriptors, semaphores orwhatever) are freed even if the thread is canceled.
You can use plainrecv
(seeReceiving Data) instead ofrecvfrom
if you don’t need to find out who sent the packet(either because you know where it should come from or because youtreat all possible senders alike). Evenread
can be used ifyou don’t want to specifyflags (seeInput and Output Primitives).
If you need more flexibility and/or control over sending and receivingpackets, seesendmsg
andrecvmsg
(seeOther Socket APIs).
Next:Example of Reading Datagrams, Previous:Receiving Datagrams, Up:Datagram Socket Operations [Contents][Index]
Here is a set of example programs that send messages over a datagramstream in the local namespace. Both the client and server programs usethemake_named_socket
function that was presented inExample of Local-Namespace Sockets, to create and name their sockets.
First, here is the server program. It sits in a loop waiting formessages to arrive, bouncing each message back to the sender.Obviously this isn’t a particularly useful program, but it does showthe general ideas involved.
#include <stdio.h>#include <errno.h>#include <stdlib.h>#include <sys/socket.h>#include <sys/un.h>#define SERVER "/tmp/serversocket"#define MAXMSG 512intmain (void){ int sock; char message[MAXMSG]; struct sockaddr_un name; size_t size; int nbytes; /*Remove the filename first, it’s ok if the call fails */ unlink (SERVER); /*Make the socket, then loop endlessly. */ sock = make_named_socket (SERVER); while (1) { /*Wait for a datagram. */ size = sizeof (name); nbytes = recvfrom (sock, message, MAXMSG, 0, (struct sockaddr *) & name, &size); if (nbytes < 0) { perror ("recfrom (server)"); exit (EXIT_FAILURE); } /*Give a diagnostic message. */ fprintf (stderr, "Server: got message: %s\n", message); /*Bounce the message back to the sender. */ nbytes = sendto (sock, message, nbytes, 0, (struct sockaddr *) & name, size); if (nbytes < 0) { perror ("sendto (server)"); exit (EXIT_FAILURE); } }}
Previous:Datagram Socket Example, Up:Datagram Socket Operations [Contents][Index]
Here is the client program corresponding to the server above.
It sends a datagram to the server and then waits for a reply. Noticethat the socket for the client (as well as for the server) in thisexample has to be given a name. This is so that the server can directa message back to the client. Since the socket has no associatedconnection state, the only way the server can do this is byreferencing the name of the client.
#include <stdio.h>#include <errno.h>#include <unistd.h>#include <stdlib.h>#include <sys/socket.h>#include <sys/un.h>#define SERVER "/tmp/serversocket"#define CLIENT "/tmp/mysocket"#define MAXMSG 512#define MESSAGE "Yow!!! Are we having fun yet?!?"intmain (void){ extern int make_named_socket (const char *name); int sock; char message[MAXMSG]; struct sockaddr_un name; size_t size; int nbytes; /*Make the socket. */ sock = make_named_socket (CLIENT); /*Initialize the server socket address. */ name.sun_family = AF_LOCAL; strcpy (name.sun_path, SERVER); size = strlen (name.sun_path) + sizeof (name.sun_family); /*Send the datagram. */ nbytes = sendto (sock, MESSAGE, strlen (MESSAGE) + 1, 0, (struct sockaddr *) & name, size); if (nbytes < 0) { perror ("sendto (client)"); exit (EXIT_FAILURE); } /*Wait for a reply. */ nbytes = recvfrom (sock, message, MAXMSG, 0, NULL, 0); if (nbytes < 0) { perror ("recfrom (client)"); exit (EXIT_FAILURE); } /*Print a diagnostic message. */ fprintf (stderr, "Client: got message: %s\n", message); /*Clean up. */ remove (CLIENT); close (sock);}
Keep in mind that datagram socket communications are unreliable. Inthis example, the client program waits indefinitely if the messagenever reaches the server or if the server’s response never comesback. It’s up to the user running the program to kill and restartit if desired. A more automatic solution could be to useselect
(seeWaiting for Input or Output) to establish a timeout periodfor the reply, and in case of timeout either re-send the message orshut down the socket and exit.
Next:Socket Options, Previous:Datagram Socket Operations, Up:Sockets [Contents][Index]
inetd
Daemon ¶We’ve explained above how to write a server program that does its ownlistening. Such a server must already be running in order for anyoneto connect to it.
Another way to provide a service on an Internet port is to let the daemonprograminetd
do the listening.inetd
is a program thatruns all the time and waits (usingselect
) for messages on aspecified set of ports. When it receives a message, it accepts theconnection (if the socket style calls for connections) and then forks achild process to run the corresponding server program. You specify theports and their programs in the file/etc/inetd.conf.
Next:Configuringinetd
, Up:Theinetd
Daemon [Contents][Index]
inetd
Servers ¶Writing a server program to be run byinetd
is very simple. Each timesomeone requests a connection to the appropriate port, a new serverprocess starts. The connection already exists at this time; thesocket is available as the standard input descriptor and as thestandard output descriptor (descriptors 0 and 1) in the serverprocess. Thus the server program can begin reading and writing dataright away. Often the program needs only the ordinary I/O facilities;in fact, a general-purpose filter program that knows nothing aboutsockets can work as a byte stream server run byinetd
.
You can also useinetd
for servers that use connectionlesscommunication styles. For these servers,inetd
does not try to accepta connection since no connection is possible. It just starts theserver program, which can read the incoming datagram packet fromdescriptor 0. The server program can handle one request and thenexit, or you can choose to write it to keep reading more requestsuntil no more arrive, and then exit. You must specify which of thesetwo techniques the server uses when you configureinetd
.
Previous:inetd
Servers, Up:Theinetd
Daemon [Contents][Index]
inetd
¶The file/etc/inetd.conf tellsinetd
which ports to listen toand what server programs to run for them. Normally each entry in thefile is one line, but you can split it onto multiple lines providedall but the first line of the entry start with whitespace. Lines thatstart with ‘#’ are comments.
Here are two standard entries in/etc/inetd.conf:
ftpstreamtcpnowaitroot/libexec/ftpdftpdtalkdgramudpwaitroot/libexec/talkdtalkd
An entry has this format:
servicestyleprotocolwaitusernameprogramarguments
Theservice field says which service this program provides. Itshould be the name of a service defined in/etc/services.inetd
usesservice to decide which port to listen on forthis entry.
The fieldsstyle andprotocol specify the communicationstyle and the protocol to use for the listening socket. The styleshould be the name of a communication style, converted to lower caseand with ‘SOCK_’ deleted—for example, ‘stream’ or‘dgram’.protocol should be one of the protocols listed in/etc/protocols. The typical protocol names are ‘tcp’ forbyte stream connections and ‘udp’ for unreliable datagrams.
Thewait field should be either ‘wait’ or ‘nowait’.Use ‘wait’ ifstyle is a connectionless style and theserver, once started, handles multiple requests as they come in.Use ‘nowait’ ifinetd
should start a new process for each messageor request that comes in. Ifstyle uses connections, thenwaitmust be ‘nowait’.
user is the user name that the server should run as.inetd
runsas root, so it can set the user ID of its children arbitrarily. It’sbest to avoid using ‘root’ foruser if you can; but someservers, such as Telnet and FTP, read a username and passphrasethemselves. These servers need to be root initially so they can login as commanded by the data coming over the network.
program together witharguments specifies the command torun to start the server.program should be an absolute filename specifying the executable file to run.arguments consistsof any number of whitespace-separated words, which become thecommand-line arguments ofprogram. The first word inarguments is argument zero, which should by convention be theprogram name itself (sans directories).
If you edit/etc/inetd.conf, you can tellinetd
to reread thefile and obey its new contents by sending theinetd
process theSIGHUP
signal. You’ll have to useps
to determine theprocess ID of theinetd
process as it is not fixed.
Next:Networks Database, Previous:Theinetd
Daemon, Up:Sockets [Contents][Index]
This section describes how to read or set various options that modifythe behavior of sockets and their underlying communications protocols.
When you are manipulating a socket option, you must specify whichlevel the option pertains to. This describes whether the optionapplies to the socket interface, or to a lower-level communicationsprotocol interface.
Next:Socket-Level Options, Up:Socket Options [Contents][Index]
Here are the functions for examining and modifying socket options.They are declared insys/socket.h.
int
getsockopt(intsocket, intlevel, intoptname, void *optval, socklen_t *optlen-ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetsockopt
function gets information about the value ofoptionoptname at levellevel for socketsocket.
The option value is stored in the buffer thatoptval points to.Before the call, you should supply in*optlen-ptr
thesize of this buffer; on return, it contains the number of bytes ofinformation actually stored in the buffer.
Most options interpret theoptval buffer as a singleint
value.
The actual return value ofgetsockopt
is0
on successand-1
on failure. The followingerrno
error conditionsare defined:
EBADF
Thesocket argument is not a valid file descriptor.
ENOTSOCK
The descriptorsocket is not a socket.
ENOPROTOOPT
Theoptname doesn’t make sense for the givenlevel.
int
setsockopt(intsocket, intlevel, intoptname, const void *optval, socklen_toptlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is used to set the socket optionoptname at levellevel for socketsocket. The value of the option is passedin the bufferoptval of sizeoptlen.
Previous:Socket Option Functions, Up:Socket Options [Contents][Index]
int
SOL_SOCKET ¶Use this constant as thelevel argument togetsockopt
orsetsockopt
to manipulate the socket-level options described inthis section.
Here is a table of socket-level option names; all are defined in theheader filesys/socket.h.
SO_DEBUG
¶This option toggles recording of debugging information in the underlyingprotocol modules. The value has typeint
; a nonzero value means“yes”.
SO_REUSEADDR
¶This option controls whetherbind
(seeSetting the Address of a Socket)should permit reuse of local addresses for this socket. If you enablethis option, you can actually have two sockets with the same Internetport number; but the system won’t allow you to use the twoidentically-named sockets in a way that would confuse the Internet. Thereason for this option is that some higher-level Internet protocols,including FTP, require you to keep reusing the same port number.
The value has typeint
; a nonzero value means “yes”.
SO_KEEPALIVE
¶This option controls whether the underlying protocol shouldperiodically transmit messages on a connected socket. If the peerfails to respond to these messages, the connection is consideredbroken. The value has typeint
; a nonzero value means“yes”.
SO_DONTROUTE
¶This option controls whether outgoing messages bypass the normalmessage routing facilities. If set, messages are sent directly to thenetwork interface instead. The value has typeint
; a nonzerovalue means “yes”.
SO_LINGER
¶This option specifies what should happen when the socket of a typethat promises reliable delivery still has untransmitted messages whenit is closed; seeClosing a Socket. The value has typestruct linger
.
This structure type has the following members:
int l_onoff
This field is interpreted as a boolean. If nonzero,close
blocks until the data are transmitted or the timeout period has expired.
int l_linger
This specifies the timeout period, in seconds.
SO_BROADCAST
¶This option controls whether datagrams may be broadcast from the socket.The value has typeint
; a nonzero value means “yes”.
SO_OOBINLINE
¶If this option is set, out-of-band data received on the socket isplaced in the normal input queue. This permits it to be read usingread
orrecv
without specifying theMSG_OOB
flag. SeeOut-of-Band Data. The value has typeint
; anonzero value means “yes”.
SO_SNDBUF
¶This option gets or sets the size of the output buffer. The value is asize_t
, which is the size in bytes.
SO_RCVBUF
¶This option gets or sets the size of the input buffer. The value is asize_t
, which is the size in bytes.
SO_STYLE
¶SO_TYPE
¶This option can be used withgetsockopt
only. It is used toget the socket’s communication style.SO_TYPE
is thehistorical name, andSO_STYLE
is the preferred name in GNU.The value has typeint
and its value designates a communicationstyle; seeCommunication Styles.
SO_ERROR
¶This option can be used withgetsockopt
only. It is used to resetthe error status of the socket. The value is anint
, which representsthe previous error status.
Next:Other Socket APIs, Previous:Socket Options, Up:Sockets [Contents][Index]
Many systems come with a database that records a list of networks knownto the system developer. This is usually kept either in the file/etc/networks or in an equivalent from a name server. This database is useful for routing programs such asroute
, but it is notuseful for programs that simply communicate over the network. Weprovide functions to access this database, which are declared innetdb.h.
This data type is used to represent information about entries in thenetworks database. It has the following members:
char *n_name
This is the “official” name of the network.
char **n_aliases
These are alternative names for the network, represented as a vectorof strings. A null pointer terminates the array.
int n_addrtype
This is the type of the network number; this is always equal toAF_INET
for Internet networks.
unsigned long int n_net
This is the network number. Network numbers are returned in hostbyte order; seeByte Order Conversion.
Use thegetnetbyname
orgetnetbyaddr
functions to searchthe networks database for information about a specific network. Theinformation is returned in a statically-allocated structure; you mustcopy the information if you need to save it.
struct netent *
getnetbyname(const char *name)
¶Preliminary:| MT-Unsafe race:netbyname env locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegetnetbyname
function returns information about the networknamedname. It returns a null pointer if there is no suchnetwork.
struct netent *
getnetbyaddr(uint32_tnet, inttype)
¶Preliminary:| MT-Unsafe race:netbyaddr locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegetnetbyaddr
function returns information about the networkof typetype with numbernet. You should specify a value ofAF_INET
for thetype argument for Internet networks.
getnetbyaddr
returns a null pointer if there is no suchnetwork.
You can also scan the networks database usingsetnetent
,getnetent
andendnetent
. Be careful when using thesefunctions because they are not reentrant.
void
setnetent(intstayopen)
¶Preliminary:| MT-Unsafe race:netent env locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function opens and rewinds the networks database.
If thestayopen argument is nonzero, this sets a flag so thatsubsequent calls togetnetbyname
orgetnetbyaddr
willnot close the database (as they usually would). This makes for moreefficiency if you call those functions several times, by avoidingreopening the database for each call.
struct netent *
getnetent(void)
¶Preliminary:| MT-Unsafe race:netent race:netentbuf env locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function returns the next entry in the networks database. Itreturns a null pointer if there are no more entries.
void
endnetent(void)
¶Preliminary:| MT-Unsafe race:netent env locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function closes the networks database.
Previous:Networks Database, Up:Sockets [Contents][Index]
ssize_t
sendmsg(intsocket, const struct msghdr *message, intflags)
¶This documentation is a stub. For additional information on thisfunction, consult the manual pagesendmsg(2)SeeLinux (The Linux Kernel).
ssize_t
recvmsg(intsocket, struct msghdr *message, intflags)
¶This documentation is a stub. For additional information on thisfunction, consult the manual pagerecvmsg(2)SeeLinux (The Linux Kernel).
This chapter describes functions that are specific to terminal devices.You can use these functions to do things like turn off input echoing;set serial line characteristics such as line speed and flow control; andchange which characters are used for end-of-file, command-line editing,sending signals, and similar control functions.
Most of the functions in this chapter operate on file descriptors.SeeLow-Level Input/Output, for more information about what a filedescriptor is and how to open a file descriptor for a terminal device.
Aterminal device, abbreviatedtty
(forteletype), isa character device which implements a set of functionality appropriatefor communications devices, and which can host an interactive loginsession. Conceptually, a terminal device implements an RS232asynchronous serial interface, but the actual hardware implementationmay be entirely different, or it may be entirely virtual, notablyseePseudo-Terminals.
For a true conventional asynchronous serial port, such as RS232/V.24,RS422/V.11, RS423, or RS485, the functionality is generally asdescribed, whereas for other devices, the meaning of serial portspecific functionality such as modem control signals, BREAK, and linespeed is device specific.
The rest of this section is described in terms of a physical RS232interface.
The RS232 specification assumes the host (Data Terminal Equipment, DTE)connects to a modem (Data Communications Equipment, DCE), regardless ofif a physical modem is present or not.
In addition to the serial data, the DTE provides a set of controlsignals to the DCE, and the DCE a set of status signals to the DTE. Thefull RS232 and V.24 specifications provide a large number of signals,but the ones that are typically implemented in contemporary hardware andare relevant to the terminal device interface are:
If asserted (true), the DTE is ready to accept/continue an incomingcommunications session. If deasserted (false), this is amodem disconnect request to the DCE. The DCE may, but is notrequired to, trigger a modem disconnect in response.
This signal is also referred to as Ready To Receive (RTR).
If asserted, the DTE is ready to accept data. If deasserted, the DCE isrequested to hold data temporarily without disconnecting. This is knownas hardware or RTS/CTSflow control and can be handledautomatically if the appropriate terminal mode flags are set.
If asserted, the DCE is ready to communicate, but may or may not have aconnection to a remote peer.
If asserted, the DCE has a connection to the remote peer. Ifdeasserted, this is amodem disconnect signal to the DTE. A modemdisconnect may be triggered in response to the DTR control signal beingdeasserted, or it may be caused by an external event.
If asserted, the DCE is ready to accept data. If deasserted, the DTE isrequested to hold data temporarily but should not interpret it as adisconnect. This is the DCE to DTE part of RTS/CTS flowcontrol.
If asserted, this indicates that a remote peer is requesting to connect(“the phone is ringing”). Depending on how the DCE is configured, theDTE may need to assert the DTR control signal before the DCE will acceptthe incoming connection.
Next:I/O Queues, Previous:Terminal Device Model, Up:Low-Level Terminal Interface [Contents][Index]
The functions described in this chapter only work on files thatcorrespond to terminal devices. You can find out whether a filedescriptor is associated with a terminal by using theisatty
function.
Prototypes for the functions in this section are declared in the headerfileunistd.h.
int
isatty(intfiledes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns1
iffiledes is a file descriptorassociated with an open terminal device, and0 otherwise.
If a file descriptor is associated with a terminal, you can get itsassociated file name using thettyname
function. See also thectermid
function, described inIdentifying the Controlling Terminal.
char *
ttyname(intfiledes)
¶Preliminary:| MT-Unsafe race:ttyname| AS-Unsafe heap lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
If the file descriptorfiledes is associated with a terminaldevice, thettyname
function returns a pointer to astatically-allocated, null-terminated string containing the file name ofthe terminal file. The value is a null pointer if the file descriptorisn’t associated with a terminal, or the file name cannot be determined.
int
ttyname_r(intfiledes, char *buf, size_tlen)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Thettyname_r
function is similar to thettyname
functionexcept that it places its result into the user-specified buffer startingatbuf with lengthlen.
The normal return value fromttyname_r
is0. Otherwise anerror number is returned to indicate the error. The followingerrno
error conditions are defined for this function:
EBADF
Thefiledes argument is not a valid file descriptor.
ENOTTY
Thefiledes is not associated with a terminal.
ERANGE
The buffer lengthlen is too small to store the string to bereturned.
ENODEV
Thefiledes is associated with a terminal device that is a slavepseudo-terminal, but the file name associated with that device couldnot be determined. This is a GNU extension.
Next:Two Styles of Input: Canonical or Not, Previous:Identifying Terminals, Up:Low-Level Terminal Interface [Contents][Index]
Many of the remaining functions in this section refer to the input andoutput queues of a terminal device. These queues implement a form ofbufferingwithin the kernel independent of the bufferingimplemented by I/O streams (seeInput/Output on Streams).
Theterminal input queue is also sometimes referred to as itstypeahead buffer. It holds the characters that have been receivedfrom the terminal but not yet read by any process.
The size of the input queue is described by theMAX_INPUT
and_POSIX_MAX_INPUT
parameters; seeLimits on File System Capacity. Youare guaranteed a queue size of at leastMAX_INPUT
, but the queuemight be larger, and might even dynamically change size. If input flowcontrol is enabled by setting theIXOFF
input mode bit(seeInput Modes), the terminal driver transmits STOP and STARTcharacters to the terminal when necessary to prevent the queue fromoverflowing. Otherwise, input may be lost if it comes in too fast fromthe terminal. In canonical mode, all input stays in the queue until anewline character is received, so the terminal input queue can fill upwhen you type a very long line. SeeTwo Styles of Input: Canonical or Not.
Theterminal output queue is like the input queue, but for output;it contains characters that have been written by processes, but not yettransmitted to the terminal. If output flow control is enabled bysetting theIXON
input mode bit (seeInput Modes), theterminal driver obeys START and STOP characters sent by the terminal tostop and restart transmission of output.
Clearing the terminal input queue means discarding any charactersthat have been received but not yet read. Similarly, clearing theterminal output queue means discarding any characters that have beenwritten but not yet transmitted.
Next:Terminal Modes, Previous:I/O Queues, Up:Low-Level Terminal Interface [Contents][Index]
POSIX systems support two basic modes of input: canonical andnoncanonical.
Incanonical input processing mode, terminal input is processed inlines terminated by newline ('\n'
), EOF, or EOL characters. Noinput can be read until an entire line has been typed by the user, andtheread
function (seeInput and Output Primitives) returns at most asingle line of input, no matter how many bytes are requested.
In canonical input mode, the operating system provides input editingfacilities: some characters are interpreted specially to perform editingoperations within the current line of text, such as ERASE and KILL.SeeCharacters for Input Editing.
The constants_POSIX_MAX_CANON
andMAX_CANON
parameterizethe maximum number of bytes which may appear in a single line ofcanonical input. SeeLimits on File System Capacity. You are guaranteed a maximumline length of at leastMAX_CANON
bytes, but the maximum might belarger, and might even dynamically change size.
Innoncanonical input processing mode, characters are not groupedinto lines, and ERASE and KILL processing is not performed. Thegranularity with which bytes are read in noncanonical input mode iscontrolled by the MIN and TIME settings. SeeNoncanonical Input.
Most programs use canonical input mode, because this gives the user away to edit input line by line. The usual reason to use noncanonicalmode is when the program accepts single-character commands or providesits own editing facilities.
The choice of canonical or noncanonical input is controlled by theICANON
flag in thec_lflag
member ofstruct termios
.SeeLocal Modes.
Next:BSD Terminal Modes, Previous:Two Styles of Input: Canonical or Not, Up:Low-Level Terminal Interface [Contents][Index]
This section describes the various terminal attributes that control howinput and output are done. The functions, data structures, and symbolicconstants are all declared in the header filetermios.h.
Don’t confuse terminal attributes with file attributes. A device specialfile which is associated with a terminal has file attributes as describedinFile Attributes. These are unrelated to the attributes of theterminal device itself, which are discussed in this section.
Next:Terminal Mode Functions, Up:Terminal Modes [Contents][Index]
The entire collection of attributes of a terminal is stored in astructure of typestruct termios
. This structure is usedwith the functionstcgetattr
andtcsetattr
to readand set the attributes.
Astruct termios
records all the I/O attributes of a terminal. Thestructure includes at least the following members:
tcflag_t c_iflag
A bit mask specifying flags for input modes; seeInput Modes.
tcflag_t c_oflag
A bit mask specifying flags for output modes; seeOutput Modes.
tcflag_t c_cflag
A bit mask specifying flags for control modes; seeControl Modes.
tcflag_t c_lflag
A bit mask specifying flags for local modes; seeLocal Modes.
cc_t c_cc[NCCS]
An array specifying which characters are associated with variouscontrol functions; seeSpecial Characters.
Thestruct termios
structure also contains members whichencode input and output transmission speeds, but the representation isnot specified. SeeLine Speed, for how to examine and store thespeed values.
The following sections describe the details of the members of thestruct termios
structure.
This is an unsigned integer type used to represent the variousbit masks for terminal flags.
This is an unsigned integer type used to represent characters associatedwith various terminal control functions.
int
NCCS ¶The value of this macro is the number of elements in thec_cc
array.
Next:Setting Terminal Modes Properly, Previous:Terminal Mode Data Types, Up:Terminal Modes [Contents][Index]
int
tcgetattr(intfiledes, struct termios *termios-p)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is used to examine the attributes of the terminaldevice with file descriptorfiledes. The attributes are returnedin the structure thattermios-p points to.
If successful,tcgetattr
returns0. A return value of-1indicates an error. The followingerrno
error conditions aredefined for this function:
EBADF
Thefiledes argument is not a valid file descriptor.
ENOTTY
Thefiledes is not associated with a terminal.
int
tcsetattr(intfiledes, intwhen, const struct termios *termios-p)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function sets the attributes of the terminal device with filedescriptorfiledes. The new attributes are taken from thestructure thattermios-p points to.
Thewhen argument specifies how to deal with input and outputalready queued. It can be one of the following values:
TCSANOW
¶Make the change immediately.
TCSADRAIN
¶Make the change after waiting until all queued output has been written.You should usually use this option when changing parameters that affectoutput.
TCSAFLUSH
¶This is likeTCSADRAIN
, but also discards any queued input.
TCSASOFT
¶This is a flag bit that you can add to any of the above alternatives.Its meaning is to inhibit alteration of the state of the terminalhardware. It is a BSD extension; it is only supported on BSD systemsand GNU/Hurd systems.
UsingTCSASOFT
is exactly the same as setting theCIGNORE
bit in thec_cflag
member of the structuretermios-p pointsto. SeeControl Modes, for a description ofCIGNORE
.
If this function is called from a background process on its controllingterminal, normally all processes in the process group are sent aSIGTTOU
signal, in the same way as if the process were trying towrite to the terminal. The exception is if the calling process itselfis ignoring or blockingSIGTTOU
signals, in which case theoperation is performed and no signal is sent. SeeJob Control.
If successful,tcsetattr
returns0. A return value of-1 indicates an error. The followingerrno
errorconditions are defined for this function:
EBADF
Thefiledes argument is not a valid file descriptor.
ENOTTY
Thefiledes is not associated with a terminal.
EINVAL
Either the value of thewhen
argument is not valid, or there issomething wrong with the data in thetermios-p argument.
Althoughtcgetattr
andtcsetattr
specify the terminaldevice with a file descriptor, the attributes are those of the terminaldevice itself and not of the file descriptor. This means that theeffects of changing terminal attributes are persistent; if anotherprocess opens the terminal file later on, it will see the changedattributes even though it doesn’t have anything to do with the open filedescriptor you originally specified in changing the attributes.
Similarly, if a single process has multiple or duplicated filedescriptors for the same terminal device, changing the terminalattributes affects input and output to all of these filedescriptors. This means, for example, that you can’t open one filedescriptor or stream to read from a terminal in the normalline-buffered, echoed mode; and simultaneously have another filedescriptor for the same terminal that you use to read from it insingle-character, non-echoed mode. Instead, you have to explicitlyswitch the terminal back and forth between the two modes.
Next:Input Modes, Previous:Terminal Mode Functions, Up:Terminal Modes [Contents][Index]
When you set terminal modes, you should calltcgetattr
first toget the current modes of the particular terminal device, modify onlythose modes that you are really interested in, and store the result withtcsetattr
.
It’s a bad idea to simply initialize astruct termios
structureto a chosen set of attributes and pass it directly totcsetattr
.Your program may be run years from now, on systems that support membersnot documented in this manual. The way to avoid setting these membersto unreasonable values is to avoid changing them.
What’s more, different terminal devices may require different modesettings in order to function properly. So you should avoid blindlycopying attributes from one terminal device to another.
When a member contains a collection of independent flags, as thec_iflag
,c_oflag
andc_cflag
members do, evensetting the entire member is a bad idea, because particular operatingsystems have their own flags. Instead, you should start with thecurrent value of the member and alter only the flags whose values matterin your program, leaving any other flags unchanged.
Here is an example of how to set one flag (ISTRIP
) in thestruct termios
structure while properly preserving all the otherdata in the structure:
intset_istrip (int desc, int value){ struct termios settings; int result;
result = tcgetattr (desc, &settings); if (result < 0) { perror ("error in tcgetattr"); return 0; }
settings.c_iflag &= ~ISTRIP; if (value) settings.c_iflag |= ISTRIP;
result = tcsetattr (desc, TCSANOW, &settings); if (result < 0) { perror ("error in tcsetattr"); return 0; } return 1;}
Next:Output Modes, Previous:Setting Terminal Modes Properly, Up:Terminal Modes [Contents][Index]
This section describes the terminal attribute flags that controlfairly low-level aspects of input processing: handling of parity errors,break signals, flow control, andRET andLFD characters.
All of these flags are bits in thec_iflag
member of thestruct termios
structure. The member is an integer, and youchange flags using the operators&
,|
and^
. Don’ttry to specify the entire value forc_iflag
—instead, changeonly specific flags and leave the rest untouched (seeSetting Terminal Modes Properly).
tcflag_t
INPCK ¶If this bit is set, input parity checking is enabled. If it is not set,no checking at all is done for parity errors on input; thecharacters are simply passed through to the application.
Parity checking on input processing is independent of whether paritydetection and generation on the underlying terminal hardware is enabled;seeControl Modes. For example, you could clear theINPCK
input mode flag and set thePARENB
control mode flag to ignoreparity errors on input, but still generate parity on output.
If this bit is set, what happens when a parity error is detected dependson whether theIGNPAR
orPARMRK
bits are set. If neitherof these bits are set, a byte with a parity error is passed to theapplication as a'\0'
character.
tcflag_t
IGNPAR ¶If this bit is set, any byte with a framing or parity error is ignored.This is only useful ifINPCK
is also set.
tcflag_t
PARMRK ¶If this bit is set, input bytes with parity or framing errors are markedwhen passed to the program. This bit is meaningful only whenINPCK
is set andIGNPAR
is not set.
The way erroneous bytes are marked is with two preceding bytes,377
and0
. Thus, the program actually reads three bytesfor one erroneous byte received from the terminal.
If a valid byte has the value0377
, andISTRIP
(see below)is not set, the program might confuse it with the prefix that marks aparity error. So a valid byte0377
is passed to the program astwo bytes,0377
0377
, in this case.
tcflag_t
ISTRIP ¶If this bit is set, valid input bytes are stripped to seven bits;otherwise, all eight bits are available for programs to read.
tcflag_t
IGNBRK ¶If this bit is set, break conditions are ignored.
Abreak condition is defined in the context of asynchronousserial data transmission as a series of zero-value bits longer than asingle byte.
tcflag_t
BRKINT ¶If this bit is set andIGNBRK
is not set, a break conditionclears the terminal input and output queues and raises aSIGINT
signal for the foreground process group associated with the terminal.
If neitherBRKINT
norIGNBRK
are set, a break condition ispassed to the application as a single'\0'
character ifPARMRK
is not set, or otherwise as a three-character sequence'\377'
,'\0'
,'\0'
.
tcflag_t
IGNCR ¶If this bit is set, carriage return characters ('\r'
) arediscarded on input. Discarding carriage return may be useful onterminals that send both carriage return and linefeed when you type theRET key.
tcflag_t
ICRNL ¶If this bit is set andIGNCR
is not set, carriage return characters('\r'
) received as input are passed to the application as newlinecharacters ('\n'
).
tcflag_t
INLCR ¶If this bit is set, newline characters ('\n'
) received as inputare passed to the application as carriage return characters ('\r'
).
tcflag_t
IXOFF ¶If this bit is set, start/stop control on input is enabled. In otherwords, the computer sends STOP and START characters as necessary toprevent input from coming in faster than programs are reading it. Theidea is that the actual terminal hardware that is generating the inputdata responds to a STOP character by suspending transmission, and to aSTART character by resuming transmission. SeeSpecial Characters for Flow Control.
tcflag_t
IXON ¶If this bit is set, start/stop control on output is enabled. In otherwords, if the computer receives a STOP character, it suspends outputuntil a START character is received. In this case, the STOP and STARTcharacters are never passed to the application program. If this bit isnot set, then START and STOP can be read as ordinary characters.SeeSpecial Characters for Flow Control.
tcflag_t
IXANY ¶If this bit is set, any input character restarts output when output hasbeen suspended with the STOP character. Otherwise, only the STARTcharacter restarts output.
This is a BSD extension; it exists only on BSD systems andGNU/Linux and GNU/Hurd systems.
tcflag_t
IMAXBEL ¶If this bit is set, then filling up the terminal input buffer sends aBEL character (code007
) to the terminal to ring the bell.
This is a BSD extension.
Next:Control Modes, Previous:Input Modes, Up:Terminal Modes [Contents][Index]
This section describes the terminal flags and fields that control howoutput characters are translated and padded for display. All of theseare contained in thec_oflag
member of thestruct termios
structure.
Thec_oflag
member itself is an integer, and you change the flagsand fields using the operators&
,|
, and^
. Don’ttry to specify the entire value forc_oflag
—instead, changeonly specific flags and leave the rest untouched (seeSetting Terminal Modes Properly).
tcflag_t
OPOST ¶If this bit is set, output data is processed in some unspecified way sothat it is displayed appropriately on the terminal device. Thistypically includes mapping newline characters ('\n'
) ontocarriage return and linefeed pairs.
If this bit isn’t set, the characters are transmitted as-is.
The following three bits are effective only ifOPOST
is set.
tcflag_t
ONLCR ¶If this bit is set, convert the newline character on output into a pairof characters, carriage return followed by linefeed.
tcflag_t
OXTABS ¶If this bit is set, convert tab characters on output into the appropriatenumber of spaces to emulate a tab stop every eight columns. This bitexists only on BSD systems and GNU/Hurd systems; onGNU/Linux systems it is available asXTABS
.
tcflag_t
ONOEOT ¶If this bit is set, discardC-d characters (code004
) onoutput. These characters cause many dial-up terminals to disconnect.This bit exists only on BSD systems and GNU/Hurd systems.
Next:Local Modes, Previous:Output Modes, Up:Terminal Modes [Contents][Index]
This section describes the terminal flags and fields that controlparameters usually associated with asynchronous serial datatransmission. These flags may not make sense for other kinds ofterminal ports (such as a network connection pseudo-terminal). All ofthese are contained in thec_cflag
member of thestructtermios
structure.
Thec_cflag
member itself is an integer, and you change the flagsand fields using the operators&
,|
, and^
. Don’ttry to specify the entire value forc_cflag
—instead, changeonly specific flags and leave the rest untouched (seeSetting Terminal Modes Properly).
tcflag_t
CLOCAL ¶If this bit is set, it indicates that the terminal is connected“locally” and that the modem status lines (such as carrier detect)should be ignored.
On many systems if this bit is not set and you callopen
withouttheO_NONBLOCK
flag set,open
blocks until a modemconnection is established.
If this bit is not set and a modem disconnect is detected, aSIGHUP
signal is sent to the controlling process group for theterminal (if it has one). Normally, this causes the process to exit;seeSignal Handling. Reading from the terminal after a disconnectcauses an end-of-file condition, and writing causes anEIO
errorto be returned. The terminal device must be closed and reopened toclear the condition.
tcflag_t
HUPCL ¶If this bit is set, a modem disconnect request is generated when allprocesses that have the terminal device open have either closed the fileor exited.
tcflag_t
CREAD ¶If this bit is set, input can be read from the terminal. Otherwise,input is discarded when it arrives.
tcflag_t
CSTOPB ¶If this bit is set, two stop bits are used. Otherwise, only one stop bitis used.
tcflag_t
PARENB ¶If this bit is set, generation and detection of a parity bit are enabled.SeeInput Modes, for information on how input parity errors are handled.
If this bit is not set, no parity bit is added to output characters, andinput characters are not checked for correct parity.
tcflag_t
PARODD ¶This bit is only useful ifPARENB
is set. IfPARODD
is set,odd parity is used, otherwise even parity is used.
The control mode flags also includes a field for the number of bits percharacter. You can use theCSIZE
macro as a mask to extract thevalue, like this:settings.c_cflag & CSIZE
.
tcflag_t
CSIZE ¶This is a mask for the number of bits per character.
tcflag_t
CS5 ¶This specifies five bits per byte.
tcflag_t
CS6 ¶This specifies six bits per byte.
tcflag_t
CS7 ¶This specifies seven bits per byte.
tcflag_t
CS8 ¶This specifies eight bits per byte.
The following four bits are BSD extensions; these exist only on BSDsystems and GNU/Hurd systems.
tcflag_t
CCTS_OFLOW ¶If this bit is set, enable flow control of output based on the CTS wire(RS232 protocol).
tcflag_t
CRTS_IFLOW ¶If this bit is set, enable flow control of input based on the RTS wire(RS232 protocol).
tcflag_t
MDMBUF ¶If this bit is set, enable carrier-based flow control of output.
tcflag_t
CIGNORE ¶If this bit is set, it says to ignore the control modes and line speedvalues entirely. This is only meaningful in a call totcsetattr
.
Thec_cflag
member and the line speed values returned bycfgetispeed
,cfgetospeed
,cfgetibaud
andcfsetibaud
will be unaffected by the call.CIGNORE
isuseful if you want to set all the software modes in the other members,but leave the hardware details inc_cflag
unchanged. (This ishow theTCSASOFT
flag totcsetattr
works.)
This bit is never set in the structure filled in bytcgetattr
.
Next:Line Speed, Previous:Control Modes, Up:Terminal Modes [Contents][Index]
This section describes the flags for thec_lflag
member of thestruct termios
structure. These flags generally controlhigher-level aspects of input processing than the input modes flagsdescribed inInput Modes, such as echoing, signals, and the choiceof canonical or noncanonical input.
Thec_lflag
member itself is an integer, and you change the flagsand fields using the operators&
,|
, and^
. Don’ttry to specify the entire value forc_lflag
—instead, changeonly specific flags and leave the rest untouched (seeSetting Terminal Modes Properly).
tcflag_t
ICANON ¶This bit, if set, enables canonical input processing mode. Otherwise,input is processed in noncanonical mode. SeeTwo Styles of Input: Canonical or Not.
tcflag_t
ECHO ¶If this bit is set, echoing of input characters back to the terminalis enabled.
tcflag_t
ECHOE ¶If this bit is set, echoing indicates erasure of input with the ERASEcharacter by erasing the last character in the current line from thescreen. Otherwise, the character erased is re-echoed to show what hashappened (suitable for a printing terminal).
This bit only controls the display behavior; theICANON
bit byitself controls actual recognition of the ERASE character and erasure ofinput, without whichECHOE
is simply irrelevant.
tcflag_t
ECHOPRT ¶This bit, likeECHOE
, enables display of the ERASE character ina way that is geared to a hardcopy terminal. When you type the ERASEcharacter, a ‘\’ character is printed followed by the firstcharacter erased. Typing the ERASE character again just prints the nextcharacter erased. Then, the next time you type a normal character, a‘/’ character is printed before the character echoes.
This is a BSD extension, and exists only in BSD systems andGNU/Linux and GNU/Hurd systems.
tcflag_t
ECHOK ¶This bit enables special display of the KILL character by moving to anew line after echoing the KILL character normally. The behavior ofECHOKE
(below) is nicer to look at.
If this bit is not set, the KILL character echoes just as it would if itwere not the KILL character. Then it is up to the user to remember thatthe KILL character has erased the preceding input; there is noindication of this on the screen.
This bit only controls the display behavior; theICANON
bit byitself controls actual recognition of the KILL character and erasure ofinput, without whichECHOK
is simply irrelevant.
tcflag_t
ECHOKE ¶This bit is similar toECHOK
. It enables special display of theKILL character by erasing on the screen the entire line that has beenkilled. This is a BSD extension, and exists only in BSD systems andGNU/Linux and GNU/Hurd systems.
tcflag_t
ECHONL ¶If this bit is set and theICANON
bit is also set, then thenewline ('\n'
) character is echoed even if theECHO
bitis not set.
tcflag_t
ECHOCTL ¶If this bit is set and theECHO
bit is also set, echo controlcharacters with ‘^’ followed by the corresponding text character.Thus, control-A echoes as ‘^A’. This is usually the preferred modefor interactive input, because echoing a control character back to theterminal could have some undesired effect on the terminal.
This is a BSD extension, and exists only in BSD systems andGNU/Linux and GNU/Hurd systems.
tcflag_t
ISIG ¶This bit controls whether the INTR, QUIT, and SUSP characters arerecognized. The functions associated with these characters are performedif and only if this bit is set. Being in canonical or noncanonicalinput mode has no effect on the interpretation of these characters.
You should use caution when disabling recognition of these characters.Programs that cannot be interrupted interactively are veryuser-unfriendly. If you clear this bit, your program should providesome alternate interface that allows the user to interactively send thesignals associated with these characters, or to escape from the program.
tcflag_t
IEXTEN ¶POSIX.1 givesIEXTEN
implementation-defined meaning,so you cannot rely on this interpretation on all systems.
On BSD systems and GNU/Linux and GNU/Hurd systems, it enables the LNEXT andDISCARD characters.SeeOther Special Characters.
tcflag_t
NOFLSH ¶Normally, the INTR, QUIT, and SUSP characters cause input and outputqueues for the terminal to be cleared. If this bit is set, the queuesare not cleared.
tcflag_t
TOSTOP ¶If this bit is set and the system supports job control, thenSIGTTOU
signals are generated by background processes thatattempt to write to the terminal. SeeAccess to the Controlling Terminal.
The following bits are BSD extensions; they exist only on BSD systemsand GNU/Hurd systems.
tcflag_t
ALTWERASE ¶This bit determines how far the WERASE character should erase. TheWERASE character erases back to the beginning of a word; the questionis, where do words begin?
If this bit is clear, then the beginning of a word is a nonwhitespacecharacter following a whitespace character. If the bit is set, then thebeginning of a word is an alphanumeric character or underscore followinga character which is none of those.
SeeCharacters for Input Editing, for more information about the WERASE character.
tcflag_t
FLUSHO ¶This is the bit that toggles when the user types the DISCARD character.While this bit is set, all output is discarded. SeeOther Special Characters.
tcflag_t
NOKERNINFO ¶Setting this bit disables handling of the STATUS character.SeeOther Special Characters.
tcflag_t
PENDIN ¶If this bit is set, it indicates that there is a line of input thatneeds to be reprinted. Typing the REPRINT character sets this bit; thebit remains set until reprinting is finished. SeeCharacters for Input Editing.
Next:Special Characters, Previous:Local Modes, Up:Terminal Modes [Contents][Index]
The terminal line speed tells the computer how fast to read and writedata on the terminal.
For standard asynchronous serial lines employing binary NRZ encodingsuch as RS232, RS422, RS423, or RS485, the terminal speed will equal thephysical layer baud rate including asynchronous framing and parity bits.This needs to match the communication speed expected by the peer device,or communication will not work. Which particular speeds are supportedby any particular interface is hardware specific.
For other types of devices the meaning of the line speed isdevice-specific and may not even affect the actual data transmissionspeed at all (for example, if it is a pseudo-terminal or networkconnection), but some programs will use it to determine the amount ofpadding needed. It’s best to specify a line speed value that matchesthe actual speed of the actual terminal, but you can safely experimentwith different values to vary the amount of padding.
As the terminal interface models an RS232 serial interface(seeTerminal Device Model), the term “baud rate” is frequentlyused as a direct alias for “line speed”; this convention is followedin the following descriptions.
There are actually two line speeds for each terminal, one for input andone for output. You can set them independently, but most oftenterminals use the same speed for both directions. If the hardware doesnot support different speeds for each direction, the output speed willbe used for both input and output.
Specifying an output speed of zero generates a modem disconnect request.For thespeed_t
interface, this is the constantB0
whichmay or may not have the numeric value0.
Specifying an input speed value of zero sets the input speed to equalthe output speed. This is the numeric constant0 (notnecessarily the same asB0
) for both thespeed_t
andbaud_t
interfaces. This use is deprecated.
The line speed values are stored in thestruct termios
structure, butdon’t try to access them in thestruct termios
structuredirectly. Instead, you should use the functions defined by theinterfaces below to access them.
The line speed setting functions report errors only when attempting toset line rate values that the system simply cannot handle. If youspecify a line speed value that is plausible for the system, then thefunctions will succeed. However, they do not check that a particularhardware device can actually support the specified value—in fact, theydon’t know which device you plan to set the line speed for untiltcsetattr
is called. If you usetcsetattr
to set thespeed of a particular device to a value that it cannot handle, eithertcsetattr
returns-1 and setserrno
toEINVAL
, or the value is adjusted to the closest supported value,depending on the policy of the kernel driver. In the latter case, asubsequent call totcgetattr
may or may not reflect thisadjustment.
The GNU C Library supports two interoperable interfaces for setting the linespeed: the POSIX.1speed_t
interface, which requires the use of aset of enumerated constants, and thebaud_t
interface, a GNUextension, which is guaranteed to use plain numeric values.
speed_t
interface ¶Thespeed_t
type is an unsigned integer data type used torepresent line speeds.
Portability note: In the current version of the GNU C Library, thespeed_t
type is numerically indentical to the line speed rate.Other libraries and older versions of the GNU C Library may require speeds tobe indicated by enumerated constants, which may not be numericallyidentical to the requested line speed. For portability, you must useone of the following symbols to represent the speed; their precisenumeric values are system-dependent, but each name has a fixed meaning:B110
stands for 110 bps,B300
for 300 bps, and so on.There is no portable way to represent any speed but these.
B0 B50 B75 B110 B134 B150 B200 B300 B600 B1200B1800 B2400 B4800 B9600 B19200 B38400
The GNU C Library defines these additional constants:
B7200 B14400 B28800 B33600 B57600 B76800 B115200 B153600 B230400 B307200B460800 B500000 B576000 B614400 B921600 B1000000 B1152000 B1500000B2000000 B2500000 B3000000 B3500000 B4000000 B5000000 B10000000
BSD defines two additional speed symbols as aliases:EXTA
is analias forB19200
andEXTB
is an alias forB38400
.These aliases are obsolete.
speed_t
SPEED_MAX ¶The GNU C Library defines the constantSPEED_MAX
for the largest validvalue of typespeed_t
. This value may be smaller than theunderlying C type can store.
For compatiblity with some other platforms the alias__MAX_BAUD
is defined for this constant.
speed_t
cfgetospeed(const struct termios *termios-p)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the output line speed stored in the structure*termios-p
.
speed_t
cfgetispeed(const struct termios *termios-p)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the input line speed stored in the structure*termios-p
.
int
cfsetospeed(struct termios *termios-p, speed_tspeed)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function storesspeed in*termios-p
as theoutput line speed. Ifspeed isB0
, generates a modemdisconnect request.
Ifspeed is neither a plausible line speed norB0
,cfsetospeed
returns-1 and setserrno
toEINVAL
.
int
cfsetispeed(struct termios *termios-p, speed_tspeed)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function storesspeed in*termios-p
as the inputspeed. Ifspeed is0, the input speed is set to equal theoutput speed; note that POSIX.1 specifies this as the numeric value0 which is not required to equal the constantB0
.
Ifspeed is not a plausible line speed or0,cfsetispeed
returns-1 and setserrno
toEINVAL
.
Portability note: POSIX.1-2024 has deprecated setting of theinput speed to0 to set the input line speed to equal the outputline speed. After callingtcsetattr
followed bytcgetattr
,cfgetispeed
may report the input line speedeither as0 or the same ascfgetospeed
.
int
cfsetspeed(struct termios *termios-p, speed_tspeed)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function storesspeed in*termios-p
as both theinput and output speeds.
Ifbaud is not a plausible line speed,cfsetbaud
returns-1 and setserrno
toEINVAL
.
This function is an extension which originated in 4.4 BSD.
baud_t
interface ¶Thebaud_t
type is a numeric data type used to represent linebaud rates. It will always represent the actual numeric valuecorresponding to the line speed, unlikespeed_t
. In the currentversion of the GNU C Library this is the same type asspeed_t
, but thismay not be the case in future versions or on other implementations; itis specifically not guaranteed to be an integer type.
baud_t
BAUD_MAX ¶The constantBAUD_MAX
is defined to the maximum valid value oftypebaud_t
. This value may be smaller than the underlying Ctype can store.
baud_t
cfgetobaud(const struct termios *termios-p)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the output line speed stored in the structure*termios-p
as a numeric value.
baud_t
cfgetibaud(const struct termios *termios-p)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the input line speed stored in the structure*termios-p
as a numeric value.
int
cfsetobaud(struct termios *termios-p, baud_tbaud)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function storesbaud in*termios-p
as the outputline speed. Ifbaud is0, generates a modem disconnect.
Ifspeed is not a plausible line speed,cfsetspeed
returns-1 and setserrno
toEINVAL
.
int
cfsetibaud(struct termios *termios-p, baud_tbaud)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function storesbaud in*termios-p
as the inputline speed.
To simplify conversions from thespeed_t
interface, setting theinput line speed to0 is interpreted as setting the input linespeed equal to the output line speed. The caveats described undercfsetispeed
apply equally tocfsetibaud
. As forcfsetispeed
, this usage is deprecated.
Ifbaud is not a plausible line speed or0,cfsetibaud
returns-1 and setserrno
toEINVAL
.
int
cfsetbaud(struct termios *termios-p, baud_tbaud)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function storesbaud in*termios-p
as both theinput and output line speeds.
Ifbaud is not a plausible line speed,cfsetbaud
returns-1 and setserrno
toEINVAL
.
Next:Noncanonical Input, Previous:Line Speed, Up:Terminal Modes [Contents][Index]
In canonical input, the terminal driver recognizes a number of specialcharacters which perform various control functions. These include theERASE character (usuallyDEL) for editing input, and other editingcharacters. The INTR character (normallyC-c) for sending aSIGINT
signal, and other signal-raising characters, may beavailable in either canonical or noncanonical input mode. All thesecharacters are described in this section.
The particular characters used are specified in thec_cc
memberof thestruct termios
structure. This member is an array; eachelement specifies the character for a particular role. Each element hasa symbolic constant that stands for the index of that element—forexample,VINTR
is the index of the element that specifies the INTRcharacter, so storing'='
intermios.c_cc[VINTR]
specifies ‘=’ as the INTR character.
On some systems, you can disable a particular special character functionby specifying the value_POSIX_VDISABLE
for that role. Thisvalue is unequal to any possible character code. SeeOptional Features in File Support, for more information about how to tell whether the operatingsystem you are using supports_POSIX_VDISABLE
.
Next:Characters that Cause Signals, Up:Special Characters [Contents][Index]
These special characters are active only in canonical input mode.SeeTwo Styles of Input: Canonical or Not.
int
VEOF ¶This is the subscript for the EOF character in the special controlcharacter array.termios.c_cc[VEOF]
holds the characteritself.
The EOF character is recognized only in canonical input mode. It actsas a line terminator in the same way as a newline character, but if theEOF character is typed at the beginning of a line it causesread
to return a byte count of zero, indicating end-of-file. The EOFcharacter itself is discarded.
Usually, the EOF character isC-d.
int
VEOL ¶This is the subscript for the EOL character in the special controlcharacter array.termios.c_cc[VEOL]
holds the characteritself.
The EOL character is recognized only in canonical input mode. It actsas a line terminator, just like a newline character. The EOL characteris not discarded; it is read as the last character in the input line.
You don’t need to use the EOL character to makeRET end a line.Just set the ICRNL flag. In fact, this is the default state ofaffairs.
int
VEOL2 ¶This is the subscript for the EOL2 character in the special controlcharacter array.termios.c_cc[VEOL2]
holds the characteritself.
The EOL2 character works just like the EOL character (see above), but itcan be a different character. Thus, you can specify two characters toterminate an input line, by setting EOL to one of them and EOL2 to theother.
The EOL2 character is a BSD extension; it exists only on BSD systemsand GNU/Linux and GNU/Hurd systems.
int
VERASE ¶This is the subscript for the ERASE character in the special controlcharacter array.termios.c_cc[VERASE]
holds thecharacter itself.
The ERASE character is recognized only in canonical input mode. Whenthe user types the erase character, the previous character typed isdiscarded. (If the terminal generates multibyte character sequences,this may cause more than one byte of input to be discarded.) Thiscannot be used to erase past the beginning of the current line of text.The ERASE character itself is discarded.
Usually, the ERASE character isDEL.
int
VWERASE ¶This is the subscript for the WERASE character in the special controlcharacter array.termios.c_cc[VWERASE]
holds the characteritself.
The WERASE character is recognized only in canonical mode. It erases anentire word of prior input, and any whitespace after it; whitespacecharacters before the word are not erased.
The definition of a “word” depends on the setting of theALTWERASE
mode; seeLocal Modes.
If theALTWERASE
mode is not set, a word is defined as a sequenceof any characters except space or tab.
If theALTWERASE
mode is set, a word is defined as a sequence ofcharacters containing only letters, numbers, and underscores, optionallyfollowed by one character that is not a letter, number, or underscore.
The WERASE character is usuallyC-w.
This is a BSD extension.
int
VKILL ¶This is the subscript for the KILL character in the special controlcharacter array.termios.c_cc[VKILL]
holds the characteritself.
The KILL character is recognized only in canonical input mode. When theuser types the kill character, the entire contents of the current lineof input are discarded. The kill character itself is discarded too.
The KILL character is usuallyC-u.
int
VREPRINT ¶This is the subscript for the REPRINT character in the special controlcharacter array.termios.c_cc[VREPRINT]
holds the characteritself.
The REPRINT character is recognized only in canonical mode. It reprintsthe current input line. If some asynchronous output has come while youare typing, this lets you see the line you are typing clearly again.
The REPRINT character is usuallyC-r.
This is a BSD extension.
Next:Special Characters for Flow Control, Previous:Characters for Input Editing, Up:Special Characters [Contents][Index]
These special characters may be active in either canonical or noncanonicalinput mode, but only when theISIG
flag is set (seeLocal Modes).
int
VINTR ¶This is the subscript for the INTR character in the special controlcharacter array.termios.c_cc[VINTR]
holds the characteritself.
The INTR (interrupt) character raises aSIGINT
signal for allprocesses in the foreground job associated with the terminal. The INTRcharacter itself is then discarded. SeeSignal Handling, for moreinformation about signals.
Typically, the INTR character isC-c.
int
VQUIT ¶This is the subscript for the QUIT character in the special controlcharacter array.termios.c_cc[VQUIT]
holds the characteritself.
The QUIT character raises aSIGQUIT
signal for all processes inthe foreground job associated with the terminal. The QUIT characteritself is then discarded. SeeSignal Handling, for more informationabout signals.
Typically, the QUIT character isC-\.
int
VSUSP ¶This is the subscript for the SUSP character in the special controlcharacter array.termios.c_cc[VSUSP]
holds the characteritself.
The SUSP (suspend) character is recognized only if the implementationsupports job control (seeJob Control). It causes aSIGTSTP
signal to be sent to all processes in the foreground job associated withthe terminal. The SUSP character itself is then discarded.SeeSignal Handling, for more information about signals.
Typically, the SUSP character isC-z.
Few applications disable the normal interpretation of the SUSPcharacter. If your program does this, it should provide some othermechanism for the user to stop the job. When the user invokes thismechanism, the program should send aSIGTSTP
signal to theprocess group of the process, not just to the process itself.SeeSignaling Another Process.
int
VDSUSP ¶This is the subscript for the DSUSP character in the special controlcharacter array.termios.c_cc[VDSUSP]
holds the characteritself.
The DSUSP (suspend) character is recognized only if the implementationsupports job control (seeJob Control). It sends aSIGTSTP
signal, like the SUSP character, but not right away—only when theprogram tries to read it as input. Not all systems with job controlsupport DSUSP; only BSD-compatible systems do (including GNU/Hurd systems).
SeeSignal Handling, for more information about signals.
Typically, the DSUSP character isC-y.
Next:Other Special Characters, Previous:Characters that Cause Signals, Up:Special Characters [Contents][Index]
These special characters may be active in either canonical or noncanonicalinput mode, but their use is controlled by the flagsIXON
andIXOFF
(seeInput Modes).
int
VSTART ¶This is the subscript for the START character in the special controlcharacter array.termios.c_cc[VSTART]
holds thecharacter itself.
The START character is used to support theIXON
andIXOFF
input modes. IfIXON
is set, receiving a START character resumessuspended output; the START character itself is discarded. IfIXANY
is set, receiving any character at all resumes suspendedoutput; the resuming character is not discarded unless it is the STARTcharacter. IfIXOFF
is set, the system may also transmit STARTcharacters to the terminal.
The usual value for the START character isC-q. You may not beable to change this value—the hardware may insist on usingC-qregardless of what you specify.
int
VSTOP ¶This is the subscript for the STOP character in the special controlcharacter array.termios.c_cc[VSTOP]
holds the characteritself.
The STOP character is used to support theIXON
andIXOFF
input modes. IfIXON
is set, receiving a STOP character causesoutput to be suspended; the STOP character itself is discarded. IfIXOFF
is set, the system may also transmit STOP characters to theterminal, to prevent the input queue from overflowing.
The usual value for the STOP character isC-s. You may not beable to change this value—the hardware may insist on usingC-sregardless of what you specify.
Previous:Special Characters for Flow Control, Up:Special Characters [Contents][Index]
int
VLNEXT ¶This is the subscript for the LNEXT character in the special controlcharacter array.termios.c_cc[VLNEXT]
holds the characteritself.
The LNEXT character is recognized only whenIEXTEN
is set, but inboth canonical and noncanonical mode. It disables any specialsignificance of the next character the user types. Even if thecharacter would normally perform some editing function or generate asignal, it is read as a plain character. This is the analogue of theC-q command in Emacs. “LNEXT” stands for “literal next.”
The LNEXT character is usuallyC-v.
This character is available on BSD systems and GNU/Linux and GNU/Hurd systems.
int
VDISCARD ¶This is the subscript for the DISCARD character in the special controlcharacter array.termios.c_cc[VDISCARD]
holds the characteritself.
The DISCARD character is recognized only whenIEXTEN
is set, butin both canonical and noncanonical mode. Its effect is to toggle thediscard-output flag. When this flag is set, all program output isdiscarded. Setting the flag also discards all output currently in theoutput buffer. Typing any other character resets the flag.
This character is available on BSD systems and GNU/Linux and GNU/Hurd systems.
int
VSTATUS ¶This is the subscript for the STATUS character in the special controlcharacter array.termios.c_cc[VSTATUS]
holds the characteritself.
The STATUS character’s effect is to print out a status message about howthe current process is running.
The STATUS character is recognized only in canonical mode, and only ifNOKERNINFO
is not set.
This character is available only on BSD systems and GNU/Hurd systems.
Previous:Special Characters, Up:Terminal Modes [Contents][Index]
In noncanonical input mode, the special editing characters such asERASE and KILL are ignored. The system facilities for the user to editinput are disabled in noncanonical mode, so that all input characters(unless they are special for signal or flow-control purposes) are passedto the application program exactly as typed. It is up to theapplication program to give the user ways to edit the input, ifappropriate.
Noncanonical mode offers special parameters called MIN and TIME forcontrolling whether and how long to wait for input to be available. Youcan even use them to avoid ever waiting—to return immediately withwhatever input is available, or with no input.
The MIN and TIME are stored in elements of thec_cc
array, whichis a member of thestruct termios
structure. Each element ofthis array has a particular role, and each element has a symbolicconstant that stands for the index of that element.VMIN
andVTIME
are the names for the indices in the array of the MIN andTIME slots.
int
VMIN ¶This is the subscript for the MIN slot in thec_cc
array. Thus,termios.c_cc[VMIN]
is the value itself.
The MIN slot is only meaningful in noncanonical input mode; itspecifies the minimum number of bytes that must be available in theinput queue in order forread
to return.
int
VTIME ¶This is the subscript for the TIME slot in thec_cc
array. Thus,termios.c_cc[VTIME]
is the value itself.
The TIME slot is only meaningful in noncanonical input mode; itspecifies how long to wait for input before returning, in units of 0.1seconds.
The MIN and TIME values interact to determine the criterion for whenread
should return; their precise meanings depend on which ofthem are nonzero. There are four possible cases:
In this case, TIME specifies how long to wait after each input characterto see if more input arrives. After the first character received,read
keeps waiting until either MIN bytes have arrived in all, orTIME elapses with no further input.
read
always blocks until the first character arrives, even ifTIME elapses first.read
can return more than MIN characters ifmore than MIN happen to be in the queue.
In this case,read
always returns immediately with as manycharacters as are available in the queue, up to the number requested.If no input is immediately available,read
returns a value ofzero.
In this case,read
waits for time TIME for input to becomeavailable; the availability of a single byte is enough to satisfy theread request and causeread
to return. When it returns, itreturns as many characters as are available, up to the number requested.If no input is available before the timer expires,read
returns avalue of zero.
In this case,read
waits until at least MIN bytes are availablein the queue. At that time,read
returns as many characters asare available, up to the number requested.read
can return morethan MIN characters if more than MIN happen to be in the queue.
What happens if MIN is 50 and you ask to read just 10 bytes?Normally,read
waits until there are 50 bytes in the buffer (or,more generally, the wait condition described above is satisfied), andthen reads 10 of them, leaving the other 40 buffered in the operatingsystem for a subsequent call toread
.
Portability note: On some systems, the MIN and TIME slots areactually the same as the EOF and EOL slots. This causes no seriousproblem because the MIN and TIME slots are used only in noncanonicalinput and the EOF and EOL slots are used only in canonical input, but itisn’t very clean. The GNU C Library allocates separate slots for theseuses.
void
cfmakeraw(struct termios *termios-p)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function provides an easy way to set up*termios-p
forwhat has traditionally been called “raw mode” in BSD. This usesnoncanonical input, and turns off most processing to give an unmodifiedchannel to the terminal.
It does exactly this:
termios-p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP |INLCR|IGNCR|ICRNL|IXON);termios-p->c_oflag &= ~OPOST;termios-p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);termios-p->c_cflag &= ~(CSIZE|PARENB);termios-p->c_cflag |= CS8;
Next:Line Control Functions, Previous:Terminal Modes, Up:Low-Level Terminal Interface [Contents][Index]
The usual way to get and set terminal modes is with the functions describedinTerminal Modes. However, on some systems you can use theBSD-derived functions in this section to do some of the same things. Onmany systems, these functions do not exist. Even with the GNU C Library,the functions simply fail witherrno
=ENOSYS
with manykernels, including Linux.
The symbols used in this section are declared insgtty.h.
This structure is an input or output parameter list forgtty
andstty
.
char sg_ispeed
Line speed for input
char sg_ospeed
Line speed for output
char sg_erase
Erase character
char sg_kill
Kill character
int sg_flags
Various flags
int
gtty(intfiledes, struct sgttyb *attributes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function gets the attributes of a terminal.
gtty
sets *attributes to describe the terminal attributesof the terminal which is open with file descriptorfiledes.
int
stty(intfiledes, const struct sgttyb *attributes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function sets the attributes of a terminal.
stty
sets the terminal attributes of the terminal which is open withfile descriptorfiledes to those described by *attributes.
Next:Noncanonical Mode Example, Previous:BSD Terminal Modes, Up:Low-Level Terminal Interface [Contents][Index]
These functions perform miscellaneous control actions on terminaldevices. As regards terminal access, they are treated like doingoutput: if any of these functions is used by a background process on itscontrolling terminal, normally all processes in the process group aresent aSIGTTOU
signal. The exception is if the calling processitself is ignoring or blockingSIGTTOU
signals, in which case theoperation is performed and no signal is sent. SeeJob Control.
int
tcsendbreak(intfiledes, intduration)
¶Preliminary:| MT-Unsafe race:tcattr(filedes)/bsd| AS-Unsafe | AC-Unsafe corrupt/bsd| SeePOSIX Safety Concepts.
This function generates a break condition by transmitting a stream ofzero bits on the terminal associated with the file descriptorfiledes. The duration of the break is controlled by theduration argument. If zero, the duration is between 0.25 and 0.5seconds. The meaning of a nonzero value depends on the operating system.
This function does nothing if the terminal is not an asynchronous serialdata port.
The return value is normally zero. In the event of an error, a valueof-1 is returned. The followingerrno
error conditionsare defined for this function:
EBADF
Thefiledes is not a valid file descriptor.
ENOTTY
Thefiledes is not associated with a terminal device.
int
tcdrain(intfiledes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thetcdrain
function waits until all queuedoutput to the terminalfiledes has been transmitted.
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timetcdrain
iscalled. If the thread gets canceled these resources stay allocateduntil the program ends. To avoid this calls totcdrain
should beprotected using cancellation handlers.
The return value is normally zero. In the event of an error, a valueof-1 is returned. The followingerrno
error conditionsare defined for this function:
EBADF
Thefiledes is not a valid file descriptor.
ENOTTY
Thefiledes is not associated with a terminal device.
EINTR
The operation was interrupted by delivery of a signal.SeePrimitives Interrupted by Signals.
int
tcflush(intfiledes, intqueue)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thetcflush
function is used to clear the input and/or outputqueues associated with the terminal filefiledes. Thequeueargument specifies which queue(s) to clear, and can be one of thefollowing values:
TCIFLUSH
¶Clear any input data received, but not yet read.
TCOFLUSH
¶Clear any output data written, but not yet transmitted.
TCIOFLUSH
¶Clear both queued input and output.
The return value is normally zero. In the event of an error, a valueof-1 is returned. The followingerrno
error conditionsare defined for this function:
EBADF
Thefiledes is not a valid file descriptor.
ENOTTY
Thefiledes is not associated with a terminal device.
EINVAL
A bad value was supplied as thequeue argument.
It is unfortunate that this function is namedtcflush
, becausethe term “flush” is normally used for quite another operation—waitinguntil all output is transmitted—and using it for discarding input oroutput would be confusing. Unfortunately, the nametcflush
comesfrom POSIX and we cannot change it.
int
tcflow(intfiledes, intaction)
¶Preliminary:| MT-Unsafe race:tcattr(filedes)/bsd| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
Thetcflow
function is used to perform operations relating toXON/XOFF flow control on the terminal file specified byfiledes.
Theaction argument specifies what operation to perform, and canbe one of the following values:
TCOOFF
¶Suspend transmission of output.
TCOON
¶Restart transmission of output.
TCIOFF
¶Transmit a STOP character.
TCION
¶Transmit a START character.
For more information about the STOP and START characters, seeSpecial Characters.
The return value is normally zero. In the event of an error, a valueof-1 is returned. The followingerrno
error conditionsare defined for this function:
Next:Reading Passphrases, Previous:Line Control Functions, Up:Low-Level Terminal Interface [Contents][Index]
Here is an example program that shows how you can set up a terminaldevice to read single characters in noncanonical input mode, withoutecho.
#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <termios.h>/*Use this variable to remember original terminal attributes. */struct termios saved_attributes;voidreset_input_mode (void){ tcsetattr (STDIN_FILENO, TCSANOW, &saved_attributes);}voidset_input_mode (void){ struct termios tattr; /*Make sure stdin is a terminal. */ if (!isatty (STDIN_FILENO)) { fprintf (stderr, "Not a terminal.\n"); exit (EXIT_FAILURE); } /*Save the terminal attributes so we can restore them later. */ tcgetattr (STDIN_FILENO, &saved_attributes); atexit (reset_input_mode);
/*Set the funny terminal modes. */ tcgetattr (STDIN_FILENO, &tattr); tattr.c_lflag &= ~(ICANON|ECHO); /*Clear ICANON and ECHO. */ tattr.c_cc[VMIN] = 1; tattr.c_cc[VTIME] = 0; tcsetattr (STDIN_FILENO, TCSAFLUSH, &tattr);}
intmain (void){ char c; set_input_mode (); while (1) { read (STDIN_FILENO, &c, 1); if (c == '\004') /*C-d */ break; else write (STDOUT_FILENO, &c, 1); } return EXIT_SUCCESS;}
This program is careful to restore the original terminal modes beforeexiting or terminating with a signal. It uses theatexit
function (seeCleanups on Exit) to make sure this is donebyexit
.
The shell is supposed to take care of resetting the terminal modes whena process is stopped or continued; seeJob Control. But someexisting shells do not actually do this, so you may wish to establishhandlers for job control signals that reset terminal modes. The aboveexample does so.
Next:Pseudo-Terminals, Previous:Noncanonical Mode Example, Up:Low-Level Terminal Interface [Contents][Index]
When reading in a passphrase, it is desirable to avoid displaying it onthe screen, to help keep it secret. The following function handles thisin a convenient way.
char *
getpass(const char *prompt)
¶Preliminary:| MT-Unsafe term| AS-Unsafe heap lock corrupt| AC-Unsafe term lock corrupt| SeePOSIX Safety Concepts.
getpass
outputsprompt, then reads a string in from theterminal without echoing it. It tries to connect to the real terminal,/dev/tty, if possible, to encourage users not to put plaintextpassphrases in files; otherwise, it usesstdin
andstderr
.getpass
also disables the INTR, QUIT, and SUSP characters on theterminal using theISIG
terminal attribute (seeLocal Modes).The terminal is flushed before and aftergetpass
, so thatcharacters of a mistyped passphrase are not accidentally visible.
In other C libraries,getpass
may only return the firstPASS_MAX
bytes of a passphrase. The GNU C Library has no limit, soPASS_MAX
is undefined.
The prototype for this function is inunistd.h.PASS_MAX
would be defined inlimits.h.
This precise set of operations may not suit all possible situations. Inthis case, it is recommended that users write their owngetpass
substitute. For instance, a very simple substitute is as follows:
#include <termios.h>#include <stdio.h>ssize_tmy_getpass (char **lineptr, size_t *n, FILE *stream){ struct termios old, new; int nread; /*Turn echoing off and fail if we can’t. */ if (tcgetattr (fileno (stream), &old) != 0) return -1; new = old; new.c_lflag &= ~ECHO; if (tcsetattr (fileno (stream), TCSAFLUSH, &new) != 0) return -1; /*Read the passphrase */ nread = getline (lineptr, n, stream); /*Restore terminal. */ (void) tcsetattr (fileno (stream), TCSAFLUSH, &old); return nread;}
The substitute takes the same parameters asgetline
(seeLine-Oriented Input); the user must print any prompt desired.
Previous:Reading Passphrases, Up:Low-Level Terminal Interface [Contents][Index]
Apseudo-terminal is a special interprocess communication channelthat acts like a terminal. One end of the channel is called themaster side ormaster pseudo-terminal device, the other sideis called theslave side. Data written to the master side isreceived by the slave side as if it was the result of a user typing atan ordinary terminal, and data written to the slave side is sent to themaster side as if it was written on an ordinary terminal.
Pseudo terminals are the way programs likexterm
andemacs
implement their terminal emulation functionality.
Next:Opening a Pseudo-Terminal Pair, Up:Pseudo-Terminals [Contents][Index]
This subsection describes functions for allocating a pseudo-terminal,and for making this pseudo-terminal available for actual use. Thesefunctions are declared in the header filestdlib.h.
int
posix_openpt(intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
posix_openpt
returns a new file descriptor for the nextavailable master pseudo-terminal. In the case of an error, it returnsa value of-1 instead, and setserrno
to indicatethe error. SeeOpening and Closing Files for possible valuesoferrno
.
flags is a bit mask created from a bitwise OR of zero or moreof the following flags:
O_RDWR
Open the device for both reading and writing. It is usual to specifythis flag.
O_NOCTTY
Do not make the device the controlling terminal for the process.
These flags are defined infcntl.h. SeeFile Access Modes.
For this function to be available,_XOPEN_SOURCE
must be definedto a value greater than ‘600’. SeeFeature Test Macros.
int
getpt(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
getpt
is similar toposix_openpt
. This function is aGNU extension and should not be used in portable programs.
Thegetpt
function returns a new file descriptor for the nextavailable master pseudo-terminal. The normal return value fromgetpt
is a non-negative integer file descriptor. In the case ofan error, a value of-1 is returned instead. The followingerrno
conditions are defined for this function:
ENOENT
There are no free master pseudo-terminals available.
int
grantpt(intfiledes)
¶Preliminary:| MT-Safe locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegrantpt
function changes the ownership and access permissionof the slave pseudo-terminal device corresponding to the masterpseudo-terminal device associated with the file descriptorfiledes. The owner is set from the real user ID of the callingprocess (seeThe Persona of a Process), and the group is set to a specialgroup (typicallytty) or from the real group ID of the callingprocess. The access permission is set such that the file is bothreadable and writable by the owner and only writable by the group.
On some systems this function is implemented by invoking a specialsetuid
root program (seeHow an Application Can Change Persona). As aconsequence, installing a signal handler for theSIGCHLD
signal(seeJob Control Signals) may interfere with a call tograntpt
.
The normal return value fromgrantpt
is0; a value of-1 is returned in case of failure. The followingerrno
error conditions are defined for this function:
EBADF
Thefiledes argument is not a valid file descriptor.
EINVAL
Thefiledes argument is not associated with a master pseudo-terminaldevice.
EACCES
The slave pseudo-terminal device corresponding to the master associatedwithfiledes could not be accessed.
int
unlockpt(intfiledes)
¶Preliminary:| MT-Safe | AS-Unsafe heap/bsd| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Theunlockpt
function unlocks the slave pseudo-terminal devicecorresponding to the master pseudo-terminal device associated with thefile descriptorfiledes. On many systems, the slave can only beopened after unlocking, so portable applications should always callunlockpt
before trying to open the slave.
The normal return value fromunlockpt
is0; a value of-1 is returned in case of failure. The followingerrno
error conditions are defined for this function:
EBADF
Thefiledes argument is not a valid file descriptor.
EINVAL
Thefiledes argument is not associated with a master pseudo-terminaldevice.
char *
ptsname(intfiledes)
¶Preliminary:| MT-Unsafe race:ptsname| AS-Unsafe heap/bsd| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
If the file descriptorfiledes is associated with amaster pseudo-terminal device, theptsname
function returns apointer to a statically-allocated, null-terminated string containing thefile name of the associated slave pseudo-terminal file. This stringmight be overwritten by subsequent calls toptsname
.
int
ptsname_r(intfiledes, char *buf, size_tlen)
¶Preliminary:| MT-Safe | AS-Unsafe heap/bsd| AC-Unsafe mem fd| SeePOSIX Safety Concepts.
Theptsname_r
function is similar to theptsname
functionexcept that it places its result into the user-specified buffer startingatbuf with lengthlen.
This function was originally a GNU extension, but was added inPOSIX.1-2024.
Typical usage of these functions is illustrated by the following example:
intopen_pty_pair (int *amaster, int *aslave){ int master, slave; char *name; master = posix_openpt (O_RDWR | O_NOCTTY); if (master < 0) return 0; if (grantpt (master) < 0 || unlockpt (master) < 0) goto close_master; name = ptsname (master); if (name == NULL) goto close_master; slave = open (name, O_RDWR); if (slave == -1) goto close_master; *amaster = master; *aslave = slave; return 1;close_slave: close (slave);close_master: close (master); return 0;}
Previous:Allocating Pseudo-Terminals, Up:Pseudo-Terminals [Contents][Index]
These functions, derived from BSD, are available in the separatelibutil library, and declared inpty.h.
int
openpty(int *amaster, int *aslave, char *name, const struct termios *termp, const struct winsize *winp)
¶Preliminary:| MT-Safe locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function allocates and opens a pseudo-terminal pair, returning thefile descriptor for the master in*amaster, and the filedescriptor for the slave in*aslave. If the argumentnameis not a null pointer, the file name of the slave pseudo-terminaldevice is stored in*name
. Iftermp is not a null pointer,the terminal attributes of the slave are set to the ones specified inthe structure thattermp points to (seeTerminal Modes).Likewise, ifwinp is not a null pointer, the screen size ofthe slave is set to the values specified in the structure thatwinp points to.
The normal return value fromopenpty
is0; a value of-1 is returned in case of failure. The followingerrno
conditions are defined for this function:
ENOENT
There are no free pseudo-terminal pairs available.
Warning: Using theopenpty
function withname notset toNULL
isvery dangerous because it provides noprotection against overflowing the stringname. You should usethettyname
function on the file descriptor returned in*slave to find out the file name of the slave pseudo-terminaldevice instead.
int
forkpty(int *amaster, char *name, const struct termios *termp, const struct winsize *winp)
¶Preliminary:| MT-Safe locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function is similar to theopenpty
function, but inaddition, forks a new process (seeCreating a Process) and makes thenewly opened slave pseudo-terminal device the controlling terminal(seeControlling Terminal of a Process) for the child process.
If the operation is successful, there are then both parent and childprocesses and both seeforkpty
return, but with different values:it returns a value of0 in the child process and returns the child’sprocess ID in the parent process.
If the allocation of a pseudo-terminal pair or the process creationfailed,forkpty
returns a value of-1 in the parentprocess.
Warning: Theforkpty
function has the same problems withrespect to thename argument asopenpty
.
Next:Mathematics, Previous:Low-Level Terminal Interface, Up:Main Menu [Contents][Index]
This chapter describes facilities for issuing and logging messages ofsystem administration interest. This chapter has nothing to do withprograms issuing messages to their own users or keeping private logs(One would typically do that with the facilities described inInput/Output on Streams).
Most systems have a facility called “Syslog” that allows programs tosubmit messages of interest to system administrators and can beconfigured to pass these messages on in various ways, such as printingon the console, mailing to a particular person, or recording in a logfile for future reference.
A program uses the facilities in this chapter to submit such messages.
Next:Submitting Syslog Messages, Up:Syslog [Contents][Index]
System administrators have to deal with lots of different kinds ofmessages from a plethora of subsystems within each system, and usuallylots of systems as well. For example, an FTP server might report everyconnection it gets. The kernel might report hardware failures on a diskdrive. A DNS server might report usage statistics at regular intervals.
Some of these messages need to be brought to a system administrator’sattention immediately. And it may not be just any system administrator– there may be a particular system administrator who deals with aparticular kind of message. Other messages just need to be recorded forfuture reference if there is a problem. Still others may need to haveinformation extracted from them by an automated process that generatesmonthly reports.
To deal with these messages, most Unix systems have a facility called"Syslog." It is generally based on a daemon called “Syslogd”Syslogd listens for messages on a Unix domain socket named/dev/log. Based on classification information in the messagesand its configuration file (usually/etc/syslog.conf), Syslogdroutes them in various ways. Some of the popular routings are:
Syslogd can also handle messages from other systems. It listens on thesyslog
UDP port as well as the local socket for messages.
Syslog can handle messages from the kernel itself. But the kerneldoesn’t write to/dev/log; rather, another daemon (sometimescalled “Klogd”) extracts messages from the kernel and passes them on toSyslog as any other process would (and it properly identifies them asmessages from the kernel).
Syslog can even handle messages that the kernel issued before Syslogd orKlogd was running. A Linux kernel, for example, stores startup messagesin a kernel message ring and they are normally still there when Klogdlater starts up. Assuming Syslogd is running by the time Klogd starts,Klogd then passes everything in the message ring to it.
In order to classify messages for disposition, Syslog requires any processthat submits a message to it to provide two pieces of classificationinformation with it:
This identifies who submitted the message. There are a small number offacilities defined. The kernel, the mail subsystem, and an FTP serverare examples of recognized facilities. For the complete list,Seesyslog, vsyslog. Keep in mind that these areessentially arbitrary classifications. "Mail subsystem" doesn’t have anymore meaning than the system administrator gives to it.
This tells how important the content of the message is. Examples ofdefined priority values are: debug, informational, warning and critical.For the complete list, seesyslog, vsyslog. Except forthe fact that the priorities have a defined order, the meaning of eachof these priorities is entirely determined by the system administrator.
A “facility/priority” is a number that indicates both the facilityand the priority.
Warning: This terminology is not universal. Some people use“level” to refer to the priority and “priority” to refer to thecombination of facility and priority. A Linux kernel has a concept of amessage “level,” which corresponds both to a Syslog priority and to aSyslog facility/priority (It can be both because the facility code forthe kernel is zero, and that makes priority and facility/priority thesame value).
The GNU C Library provides functions to submit messages to Syslog. Theydo it by writing to the/dev/log socket. SeeSubmitting Syslog Messages.
The GNU C Library functions only work to submit messages to the Syslogfacility on the same system. To submit a message to the Syslog facilityon another system, use the socket I/O functions to write a UDP datagramto thesyslog
UDP port on that system. SeeSockets.
Previous:Overview of Syslog, Up:Syslog [Contents][Index]
The GNU C Library provides functions to submit messages to the Syslogfacility:
These functions only work to submit messages to the Syslog facility onthe same system. To submit a message to the Syslog facility on anothersystem, use the socket I/O functions to write a UDP datagram to thesyslog
UDP port on that system. SeeSockets.
Next:syslog, vsyslog, Up:Submitting Syslog Messages [Contents][Index]
The symbols referred to in this section are declared in the filesyslog.h.
void
openlog(const char *ident, intoption, intfacility)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
openlog
opens or reopens a connection to Syslog in preparationfor submitting messages.
ident is an arbitrary identification string which futuresyslog
invocations will prefix to each message. This is intendedto identify the source of the message, and people conventionally set itto the name of the program that will submit the messages.
Ifident is NULL, or ifopenlog
is not called, the defaultidentification string used in Syslog messages will be the program name,taken from argv[0].
Please note that the string pointerident will be retainedinternally by the Syslog routines. You must not free the memory thatident points to. It is also dangerous to pass a reference to anautomatic variable since leaving the scope would mean ending thelifetime of the variable. If you want to change theident string,you must callopenlog
again; overwriting the string pointed to byident is not thread-safe.
You can cause the Syslog routines to drop the reference toident andgo back to the default string (the program name taken from argv[0]), bycallingcloselog
: Seecloselog.
In particular, if you are writing code for a shared library that might getloaded and then unloaded (e.g. a PAM module), and you useopenlog
,you must callcloselog
before any point where your library mightget unloaded, as in this example:
#include <syslog.h>voidshared_library_function (void){ openlog ("mylibrary", option, priority); syslog (LOG_INFO, "shared library has been invoked"); closelog ();}
Without the call tocloselog
, future invocations ofsyslog
by the program using the shared library may crash, if the library getsunloaded and the memory containing the string"mylibrary"
becomesunmapped. This is a limitation of the BSD syslog interface.
openlog
may or may not open the/dev/log socket, dependingonoption. If it does, it tries to open it and connect it as astream socket. If that doesn’t work, it tries to open it and connect itas a datagram socket. The socket has the “Close on Exec” attribute,so the kernel will close it if the process performs an exec.
You don’t have to useopenlog
. If you callsyslog
withouthaving calledopenlog
,syslog
just opens the connectionimplicitly and uses defaults for the information inident andoptions.
options is a bit string, with the bits as defined by the followingsingle bit masks:
LOG_PERROR
¶If on,openlog
sets up the connection so that anysyslog
on this connection writes its message to the calling process’ StandardError stream in addition to submitting it to Syslog. If off,syslog
does not write the message to Standard Error.
LOG_CONS
¶If on,openlog
sets up the connection so that asyslog
onthis connection that fails to submit a message to Syslog writes themessage instead to system console. If off,syslog
does not writeto the system console (but of course Syslog may write messages itreceives to the console).
LOG_PID
¶When on,openlog
sets up the connection so that asyslog
on this connection inserts the calling process’ Process ID (PID) intothe message. When off,openlog
does not insert the PID.
LOG_NDELAY
¶When on,openlog
opens and connects the/dev/log socket.When off, a futuresyslog
call must open and connect the socket.
Portability note: In early systems, the sense of this bit wasexactly the opposite.
LOG_ODELAY
¶This bit does nothing. It exists for backward compatibility.
If any other bit inoptions is on, the result is undefined.
facility is the default facility code for this connection. Asyslog
on this connection that specifies default facility causesthis facility to be associated with the message. Seesyslog
forpossible values. A value of zero means the default, which isLOG_USER
.
If a Syslog connection is already open when you callopenlog
,openlog
“reopens” the connection. Reopening is like openingexcept that if you specify zero for the default facility code, thedefault facility code simply remains unchanged and if you specifyLOG_NDELAY and the socket is already open and connected,openlog
just leaves it that way.
Next:closelog, Previous:openlog, Up:Submitting Syslog Messages [Contents][Index]
The symbols referred to in this section are declared in the filesyslog.h.
void
syslog(intfacility_priority, const char *format, …)
¶Preliminary:| MT-Safe env locale| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
syslog
submits a message to the Syslog facility. It does this bywriting to the Unix domain socket/dev/log
.
syslog
submits the message with the facility and priority indicatedbyfacility_priority. The macroLOG_MAKEPRI
generates afacility/priority from a facility and a priority, as in the followingexample:
LOG_MAKEPRI(LOG_USER, LOG_WARNING)
The possible values for the facility code are (macros):
LOG_USER
¶A miscellaneous user process
LOG_MAIL
¶LOG_DAEMON
¶A miscellaneous system daemon
LOG_AUTH
¶Security (authorization)
LOG_SYSLOG
¶Syslog
LOG_LPR
¶Central printer
LOG_NEWS
¶Network news (e.g. Usenet)
LOG_UUCP
¶UUCP
LOG_CRON
¶Cron and At
LOG_AUTHPRIV
¶Private security (authorization)
LOG_FTP
¶Ftp server
LOG_LOCAL0
¶Locally defined
LOG_LOCAL1
¶Locally defined
LOG_LOCAL2
¶Locally defined
LOG_LOCAL3
¶Locally defined
LOG_LOCAL4
¶Locally defined
LOG_LOCAL5
¶Locally defined
LOG_LOCAL6
¶Locally defined
LOG_LOCAL7
¶Locally defined
Results are undefined if the facility code is anything else.
NB:syslog
recognizes one other facility code: that ofthe kernel. But you can’t specify that facility code with thesefunctions. If you try, it looks the same tosyslog
as if you arerequesting the default facility. But you wouldn’t want to anyway,because any program that uses the GNU C Library is not the kernel.
You can use just a priority code asfacility_priority. In thatcase,syslog
assumes the default facility established when theSyslog connection was opened. SeeSyslog Example.
The possible values for the priority code are (macros):
LOG_EMERG
¶The message says the system is unusable.
LOG_ALERT
¶Action on the message must be taken immediately.
LOG_CRIT
¶The message states a critical condition.
LOG_ERR
¶The message describes an error.
LOG_WARNING
¶The message is a warning.
LOG_NOTICE
¶The message describes a normal but important event.
LOG_INFO
¶The message is purely informational.
LOG_DEBUG
¶The message is only for debugging purposes.
Results are undefined if the priority code is anything else.
If the process does not presently have a Syslog connection open (i.e.,it did not callopenlog
),syslog
implicitly opens theconnection the same asopenlog
would, with the following defaultsfor information that would otherwise be included in anopenlog
call: The default identification string is the program name. Thedefault default facility isLOG_USER
. The default for all theconnection options inoptions is as if those bits were off.syslog
leaves the Syslog connection open.
If the/dev/log socket is not open and connected,syslog
opens and connects it, the same asopenlog
with theLOG_NDELAY
option would.
syslog
leaves/dev/log open and connected unless its attemptto send the message failed, in which casesyslog
closes it (with thehope that a future implicit open will restore the Syslog connection to ausable state).
Example:
#include <syslog.h>syslog (LOG_MAKEPRI(LOG_LOCAL1, LOG_ERROR), "Unable to make network connection to %s. Error=%m", host);
void
vsyslog(intfacility_priority, const char *format, va_listarglist)
¶Preliminary:| MT-Safe env locale| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
This is functionally identical tosyslog
, with the BSD style variablelength argument.
Next:setlogmask, Previous:syslog, vsyslog, Up:Submitting Syslog Messages [Contents][Index]
The symbols referred to in this section are declared in the filesyslog.h.
void
closelog(void)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
closelog
closes the current Syslog connection, if there is one.This includes closing the/dev/log socket, if it is open.closelog
also sets the identification string for Syslog messagesback to the default, ifopenlog
was called with a non-NULL argumenttoident. The default identification string is the program nametaken from argv[0].
If you are writing shared library code that usesopenlog
togenerate custom syslog output, you should usecloselog
to dropthe GNU C Library’s internal reference to theident pointer when you aredone. Please read the section onopenlog
for more information:Seeopenlog.
closelog
does not flush any buffers. You do not have to callcloselog
before re-opening a Syslog connection withopenlog
.Syslog connections are automatically closed on exec or exit.
Next:Syslog Example, Previous:closelog, Up:Submitting Syslog Messages [Contents][Index]
The symbols referred to in this section are declared in the filesyslog.h.
int
setlogmask(intmask)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
setlogmask
sets a mask (the “logmask”) that determines whichfuturesyslog
calls shall be ignored. If a program has notcalledsetlogmask
,syslog
doesn’t ignore any calls. Youcan usesetlogmask
to specify that messages of particularpriorities shall be ignored in the future.
Asetlogmask
call overrides any previoussetlogmask
call.
Note that the logmask exists entirely independently of opening andclosing of Syslog connections.
Setting the logmask has a similar effect to, but is not the same as,configuring Syslog. The Syslog configuration may cause Syslog todiscard certain messages it receives, but the logmask causes certainmessages never to get submitted to Syslog in the first place.
mask is a bit string with one bit corresponding to each of thepossible message priorities. If the bit is on,syslog
handlesmessages of that priority normally. If it is off,syslog
discards messages of that priority. Use the message priority macrosdescribed insyslog, vsyslog and theLOG_MASK
to constructan appropriatemask value, as in this example:
LOG_MASK(LOG_EMERG) | LOG_MASK(LOG_ERROR)
or
~(LOG_MASK(LOG_INFO))
There is also aLOG_UPTO
macro, which generates a mask with the bitson for a certain priority and all priorities above it:
LOG_UPTO(LOG_ERROR)
The unfortunate naming of the macro is due to the fact that internally,higher numbers are used for lower message priorities.
Previous:setlogmask, Up:Submitting Syslog Messages [Contents][Index]
Here is an example ofopenlog
,syslog
, andcloselog
:
This example sets the logmask so that debug and informational messagesget discarded without ever reaching Syslog. So the secondsyslog
in the example does nothing.
#include <syslog.h>setlogmask (LOG_UPTO (LOG_NOTICE));openlog ("exampleprog", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);syslog (LOG_NOTICE, "Program started by User %d", getuid ());syslog (LOG_INFO, "A tree falls in a forest");closelog ();
Next:Arithmetic Functions, Previous:Syslog, Up:Main Menu [Contents][Index]
This chapter contains information about functions for performingmathematical computations, such as trigonometric functions. Most ofthese functions have prototypes declared in the header filemath.h. The complex-valued functions are defined incomplex.h.
All mathematical functions which take a floating-point argumenthave three variants, one each fordouble
,float
, andlong double
arguments. Thedouble
versions are mostlydefined in ISO C89. Thefloat
andlong double
versions are from the numeric extensions to C included in ISO C99.
Which of the three versions of a function should be used depends on thesituation. For most calculations, thefloat
functions are thefastest. On the other hand, thelong double
functions have thehighest precision.double
is somewhere in between. It isusually wise to pick the narrowest type that can accommodate your data.Not all machines have a distinctlong double
type; it may be thesame asdouble
.
The GNU C Library also provides_FloatN
and_FloatNx
types. These types are defined in ISO/IEC TS 18661-3, which extends ISO C and defines floating-point types thatare not machine-dependent. When such a type, such as_Float128
,is supported by the GNU C Library, extra variants for most of the mathematicalfunctions provided fordouble
,float
, andlongdouble
are also provided for the supported type. Throughout thismanual, the_FloatN
and_FloatNx
variants ofthese functions are described along with thedouble
,float
, andlong double
variants and they come fromISO/IEC TS 18661-3, unless explicitly stated otherwise.
Support for_FloatN
or_FloatNx
types isprovided for_Float32
,_Float64
and_Float32x
onall platforms.It is also provided for_Float128
and_Float64x
onpowerpc64le (PowerPC 64-bits little-endian), x86_64, x86,aarch64, alpha, loongarch, mips64, riscv, s390 and sparc.
Next:Trigonometric Functions, Up:Mathematics [Contents][Index]
The headermath.h defines several useful mathematical constants.All values are defined as preprocessor macros starting withM_
.The values provided are:
M_E
¶The base of natural logarithms.
M_LOG2E
¶The logarithm to base2
ofM_E
.
M_LOG10E
¶The logarithm to base10
ofM_E
.
M_LN2
¶The natural logarithm of2
.
M_LN10
¶The natural logarithm of10
.
M_PI
¶Pi, the ratio of a circle’s circumference to its diameter.
M_PI_2
¶Pi divided by two.
M_PI_4
¶Pi divided by four.
M_1_PI
¶The reciprocal of pi (1/pi)
M_2_PI
¶Two times the reciprocal of pi.
M_2_SQRTPI
¶Two times the reciprocal of the square root of pi.
M_SQRT2
¶The square root of two.
M_SQRT1_2
¶The reciprocal of the square root of two (also the square root of 1/2).
These constants come from the Unix98 standard and were also available in4.4BSD; therefore they are only defined if_XOPEN_SOURCE=500
, or a more general feature select macro, isdefined. The default set of features includes these constants.SeeFeature Test Macros.
All values are of typedouble
. As an extension, the GNU C Libraryalso defines these constants with typelong double
andfloat
. Thelong double
macros have a lowercase ‘l’while thefloat
macros have a lowercase ‘f’ appended totheir names:M_El
,M_PIl
, and so forth. These are onlyavailable if_GNU_SOURCE
is defined.
Likewise, the GNU C Library also defines these constants with the types_FloatN
and_FloatNx
for the machines thathave support for such types enabled (seeMathematics) and if_GNU_SOURCE
is defined. When available, the macros names areappended with ‘fN’ or ‘fNx’, such as ‘f128’for the type_Float128
.
Note: Some programs use a constant namedPI
which has thesame value asM_PI
. This constant is not standard; it may haveappeared in some old AT&T headers, and is mentioned in Stroustrup’s bookon C++. It infringes on the user’s name space, so the GNU C Librarydoes not define it. Fixing programs written to expect it is simple:replacePI
withM_PI
throughout, or put ‘-DPI=M_PI’on the compiler command line.
Next:Inverse Trigonometric Functions, Previous:Predefined Mathematical Constants, Up:Mathematics [Contents][Index]
These are the familiarsin
,cos
, andtan
functions.The arguments to all of these functions are in units of radians; recallthat pi radians equals 180 degrees.
The math library normally definesM_PI
to adouble
approximation of pi. If strict ISO and/or POSIX complianceare requested this constant is not defined, but you can easily define ityourself:
#define M_PI 3.14159265358979323846264338327
You can also compute the value of pi with the expressionacos(-1.0)
.
double
sin(doublex)
¶float
sinf(floatx)
¶long double
sinl(long doublex)
¶_FloatN
sinfN(_FloatNx)
¶_FloatNx
sinfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the sine ofx, wherex is given inradians. The return value is in the range-1
to1
.
double
cos(doublex)
¶float
cosf(floatx)
¶long double
cosl(long doublex)
¶_FloatN
cosfN(_FloatNx)
¶_FloatNx
cosfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the cosine ofx, wherex is given inradians. The return value is in the range-1
to1
.
double
tan(doublex)
¶float
tanf(floatx)
¶long double
tanl(long doublex)
¶_FloatN
tanfN(_FloatNx)
¶_FloatNx
tanfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the tangent ofx, wherex is given inradians.
Mathematically, the tangent function has singularities at odd multiplesof pi/2. If the argumentx is too close to one of thesesingularities,tan
will signal overflow.
In many applications wheresin
andcos
are used, the sineand cosine of the same angle are needed at the same time. It is moreefficient to compute them simultaneously, so the library provides afunction to do that.
void
sincos(doublex, double *sinx, double *cosx)
¶void
sincosf(floatx, float *sinx, float *cosx)
¶void
sincosl(long doublex, long double *sinx, long double *cosx)
¶_FloatN
sincosfN(_FloatNx, _FloatN *sinx, _FloatN *cosx)
¶_FloatNx
sincosfNx(_FloatNxx, _FloatNx *sinx, _FloatNx *cosx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the sine ofx in*sinx
and thecosine ofx in*cosx
, wherex is given inradians. Both values,*sinx
and*cosx
, are inthe range of-1
to1
.
All these functions, including the_FloatN
and_FloatNx
variants, are GNU extensions. Portable programsshould be prepared to cope with their absence.
double
sinpi(doublex)
¶float
sinpif(floatx)
¶long double
sinpil(long doublex)
¶_FloatN
sinpifN(_FloatNx)
¶_FloatNx
sinpifNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the sine of pi multiplied byx. Thereturn value is in the range-1
to1
.
Thesinpi
functions are from TS 18661-4:2015.
double
cospi(doublex)
¶float
cospif(floatx)
¶long double
cospil(long doublex)
¶_FloatN
cospifN(_FloatNx)
¶_FloatNx
cospifNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the cosine of pi multiplied byx. Thereturn value is in the range-1
to1
.
Thecospi
functions are from TS 18661-4:2015.
double
tanpi(doublex)
¶float
tanpif(floatx)
¶long double
tanpil(long doublex)
¶_FloatN
tanpifN(_FloatNx)
¶_FloatNx
tanpifNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the tangent of pi multiplied byx.
Thetanpi
functions are from TS 18661-4:2015.
ISO C99 defines variants of the trig functions which work oncomplex numbers. The GNU C Library provides these functions, but theyare only useful if your compiler supports the new complex types definedby the standard.(As of this writing GCC supports complex numbers, but there are bugs inthe implementation.)
complex double
csin(complex doublez)
¶complex float
csinf(complex floatz)
¶complex long double
csinl(complex long doublez)
¶complex _FloatN
csinfN(complex _FloatNz)
¶complex _FloatNx
csinfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the complex sine ofz.The mathematical definition of the complex sine is
sin (z) = 1/(2*i) * (exp (z*i) - exp (-z*i)).
complex double
ccos(complex doublez)
¶complex float
ccosf(complex floatz)
¶complex long double
ccosl(complex long doublez)
¶complex _FloatN
ccosfN(complex _FloatNz)
¶complex _FloatNx
ccosfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the complex cosine ofz.The mathematical definition of the complex cosine is
cos (z) = 1/2 * (exp (z*i) + exp (-z*i))
complex double
ctan(complex doublez)
¶complex float
ctanf(complex floatz)
¶complex long double
ctanl(complex long doublez)
¶complex _FloatN
ctanfN(complex _FloatNz)
¶complex _FloatNx
ctanfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the complex tangent ofz.The mathematical definition of the complex tangent is
tan (z) = -i * (exp (z*i) - exp (-z*i)) / (exp (z*i) + exp (-z*i))
The complex tangent has poles atpi/2 + 2n, wheren is aninteger.ctan
may signal overflow ifz is too close to apole.
Next:Exponentiation and Logarithms, Previous:Trigonometric Functions, Up:Mathematics [Contents][Index]
These are the usual arcsine, arccosine and arctangent functions,which are the inverses of the sine, cosine and tangent functionsrespectively.
double
asin(doublex)
¶float
asinf(floatx)
¶long double
asinl(long doublex)
¶_FloatN
asinfN(_FloatNx)
¶_FloatNx
asinfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the arcsine ofx—that is, the value whosesine isx. The value is in units of radians. Mathematically,there are infinitely many such values; the one actually returned is theone between-pi/2
andpi/2
(inclusive).
The arcsine function is defined mathematically onlyover the domain-1
to1
. Ifx is outside thedomain,asin
signals a domain error.
double
acos(doublex)
¶float
acosf(floatx)
¶long double
acosl(long doublex)
¶_FloatN
acosfN(_FloatNx)
¶_FloatNx
acosfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the arccosine ofx—that is, the valuewhose cosine isx. The value is in units of radians.Mathematically, there are infinitely many such values; the one actuallyreturned is the one between0
andpi
(inclusive).
The arccosine function is defined mathematically onlyover the domain-1
to1
. Ifx is outside thedomain,acos
signals a domain error.
double
atan(doublex)
¶float
atanf(floatx)
¶long double
atanl(long doublex)
¶_FloatN
atanfN(_FloatNx)
¶_FloatNx
atanfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the arctangent ofx—that is, the valuewhose tangent isx. The value is in units of radians.Mathematically, there are infinitely many such values; the one actuallyreturned is the one between-pi/2
andpi/2
(inclusive).
double
atan2(doubley, doublex)
¶float
atan2f(floaty, floatx)
¶long double
atan2l(long doubley, long doublex)
¶_FloatN
atan2fN(_FloatNy, _FloatNx)
¶_FloatNx
atan2fNx(_FloatNxy, _FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function computes the arctangent ofy/x, but the signsof both arguments are used to determine the quadrant of the result, andx is permitted to be zero. The return value is given in radiansand is in the range-pi
topi
, inclusive.
Ifx andy are coordinates of a point in the plane,atan2
returns the signed angle between the line from the originto that point and the x-axis. Thus,atan2
is useful forconverting Cartesian coordinates to polar coordinates. (To compute theradial coordinate, usehypot
; seeExponentiation and Logarithms.)
If bothx andy are zero,atan2
returns zero.
double
asinpi(doublex)
¶float
asinpif(floatx)
¶long double
asinpil(long doublex)
¶_FloatN
asinpifN(_FloatNx)
¶_FloatNx
asinpifNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the arcsine ofx, divided by pi. Theresult is in the interval between-0.5
and0.5
(inclusive).
The arcsine function is defined mathematically only over the domain-1
to1
. Ifx is outside the domain,asinpi
signals a domain error.
Theasinpi
functions are from TS 18661-4:2015.
double
acospi(doublex)
¶float
acospif(floatx)
¶long double
acospil(long doublex)
¶_FloatN
acospifN(_FloatNx)
¶_FloatNx
acospifNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the arccosine ofx, divided by pi. Theresult is in the interval between0
and1
(inclusive).
The arccosine function is defined mathematically onlyover the domain-1
to1
. Ifx is outside thedomain,acospi
signals a domain error.
Theacospi
functions are from TS 18661-4:2015.
double
atanpi(doublex)
¶float
atanpif(floatx)
¶long double
atanpil(long doublex)
¶_FloatN
atanpifN(_FloatNx)
¶_FloatNx
atanpifNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the arctangent ofx, divided by pi. Theresult is in the interval between-0.5
and0.5
(inclusive).
Theatanpi
functions are from TS 18661-4:2015.
double
atan2pi(doubley, doublex)
¶float
atan2pif(floaty, floatx)
¶long double
atan2pil(long doubley, long doublex)
¶_FloatN
atan2pifN(_FloatNy, _FloatNx)
¶_FloatNx
atan2pifNx(_FloatNxy, _FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These function computes the arctangent ofy/x, divided bypi, with the signs of both arguments used to determine the quadrant ofthe result, as foratan2
.
Theatan2pi
functions are from TS 18661-4:2015.
ISO C99 defines complex versions of the inverse trig functions.
complex double
casin(complex doublez)
¶complex float
casinf(complex floatz)
¶complex long double
casinl(complex long doublez)
¶complex _FloatN
casinfN(complex _FloatNz)
¶complex _FloatNx
casinfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the complex arcsine ofz—that is, thevalue whose sine isz. The value returned is in radians.
Unlike the real-valued functions,casin
is defined for allvalues ofz.
complex double
cacos(complex doublez)
¶complex float
cacosf(complex floatz)
¶complex long double
cacosl(complex long doublez)
¶complex _FloatN
cacosfN(complex _FloatNz)
¶complex _FloatNx
cacosfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the complex arccosine ofz—that is, thevalue whose cosine isz. The value returned is in radians.
Unlike the real-valued functions,cacos
is defined for allvalues ofz.
complex double
catan(complex doublez)
¶complex float
catanf(complex floatz)
¶complex long double
catanl(complex long doublez)
¶complex _FloatN
catanfN(complex _FloatNz)
¶complex _FloatNx
catanfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the complex arctangent ofz—that is,the value whose tangent isz. The value is in units of radians.
Next:Hyperbolic Functions, Previous:Inverse Trigonometric Functions, Up:Mathematics [Contents][Index]
double
exp(doublex)
¶float
expf(floatx)
¶long double
expl(long doublex)
¶_FloatN
expfN(_FloatNx)
¶_FloatNx
expfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions computee
(the base of natural logarithms) raisedto the powerx.
If the magnitude of the result is too large to be representable,exp
signals overflow.
double
exp2(doublex)
¶float
exp2f(floatx)
¶long double
exp2l(long doublex)
¶_FloatN
exp2fN(_FloatNx)
¶_FloatNx
exp2fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute2
raised to the powerx.Mathematically,exp2 (x)
is the same asexp (x * log (2))
.
double
exp10(doublex)
¶float
exp10f(floatx)
¶long double
exp10l(long doublex)
¶_FloatN
exp10fN(_FloatNx)
¶_FloatNx
exp10fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute10
raised to the powerx.Mathematically,exp10 (x)
is the same asexp (x * log (10))
.
Theexp10
functions are from TS 18661-4:2015.
double
log(doublex)
¶float
logf(floatx)
¶long double
logl(long doublex)
¶_FloatN
logfN(_FloatNx)
¶_FloatNx
logfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the natural logarithm ofx.exp (log(x))
equalsx, exactly in mathematics and approximately inC.
Ifx is negative,log
signals a domain error. Ifxis zero, it returns negative infinity; ifx is too close to zero,it may signal overflow.
double
log10(doublex)
¶float
log10f(floatx)
¶long double
log10l(long doublex)
¶_FloatN
log10fN(_FloatNx)
¶_FloatNx
log10fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the base-10 logarithm ofx.log10 (x)
equalslog (x) / log (10)
.
double
log2(doublex)
¶float
log2f(floatx)
¶long double
log2l(long doublex)
¶_FloatN
log2fN(_FloatNx)
¶_FloatNx
log2fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the base-2 logarithm ofx.log2 (x)
equalslog (x) / log (2)
.
double
logb(doublex)
¶float
logbf(floatx)
¶long double
logbl(long doublex)
¶_FloatN
logbfN(_FloatNx)
¶_FloatNx
logbfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions extract the exponent ofx and return it as afloating-point value.IfFLT_RADIX
is two,logb (x)
is similar tofloor (log2 (fabs (x)))
,except that the latter may give an incorrect integerdue to intermediate rounding.
Ifx is de-normalized,logb
returns the exponentxwould have if it were normalized. Ifx is infinity (positive ornegative),logb
returns∞. Ifx is zero,logb
returns∞. It does not signal.
int
ilogb(doublex)
¶int
ilogbf(floatx)
¶int
ilogbl(long doublex)
¶int
ilogbfN(_FloatNx)
¶int
ilogbfNx(_FloatNxx)
¶long int
llogb(doublex)
¶long int
llogbf(floatx)
¶long int
llogbl(long doublex)
¶long int
llogbfN(_FloatNx)
¶long int
llogbfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are equivalent to the correspondinglogb
functions except that they return signed integer values. Theilogb
,ilogbf
, andilogbl
functions are from ISOC99; thellogb
,llogbf
,llogbl
functions are fromTS 18661-1:2014; theilogbfN
,ilogbfNx
,llogbfN
,andllogbfNx
functions are from TS 18661-3:2015.
Since integers cannot represent infinity and NaN,ilogb
insteadreturns an integer that can’t be the exponent of a normal floating-pointnumber.math.h defines constants so you can check for this.
int
FP_ILOGB0 ¶ilogb
returns this value if its argument is0
. Thenumeric value is eitherINT_MIN
or-INT_MAX
.
This macro is defined in ISO C99.
long int
FP_LLOGB0 ¶llogb
returns this value if its argument is0
. Thenumeric value is eitherLONG_MIN
or-LONG_MAX
.
This macro is defined in TS 18661-1:2014.
int
FP_ILOGBNAN ¶ilogb
returns this value if its argument isNaN
. Thenumeric value is eitherINT_MIN
orINT_MAX
.
This macro is defined in ISO C99.
long int
FP_LLOGBNAN ¶llogb
returns this value if its argument isNaN
. Thenumeric value is eitherLONG_MIN
orLONG_MAX
.
This macro is defined in TS 18661-1:2014.
These values are system specific. They might even be the same. Theproper way to test the result ofilogb
is as follows:
i = ilogb (f);if (i == FP_ILOGB0 || i == FP_ILOGBNAN) { if (isnan (f)) { /*Handle NaN. */ } else if (f == 0.0) { /*Handle 0.0. */ } else { /*Some other value with large exponent,perhaps +Inf. */ } }
double
pow(doublebase, doublepower)
¶float
powf(floatbase, floatpower)
¶long double
powl(long doublebase, long doublepower)
¶_FloatN
powfN(_FloatNbase, _FloatNpower)
¶_FloatNx
powfNx(_FloatNxbase, _FloatNxpower)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These are general exponentiation functions, returningbase raisedtopower.
Mathematically,pow
would return a complex number whenbaseis negative andpower is not an integral value.pow
can’tdo that, so instead it signals a domain error.pow
may alsounderflow or overflow the destination type.
double
powr(doublebase, doublepower)
¶float
powrf(floatbase, floatpower)
¶long double
powrl(long doublebase, long doublepower)
¶_FloatN
powrfN(_FloatNbase, _FloatNpower)
¶_FloatNx
powrfNx(_FloatNxbase, _FloatNxpower)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These returnbase raised topower, but with special casesbased onexp (power * log (base))
. For example, ifbaseis negative, thepowr
functions always signal a domain error,but this is valid forpow
ifpower is an integer.
Thepowr
functions are from TS 18661-4:2015.
double
pown(doublebase, long long intpower)
¶float
pownf(floatbase, long long intpower)
¶long double
pownl(long doublebase, long long intpower)
¶_FloatN
pownfN(_FloatNbase, long long intpower)
¶_FloatNx
pownfNx(_FloatNxbase, long long intpower)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These returnbase raised topower (an integer).
Thepown
functions are from TS 18661-4:2015 (which usedintmax_t
as the type ofpower; the type changed tolong long int
in C23).
double
compoundn(doublex, long long intpower)
¶float
compoundnf(floatx, long long intpower)
¶long double
compoundnl(long doublex, long long intpower)
¶_FloatN
compoundnfN(_FloatNx, long long intpower)
¶_FloatNx
compoundnfNx(_FloatNxx, long long intpower)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These return1 +x
raised topower (an integer).Ifx is less than −1,compoundn
signals a domainerror.
Thecompoundn
functions are from TS 18661-4:2015 (which usedintmax_t
as the type ofpower; the type changed tolong long int
in C23).
double
sqrt(doublex)
¶float
sqrtf(floatx)
¶long double
sqrtl(long doublex)
¶_FloatN
sqrtfN(_FloatNx)
¶_FloatNx
sqrtfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the nonnegative square root ofx.
Ifx is negative,sqrt
signals a domain error.Mathematically, it should return a complex number.
double
rsqrt(doublex)
¶float
rsqrtf(floatx)
¶long double
rsqrtl(long doublex)
¶_FloatN
rsqrtfN(_FloatNx)
¶_FloatNx
rsqrtfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the reciprocal of the nonnegative square root ofx.Ifx is negative,rsqrt
signals a domain error.
Thersqrt
functions are from TS 18661-4:2015.
double
cbrt(doublex)
¶float
cbrtf(floatx)
¶long double
cbrtl(long doublex)
¶_FloatN
cbrtfN(_FloatNx)
¶_FloatNx
cbrtfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the cube root ofx.They cannot fail;every representable real valuehas a real cube root,and rounding it to a representable valuenever causes overflow nor underflow.
double
hypot(doublex, doubley)
¶float
hypotf(floatx, floaty)
¶long double
hypotl(long doublex, long doubley)
¶_FloatN
hypotfN(_FloatNx, _FloatNy)
¶_FloatNx
hypotfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions returnsqrt (x*x +y*y)
. This is the length of the hypotenuse of a righttriangle with sides of lengthx andy, or the distanceof the point (x,y) from the origin. Using this functioninstead of the direct formula is wise, since the error ismuch smaller. See also the functioncabs
inAbsolute Value.
double
rootn(doublex, long long intn)
¶float
rootnf(floatx, long long intn)
¶long double
rootnl(long doublex, long long intn)
¶_FloatN
rootnfN(_FloatNx, long long intn)
¶_FloatNx
rootnfNx(_FloatNxx, long long intn)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These return thenth root ofx. Ifn is zero, or ifx is negative andn is even,rootn
signals a domainerror.
Therootn
functions are from TS 18661-4:2015 (which usedintmax_t
as the type ofn; the type changed tolong long int
in C23).
double
expm1(doublex)
¶float
expm1f(floatx)
¶long double
expm1l(long doublex)
¶_FloatN
expm1fN(_FloatNx)
¶_FloatNx
expm1fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return a value equivalent toexp (x) - 1
.They are computed in a way that is accurate even ifx isnear zero—a case whereexp (x) - 1
would be inaccurate owingto subtraction of two numbers that are nearly equal.
double
exp2m1(doublex)
¶float
exp2m1f(floatx)
¶long double
exp2m1l(long doublex)
¶_FloatN
exp2m1fN(_FloatNx)
¶_FloatNx
exp2m1fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return a value equivalent toexp2 (x) - 1
.They are computed in a way that is accurate even ifx isnear zero—a case whereexp2 (x) - 1
would be inaccurate owingto subtraction of two numbers that are nearly equal.
Theexp2m1
functions are from TS 18661-4:2015.
double
exp10m1(doublex)
¶float
exp10m1f(floatx)
¶long double
exp10m1l(long doublex)
¶_FloatN
exp10m1fN(_FloatNx)
¶_FloatNx
exp10m1fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return a value equivalent toexp10 (x) - 1
.They are computed in a way that is accurate even ifx isnear zero—a case whereexp10 (x) - 1
would be inaccurate owingto subtraction of two numbers that are nearly equal.
Theexp10m1
functions are from TS 18661-4:2015.
double
log1p(doublex)
¶float
log1pf(floatx)
¶long double
log1pl(long doublex)
¶_FloatN
log1pfN(_FloatNx)
¶_FloatNx
log1pfNx(_FloatNxx)
¶double
logp1(doublex)
¶float
logp1f(floatx)
¶long double
logp1l(long doublex)
¶_FloatN
logp1fN(_FloatNx)
¶_FloatNx
logp1fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return a value equivalent tolog (1 + x)
.They are computed in a way that is accurate even ifx isnear zero.
Thelogp1
names for these functions are from TS 18661-4:2015.
double
log2p1(doublex)
¶float
log2p1f(floatx)
¶long double
log2p1l(long doublex)
¶_FloatN
log2p1fN(_FloatNx)
¶_FloatNx
log2p1fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return a value equivalent tolog2 (1 + x)
.They are computed in a way that is accurate even ifx isnear zero.
Thelog2p1
functions are from TS 18661-4:2015.
double
log10p1(doublex)
¶float
log10p1f(floatx)
¶long double
log10p1l(long doublex)
¶_FloatN
log10p1fN(_FloatNx)
¶_FloatNx
log10p1fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return a value equivalent tolog10 (1 + x)
.They are computed in a way that is accurate even ifx isnear zero.
Thelog10p1
functions are from TS 18661-4:2015.
ISO C99 defines complex variants of some of the exponentiation andlogarithm functions.
complex double
cexp(complex doublez)
¶complex float
cexpf(complex floatz)
¶complex long double
cexpl(complex long doublez)
¶complex _FloatN
cexpfN(complex _FloatNz)
¶complex _FloatNx
cexpfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions returne
(the base of naturallogarithms) raised to the power ofz.Mathematically, this corresponds to the value
exp (z) = exp (creal (z)) * (cos (cimag (z)) + I * sin (cimag (z)))
complex double
clog(complex doublez)
¶complex float
clogf(complex floatz)
¶complex long double
clogl(complex long doublez)
¶complex _FloatN
clogfN(complex _FloatNz)
¶complex _FloatNx
clogfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the natural logarithm ofz.Mathematically, this corresponds to the value
log (z) = log (cabs (z)) + I * carg (z)
clog
has a pole at 0, and will signal overflow ifz equalsor is very close to 0. It is well-defined for all other values ofz.
complex double
clog10(complex doublez)
¶complex float
clog10f(complex floatz)
¶complex long double
clog10l(complex long doublez)
¶complex _FloatN
clog10fN(complex _FloatNz)
¶complex _FloatNx
clog10fNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the base 10 logarithm of the complex valuez. Mathematically, this corresponds to the value
log10 (z) = log10 (cabs (z)) + I * carg (z) / log (10)
All these functions, including the_FloatN
and_FloatNx
variants, are GNU extensions.
complex double
csqrt(complex doublez)
¶complex float
csqrtf(complex floatz)
¶complex long double
csqrtl(complex long doublez)
¶complex _FloatN
csqrtfN(_FloatNz)
¶complex _FloatNx
csqrtfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the complex square root of the argumentz. Unlikethe real-valued functions, they are defined for all values ofz.
complex double
cpow(complex doublebase, complex doublepower)
¶complex float
cpowf(complex floatbase, complex floatpower)
¶complex long double
cpowl(complex long doublebase, complex long doublepower)
¶complex _FloatN
cpowfN(complex _FloatNbase, complex _FloatNpower)
¶complex _FloatNx
cpowfNx(complex _FloatNxbase, complex _FloatNxpower)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions returnbase raised to the power ofpower. This is equivalent tocexp (y * clog (x))
Next:Special Functions, Previous:Exponentiation and Logarithms, Up:Mathematics [Contents][Index]
The functions in this section are related to the exponential functions;seeExponentiation and Logarithms.
double
sinh(doublex)
¶float
sinhf(floatx)
¶long double
sinhl(long doublex)
¶_FloatN
sinhfN(_FloatNx)
¶_FloatNx
sinhfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the hyperbolic sine ofx, definedmathematically as(exp (x) - exp (-x)) / 2
. Theymay signal overflow ifx is too large.
double
cosh(doublex)
¶float
coshf(floatx)
¶long double
coshl(long doublex)
¶_FloatN
coshfN(_FloatNx)
¶_FloatNx
coshfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the hyperbolic cosine ofx,defined mathematically as(exp (x) + exp (-x)) / 2
.They may signal overflow ifx is too large.
double
tanh(doublex)
¶float
tanhf(floatx)
¶long double
tanhl(long doublex)
¶_FloatN
tanhfN(_FloatNx)
¶_FloatNx
tanhfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the hyperbolic tangent ofx,defined mathematically assinh (x) / cosh (x)
.They may signal overflow ifx is too large.
There are counterparts for the hyperbolic functions which takecomplex arguments.
complex double
csinh(complex doublez)
¶complex float
csinhf(complex floatz)
¶complex long double
csinhl(complex long doublez)
¶complex _FloatN
csinhfN(complex _FloatNz)
¶complex _FloatNx
csinhfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the complex hyperbolic sine ofz, definedmathematically as(exp (z) - exp (-z)) / 2
.
complex double
ccosh(complex doublez)
¶complex float
ccoshf(complex floatz)
¶complex long double
ccoshl(complex long doublez)
¶complex _FloatN
ccoshfN(complex _FloatNz)
¶complex _FloatNx
ccoshfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the complex hyperbolic cosine ofz, definedmathematically as(exp (z) + exp (-z)) / 2
.
complex double
ctanh(complex doublez)
¶complex float
ctanhf(complex floatz)
¶complex long double
ctanhl(complex long doublez)
¶complex _FloatN
ctanhfN(complex _FloatNz)
¶complex _FloatNx
ctanhfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the complex hyperbolic tangent ofz,defined mathematically ascsinh (z) / ccosh (z)
.
double
asinh(doublex)
¶float
asinhf(floatx)
¶long double
asinhl(long doublex)
¶_FloatN
asinhfN(_FloatNx)
¶_FloatNx
asinhfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the inverse hyperbolic sine ofx—thevalue whose hyperbolic sine isx.
double
acosh(doublex)
¶float
acoshf(floatx)
¶long double
acoshl(long doublex)
¶_FloatN
acoshfN(_FloatNx)
¶_FloatNx
acoshfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the inverse hyperbolic cosine ofx—thevalue whose hyperbolic cosine isx. Ifx is less than1
,acosh
signals a domain error.
double
atanh(doublex)
¶float
atanhf(floatx)
¶long double
atanhl(long doublex)
¶_FloatN
atanhfN(_FloatNx)
¶_FloatNx
atanhfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the inverse hyperbolic tangent ofx—thevalue whose hyperbolic tangent isx. If the absolute value ofx is greater than1
,atanh
signals a domain error;if it is equal to 1,atanh
returns infinity.
complex double
casinh(complex doublez)
¶complex float
casinhf(complex floatz)
¶complex long double
casinhl(complex long doublez)
¶complex _FloatN
casinhfN(complex _FloatNz)
¶complex _FloatNx
casinhfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the inverse complex hyperbolic sine ofz—the value whose complex hyperbolic sine isz.
complex double
cacosh(complex doublez)
¶complex float
cacoshf(complex floatz)
¶complex long double
cacoshl(complex long doublez)
¶complex _FloatN
cacoshfN(complex _FloatNz)
¶complex _FloatNx
cacoshfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the inverse complex hyperbolic cosine ofz—the value whose complex hyperbolic cosine isz. Unlikethe real-valued functions, there are no restrictions on the value ofz.
complex double
catanh(complex doublez)
¶complex float
catanhf(complex floatz)
¶complex long double
catanhl(complex long doublez)
¶complex _FloatN
catanhfN(complex _FloatNz)
¶complex _FloatNx
catanhfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the inverse complex hyperbolic tangent ofz—the value whose complex hyperbolic tangent isz. Unlikethe real-valued functions, there are no restrictions on the value ofz.
Next:Errors in Math Functions, Previous:Hyperbolic Functions, Up:Mathematics [Contents][Index]
These are some more exotic mathematical functions which are sometimesuseful. Currently they only have real-valued versions.
double
erf(doublex)
¶float
erff(floatx)
¶long double
erfl(long doublex)
¶_FloatN
erffN(_FloatNx)
¶_FloatNx
erffNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
erf
returns the error function ofx. The errorfunction is defined as
erf (x) = 2/sqrt(pi) * integral from 0 to x of exp(-t^2) dt
double
erfc(doublex)
¶float
erfcf(floatx)
¶long double
erfcl(long doublex)
¶_FloatN
erfcfN(_FloatNx)
¶_FloatNx
erfcfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
erfc
returns1.0 - erf(x)
, but computed in afashion that avoids round-off error whenx is large.
double
lgamma(doublex)
¶float
lgammaf(floatx)
¶long double
lgammal(long doublex)
¶_FloatN
lgammafN(_FloatNx)
¶_FloatNx
lgammafNx(_FloatNxx)
¶Preliminary:| MT-Unsafe race:signgam| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
lgamma
returns the natural logarithm of the absolute value ofthe gamma function ofx. The gamma function is defined as
gamma (x) = integral from 0 to ∞ of t^(x-1) e^-t dt
The sign of the gamma function is stored in the global variablesigngam, which is declared inmath.h. It is1
ifthe intermediate result was positive or zero, or-1
if it wasnegative.
To compute the real gamma function you can use thetgamma
function or you can compute the values as follows:
lgam = lgamma(x);gam = signgam*exp(lgam);
The gamma function has singularities at the non-positive integers.lgamma
will raise the zero divide exception if evaluated at asingularity.
double
lgamma_r(doublex, int *signp)
¶float
lgammaf_r(floatx, int *signp)
¶long double
lgammal_r(long doublex, int *signp)
¶_FloatN
lgammafN_r(_FloatNx, int *signp)
¶_FloatNx
lgammafNx_r(_FloatNxx, int *signp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
lgamma_r
is just likelgamma
, but it stores the sign ofthe intermediate result in the variable pointed to bysignpinstead of in thesigngam global. This means it is reentrant.
ThelgammafN_r
andlgammafNx_r
functions areGNU extensions.
double
gamma(doublex)
¶float
gammaf(floatx)
¶long double
gammal(long doublex)
¶Preliminary:| MT-Unsafe race:signgam| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
These functions exist for compatibility reasons. They are equivalent tolgamma
etc. It is better to uselgamma
since for one thename reflects better the actual computation, and moreoverlgamma
isstandardized in ISO C99 whilegamma
is not.
double
tgamma(doublex)
¶float
tgammaf(floatx)
¶long double
tgammal(long doublex)
¶_FloatN
tgammafN(_FloatNx)
¶_FloatNx
tgammafNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
tgamma
applies the gamma function tox. The gammafunction is defined as
gamma (x) = integral from 0 to ∞ of t^(x-1) e^-t dt
This function was introduced in ISO C99. The_FloatN
and_FloatNx
variants were introduced in ISO/IEC TS 18661-3.
double
j0(doublex)
¶float
j0f(floatx)
¶long double
j0l(long doublex)
¶_FloatN
j0fN(_FloatNx)
¶_FloatNx
j0fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
j0
returns the Bessel function of the first kind of order 0 ofx. It may signal underflow ifx is too large.
The_FloatN
and_FloatNx
variants are GNUextensions.
double
j1(doublex)
¶float
j1f(floatx)
¶long double
j1l(long doublex)
¶_FloatN
j1fN(_FloatNx)
¶_FloatNx
j1fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
j1
returns the Bessel function of the first kind of order 1 ofx. It may signal underflow ifx is too large.
The_FloatN
and_FloatNx
variants are GNUextensions.
double
jn(intn, doublex)
¶float
jnf(intn, floatx)
¶long double
jnl(intn, long doublex)
¶_FloatN
jnfN(intn, _FloatNx)
¶_FloatNx
jnfNx(intn, _FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
jn
returns the Bessel function of the first kind of ordern ofx. It may signal underflow ifx is too large.
The_FloatN
and_FloatNx
variants are GNUextensions.
double
y0(doublex)
¶float
y0f(floatx)
¶long double
y0l(long doublex)
¶_FloatN
y0fN(_FloatNx)
¶_FloatNx
y0fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
y0
returns the Bessel function of the second kind of order 0 ofx. It may signal underflow ifx is too large. Ifxis negative,y0
signals a domain error; if it is zero,y0
signals overflow and returns-∞.
The_FloatN
and_FloatNx
variants are GNUextensions.
double
y1(doublex)
¶float
y1f(floatx)
¶long double
y1l(long doublex)
¶_FloatN
y1fN(_FloatNx)
¶_FloatNx
y1fNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
y1
returns the Bessel function of the second kind of order 1 ofx. It may signal underflow ifx is too large. Ifxis negative,y1
signals a domain error; if it is zero,y1
signals overflow and returns-∞.
The_FloatN
and_FloatNx
variants are GNUextensions.
double
yn(intn, doublex)
¶float
ynf(intn, floatx)
¶long double
ynl(intn, long doublex)
¶_FloatN
ynfN(intn, _FloatNx)
¶_FloatNx
ynfNx(intn, _FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
yn
returns the Bessel function of the second kind of ordern ofx. It may signal underflow ifx is too large. Ifxis negative,yn
signals a domain error; if it is zero,yn
signals overflow and returns-∞.
The_FloatN
and_FloatNx
variants are GNUextensions.
Next:Pseudo-Random Numbers, Previous:Special Functions, Up:Mathematics [Contents][Index]
Errors are measured in “units of the last place”. This is ameasure for the relative error. For a numberz with therepresentationd.d...d·2^e (we assume IEEEfloating-point numbers with base 2) the ULP is represented by
|d.d...d - (z / 2^e)| / 2^(p - 1)
wherep is the number of bits in the mantissa of thefloating-point number representation. Ideally the error for allfunctions is always less than 0.5ulps in round-to-nearest mode. Usingrounding bits this is alsopossible and normally implemented for the basic operations. Exceptfor certain functions such assqrt
,fma
andrint
whose results are fully specified by reference to corresponding IEEE754 floating-point operations, and conversions between strings andfloating point, the GNU C Library does not aim for correctly rounded resultsfor functions in the math library, and does not aim for correctness inwhether “inexact” exceptions are raised. Instead, the goals foraccuracy of functions without fully specified results are as follows;some functions have bugs meaning they do not meet these goals in allcases. In the future, the GNU C Library may provide some other correctlyrounding functions under the names such ascrsin
proposed foran extension to ISO C.
errno
may also be set (seeError Reporting by Mathematical Functions). (The “inexact”exception may be raised, or not raised, even if this is inconsistentwith the infinite-precision value.)long double
format, as used on PowerPC GNU/Linux,the accuracy goal is weaker for input values not exactly representablein 106 bits of precision; it is as if the input value is some valuewithin 0.5ulp of the value actually passed, where “ulp” isinterpreted in terms of a fixed-precision 106-bit mantissa, but notnecessarily the exact value actually passed with discontiguousmantissa bits.long double
format, functions whose results arefully specified by reference to corresponding IEEE 754 floating-pointoperations have the same accuracy goals as other functions, but withthe error bound being the same as that for division (3ulp).Furthermore, “inexact” and “underflow” exceptions may be raisedfor all functions for any inputs, even where such exceptions areinconsistent with the returned value, since the underlyingfloating-point arithmetic has that property.Therefore many of the functions in the math library have errors. Themath testsuite only flags results larger than 9ulp (or 16 for IBMlong double
format) as errors; although most of the implementationsshow errors smaller than the limit.
A more comprehensive analysis of the GNU C Library math functions precision couldbe found in ’Accuracy of Mathematical Functions in Single, Double, DoubleExtended, and Quadruple Precision’; Brian Gladman, Vincenzo Innocente,John Mather, and Paul Zimmermann at<https://inria.hal.science/hal-03141101>. It does not cover complexfunctions, norjn
/yn
, and it is only for x86_64, and forrounding to nearest, and does not cover any architecture variations (inparticular IBMlong double
is out of scope).
For complex functions, some analysis of the GNU C Library math functions can befound in ’Accuracy of Complex Mathematical Operations and Functions in Singleand Double Precision’; Paul Caprioli, Vincenzo Innocente, Paul Zimmermannathttps://inria.hal.science/hal-04714173. It only coversfloat
anddouble
, only for x86_64, and for rounding to nearest, and does notcover any architecture variations.
Next:Is Fast Code or Small Code preferred?, Previous:Errors in Math Functions, Up:Mathematics [Contents][Index]
This section describes the GNU facilities for generating a series ofpseudo-random numbers. The numbers generated are not truly random;typically, they form a sequence that repeats periodically, with a periodso large that you can ignore it for ordinary purposes. The randomnumber generator works by remembering aseed value which it usesto compute the next random number and also to compute a new seed.
Although the generated numbers look unpredictable within one run of aprogram, the sequence of numbers isexactly the same from one runto the next. This is because the initial seed is always the same. Thisis convenient when you are debugging a program, but it is unhelpful ifyou want the program to behave unpredictably. If you want a differentpseudo-random series each time your program runs, you must specify adifferent seed each time. For ordinary purposes, basing the seed on thecurrent time works well. For random numbers in cryptography,seeGenerating Unpredictable Bytes.
You can obtain repeatable sequences of numbers on a particular machine typeby specifying the same initial seed value for the random numbergenerator. There is no standard meaning for a particular seed value;the same seed, used in different C libraries or on different CPU types,will give you different random numbers.
The GNU C Library supports the standard ISO C random number functionsplus two other sets derived from BSD and SVID. The BSD and ISO Cfunctions provide identical, somewhat limited functionality. If only asmall number of random bits are required, we recommend you use theISO C interface,rand
andsrand
. The SVID functionsprovide a more flexible interface, which allows better random numbergenerator algorithms, provides more random bits (up to 48) per call, andcan provide random floating-point numbers. These functions are requiredby the XPG standard and therefore will be present in all modern Unixsystems.
This section describes the random number functions that are part ofthe ISO C standard.
To use these facilities, you should include the header filestdlib.h in your program.
int
RAND_MAX ¶The value of this macro is an integer constant representing the largestvalue therand
function can return. In the GNU C Library, it is2147483647
, which is the largest signed integer representable in32 bits. In other libraries, it may be as low as32767
.
int
rand(void)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Therand
function returns the next pseudo-random number in theseries. The value ranges from0
toRAND_MAX
.
void
srand(unsigned intseed)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function establishesseed as the seed for a new series ofpseudo-random numbers. If you callrand
before a seed has beenestablished withsrand
, it uses the value1
as a defaultseed.
To produce a different pseudo-random series each time your program isrun, dosrand (time (0))
.
POSIX.1 extended the C standard functions to support reproducible randomnumbers in multi-threaded programs. However, the extension is badlydesigned and unsuitable for serious work.
int
rand_r(unsigned int *seed)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns a random number in the range 0 toRAND_MAX
just asrand
does. However, all its state is stored in theseed argument. This means the RNG’s state can only have as manybits as the typeunsigned int
has. This is far too few toprovide a good RNG.
If your program requires a reentrant RNG, we recommend you use thereentrant GNU extensions to the SVID random number generator. ThePOSIX.1 interface should only be used when the GNU extensions are notavailable.
Next:SVID Random Number Function, Previous:ISO C Random Number Functions, Up:Pseudo-Random Numbers [Contents][Index]
This section describes a set of random number generation functions thatare derived from BSD. There is no advantage to using these functionswith the GNU C Library; we support them for BSD compatibility only.
The prototypes for these functions are instdlib.h.
long int
random(void)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function returns the next pseudo-random number in the sequence.The value returned ranges from0
to2147483647
.
NB: Temporarily this function was defined to return aint32_t
value to indicate that the return value always contains32 bits even iflong int
is wider. The standard demands itdifferently. Users must always be aware of the 32-bit limitation,though.
void
srandom(unsigned intseed)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Thesrandom
function sets the state of the random numbergenerator based on the integerseed. If you supply aseed valueof1
, this will causerandom
to reproduce the default setof random numbers.
To produce a different set of pseudo-random numbers each time yourprogram runs, dosrandom (time (0))
.
char *
initstate(unsigned intseed, char *state, size_tsize)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Theinitstate
function is used to initialize the random numbergenerator state. The argumentstate is an array ofsizebytes, used to hold the state information. It is initialized based onseed. The size must be between 8 and 256 bytes, and should be apower of two. The bigger thestate array, the better.
The return value is the previous value of the state information array.You can use this value later as an argument tosetstate
torestore that state.
char *
setstate(char *state)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Thesetstate
function restores the random number stateinformationstate. The argument must have been the result ofa previous call toinitstate orsetstate.
The return value is the previous value of the state information array.You can use this value later as an argument tosetstate
torestore that state.
If the function fails the return value isNULL
.
The four functions described so far in this section all work on a statewhich is shared by all threads. The state is not directly accessible tothe user and can only be modified by these functions. This makes ithard to deal with situations where each thread should have its ownpseudo-random number generator.
The GNU C Library contains four additional functions which contain thestate as an explicit parameter and therefore make it possible to handlethread-local PRNGs. Besides this there is no difference. In fact, thefour functions already discussed are implemented internally using thefollowing interfaces.
Thestdlib.h header contains a definition of the following type:
Objects of typestruct random_data
contain the informationnecessary to represent the state of the PRNG. Although a completedefinition of the type is present the type should be treated as opaque.
The functions modifying the state follow exactly the already describedfunctions.
int
random_r(struct random_data *restrictbuf, int32_t *restrictresult)
¶Preliminary:| MT-Safe race:buf| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Therandom_r
function behaves exactly like therandom
function except that it uses and modifies the state in the objectpointed to by the first parameter instead of the global state.
int
srandom_r(unsigned intseed, struct random_data *buf)
¶Preliminary:| MT-Safe race:buf| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thesrandom_r
function behaves exactly like thesrandom
function except that it uses and modifies the state in the objectpointed to by the second parameter instead of the global state.
int
initstate_r(unsigned intseed, char *restrictstatebuf, size_tstatelen, struct random_data *restrictbuf)
¶Preliminary:| MT-Safe race:buf| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theinitstate_r
function behaves exactly like theinitstate
function except that it uses and modifies the state in the objectpointed to by the fourth parameter instead of the global state.
int
setstate_r(char *restrictstatebuf, struct random_data *restrictbuf)
¶Preliminary:| MT-Safe race:buf| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thesetstate_r
function behaves exactly like thesetstate
function except that it uses and modifies the state in the objectpointed to by the first parameter instead of the global state.
Next:High Quality Random Number Functions, Previous:BSD Random Number Functions, Up:Pseudo-Random Numbers [Contents][Index]
The C library on SVID systems contains yet another kind of random numbergenerator functions. They use a state of 48 bits of data. The user canchoose among a collection of functions which return the random bitsin different forms.
Generally there are two kinds of function. The first uses a state ofthe random number generator which is shared among several functions andby all threads of the process. The second requires the user to handlethe state.
All functions have in common that they use the same congruentialformula with the same constants. The formula is
Y = (a * X + c) mod m
whereX is the state of the generator at the beginning andY the state at the end.a
andc
are constantsdetermining the way the generator works. By default they are
a = 0x5DEECE66D = 25214903917c = 0xb = 11
but they can also be changed by the user.m
is of course 2^48since the state consists of a 48-bit array.
The prototypes for these functions are instdlib.h.
double
drand48(void)
¶Preliminary:| MT-Unsafe race:drand48| AS-Unsafe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function returns adouble
value in the range of0.0
to1.0
(exclusive). The random bits are determined by the globalstate of the random number generator in the C library.
Since thedouble
type according to IEEE 754 has a 52-bitmantissa this means 4 bits are not initialized by the random numbergenerator. These are (of course) chosen to be the least significantbits and they are initialized to0
.
double
erand48(unsigned short intxsubi[3])
¶Preliminary:| MT-Unsafe race:drand48| AS-Unsafe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function returns adouble
value in the range of0.0
to1.0
(exclusive), similarly todrand48
. The argument isan array describing the state of the random number generator.
This function can be called subsequently since it updates the array toguarantee random numbers. The array should have been initialized beforeinitial use to obtain reproducible results.
long int
lrand48(void)
¶Preliminary:| MT-Unsafe race:drand48| AS-Unsafe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thelrand48
function returns an integer value in the range of0
to2^31
(exclusive). Even if the size of thelongint
type can take more than 32 bits, no higher numbers are returned.The random bits are determined by the global state of the random numbergenerator in the C library.
long int
nrand48(unsigned short intxsubi[3])
¶Preliminary:| MT-Unsafe race:drand48| AS-Unsafe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is similar to thelrand48
function in that itreturns a number in the range of0
to2^31
(exclusive) butthe state of the random number generator used to produce the random bitsis determined by the array provided as the parameter to the function.
The numbers in the array are updated afterwards so that subsequent callsto this function yield different results (as is expected of a randomnumber generator). The array should have been initialized before thefirst call to obtain reproducible results.
long int
mrand48(void)
¶Preliminary:| MT-Unsafe race:drand48| AS-Unsafe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Themrand48
function is similar tolrand48
. The onlydifference is that the numbers returned are in the range-2^31
to2^31
(exclusive).
long int
jrand48(unsigned short intxsubi[3])
¶Preliminary:| MT-Unsafe race:drand48| AS-Unsafe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thejrand48
function is similar tonrand48
. The onlydifference is that the numbers returned are in the range-2^31
to2^31
(exclusive). For thexsubi
parameter the samerequirements are necessary.
The internal state of the random number generator can be initialized inseveral ways. The methods differ in the completeness of theinformation provided.
void
srand48(long intseedval)
¶Preliminary:| MT-Unsafe race:drand48| AS-Unsafe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thesrand48
function sets the most significant 32 bits of theinternal state of the random number generator to the leastsignificant 32 bits of theseedval parameter. The lower 16 bitsare initialized to the value0x330E
. Even if thelongint
type contains more than 32 bits only the lower 32 bits are used.
Owing to this limitation, initialization of the state of thisfunction is not very useful. But it makes it easy to use a constructlikesrand48 (time (0))
.
A side-effect of this function is that the valuesa
andc
from the internal state, which are used in the congruential formula,are reset to the default values given above. This is of importance oncethe user has called thelcong48
function (see below).
unsigned short int *
seed48(unsigned short intseed16v[3])
¶Preliminary:| MT-Unsafe race:drand48| AS-Unsafe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theseed48
function initializes all 48 bits of the state of theinternal random number generator from the contents of the parameterseed16v. Here the lower 16 bits of the first element ofseed16v initialize the least significant 16 bits of the internalstate, the lower 16 bits ofseed16v[1]
initialize the mid-order16 bits of the state and the 16 lower bits ofseed16v[2]
initialize the most significant 16 bits of the state.
Unlikesrand48
this function lets the user initialize all 48 bitsof the state.
The value returned byseed48
is a pointer to an array containingthe values of the internal state before the change. This might beuseful to restart the random number generator at a certain state.Otherwise the value can simply be ignored.
As forsrand48
, the valuesa
andc
from thecongruential formula are reset to the default values.
There is one more function to initialize the random number generatorwhich enables you to specify even more information by allowing you tochange the parameters in the congruential formula.
void
lcong48(unsigned short intparam[7])
¶Preliminary:| MT-Unsafe race:drand48| AS-Unsafe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thelcong48
function allows the user to change the complete stateof the random number generator. Unlikesrand48
andseed48
, this function also changes the constants in thecongruential formula.
From the seven elements in the arrayparam the least significant16 bits of the entriesparam[0]
toparam[2]
determine the initial state, the least significant 16 bits ofparam[3]
toparam[5]
determine the 48 bitconstanta
andparam[6]
determines the 16-bit valuec
.
All the above functions have in common that they use the globalparameters for the congruential formula. In multi-threaded programs itmight sometimes be useful to have different parameters in differentthreads. For this reason all the above functions have a counterpartwhich works on a description of the random number generator in theuser-supplied buffer instead of the global state.
Please note that it is no problem if several threads use the globalstate if all threads use the functions which take a pointer to an arraycontaining the state. The random numbers are computed following thesame loop but if the state in the array is different all threads willobtain an individual random number generator.
The user-supplied buffer must be of typestruct drand48_data
.This type should be regarded as opaque and not manipulated directly.
int
drand48_r(struct drand48_data *buffer, double *result)
¶Preliminary:| MT-Safe race:buffer| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is equivalent to thedrand48
function with thedifference that it does not modify the global random number generatorparameters but instead the parameters in the buffer supplied through thepointerbuffer. The random number is returned in the variablepointed to byresult.
The return value of the function indicates whether the call succeeded.If the value is less than0
an error occurred anderrno
isset to indicate the problem.
This function is a GNU extension and should not be used in portableprograms.
int
erand48_r(unsigned short intxsubi[3], struct drand48_data *buffer, double *result)
¶Preliminary:| MT-Safe race:buffer| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theerand48_r
function works likeerand48
, but in additionit takes an argumentbuffer which describes the random numbergenerator. The state of the random number generator is taken from thexsubi
array, the parameters for the congruential formula from theglobal random number generator data. The random number is returned inthe variable pointed to byresult.
The return value is non-negative if the call succeeded.
This function is a GNU extension and should not be used in portableprograms.
int
lrand48_r(struct drand48_data *buffer, long int *result)
¶Preliminary:| MT-Safe race:buffer| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is similar tolrand48
, but in addition it takes apointer to a buffer describing the state of the random number generatorjust likedrand48
.
If the return value of the function is non-negative the variable pointedto byresult contains the result. Otherwise an error occurred.
This function is a GNU extension and should not be used in portableprograms.
int
nrand48_r(unsigned short intxsubi[3], struct drand48_data *buffer, long int *result)
¶Preliminary:| MT-Safe race:buffer| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thenrand48_r
function works likenrand48
in that itproduces a random number in the range0
to2^31
. But insteadof using the global parameters for the congruential formula it uses theinformation from the buffer pointed to bybuffer. The state isdescribed by the values inxsubi.
If the return value is non-negative the variable pointed to byresult contains the result.
This function is a GNU extension and should not be used in portableprograms.
int
mrand48_r(struct drand48_data *buffer, long int *result)
¶Preliminary:| MT-Safe race:buffer| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is similar tomrand48
but like the other reentrantfunctions it uses the random number generator described by the value inthe buffer pointed to bybuffer.
If the return value is non-negative the variable pointed to byresult contains the result.
This function is a GNU extension and should not be used in portableprograms.
int
jrand48_r(unsigned short intxsubi[3], struct drand48_data *buffer, long int *result)
¶Preliminary:| MT-Safe race:buffer| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thejrand48_r
function is similar tojrand48
. Like theother reentrant functions of this function family it uses thecongruential formula parameters from the buffer pointed to bybuffer.
If the return value is non-negative the variable pointed to byresult contains the result.
This function is a GNU extension and should not be used in portableprograms.
Before any of the above functions are used the buffer of typestruct drand48_data
should be initialized. The easiest way to dothis is to fill the whole buffer with null bytes, e.g. by
memset (buffer, '\0', sizeof (struct drand48_data));
Using any of the reentrant functions of this family now willautomatically initialize the random number generator to the defaultvalues for the state and the parameters of the congruential formula.
The other possibility is to use any of the functions which explicitlyinitialize the buffer. Though it might be obvious how to initialize thebuffer from looking at the parameter to the function, it is highlyrecommended to use these functions since the result might not always bewhat you expect.
int
srand48_r(long intseedval, struct drand48_data *buffer)
¶Preliminary:| MT-Safe race:buffer| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
The description of the random number generator represented by theinformation inbuffer is initialized similarly to what the functionsrand48
does. The state is initialized from the parameterseedval and the parameters for the congruential formula areinitialized to their default values.
If the return value is non-negative the function call succeeded.
This function is a GNU extension and should not be used in portableprograms.
int
seed48_r(unsigned short intseed16v[3], struct drand48_data *buffer)
¶Preliminary:| MT-Safe race:buffer| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function is similar tosrand48_r
but likeseed48
itinitializes all 48 bits of the state from the parameterseed16v.
If the return value is non-negative the function call succeeded. Itdoes not return a pointer to the previous state of the random numbergenerator like theseed48
function does. If the user wants topreserve the state for a later re-run s/he can copy the whole bufferpointed to bybuffer.
This function is a GNU extension and should not be used in portableprograms.
int
lcong48_r(unsigned short intparam[7], struct drand48_data *buffer)
¶Preliminary:| MT-Safe race:buffer| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function initializes all aspects of the random number generatordescribed inbuffer with the data inparam. Here it isespecially true that the function does more than just copying thecontents ofparam andbuffer. More work is required andtherefore it is important to use this function rather than initializingthe random number generator directly.
If the return value is non-negative the function call succeeded.
This function is a GNU extension and should not be used in portableprograms.
Previous:SVID Random Number Function, Up:Pseudo-Random Numbers [Contents][Index]
This section describes the random number functions provided as a GNUextension, based on OpenBSD interfaces.
The GNU C Library uses kernel entropy obtained either throughgetrandom
or by reading/dev/urandom to seed.
These functions provide higher random quality than ISO, BSD, and SVIDfunctions, and may be used in cryptographic contexts.
The prototypes for these functions are instdlib.h.
uint32_t
arc4random(void)
¶| MT-Safe | AS-Unsafe corrupt| AC-Safe | SeePOSIX Safety Concepts.
This function returns a single 32-bit value in the range of0
to2^32−1
(inclusive), which is twice the range ofrand
andrandom
.
void
arc4random_buf(void *buffer, size_tlength)
¶| MT-Safe | AS-Unsafe corrupt| AC-Safe | SeePOSIX Safety Concepts.
This function fills the regionbuffer of lengthlength byteswith random data.
uint32_t
arc4random_uniform(uint32_tupper_bound)
¶| MT-Safe | AS-Unsafe corrupt| AC-Safe | SeePOSIX Safety Concepts.
This function returns a single 32-bit value, uniformly distributed butless than theupper_bound. It avoids the modulo bias when theupper bound is not a power of two.
Previous:Pseudo-Random Numbers, Up:Mathematics [Contents][Index]
If an application uses many floating point functions it is often the casethat the cost of the function calls themselves is not negligible.Modern processors can often execute the operations themselvesvery fast, but the function call disrupts the instruction pipeline.
For this reason the GNU C Library provides optimizations for many of thefrequently-used math functions. When GNU CC is used and the useractivates the optimizer, several new inline functions and macros aredefined. These new functions and macros have the same names as thelibrary functions and so are used instead of the latter. In the case ofinline functions the compiler will decide whether it is reasonable touse them, and this decision is usually correct.
This means that no calls to the library functions may be necessary, andcan increase the speed of generated code significantly. The drawback isthat code size will increase, and the increase is not always negligible.
There are two kinds of inline functions: those that give the same resultas the library functions and others that might not seterrno
andmight have a reduced precision and/or argument range in comparison withthe library functions. The latter inline functions are only availableif the flag-ffast-math
is given to GNU CC.
Not all hardware implements the entire IEEE 754 standard, and evenif it does there may be a substantial performance penalty for using someof its features. For example, enabling traps on some processors forcesthe FPU to run un-pipelined, which can more than double calculation time.
Next:Bit Manipulation, Previous:Mathematics, Up:Main Menu [Contents][Index]
This chapter contains information about functions for doing basicarithmetic operations, such as splitting a float into its integer andfractional parts or retrieving the imaginary part of a complex value.These functions are declared in the header filesmath.h andcomplex.h.
Next:Integer Division, Up:Arithmetic Functions [Contents][Index]
The C language defines several integer data types: integer, short integer,long integer, and character, all in both signed and unsigned varieties.The GNU C compiler extends the language to contain long long integersas well.
The C integer types were intended to allow code to be portable amongmachines with different inherent data sizes (word sizes), so each typemay have different ranges on different machines. The problem withthis is that a program often needs to be written for a particular rangeof integers, and sometimes must be written for a particular size ofstorage, regardless of what machine the program runs on.
To address this problem, the GNU C Library contains C type definitionsyou can use to declare integers that meet your exact needs. Because theGNU C Library header files are customized to a specific machine, yourprogram source code doesn’t have to be.
If you require that an integer be represented in exactly N bits, use oneof the following types, with the obvious mapping to bit size and signedness:
If your C compiler and target machine do not allow integers of a certainsize, the corresponding above type does not exist.
If you don’t need a specific storage size, but want the smallest datastructure withat least N bits, use one of these:
If you don’t need a specific storage size, but want the data structurethat allows the fastest access while having at least N bits (andamong data structures with the same access speed, the smallest one), useone of these:
If you want an integer with the widest range possible on the platform onwhich it is being used, use one of the following. If you use these,you should write code that takes into account the variable size and rangeof the integer.
The GNU C Library also provides macros that tell you the maximum andminimum possible values for each integer data type. The macro namesfollow these examples:INT32_MAX
,UINT8_MAX
,INT_FAST32_MIN
,INT_LEAST64_MIN
,UINTMAX_MAX
,INTMAX_MAX
,INTMAX_MIN
. Note that there are no macros forunsigned integer minima. These are always zero. Similarly, thereare macros such asINTMAX_WIDTH
for the width of these types.Those macros for integer type widths come from TS 18661-1:2014.
There are similar macros for use with C’s built in integer types whichshould come with your C compiler. These are described inData Type Measurements.
Don’t forget you can use the Csizeof
function with any of thesedata types to get the number of bytes of storage each uses.
Next:Floating Point Numbers, Previous:Integers, Up:Arithmetic Functions [Contents][Index]
This section describes functions for performing integer division. Thesefunctions are redundant when GNU CC is used, because in GNU C the‘/’ operator always rounds towards zero. But in other Cimplementations, ‘/’ may round differently with negative arguments.div
andldiv
are useful because they specify how to roundthe quotient: towards zero. The remainder has the same sign as thenumerator.
These functions are specified to return a resultr such that the valuer.quot*denominator +r.rem
equalsnumerator.
To use these facilities, you should include the header filestdlib.h in your program.
This is a structure type used to hold the result returned by thediv
function. It has the following members:
int quot
The quotient from the division.
int rem
The remainder from the division.
div_t
div(intnumerator, intdenominator)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The functiondiv
computes the quotient and remainder fromthe division ofnumerator bydenominator, returning theresult in a structure of typediv_t
.
If the result cannot be represented (as in a division by zero), thebehavior is undefined.
Here is an example, albeit not a very useful one.
div_t result;result = div (20, -6);
Nowresult.quot
is-3
andresult.rem
is2
.
This is a structure type used to hold the result returned by theldiv
function. It has the following members:
long int quot
The quotient from the division.
long int rem
The remainder from the division.
(This is identical todiv_t
except that the components are oftypelong int
rather thanint
.)
ldiv_t
ldiv(long intnumerator, long intdenominator)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theldiv
function is similar todiv
, except that thearguments are of typelong int
and the result is returned as astructure of typeldiv_t
.
This is a structure type used to hold the result returned by thelldiv
function. It has the following members:
long long int quot
The quotient from the division.
long long int rem
The remainder from the division.
(This is identical todiv_t
except that the components are oftypelong long int
rather thanint
.)
lldiv_t
lldiv(long long intnumerator, long long intdenominator)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thelldiv
function is like thediv
function, but thearguments are of typelong long int
and the result is returned asa structure of typelldiv_t
.
Thelldiv
function was added in ISO C99.
This is a structure type used to hold the result returned by theimaxdiv
function. It has the following members:
intmax_t quot
The quotient from the division.
intmax_t rem
The remainder from the division.
(This is identical todiv_t
except that the components are oftypeintmax_t
rather thanint
.)
SeeIntegers for a description of theintmax_t
type.
imaxdiv_t
imaxdiv(intmax_tnumerator, intmax_tdenominator)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theimaxdiv
function is like thediv
function, but thearguments are of typeintmax_t
and the result is returned asa structure of typeimaxdiv_t
.
SeeIntegers for a description of theintmax_t
type.
Theimaxdiv
function was added in ISO C99.
Next:Floating-Point Number Classification Functions, Previous:Integer Division, Up:Arithmetic Functions [Contents][Index]
Most computer hardware has support for two different kinds of numbers:integers (...-3, -2, -1, 0, 1, 2, 3...) andfloating-point numbers. Floating-point numbers have three parts: themantissa, theexponent, and thesign bit. The realnumber represented by a floating-point value is given by(s ? -1 : 1) · 2^e · Mwheres is the sign bit,e the exponent, andMthe mantissa. SeeFloating Point Representation Concepts, for details. (It ispossible to have a differentbase for the exponent, but all modernhardware uses2.)
Floating-point numbers can represent a finite subset of the realnumbers. While this subset is large enough for most purposes, it isimportant to remember that the only reals that can be representedexactly are rational numbers that have a terminating binary expansionshorter than the width of the mantissa. Even simple fractions such as1/5 can only be approximated by floating point.
Mathematical operations and functions frequently need to produce valuesthat are not representable. Often these values can be approximatedclosely enough for practical purposes, but sometimes they can’t.Historically there was no way to tell when the results of a calculationwere inaccurate. Modern computers implement the IEEE 754 standardfor numerical computations, which defines a framework for indicating tothe program when the results of calculation are not trustworthy. Thisframework consists of a set ofexceptions that indicate why aresult could not be represented, and the special valuesinfinityandnot a number (NaN).
Next:Errors in Floating-Point Calculations, Previous:Floating Point Numbers, Up:Arithmetic Functions [Contents][Index]
ISO C99 defines macros that let you determine what sort offloating-point number a variable holds.
int
fpclassify(float-typex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is a generic macro which works on all floating-point types andwhich returns a value of typeint
. The possible values are:
FP_NAN
¶The floating-point numberx is “Not a Number” (seeInfinity and NaN)
FP_INFINITE
¶The value ofx is either plus or minus infinity (seeInfinity and NaN)
FP_ZERO
¶The value ofx is zero. In floating-point formats like IEEE 754, where zero can be signed, this value is also returned ifx is negative zero.
FP_SUBNORMAL
¶Numbers whose absolute value is too small to be represented in thenormal format are represented in an alternate,denormalized format(seeFloating Point Representation Concepts). This format is less precise but canrepresent values closer to zero.fpclassify
returns this valuefor values ofx in this alternate format.
FP_NORMAL
¶This value is returned for all other values ofx. It indicatesthat there is nothing special about the number.
fpclassify
is most useful if more than one property of a numbermust be tested. There are more specific macros which only test oneproperty at a time. Generally these macros execute faster thanfpclassify
, since there is special hardware support for them.You should therefore use the specific macros whenever possible.
int
iscanonical(float-typex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
In some floating-point formats, some values have canonical (preferred)and noncanonical encodings (for IEEE interchange binary formats, allencodings are canonical). This macro returns a nonzero value ifx has a canonical encoding. It is from TS 18661-1:2014.
Note that some formats have multiple encodings of a value which areall equally canonical;iscanonical
returns a nonzero value forall such encodings. Also, formats may have encodings that do notcorrespond to any valid value of the type. In ISO C terms these aretrap representations; in the GNU C Library,iscanonical
returnszero for such encodings.
int
isfinite(float-typex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value ifx is finite: not plus orminus infinity, and not NaN. It is equivalent to
(fpclassify (x) != FP_NAN && fpclassify (x) != FP_INFINITE)
isfinite
is implemented as a macro which accepts anyfloating-point type.
int
isnormal(float-typex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value ifx is finite and normalized.It is equivalent to
(fpclassify (x) == FP_NORMAL)
int
isnan(float-typex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value ifx is NaN. It is equivalentto
(fpclassify (x) == FP_NAN)
int
issignaling(float-typex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value ifx is a signaling NaN(sNaN). It is from TS 18661-1:2014.
int
issubnormal(float-typex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value ifx is subnormal. It isfrom TS 18661-1:2014.
int
iszero(float-typex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value ifx is zero. It is from TS18661-1:2014.
Another set of floating-point classification functions was provided byBSD. The GNU C Library also supports these functions; however, werecommend that you use the ISO C99 macros in new code. Those are standardand will be available more widely. Also, since they are macros, you donot have to worry about the type of their argument.
int
isinf(doublex)
¶int
isinff(floatx)
¶int
isinfl(long doublex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns-1
ifx represents negative infinity,1
ifx represents positive infinity, and0
otherwise.
int
isnan(doublex)
¶int
isnanf(floatx)
¶int
isnanl(long doublex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns a nonzero value ifx is a “not a number”value, and zero otherwise.
NB: Theisnan
macro defined by ISO C99 overridesthe BSD function. This is normally not a problem, because the tworoutines behave identically. However, if you really need to get the BSDfunction for some reason, you can write
(isnan) (x)
int
finite(doublex)
¶int
finitef(floatx)
¶int
finitel(long doublex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns a nonzero value ifx is neither infinite nora “not a number” value, and zero otherwise.
Portability Note: The functions listed in this section are BSDextensions.
Next:Rounding Modes, Previous:Floating-Point Number Classification Functions, Up:Arithmetic Functions [Contents][Index]
The IEEE 754 standard defines fiveexceptions that can occurduring a calculation. Each corresponds to a particular sort of error,such as overflow.
When exceptions occur (when exceptions areraised, in the languageof the standard), one of two things can happen. By default theexception is simply noted in the floating-pointstatus word, andthe program continues as if nothing had happened. The operationproduces a default value, which depends on the exception (see the tablebelow). Your program can check the status word to find out whichexceptions happened.
Alternatively, you can enabletraps for exceptions. In that case,when an exception is raised, your program will receive theSIGFPE
signal. The default action for this signal is to terminate theprogram. SeeSignal Handling, for how you can change the effect ofthe signal.
The exceptions defined in IEEE 754 are:
This exception is raised if the given operands are invalid for theoperation to be performed. Examples are(see IEEE 754, section 7):
If the exception does not trap, the result of the operation is NaN.
This exception is raised when a finite nonzero number is dividedby zero. If no trap occurs the result is either+∞ or-∞, depending on the signs of the operands.
This exception is raised whenever the result cannot be representedas a finite value in the precision format of the destination. If no trapoccurs the result depends on the sign of the intermediate result and thecurrent rounding mode (IEEE 754, section 7.3):
Whenever the overflow exception is raised, the inexact exception is alsoraised.
The underflow exception is raised when an intermediate result is toosmall to be calculated accurately, or if the operation’s result roundedto the destination precision is too small to be normalized.
When no trap is installed for the underflow exception, underflow issignaled (via the underflow flag) only when both tininess and loss ofaccuracy have been detected. If no trap handler is installed theoperation continues with an imprecise small value, or zero if thedestination precision cannot hold the small exact result.
This exception is signalled if a rounded result is not exact (such aswhen calculating the square root of two) or a result overflows withoutan overflow trap.
Next:Examining the FPU status word, Previous:FP Exceptions, Up:Errors in Floating-Point Calculations [Contents][Index]
IEEE 754 floating point numbers can represent positive or negativeinfinity, andNaN (not a number). These three values arise fromcalculations whose result is undefined or cannot be representedaccurately. You can also deliberately set a floating-point variable toany of them, which is sometimes useful. Some examples of calculationsthat produce infinity or NaN:
1/0 = ∞log (0) = -∞sqrt (-1) = NaN
When a calculation produces any of these values, an exception alsooccurs; seeFP Exceptions.
The basic operations and math functions all accept infinity and NaN andproduce sensible output. Infinities propagate through calculations asone would expect: for example,2 + ∞ = ∞,4/∞ = 0, atan(∞) = π/2. NaN, onthe other hand, infects any calculation that involves it. Unless thecalculation would produce the same result no matter what real valuereplaced NaN, the result is NaN.
In comparison operations, positive infinity is larger than all valuesexcept itself and NaN, and negative infinity is smaller than all valuesexcept itself and NaN. NaN isunordered: it is not equal to,greater than, or less than anything,including itself.x ==x
is false if the value ofx
is NaN. You can use this to testwhether a value is NaN or not, but the recommended way to test for NaNis with theisnan
function (seeFloating-Point Number Classification Functions). Inaddition,<
,>
,<=
, and>=
will raise anexception when applied to NaNs.
math.h defines macros that allow you to explicitly set a variableto infinity or NaN.
float
INFINITY ¶An expression representing positive infinity. It is equal to the valueproduced by mathematical operations like1.0 / 0.0
.-INFINITY
represents negative infinity.
You can test whether a floating-point value is infinite by comparing itto this macro. However, this is not recommended; you should use theisfinite
macro instead. SeeFloating-Point Number Classification Functions.
This macro was introduced in the ISO C99 standard.
float
NAN ¶An expression representing a value which is “not a number”. Thismacro is a GNU extension, available only on machines that support the“not a number” value—that is to say, on all machines that supportIEEE floating point.
You can use ‘#ifdef NAN’ to test whether the machine supportsNaN. (Of course, you must arrange for GNU extensions to be visible,such as by defining_GNU_SOURCE
, and then you must includemath.h.)
float
SNANF ¶double
SNAN ¶long double
SNANL ¶_FloatN
SNANFN ¶_FloatNx
SNANFNx ¶These macros, defined by TS 18661-1:2014 and TS 18661-3:2015, areconstant expressions for signaling NaNs.
int
FE_SNANS_ALWAYS_SIGNAL ¶This macro, defined by TS 18661-1:2014, is defined to1
infenv.h to indicate that functions and operations with signalingNaN inputs and floating-point results always raise the invalidexception and return a quiet NaN, even in cases (such asfmax
,hypot
andpow
) where a quiet NaN input can produce anon-NaN result. Because some compiler optimizations may not handlesignaling NaNs correctly, this macro is only defined if compilersupport for signaling NaNs is enabled. That support can be enabledwith the GCC option-fsignaling-nans.
IEEE 754 also allows for another unusual value: negative zero. Thisvalue is produced when you divide a positive number by negativeinfinity, or when a negative result is smaller than the limits ofrepresentation.
Next:Error Reporting by Mathematical Functions, Previous:Infinity and NaN, Up:Errors in Floating-Point Calculations [Contents][Index]
ISO C99 defines functions to query and manipulate thefloating-point status word. You can use these functions to check foruntrapped exceptions when it’s convenient, rather than worrying aboutthem in the middle of a calculation.
These constants represent the various IEEE 754 exceptions. Not allFPUs report all the different exceptions. Each constant is defined ifand only if the FPU you are compiling for supports that exception, soyou can test for FPU support with ‘#ifdef’. They are defined infenv.h.
FE_INEXACT
¶The inexact exception.
FE_DIVBYZERO
¶The divide by zero exception.
FE_UNDERFLOW
¶The underflow exception.
FE_OVERFLOW
¶The overflow exception.
FE_INVALID
¶The invalid exception.
The macroFE_ALL_EXCEPT
is the bitwise OR of all exception macroswhich are supported by the FP implementation.
These functions allow you to clear exception flags, test for exceptions,and save and restore the set of exceptions flagged.
int
feclearexcept(intexcepts)
¶Preliminary:| MT-Safe | AS-Safe !posix| AC-Safe !posix| SeePOSIX Safety Concepts.
This function clears all of the supported exception flags indicated byexcepts.
The function returns zero in case the operation was successful, anon-zero value otherwise.
int
feraiseexcept(intexcepts)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function raises the supported exceptions indicated byexcepts. If more than one exception bit inexcepts is setthe order in which the exceptions are raised is undefined except thatoverflow (FE_OVERFLOW
) or underflow (FE_UNDERFLOW
) areraised before inexact (FE_INEXACT
). Whether for overflow orunderflow the inexact exception is also raised is also implementationdependent.
The function returns zero in case the operation was successful, anon-zero value otherwise.
int
fesetexcept(intexcepts)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function sets the supported exception flags indicated byexcepts, likeferaiseexcept
, but without causing enabledtraps to be taken.fesetexcept
is from TS 18661-1:2014.
The function returns zero in case the operation was successful, anon-zero value otherwise.
int
fetestexcept(intexcepts)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Test whether the exception flags indicated by the parameterexceptare currently set. If any of them are, a nonzero value is returnedwhich specifies which exceptions are set. Otherwise the result is zero.
To understand these functions, imagine that the status word is aninteger variable namedstatus.feclearexcept
is thenequivalent to ‘status &= ~excepts’ andfetestexcept
isequivalent to ‘(status & excepts)’. The actual implementation maybe very different, of course.
Exception flags are only cleared when the program explicitly requests it,by callingfeclearexcept
. If you want to check for exceptionsfrom a set of calculations, you should clear all the flags first. Hereis a simple example of the way to usefetestexcept
:
{ double f; int raised; feclearexcept (FE_ALL_EXCEPT); f = compute (); raised = fetestexcept (FE_OVERFLOW | FE_INVALID); if (raised & FE_OVERFLOW) { /* ... */ } if (raised & FE_INVALID) { /* ... */ } /* ... */}
You cannot explicitly set bits in the status word. You can, however,save the entire status word and restore it later. This is done with thefollowing functions:
int
fegetexceptflag(fexcept_t *flagp, intexcepts)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function stores in the variable pointed to byflagp animplementation-defined value representing the current setting of theexception flags indicated byexcepts.
The function returns zero in case the operation was successful, anon-zero value otherwise.
int
fesetexceptflag(const fexcept_t *flagp, intexcepts)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function restores the flags for the exceptions indicated byexcepts to the values stored in the variable pointed to byflagp.
The function returns zero in case the operation was successful, anon-zero value otherwise.
Note that the value stored infexcept_t
bears no resemblance tothe bit mask returned byfetestexcept
. The type may not even bean integer. Do not attempt to modify anfexcept_t
variable.
int
fetestexceptflag(const fexcept_t *flagp, intexcepts)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Test whether the exception flags indicated by the parameterexcepts are set in the variable pointed to byflagp. Ifany of them are, a nonzero value is returned which specifies whichexceptions are set. Otherwise the result is zero.fetestexceptflag
is from TS 18661-1:2014.
Many of the math functions are defined only over a subset of the real orcomplex numbers. Even if they are mathematically defined, their resultmay be larger or smaller than the range representable by their returntype without loss of accuracy. These are known asdomain errors,overflows, andunderflows, respectively. Math functions do several things whenone of these errors occurs. In this manual we will refer to thecomplete response assignalling a domain error, overflow, orunderflow.
When a math function suffers a domain error, it raises the invalidexception and returns NaN. It also setserrno
toEDOM
;this is for compatibility with old systems that do not support IEEE 754 exception handling. Likewise, when overflow occurs, mathfunctions raise the overflow exception and, in the default roundingmode, return∞ or-∞ as appropriate(in other rounding modes, the largest finite value of the appropriatesign is returned when appropriate for that rounding mode). They alsoseterrno
toERANGE
if returning∞ or-∞;errno
may or may not be set toERANGE
when a finite value is returned on overflow. Whenunderflow occurs, the underflow exception is raised, and zero(appropriately signed) or a subnormal value, as appropriate for themathematical result of the function and the rounding mode, isreturned.errno
may be set toERANGE
, but this is notguaranteed; it is intended that the GNU C Library should set it when theunderflow is to an appropriately signed zero, but not necessarily forother underflows.
When a math function has an argument that is a signaling NaN,the GNU C Library does not consider this a domain error, soerrno
isunchanged, but the invalid exception is still raised (except for a fewfunctions that are specified to handle signaling NaNs differently).
Some of the math functions are defined mathematically to result in acomplex value over parts of their domains. The most familiar example ofthis is taking the square root of a negative number. The complex mathfunctions, such ascsqrt
, will return the appropriate complex valuein this case. The real-valued functions, such assqrt
, willsignal a domain error.
Some older hardware does not support infinities. On that hardware,overflows instead return a particular very large number (usually thelargest representable number).math.h defines macros you can useto test for overflow on both old and new hardware.
double
HUGE_VAL ¶float
HUGE_VALF ¶long double
HUGE_VALL ¶_FloatN
HUGE_VAL_FN ¶_FloatNx
HUGE_VAL_FNx ¶An expression representing a particular very large number. On machinesthat use IEEE 754 floating point format,HUGE_VAL
is infinity.On other machines, it’s typically the largest positive number that canbe represented.
Mathematical functions return the appropriately typed version ofHUGE_VAL
or−HUGE_VAL
when the result is too largeto be represented.
Next:Floating-Point Control Functions, Previous:Errors in Floating-Point Calculations, Up:Arithmetic Functions [Contents][Index]
Floating-point calculations are carried out internally with extraprecision, and then rounded to fit into the destination type. Thisensures that results are as precise as the input data. IEEE 754defines four possible rounding modes:
This is the default mode. It should be used unless there is a specificneed for one of the others. In this mode results are rounded to thenearest representable value. If the result is midway between tworepresentable values, the even representable is chosen.Even heremeans the lowest-order bit is zero. This rounding mode preventsstatistical bias and guarantees numeric stability: round-off errors in alengthy calculation will remain smaller than half ofFLT_EPSILON
.
All results are rounded to the smallest representable valuewhich is greater than the result.
All results are rounded to the largest representable value which is lessthan the result.
All results are rounded to the largest representable value whosemagnitude is less than that of the result. In other words, if theresult is negative it is rounded up; if it is positive, it is roundeddown.
fenv.h defines constants which you can use to refer to thevarious rounding modes. Each one will be defined if and only if the FPUsupports the corresponding rounding mode.
FE_TONEAREST
¶Round to nearest.
FE_UPWARD
¶Round toward+∞.
FE_DOWNWARD
¶Round toward-∞.
FE_TOWARDZERO
¶Round toward zero.
Underflow is an unusual case. Normally, IEEE 754 floating pointnumbers are always normalized (seeFloating Point Representation Concepts).Numbers smaller than2^r (wherer is the minimum exponent,FLT_MIN_RADIX-1
forfloat) cannot be represented asnormalized numbers. Rounding all such numbers to zero or2^rwould cause some algorithms to fail at 0. Therefore, they are left indenormalized form. That produces loss of precision, since some bits ofthe mantissa are stolen to indicate the decimal point.
If a result is too small to be represented as a denormalized number, itis rounded to zero. However, the sign of the result is preserved; ifthe calculation was negative, the result isnegative zero.Negative zero can also result from some operations on infinity, such as4/-∞.
At any time, one of the above four rounding modes is selected. You canfind out which one with this function:
int
fegetround(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Returns the currently selected rounding mode, represented by one of thevalues of the defined rounding mode macros.
To change the rounding mode, use this function:
int
fesetround(intround)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Changes the currently selected rounding mode toround. Ifround does not correspond to one of the supported rounding modesnothing is changed.fesetround
returns zero if it changed therounding mode, or a nonzero value if the mode is not supported.
You should avoid changing the rounding mode if possible. It can be anexpensive operation; also, some hardware requires you to compile yourprogram differently for it to work. The resulting code may run slower.See your compiler documentation for details.
Next:Arithmetic Functions, Previous:Rounding Modes, Up:Arithmetic Functions [Contents][Index]
IEEE 754 floating-point implementations allow the programmer todecide whether traps will occur for each of the exceptions, by settingbits in thecontrol word. In C, traps result in the programreceiving theSIGFPE
signal; seeSignal Handling.
NB: IEEE 754 says that trap handlers are given details ofthe exceptional situation, and can set the result value. C signals donot provide any mechanism to pass this information back and forth.Trapping exceptions in C is therefore not very useful.
It is sometimes necessary to save the state of the floating-point unitwhile you perform some calculation. The library provides functionswhich save and restore the exception flags, the set of exceptions thatgenerate traps, and the rounding mode. This information is known as thefloating-point environment.
The functions to save and restore the floating-point environment all usea variable of typefenv_t
to store information. This type isdefined infenv.h. Its size and contents areimplementation-defined. You should not attempt to manipulate a variableof this type directly.
To save the state of the FPU, use one of these functions:
int
fegetenv(fenv_t *envp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Store the floating-point environment in the variable pointed to byenvp.
The function returns zero in case the operation was successful, anon-zero value otherwise.
int
feholdexcept(fenv_t *envp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Store the current floating-point environment in the object pointed to byenvp. Then clear all exception flags, and set the FPU to trap noexceptions. Not all FPUs support trapping no exceptions; iffeholdexcept
cannot set this mode, it returns nonzero value. If itsucceeds, it returns zero.
The functions which restore the floating-point environment can take thesekinds of arguments:
fenv_t
objects, which were initialized previously by acall tofegetenv
orfeholdexcept
.FE_DFL_ENV
which represents the floating-pointenvironment as it was available at program start.FE_
andhaving typefenv_t *
.If possible, the GNU C Library defines a macroFE_NOMASK_ENV
which represents an environment where every exception raised causes atrap to occur. You can test for this macro using#ifdef
. It isonly defined if_GNU_SOURCE
is defined.
Some platforms might define other predefined environments.
To set the floating-point environment, you can use either of thesefunctions:
int
fesetenv(const fenv_t *envp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Set the floating-point environment to that described byenvp.
The function returns zero in case the operation was successful, anon-zero value otherwise.
int
feupdateenv(const fenv_t *envp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Likefesetenv
, this function sets the floating-point environmentto that described byenvp. However, if any exceptions wereflagged in the status word beforefeupdateenv
was called, theyremain flagged after the call. In other words, afterfeupdateenv
is called, the status word is the bitwise OR of the previous status wordand the one saved inenvp.
The function returns zero in case the operation was successful, anon-zero value otherwise.
TS 18661-1:2014 defines additional functions to save and restorefloating-point control modes (such as the rounding mode and whethertraps are enabled) while leaving other status (such as raised flags)unchanged.
The special macroFE_DFL_MODE
may be passed tofesetmode
. It represents the floating-point control modes atprogram start.
int
fegetmode(femode_t *modep)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Store the floating-point control modes in the variable pointed to bymodep.
The function returns zero in case the operation was successful, anon-zero value otherwise.
int
fesetmode(const femode_t *modep)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Set the floating-point control modes to those described bymodep.
The function returns zero in case the operation was successful, anon-zero value otherwise.
To control for individual exceptions if raising them causes a trap tooccur, you can use the following two functions.
Portability Note: These functions are all GNU extensions.
int
feenableexcept(intexcepts)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function enables traps for each of the exceptions as indicated bythe parameterexcepts. The individual exceptions are described inExamining the FPU status word. Only the specified exceptions areenabled, the status of the other exceptions is not changed.
The function returns the previous enabled exceptions in case theoperation was successful,-1
otherwise.
Note: Enabling traps for an exception for which the exception flag iscurrently already set (seeExamining the FPU status word) has unspecifiedconsequences: it may or may not trigger a trap immediately.
int
fedisableexcept(intexcepts)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function disables traps for each of the exceptions as indicated bythe parameterexcepts. The individual exceptions are described inExamining the FPU status word. Only the specified exceptions aredisabled, the status of the other exceptions is not changed.
The function returns the previous enabled exceptions in case theoperation was successful,-1
otherwise.
int
fegetexcept(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The function returns a bitmask of all currently enabled exceptions. Itreturns-1
in case of failure.
Next:Complex Numbers, Previous:Floating-Point Control Functions, Up:Arithmetic Functions [Contents][Index]
The C library provides functions to do basic operations onfloating-point numbers. These include absolute value, maximum and minimum,normalization, bit twiddling, rounding, and a few others.
Next:Normalization Functions, Up:Arithmetic Functions [Contents][Index]
These functions are provided for obtaining theabsolute value (ormagnitude) of a number. The absolute value of a real numberx isx ifx is positive, −x ifx isnegative. For a complex numberz, whose real part isx andwhose imaginary part isy, the absolute value issqrt (x*x + y*y)
.
Prototypes forabs
,labs
,llabs
,uabs
,ulabs
andullabs
are instdlib.h;imaxabs
anduimaxabs
are declared ininttypes.h;thefabs
functions are declared inmath.h;thecabs
functions are declared incomplex.h.
int
abs(intnumber)
¶long int
labs(long intnumber)
¶long long int
llabs(long long intnumber)
¶unsigned int
uabs(intnumber)
¶unsigned long int
ulabs(long intnumber)
¶unsigned long long int
ullabs(long long intnumber)
¶intmax_t
imaxabs(intmax_tnumber)
¶uintmax_t
uimaxabs(intmax_tnumber)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the absolute value ofnumber.
Most computers use a two’s complement integer representation, in whichthe absolute value ofINT_MIN
(the smallest possibleint
)cannot be represented; thus,abs (INT_MIN)
is not defined.Usinguabs
avoids this.
llabs
andimaxdiv
are new to ISO C99.uabs
,ulabs
,ullabs
anduimaxabs
are new to ISO C2Y.
SeeIntegers for a description of theintmax_t
type.
double
fabs(doublenumber)
¶float
fabsf(floatnumber)
¶long double
fabsl(long doublenumber)
¶_FloatN
fabsfN(_FloatNnumber)
¶_FloatNx
fabsfNx(_FloatNxnumber)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the absolute value of the floating-point numbernumber.
double
cabs(complex doublez)
¶float
cabsf(complex floatz)
¶long double
cabsl(complex long doublez)
¶_FloatN
cabsfN(complex _FloatNz)
¶_FloatNx
cabsfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the absolute value of the complex numberz(seeComplex Numbers). The absolute value of a complex number is:
sqrt (creal (z) * creal (z) + cimag (z) * cimag (z))
This function should always be used instead of the direct formulabecause it takes special care to avoid losing precision. It may alsotake advantage of hardware support for this operation. Seehypot
inExponentiation and Logarithms.
Next:Rounding Functions, Previous:Absolute Value, Up:Arithmetic Functions [Contents][Index]
The functions described in this section are primarily provided as a wayto efficiently perform certain low-level manipulations on floating pointnumbers that are represented internally using a binary radix;seeFloating Point Representation Concepts. These functions are required tohave equivalent behavior even if the representation does not use a radixof 2, but of course they are unlikely to be particularly efficient inthose cases.
All these functions are declared inmath.h.
double
frexp(doublevalue, int *exponent)
¶float
frexpf(floatvalue, int *exponent)
¶long double
frexpl(long doublevalue, int *exponent)
¶_FloatN
frexpfN(_FloatNvalue, int *exponent)
¶_FloatNx
frexpfNx(_FloatNxvalue, int *exponent)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are used to split the numbervalueinto a normalized fraction and an exponent.
If the argumentvalue is not zero, the return value isvaluetimes a power of two, and its magnitude is always in the range 1/2(inclusive) to 1 (exclusive). The corresponding exponent is stored in*exponent
; the return value multiplied by 2 raised to thisexponent equals the original numbervalue.
For example,frexp (12.8, &exponent)
returns0.8
andstores4
inexponent
.
Ifvalue is zero, then the return value is zero andzero is stored in*exponent
.
double
ldexp(doublevalue, intexponent)
¶float
ldexpf(floatvalue, intexponent)
¶long double
ldexpl(long doublevalue, intexponent)
¶_FloatN
ldexpfN(_FloatNvalue, intexponent)
¶_FloatNx
ldexpfNx(_FloatNxvalue, intexponent)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the result of multiplying the floating-pointnumbervalue by 2 raised to the powerexponent. (It canbe used to reassemble floating-point numbers that were taken apartbyfrexp
.)
For example,ldexp (0.8, 4)
returns12.8
.
The following functions, which come from BSD, provide facilitiesequivalent to those ofldexp
andfrexp
. See also theISO C functionlogb
which originally also appeared in BSD.The_FloatN
and_FloatN
variants of thefollowing functions come from TS 18661-3:2015.
double
scalb(doublevalue, doubleexponent)
¶float
scalbf(floatvalue, floatexponent)
¶long double
scalbl(long doublevalue, long doubleexponent)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thescalb
function is the BSD name forldexp
.
double
scalbn(doublex, intn)
¶float
scalbnf(floatx, intn)
¶long double
scalbnl(long doublex, intn)
¶_FloatN
scalbnfN(_FloatNx, intn)
¶_FloatNx
scalbnfNx(_FloatNxx, intn)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
scalbn
is identical toscalb
, except that the exponentn is anint
instead of a floating-point number.
double
scalbln(doublex, long intn)
¶float
scalblnf(floatx, long intn)
¶long double
scalblnl(long doublex, long intn)
¶_FloatN
scalblnfN(_FloatNx, long intn)
¶_FloatNx
scalblnfNx(_FloatNxx, long intn)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
scalbln
is identical toscalb
, except that the exponentn is along int
instead of a floating-point number.
double
significand(doublex)
¶float
significandf(floatx)
¶long double
significandl(long doublex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
significand
returns the mantissa ofx scaled to the range[1,FLT_RADIX
).It is equivalent toscalb (x, (double) -ilogb (x))
.
This function exists mainly for use in certain standardized testsof IEEE 754 conformance.
Next:Remainder Functions, Previous:Normalization Functions, Up:Arithmetic Functions [Contents][Index]
The functions listed here perform operations such as rounding andtruncation of floating-point values. Some of these functions convertfloating point numbers to integer values. They are all declared inmath.h.
You can also convert floating-point numbers to integers simply bycasting them toint
. This discards the fractional part,effectively rounding towards zero. However, this only works if theresult can actually be represented as anint
—for very largenumbers, this is impossible. The functions listed here return theresult as adouble
instead to get around this problem.
Thefromfp
functions use the following macros, from TS18661-1:2014, to specify the direction of rounding. These correspondto the rounding directions defined in IEEE 754-2008.
FP_INT_UPWARD
¶Round toward+∞.
FP_INT_DOWNWARD
¶Round toward-∞.
FP_INT_TOWARDZERO
¶Round toward zero.
FP_INT_TONEARESTFROMZERO
¶Round to nearest, ties round away from zero.
FP_INT_TONEAREST
¶Round to nearest, ties round to even.
double
ceil(doublex)
¶float
ceilf(floatx)
¶long double
ceill(long doublex)
¶_FloatN
ceilfN(_FloatNx)
¶_FloatNx
ceilfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions roundx upwards to the nearest integer,returning that value as adouble
. Thus,ceil (1.5)
is2.0
.
double
floor(doublex)
¶float
floorf(floatx)
¶long double
floorl(long doublex)
¶_FloatN
floorfN(_FloatNx)
¶_FloatNx
floorfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions roundx downwards to the nearestinteger, returning that value as adouble
. Thus,floor(1.5)
is1.0
andfloor (-1.5)
is-2.0
.
double
trunc(doublex)
¶float
truncf(floatx)
¶long double
truncl(long doublex)
¶_FloatN
truncfN(_FloatNx)
¶_FloatNx
truncfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thetrunc
functions roundx towards zero to the nearestinteger (returned in floating-point format). Thus,trunc (1.5)
is1.0
andtrunc (-1.5)
is-1.0
.
double
rint(doublex)
¶float
rintf(floatx)
¶long double
rintl(long doublex)
¶_FloatN
rintfN(_FloatNx)
¶_FloatNx
rintfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions roundx to an integer value according to thecurrent rounding mode. SeeFloating Point Parameters, forinformation about the various rounding modes. The defaultrounding mode is to round to the nearest integer; some machinessupport other modes, but round-to-nearest is always used unlessyou explicitly select another.
Ifx was not initially an integer, these functions raise theinexact exception.
double
nearbyint(doublex)
¶float
nearbyintf(floatx)
¶long double
nearbyintl(long doublex)
¶_FloatN
nearbyintfN(_FloatNx)
¶_FloatNx
nearbyintfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the same value as therint
functions, butdo not raise the inexact exception ifx is not an integer.
double
round(doublex)
¶float
roundf(floatx)
¶long double
roundl(long doublex)
¶_FloatN
roundfN(_FloatNx)
¶_FloatNx
roundfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are similar torint
, but they round halfwaycases away from zero instead of to the nearest integer (or othercurrent rounding mode).
double
roundeven(doublex)
¶float
roundevenf(floatx)
¶long double
roundevenl(long doublex)
¶_FloatN
roundevenfN(_FloatNx)
¶_FloatNx
roundevenfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, from TS 18661-1:2014 and TS 18661-3:2015, are similartoround
, but they round halfway cases to even instead of awayfrom zero.
long int
lrint(doublex)
¶long int
lrintf(floatx)
¶long int
lrintl(long doublex)
¶long int
lrintfN(_FloatNx)
¶long int
lrintfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are just likerint
, but they return along int
instead of a floating-point number.
long long int
llrint(doublex)
¶long long int
llrintf(floatx)
¶long long int
llrintl(long doublex)
¶long long int
llrintfN(_FloatNx)
¶long long int
llrintfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are just likerint
, but they return along long int
instead of a floating-point number.
long int
lround(doublex)
¶long int
lroundf(floatx)
¶long int
lroundl(long doublex)
¶long int
lroundfN(_FloatNx)
¶long int
lroundfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are just likeround
, but they return along int
instead of a floating-point number.
long long int
llround(doublex)
¶long long int
llroundf(floatx)
¶long long int
llroundl(long doublex)
¶long long int
llroundfN(_FloatNx)
¶long long int
llroundfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are just likeround
, but they return along long int
instead of a floating-point number.
intmax_t
fromfp(doublex, intround, unsigned intwidth)
¶intmax_t
fromfpf(floatx, intround, unsigned intwidth)
¶intmax_t
fromfpl(long doublex, intround, unsigned intwidth)
¶intmax_t
fromfpfN(_FloatNx, intround, unsigned intwidth)
¶intmax_t
fromfpfNx(_FloatNxx, intround, unsigned intwidth)
¶uintmax_t
ufromfp(doublex, intround, unsigned intwidth)
¶uintmax_t
ufromfpf(floatx, intround, unsigned intwidth)
¶uintmax_t
ufromfpl(long doublex, intround, unsigned intwidth)
¶uintmax_t
ufromfpfN(_FloatNx, intround, unsigned intwidth)
¶uintmax_t
ufromfpfNx(_FloatNxx, intround, unsigned intwidth)
¶intmax_t
fromfpx(doublex, intround, unsigned intwidth)
¶intmax_t
fromfpxf(floatx, intround, unsigned intwidth)
¶intmax_t
fromfpxl(long doublex, intround, unsigned intwidth)
¶intmax_t
fromfpxfN(_FloatNx, intround, unsigned intwidth)
¶intmax_t
fromfpxfNx(_FloatNxx, intround, unsigned intwidth)
¶uintmax_t
ufromfpx(doublex, intround, unsigned intwidth)
¶uintmax_t
ufromfpxf(floatx, intround, unsigned intwidth)
¶uintmax_t
ufromfpxl(long doublex, intround, unsigned intwidth)
¶uintmax_t
ufromfpxfN(_FloatNx, intround, unsigned intwidth)
¶uintmax_t
ufromfpxfNx(_FloatNxx, intround, unsigned intwidth)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, from TS 18661-1:2014 and TS 18661-3:2015, convert afloating-point number to an integer according to the rounding directionround (one of theFP_INT_*
macros). If the integer isoutside the range of a signed or unsigned (depending on the return typeof the function) type of widthwidth bits (or outside the range ofthe return type, ifwidth is larger), or ifx is infinite orNaN, or ifwidth is zero, a domain error occurs and an unspecifiedvalue is returned. The functions with an ‘x’ in their names raisethe inexact exception when a domain error does not occur and theargument is not an integer; the other functions do not raise the inexactexception.
double
modf(doublevalue, double *integer-part)
¶float
modff(floatvalue, float *integer-part)
¶long double
modfl(long doublevalue, long double *integer-part)
¶_FloatN
modffN(_FloatNvalue, _FloatN *integer-part)
¶_FloatNx
modffNx(_FloatNxvalue, _FloatNx *integer-part)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions break the argumentvalue into an integer part and afractional part (between-1
and1
, exclusive). Their sumequalsvalue. Each of the parts has the same sign asvalue,and the integer part is always rounded toward zero.
modf
stores the integer part in*integer-part
, andreturns the fractional part. For example,modf (2.5, &intpart)
returns0.5
and stores2.0
intointpart
.
Next:Setting and modifying single bits of FP values, Previous:Rounding Functions, Up:Arithmetic Functions [Contents][Index]
The functions in this section compute the remainder on division of twofloating-point numbers. Each is a little different; pick the one thatsuits your problem.
double
fmod(doublenumerator, doubledenominator)
¶float
fmodf(floatnumerator, floatdenominator)
¶long double
fmodl(long doublenumerator, long doubledenominator)
¶_FloatN
fmodfN(_FloatNnumerator, _FloatNdenominator)
¶_FloatNx
fmodfNx(_FloatNxnumerator, _FloatNxdenominator)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions compute the remainder from the division ofnumerator bydenominator. Specifically, the return value isnumerator -n * denominator
, wherenis the quotient ofnumerator divided bydenominator, roundedtowards zero to an integer. Thus,fmod (6.5, 2.3)
returns1.9
, which is6.5
minus4.6
.
The result has the same sign as thenumerator and has magnitudeless than the magnitude of thedenominator.
Ifdenominator is zero,fmod
signals a domain error.
double
remainder(doublenumerator, doubledenominator)
¶float
remainderf(floatnumerator, floatdenominator)
¶long double
remainderl(long doublenumerator, long doubledenominator)
¶_FloatN
remainderfN(_FloatNnumerator, _FloatNdenominator)
¶_FloatNx
remainderfNx(_FloatNxnumerator, _FloatNxdenominator)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are likefmod
except that they round theinternal quotientn to the nearest integer instead of towards zeroto an integer. For example,remainder (6.5, 2.3)
returns-0.4
, which is6.5
minus6.9
.
The absolute value of the result is less than or equal to half theabsolute value of thedenominator. The difference betweenfmod (numerator,denominator)
andremainder(numerator,denominator)
is always eitherdenominator, minusdenominator, or zero.
Ifdenominator is zero,remainder
signals a domain error.
double
drem(doublenumerator, doubledenominator)
¶float
dremf(floatnumerator, floatdenominator)
¶long double
dreml(long doublenumerator, long doubledenominator)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is another name forremainder
.
Next:Floating-Point Comparison Functions, Previous:Remainder Functions, Up:Arithmetic Functions [Contents][Index]
There are some operations that are too complicated or expensive toperform by hand on floating-point numbers. ISO C99 definesfunctions to do these operations, which mostly involve changing singlebits.
double
copysign(doublex, doubley)
¶float
copysignf(floatx, floaty)
¶long double
copysignl(long doublex, long doubley)
¶_FloatN
copysignfN(_FloatNx, _FloatNy)
¶_FloatNx
copysignfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions returnx but with the sign ofy. They workeven ifx ory are NaN or zero. Both of these can carry asign (although not all implementations support it) and this is one ofthe few operations that can tell the difference.
copysign
never raises an exception.
This function is defined in IEC 559 (and the appendix withrecommended functions in IEEE 754/IEEE 854).
int
signbit(float-typex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
signbit
is a generic macro which can work on all floating-pointtypes. It returns a nonzero value if the value ofx has its signbit set.
This is not the same asx < 0.0
, because IEEE 754 floatingpoint allows zero to be signed. The comparison-0.0 < 0.0
isfalse, butsignbit (-0.0)
will return a nonzero value.
double
nextafter(doublex, doubley)
¶float
nextafterf(floatx, floaty)
¶long double
nextafterl(long doublex, long doubley)
¶_FloatN
nextafterfN(_FloatNx, _FloatNy)
¶_FloatNx
nextafterfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thenextafter
function returns the next representable neighbor ofx in the direction towardsy. The size of the step betweenx and the result depends on the type of the result. Ifx =y the function simply returnsy. If eithervalue isNaN
,NaN
is returned. Otherwisea value corresponding to the value of the least significant bit in themantissa is added or subtracted, depending on the direction.nextafter
will signal overflow or underflow if the result goesoutside of the range of normalized numbers.
This function is defined in IEC 559 (and the appendix withrecommended functions in IEEE 754/IEEE 854).
double
nexttoward(doublex, long doubley)
¶float
nexttowardf(floatx, long doubley)
¶long double
nexttowardl(long doublex, long doubley)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are identical to the corresponding versions ofnextafter
except that their second argument is alongdouble
.
double
nextup(doublex)
¶float
nextupf(floatx)
¶long double
nextupl(long doublex)
¶_FloatN
nextupfN(_FloatNx)
¶_FloatNx
nextupfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thenextup
function returns the next representable neighbor ofxin the direction of positive infinity. Ifx is the smallest negativesubnormal number in the type ofx the function returns-0
. Ifx =0
the function returns the smallest positive subnormalnumber in the type ofx. Ifx is NaN, NaN is returned.Ifx is+∞,+∞ is returned.nextup
is from TS 18661-1:2014 and TS 18661-3:2015.nextup
never raises an exception except for signaling NaNs.
double
nextdown(doublex)
¶float
nextdownf(floatx)
¶long double
nextdownl(long doublex)
¶_FloatN
nextdownfN(_FloatNx)
¶_FloatNx
nextdownfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thenextdown
function returns the next representable neighbor ofxin the direction of negative infinity. Ifx is the smallest positivesubnormal number in the type ofx the function returns+0
. Ifx =0
the function returns the smallest negative subnormalnumber in the type ofx. Ifx is NaN, NaN is returned.Ifx is-∞,-∞ is returned.nextdown
is from TS 18661-1:2014 and TS 18661-3:2015.nextdown
never raises an exception except for signaling NaNs.
double
nan(const char *tagp)
¶float
nanf(const char *tagp)
¶long double
nanl(const char *tagp)
¶_FloatN
nanfN(const char *tagp)
¶_FloatNx
nanfNx(const char *tagp)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thenan
function returns a representation of NaN, provided thatNaN is supported by the target platform.nan ("n-char-sequence")
is equivalent tostrtod ("NAN(n-char-sequence)")
.
The argumenttagp is used in an unspecified manner. On IEEE 754 systems, there are many representations of NaN, andtagpselects one. On other systems it may do nothing.
int
canonicalize(double *cx, const double *x)
¶int
canonicalizef(float *cx, const float *x)
¶int
canonicalizel(long double *cx, const long double *x)
¶int
canonicalizefN(_FloatN *cx, const _FloatN *x)
¶int
canonicalizefNx(_FloatNx *cx, const _FloatNx *x)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
In some floating-point formats, some values have canonical (preferred)and noncanonical encodings (for IEEE interchange binary formats, allencodings are canonical). These functions, defined by TS18661-1:2014 and TS 18661-3:2015, attempt to produce a canonical versionof the floating-point value pointed to byx; if that value is asignaling NaN, they raise the invalid exception and produce a quietNaN. If a canonical value is produced, it is stored in the objectpointed to bycx, and these functions return zero. Otherwise(if a canonical value could not be produced because the object pointedto byx is not a valid representation of any floating-pointvalue), the object pointed to bycx is unchanged and a nonzerovalue is returned.
Note that some formats have multiple encodings of a value which areall equally canonical; when such an encoding is used as an input tothis function, any such encoding of the same value (or of thecorresponding quiet NaN, if that value is a signaling NaN) may beproduced as output.
double
getpayload(const double *x)
¶float
getpayloadf(const float *x)
¶long double
getpayloadl(const long double *x)
¶_FloatN
getpayloadfN(const _FloatN *x)
¶_FloatNx
getpayloadfNx(const _FloatNx *x)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
IEEE 754 defines thepayload of a NaN to be an integer valueencoded in the representation of the NaN. Payloads are typicallypropagated from NaN inputs to the result of a floating-pointoperation. These functions, defined by TS 18661-1:2014 and TS18661-3:2015, return the payload of the NaN pointed to byx(returned as a positive integer, or positive zero, represented as afloating-point number); ifx is not a NaN, they return−1. They raise no floating-point exceptions even for signalingNaNs. (The return value of −1 for an argument that is not aNaN is specified in C23; the value was unspecified in TS 18661.)
int
setpayload(double *x, doublepayload)
¶int
setpayloadf(float *x, floatpayload)
¶int
setpayloadl(long double *x, long doublepayload)
¶int
setpayloadfN(_FloatN *x, _FloatNpayload)
¶int
setpayloadfNx(_FloatNx *x, _FloatNxpayload)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, defined by TS 18661-1:2014 and TS 18661-3:2015, set theobject pointed to byx to a quiet NaN with payloadpayloadand a zero sign bit and return zero. Ifpayload is not apositive-signed integer that is a valid payload for a quiet NaN of thegiven type, the object pointed to byx is set to positive zero anda nonzero value is returned. They raise no floating-point exceptions.
int
setpayloadsig(double *x, doublepayload)
¶int
setpayloadsigf(float *x, floatpayload)
¶int
setpayloadsigl(long double *x, long doublepayload)
¶int
setpayloadsigfN(_FloatN *x, _FloatNpayload)
¶int
setpayloadsigfNx(_FloatNx *x, _FloatNxpayload)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, defined by TS 18661-1:2014 and TS 18661-3:2015, set theobject pointed to byx to a signaling NaN with payloadpayload and a zero sign bit and return zero. Ifpayload isnot a positive-signed integer that is a valid payload for a signalingNaN of the given type, the object pointed to byx is set topositive zero and a nonzero value is returned. They raise nofloating-point exceptions.
Next:Miscellaneous FP arithmetic functions, Previous:Setting and modifying single bits of FP values, Up:Arithmetic Functions [Contents][Index]
The standard C comparison operators provoke exceptions when one or otherof the operands is NaN. For example,
int v = a < 1.0;
will raise an exception ifa is NaN. (This doesnothappen with==
and!=
; those merely return false and true,respectively, when NaN is examined.) Frequently this exception isundesirable. ISO C99 therefore defines comparison functions thatdo not raise exceptions when NaN is examined. All of the functions areimplemented as macros which allow their arguments to be of anyfloating-point type. The macros are guaranteed to evaluate theirarguments only once. TS 18661-1:2014 adds such a macro for anequality comparison thatdoes raise an exception for a NaNargument; it also adds functions that provide a total ordering on allfloating-point values, including NaNs, without raising any exceptionseven for signaling NaNs.
int
isgreater(real-floatingx,real-floatingy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro determines whether the argumentx is greater thany. It is equivalent to(x) > (y)
, but noexception is raised ifx ory are NaN.
int
isgreaterequal(real-floatingx,real-floatingy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro determines whether the argumentx is greater than orequal toy. It is equivalent to(x) >= (y)
, but noexception is raised ifx ory are NaN.
int
isless(real-floatingx,real-floatingy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro determines whether the argumentx is less thany.It is equivalent to(x) < (y)
, but no exception israised ifx ory are NaN.
int
islessequal(real-floatingx,real-floatingy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro determines whether the argumentx is less than or equaltoy. It is equivalent to(x) <= (y)
, but noexception is raised ifx ory are NaN.
int
islessgreater(real-floatingx,real-floatingy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro determines whether the argumentx is less or greaterthany. It is equivalent to(x) < (y) ||(x) > (y)
(although it only evaluatesx andyonce), but no exception is raised ifx ory are NaN.
This macro is not equivalent tox !=y
, because thatexpression is true ifx ory are NaN.
int
isunordered(real-floatingx,real-floatingy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro determines whether its arguments are unordered. In otherwords, it is true ifx ory are NaN, and false otherwise.
int
iseqsig(real-floatingx,real-floatingy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro determines whether its arguments are equal. It isequivalent to(x) == (y)
, but it raises the invalidexception and setserrno
toEDOM
if either argument is aNaN.
int
totalorder(const double *x, const double *y)
¶int
totalorderf(const float *x, const float *y)
¶int
totalorderl(const long double *x, const long double *y)
¶int
totalorderfN(const _FloatN *x, const _FloatN *y)
¶int
totalorderfNx(const _FloatNx *x, const _FloatNx *y)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions determine whether the total order relationship,defined in IEEE 754-2008, is true for*x
and*y
, returningnonzero if it is true and zero if it is false. No exceptions areraised even for signaling NaNs. The relationship is true if they arethe same floating-point value (including sign for zero and NaNs, andpayload for NaNs), or if*x
comes before*y
in the followingorder: negative quiet NaNs, in order of decreasing payload; negativesignaling NaNs, in order of decreasing payload; negative infinity;finite numbers, in ascending order, with negative zero before positivezero; positive infinity; positive signaling NaNs, in order ofincreasing payload; positive quiet NaNs, in order of increasingpayload.
int
totalordermag(const double *x, const double *y)
¶int
totalordermagf(const float *x, const float *y)
¶int
totalordermagl(const long double *x, const long double *y)
¶int
totalordermagfN(const _FloatN *x, const _FloatN *y)
¶int
totalordermagfNx(const _FloatNx *x, const _FloatNx *y)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions determine whether the total order relationship,defined in IEEE 754-2008, is true for the absolute values of*x
and*y
, returning nonzero if it is true and zero if it is false.No exceptions are raised even for signaling NaNs.
Not all machines provide hardware support for these operations. Onmachines that don’t, the macros can be very slow. Therefore, you shouldnot use these functions when NaN is not a concern.
NB: There are no macrosisequal
orisunequal
.They are unnecessary, because the==
and!=
operators donot throw an exception if one or both of the operands are NaN.
Previous:Floating-Point Comparison Functions, Up:Arithmetic Functions [Contents][Index]
The functions in this section perform miscellaneous but commonoperations that are awkward to express with C operators. On someprocessors these functions can use special machine instructions toperform these operations faster than the equivalent C code.
double
fmin(doublex, doubley)
¶float
fminf(floatx, floaty)
¶long double
fminl(long doublex, long doubley)
¶_FloatN
fminfN(_FloatNx, _FloatNy)
¶_FloatNx
fminfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefmin
function returns the lesser of the two valuesxandy. It is similar to the expression
((x) < (y) ? (x) : (y))
except thatx andy are only evaluated once.
If an argument is a quiet NaN, the other argument is returned. If both argumentsare NaN, or either is a signaling NaN, NaN is returned.
double
fmax(doublex, doubley)
¶float
fmaxf(floatx, floaty)
¶long double
fmaxl(long doublex, long doubley)
¶_FloatN
fmaxfN(_FloatNx, _FloatNy)
¶_FloatNx
fmaxfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefmax
function returns the greater of the two valuesxandy.
If an argument is a quiet NaN, the other argument is returned. If both argumentsare NaN, or either is a signaling NaN, NaN is returned.
double
fminimum(doublex, doubley)
¶float
fminimumf(floatx, floaty)
¶long double
fminimuml(long doublex, long doubley)
¶_FloatN
fminimumfN(_FloatNx, _FloatNy)
¶_FloatNx
fminimumfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefminimum
function returns the lesser of the two valuesxandy. Unlikefmin
, if either argument is a NaN, NaN is returned.Positive zero is treated as greater than negative zero.
double
fmaximum(doublex, doubley)
¶float
fmaximumf(floatx, floaty)
¶long double
fmaximuml(long doublex, long doubley)
¶_FloatN
fmaximumfN(_FloatNx, _FloatNy)
¶_FloatNx
fmaximumfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefmaximum
function returns the greater of the two valuesxandy. Unlikefmax
, if either argument is a NaN, NaN is returned.Positive zero is treated as greater than negative zero.
double
fminimum_num(doublex, doubley)
¶float
fminimum_numf(floatx, floaty)
¶long double
fminimum_numl(long doublex, long doubley)
¶_FloatN
fminimum_numfN(_FloatNx, _FloatNy)
¶_FloatNx
fminimum_numfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefminimum_num
function returns the lesser of the two valuesx andy. If one argument is a number and the other is aNaN, even a signaling NaN, the number is returned. Positive zero istreated as greater than negative zero.
double
fmaximum_num(doublex, doubley)
¶float
fmaximum_numf(floatx, floaty)
¶long double
fmaximum_numl(long doublex, long doubley)
¶_FloatN
fmaximum_numfN(_FloatNx, _FloatNy)
¶_FloatNx
fmaximum_numfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefmaximum_num
function returns the greater of the two valuesx andy. If one argument is a number and the other is aNaN, even a signaling NaN, the number is returned. Positive zero istreated as greater than negative zero.
double
fminmag(doublex, doubley)
¶float
fminmagf(floatx, floaty)
¶long double
fminmagl(long doublex, long doubley)
¶_FloatN
fminmagfN(_FloatNx, _FloatNy)
¶_FloatNx
fminmagfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, from TS 18661-1:2014 and TS 18661-3:2015, returnwhichever of the two valuesx andy has the smaller absolutevalue. If both have the same absolute value, or either is NaN, theybehave the same as thefmin
functions.
double
fmaxmag(doublex, doubley)
¶float
fmaxmagf(floatx, floaty)
¶long double
fmaxmagl(long doublex, long doubley)
¶_FloatN
fmaxmagfN(_FloatNx, _FloatNy)
¶_FloatNx
fmaxmagfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, from TS 18661-1:2014, return whichever of the twovaluesx andy has the greater absolute value. If bothhave the same absolute value, or either is NaN, they behave the sameas thefmax
functions.
double
fminimum_mag(doublex, doubley)
¶float
fminimum_magf(floatx, floaty)
¶long double
fminimum_magl(long doublex, long doubley)
¶_FloatN
fminimum_magfN(_FloatNx, _FloatNy)
¶_FloatNx
fminimum_magfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return whichever of the two valuesx andyhas the smaller absolute value. If both have the same absolute value,or either is NaN, they behave the same as thefminimum
functions.
double
fmaximum_mag(doublex, doubley)
¶float
fmaximum_magf(floatx, floaty)
¶long double
fmaximum_magl(long doublex, long doubley)
¶_FloatN
fmaximum_magfN(_FloatNx, _FloatNy)
¶_FloatNx
fmaximum_magfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return whichever of the two valuesx andyhas the greater absolute value. If both have the same absolute value,or either is NaN, they behave the same as thefmaximum
functions.
double
fminimum_mag_num(doublex, doubley)
¶float
fminimum_mag_numf(floatx, floaty)
¶long double
fminimum_mag_numl(long doublex, long doubley)
¶_FloatN
fminimum_mag_numfN(_FloatNx, _FloatNy)
¶_FloatNx
fminimum_mag_numfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return whichever of the two valuesx andyhas the smaller absolute value. If both have the same absolute value,or either is NaN, they behave the same as thefminimum_num
functions.
double
fmaximum_mag_num(doublex, doubley)
¶float
fmaximum_mag_numf(floatx, floaty)
¶long double
fmaximum_mag_numl(long doublex, long doubley)
¶_FloatN
fmaximum_mag_numfN(_FloatNx, _FloatNy)
¶_FloatNx
fmaximum_mag_numfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return whichever of the two valuesx andyhas the greater absolute value. If both have the same absolute value,or either is NaN, they behave the same as thefmaximum_num
functions.
double
fdim(doublex, doubley)
¶float
fdimf(floatx, floaty)
¶long double
fdiml(long doublex, long doubley)
¶_FloatN
fdimfN(_FloatNx, _FloatNy)
¶_FloatNx
fdimfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefdim
function returns the positive difference betweenx andy. The positive difference isx -y ifx is greater thany, and0 otherwise.
Ifx,y, or both are NaN, NaN is returned.
double
fma(doublex, doubley, doublez)
¶float
fmaf(floatx, floaty, floatz)
¶long double
fmal(long doublex, long doubley, long doublez)
¶_FloatN
fmafN(_FloatNx, _FloatNy, _FloatNz)
¶_FloatNx
fmafNx(_FloatNxx, _FloatNxy, _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefma
function performs floating-point multiply-add. This isthe operation(x ·y) +z, but theintermediate result is not rounded to the destination type. This cansometimes improve the precision of a calculation.
This function was introduced because some processors have a specialinstruction to perform multiply-add. The C compiler cannot use itdirectly, because the expression ‘x*y + z’ is defined to round theintermediate result.fma
lets you choose when you want to roundonly once.
On processors which do not implement multiply-add in hardware,fma
can be very slow since it must avoid intermediate rounding.math.h defines the symbolsFP_FAST_FMA
,FP_FAST_FMAF
, andFP_FAST_FMAL
when the correspondingversion offma
is no slower than the expression ‘x*y + z’.In the GNU C Library, this always means the operation is implemented inhardware.
float
fadd(doublex, doubley)
¶float
faddl(long doublex, long doubley)
¶double
daddl(long doublex, long doubley)
¶_FloatM
fMaddfN(_FloatNx, _FloatNy)
¶_FloatM
fMaddfNx(_FloatNxx, _FloatNxy)
¶_FloatMx
fMxaddfN(_FloatNx, _FloatNy)
¶_FloatMx
fMxaddfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, from TS 18661-1:2014 and TS 18661-3:2015, returnx +y, rounded once to the return type of thefunction without any intermediate rounding to the type of thearguments.
float
fsub(doublex, doubley)
¶float
fsubl(long doublex, long doubley)
¶double
dsubl(long doublex, long doubley)
¶_FloatM
fMsubfN(_FloatNx, _FloatNy)
¶_FloatM
fMsubfNx(_FloatNxx, _FloatNxy)
¶_FloatMx
fMxsubfN(_FloatNx, _FloatNy)
¶_FloatMx
fMxsubfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, from TS 18661-1:2014 and TS 18661-3:2015, returnx -y, rounded once to the return type of thefunction without any intermediate rounding to the type of thearguments.
float
fmul(doublex, doubley)
¶float
fmull(long doublex, long doubley)
¶double
dmull(long doublex, long doubley)
¶_FloatM
fMmulfN(_FloatNx, _FloatNy)
¶_FloatM
fMmulfNx(_FloatNxx, _FloatNxy)
¶_FloatMx
fMxmulfN(_FloatNx, _FloatNy)
¶_FloatMx
fMxmulfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, from TS 18661-1:2014 and TS 18661-3:2015, returnx *y, rounded once to the return type of thefunction without any intermediate rounding to the type of thearguments.
float
fdiv(doublex, doubley)
¶float
fdivl(long doublex, long doubley)
¶double
ddivl(long doublex, long doubley)
¶_FloatM
fMdivfN(_FloatNx, _FloatNy)
¶_FloatM
fMdivfNx(_FloatNxx, _FloatNxy)
¶_FloatMx
fMxdivfN(_FloatNx, _FloatNy)
¶_FloatMx
fMxdivfNx(_FloatNxx, _FloatNxy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, from TS 18661-1:2014 and TS 18661-3:2015, returnx /y, rounded once to the return type of thefunction without any intermediate rounding to the type of thearguments.
float
fsqrt(doublex)
¶float
fsqrtl(long doublex)
¶double
dsqrtl(long doublex)
¶_FloatM
fMsqrtfN(_FloatNx)
¶_FloatM
fMsqrtfNx(_FloatNxx)
¶_FloatMx
fMxsqrtfN(_FloatNx)
¶_FloatMx
fMxsqrtfNx(_FloatNxx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, from TS 18661-1:2014 and TS 18661-3:2015, return thesquare root ofx, rounded once to the return type of thefunction without any intermediate rounding to the type of thearguments.
float
ffma(doublex, doubley, doublez)
¶float
ffmal(long doublex, long doubley, long doublez)
¶double
dfmal(long doublex, long doubley, long doublez)
¶_FloatM
fMfmafN(_FloatNx, _FloatNy, _FloatNz)
¶_FloatM
fMfmafNx(_FloatNxx, _FloatNxy, _FloatNxz)
¶_FloatMx
fMxfmafN(_FloatNx, _FloatNy, _FloatNz)
¶_FloatMx
fMxfmafNx(_FloatNxx, _FloatNxy, _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions, from TS 18661-1:2014 and TS 18661-3:2015, return(x ·y) +z, rounded once to the returntype of the function without any intermediate rounding to the type ofthe arguments and without any intermediate rounding of result of themultiplication.
Next:Projections, Conjugates, and Decomposing of Complex Numbers, Previous:Arithmetic Functions, Up:Arithmetic Functions [Contents][Index]
ISO C99 introduces support for complex numbers in C. This is donewith a new type qualifier,complex
. It is a keyword if and onlyifcomplex.h has been included. There are three complex types,corresponding to the three real types:float complex
,double complex
, andlong double complex
.
Likewise, on machines that have support for_FloatN
or_FloatNx
enabled, the complex types_FloatNcomplex
and_FloatNx complex
are also available ifcomplex.h has been included; seeMathematics.
To construct complex numbers you need a way to indicate the imaginarypart of a number. There is no standard notation for an imaginaryfloating point constant. Instead,complex.h defines two macrosthat can be used to create complex numbers.
const float complex
_Complex_I ¶This macro is a representation of the complex number “0+1i”.Multiplying a real floating-point value by_Complex_I
gives acomplex number whose value is purely imaginary. You can use this toconstruct complex constants:
3.0 + 4.0i =3.0 + 4.0 * _Complex_I
Note that_Complex_I * _Complex_I
has the value-1
, butthe type of that value iscomplex
.
_Complex_I
is a bit of a mouthful.complex.h also definesa shorter name for the same constant.
const float complex
I ¶This macro has exactly the same value as_Complex_I
. Most of thetime it is preferable. However, it causes problems if you want to usethe identifierI
for something else. You can safely write
#include <complex.h>#undef I
if you needI
for your own purposes. (In that case we recommendyou also define some other short name for_Complex_I
, such asJ
.)
Next:Parsing of Numbers, Previous:Complex Numbers, Up:Arithmetic Functions [Contents][Index]
ISO C99 also defines functions that perform basic operations oncomplex numbers, such as decomposition and conjugation. The prototypesfor all these functions are incomplex.h. All functions areavailable in three variants, one for each of the three complex types.
double
creal(complex doublez)
¶float
crealf(complex floatz)
¶long double
creall(complex long doublez)
¶_FloatN
crealfN(complex _FloatNz)
¶_FloatNx
crealfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the real part of the complex numberz.
double
cimag(complex doublez)
¶float
cimagf(complex floatz)
¶long double
cimagl(complex long doublez)
¶_FloatN
cimagfN(complex _FloatNz)
¶_FloatNx
cimagfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the imaginary part of the complex numberz.
complex double
conj(complex doublez)
¶complex float
conjf(complex floatz)
¶complex long double
conjl(complex long doublez)
¶complex _FloatN
conjfN(complex _FloatNz)
¶complex _FloatNx
conjfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the conjugate value of the complex numberz. The conjugate of a complex number has the same real part and anegated imaginary part. In other words, ‘conj(a + bi) = a + -bi’.
double
carg(complex doublez)
¶float
cargf(complex floatz)
¶long double
cargl(complex long doublez)
¶_FloatN
cargfN(complex _FloatNz)
¶_FloatNx
cargfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the argument of the complex numberz.The argument of a complex number is the angle in the complex planebetween the positive real axis and a line passing through zero and thenumber. This angle is measured in the usual fashion and ranges from-π toπ.
carg
has a branch cut along the negative real axis.
complex double
cproj(complex doublez)
¶complex float
cprojf(complex floatz)
¶complex long double
cprojl(complex long doublez)
¶complex _FloatN
cprojfN(complex _FloatNz)
¶complex _FloatNx
cprojfNx(complex _FloatNxz)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions return the projection of the complex valuez ontothe Riemann sphere. Values with an infinite imaginary part are projectedto positive infinity on the real axis, even if the real part is NaN. Ifthe real part is infinite, the result is equivalent to
INFINITY + I * copysign (0.0, cimag (z))
Next:Printing of Floats, Previous:Projections, Conjugates, and Decomposing of Complex Numbers, Up:Arithmetic Functions [Contents][Index]
This section describes functions for “reading” integer andfloating-point numbers from a string. It may be more convenient in somecases to usesscanf
or one of the related functions; seeFormatted Input. But often you can make a program more robust byfinding the tokens in the string by hand, then converting the numbersone by one.
Next:Parsing of Floats, Up:Parsing of Numbers [Contents][Index]
The ‘str’ functions are declared instdlib.h and thosebeginning with ‘wcs’ are declared inwchar.h. One mightwonder about the use ofrestrict
in the prototypes of thefunctions in this section. It is seemingly useless but the ISO Cstandard uses it (for the functions defined there) so we have to do itas well.
long int
strtol(const char *restrictstring, char **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrtol
(“string-to-long”) function converts the initialpart ofstring to a signed integer, which is returned as a valueof typelong int
.
This function attempts to decomposestring as follows:
isspace
function(seeClassification of Characters). These are discarded.Ifbase is zero, decimal radix is assumed unless the series ofdigits begins with ‘0’ (specifying octal radix), or ‘0x’ or‘0X’ (specifying hexadecimal radix), or ‘0b’ or ‘0B’(specifying binary radix; only supported when C23 features areenabled); in other words, the same syntax used for integer constants in C.
Otherwisebase must have a value between2
and36
.Ifbase is16
, the digits may optionally be preceded by‘0x’ or ‘0X’. Ifbase is2
, and C23 featuresare enabled, the digits may optionally be preceded by‘0b’ or ‘0B’. If base has no legal value the value returnedis0l
and the global variableerrno
is set toEINVAL
.
strtol
stores a pointer to this tail in*tailptr
.If the string is empty, contains only whitespace, or does not contain aninitial substring that has the expected syntax for an integer in thespecifiedbase, no conversion is performed. In this case,strtol
returns a value of zero and the value stored in*tailptr
is the value ofstring.
In a locale other than the standard"C"
locale, this functionmay recognize additional implementation-dependent syntax.
If the string has valid syntax for an integer but the value is notrepresentable because of overflow,strtol
returns eitherLONG_MAX
orLONG_MIN
(seeRange of an Integer Type), asappropriate for the sign of the value. It also setserrno
toERANGE
to indicate there was overflow.
You should not check for errors by examining the return value ofstrtol
, because the string might be a valid representation of0l
,LONG_MAX
, orLONG_MIN
. Instead, check whethertailptr points to what you expect after the number(e.g.'\0'
if the string should end after the number). You alsoneed to clearerrno
before the call and check it afterward, incase there was overflow.
There is an example at the end of this section.
long int
wcstol(const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcstol
function is equivalent to thestrtol
functionin nearly all aspects but handles wide character strings.
Thewcstol
function was introduced in Amendment 1 of ISO C90.
unsigned long int
strtoul(const char *restrictstring, char **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrtoul
(“string-to-unsigned-long”) function is likestrtol
except it converts to anunsigned long int
value.The syntax is the same as described above forstrtol
. The valuereturned on overflow isULONG_MAX
(seeRange of an Integer Type).
Ifstring depicts a negative number,strtoul
acts the sameasstrtol but casts the result to an unsigned integer. That meansfor example thatstrtoul
on"-1"
returnsULONG_MAX
and an input more negative thanLONG_MIN
returns(ULONG_MAX
+ 1) / 2.
strtoul
setserrno
toEINVAL
ifbase is out ofrange, orERANGE
on overflow.
unsigned long int
wcstoul(const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcstoul
function is equivalent to thestrtoul
functionin nearly all aspects but handles wide character strings.
Thewcstoul
function was introduced in Amendment 1 of ISO C90.
long long int
strtoll(const char *restrictstring, char **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrtoll
function is likestrtol
except that it returnsalong long int
value, and accepts numbers with a correspondinglylarger range.
If the string has valid syntax for an integer but the value is notrepresentable because of overflow,strtoll
returns eitherLLONG_MAX
orLLONG_MIN
(seeRange of an Integer Type), asappropriate for the sign of the value. It also setserrno
toERANGE
to indicate there was overflow.
Thestrtoll
function was introduced in ISO C99.
long long int
wcstoll(const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcstoll
function is equivalent to thestrtoll
functionin nearly all aspects but handles wide character strings.
Thewcstoll
function was introduced in Amendment 1 of ISO C90.
long long int
strtoq(const char *restrictstring, char **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
strtoq
(“string-to-quad-word”) is the BSD name forstrtoll
.
long long int
wcstoq(const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcstoq
function is equivalent to thestrtoq
functionin nearly all aspects but handles wide character strings.
Thewcstoq
function is a GNU extension.
unsigned long long int
strtoull(const char *restrictstring, char **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrtoull
function is related tostrtoll
the same waystrtoul
is related tostrtol
.
Thestrtoull
function was introduced in ISO C99.
unsigned long long int
wcstoull(const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcstoull
function is equivalent to thestrtoull
functionin nearly all aspects but handles wide character strings.
Thewcstoull
function was introduced in Amendment 1 of ISO C90.
unsigned long long int
strtouq(const char *restrictstring, char **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
strtouq
is the BSD name forstrtoull
.
unsigned long long int
wcstouq(const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcstouq
function is equivalent to thestrtouq
functionin nearly all aspects but handles wide character strings.
Thewcstouq
function is a GNU extension.
intmax_t
strtoimax(const char *restrictstring, char **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrtoimax
function is likestrtol
except that it returnsaintmax_t
value, and accepts numbers of a corresponding range.
If the string has valid syntax for an integer but the value is notrepresentable because of overflow,strtoimax
returns eitherINTMAX_MAX
orINTMAX_MIN
(seeIntegers), asappropriate for the sign of the value. It also setserrno
toERANGE
to indicate there was overflow.
SeeIntegers for a description of theintmax_t
type. Thestrtoimax
function was introduced in ISO C99.
intmax_t
wcstoimax(const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcstoimax
function is equivalent to thestrtoimax
functionin nearly all aspects but handles wide character strings.
Thewcstoimax
function was introduced in ISO C99.
uintmax_t
strtoumax(const char *restrictstring, char **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrtoumax
function is related tostrtoimax
the same way thatstrtoul
is related tostrtol
.
SeeIntegers for a description of theintmax_t
type. Thestrtoumax
function was introduced in ISO C99.
uintmax_t
wcstoumax(const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcstoumax
function is equivalent to thestrtoumax
functionin nearly all aspects but handles wide character strings.
Thewcstoumax
function was introduced in ISO C99.
long int
atol(const char *string)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thestrtol
function with abaseargument of10
, except that it need not detect overflow errors.Theatol
function is provided mostly for compatibility withexisting code; usingstrtol
is more robust.
int
atoi(const char *string)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is likeatol
, except that it returns anint
.Theatoi
function is also considered obsolete; usestrtol
instead.
long long int
atoll(const char *string)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar toatol
, except it returns alonglong int
.
Theatoll
function was introduced in ISO C99. It too isobsolete (despite having just been added); usestrtoll
instead.
All the functions mentioned in this section so far do not handlealternative representations of characters as described in the localedata. Some locales specify thousands separator and the way they have tobe used which can help to make large numbers more readable. To readsuch numbers one has to use thescanf
functions with the ‘'’flag.
Here is a function which parses a string as a sequence of integers andreturns the sum of them:
intsum_ints_from_string (char *string){ int sum = 0; while (1) { char *tail; int next; /*Skip whitespace by hand, to detect the end. */ while (isspace (*string)) string++; if (*string == 0) break; /*There is more nonwhitespace, */ /*so it ought to be another number. */ errno = 0; /*Parse it. */ next = strtol (string, &tail, 0); /*Add it in, if not overflow. */ if (errno) printf ("Overflow\n"); else sum += next; /*Advance past it. */ string = tail; } return sum;}
Previous:Parsing of Integers, Up:Parsing of Numbers [Contents][Index]
The ‘str’ functions are declared instdlib.h and thosebeginning with ‘wcs’ are declared inwchar.h. One mightwonder about the use ofrestrict
in the prototypes of thefunctions in this section. It is seemingly useless but the ISO Cstandard uses it (for the functions defined there) so we have to do itas well.
double
strtod(const char *restrictstring, char **restricttailptr)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestrtod
(“string-to-double”) function converts the initialpart ofstring to a floating-point number, which is returned as avalue of typedouble
.
This function attempts to decomposestring as follows:
isspace
function(seeClassification of Characters). These are discarded.The hexadecimal format is as follows:
*tailptr
.If the string is empty, contains only whitespace, or does not contain aninitial substring that has the expected syntax for a floating-pointnumber, no conversion is performed. In this case,strtod
returnsa value of zero and the value returned in*tailptr
is thevalue ofstring.
In a locale other than the standard"C"
or"POSIX"
locales,this function may recognize additional locale-dependent syntax.
If the string has valid syntax for a floating-point number but the valueis outside the range of adouble
,strtod
will signaloverflow or underflow as described inError Reporting by Mathematical Functions.
strtod
recognizes four special input strings. The strings"inf"
and"infinity"
are converted to∞,or to the largest representable value if the floating-point formatdoesn’t support infinities. You can prepend a"+"
or"-"
to specify the sign. Case is ignored when scanning these strings.
The strings"nan"
and"nan(chars…)"
are convertedto NaN. Again, case is ignored. Ifchars… are provided, theyare used in some unspecified fashion to select a particularrepresentation of NaN (there can be several).
Since zero is a valid result as well as the value returned on error, youshould check for errors in the same way as forstrtol
, byexaminingerrno
andtailptr.
float
strtof(const char *string, char **tailptr)
¶long double
strtold(const char *string, char **tailptr)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are analogous tostrtod
, but returnfloat
andlong double
values respectively. They report errors in thesame way asstrtod
.strtof
can be substantially fasterthanstrtod
, but has less precision; conversely,strtold
can be much slower but has more precision (on systems wherelongdouble
is a separate type).
These functions have been GNU extensions and are new to ISO C99.
_FloatN
strtofN(const char *string, char **tailptr)
¶_FloatNx
strtofNx(const char *string, char **tailptr)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
These functions are likestrtod
, except for the return type.
They were introduced in ISO/IEC TS 18661-3 and are available on machinesthat support the related types; seeMathematics.
double
wcstod(const wchar_t *restrictstring, wchar_t **restricttailptr)
¶float
wcstof(const wchar_t *string, wchar_t **tailptr)
¶long double
wcstold(const wchar_t *string, wchar_t **tailptr)
¶_FloatN
wcstofN(const wchar_t *string, wchar_t **tailptr)
¶_FloatNx
wcstofNx(const wchar_t *string, wchar_t **tailptr)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewcstod
,wcstof
,wcstol
,wcstofN
,andwcstofNx
functions are equivalent in nearly all aspectsto thestrtod
,strtof
,strtold
,strtofN
, andstrtofNx
functions, but theyhandle wide character strings.
Thewcstod
function was introduced in Amendment 1 of ISO C90. Thewcstof
andwcstold
functions were introduced inISO C99.
ThewcstofN
andwcstofNx
functions are not inany standard, but are added to provide completeness for thenon-deprecated interface of wide character string to floating-pointconversion functions. They are only available on machines that supportthe related types; seeMathematics.
double
atof(const char *string)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar to thestrtod
function, except that itneed not detect overflow and underflow errors. Theatof
functionis provided mostly for compatibility with existing code; usingstrtod
is more robust.
The GNU C Library also provides ‘_l’ versions of these functions,which take an additional argument, the locale to use in conversion.
See alsoParsing of Integers.
Next:Old-fashioned System V number-to-string functions, Previous:Parsing of Numbers, Up:Arithmetic Functions [Contents][Index]
The ‘strfrom’ functions are declared instdlib.h.
int
strfromd(char *restrictstring, size_tsize, const char *restrictformat, doublevalue)
¶int
strfromf(char *restrictstring, size_tsize, const char *restrictformat, floatvalue)
¶int
strfroml(char *restrictstring, size_tsize, const char *restrictformat, long doublevalue)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
The functionsstrfromd
(“string-from-double”),strfromf
(“string-from-float”), andstrfroml
(“string-from-long-double”)convert the floating-point numbervalue to a string of characters andstores them into the area pointed to bystring. The conversionwrites at mostsize characters and respects the format specified byformat.
The format string must start with the character ‘%’. An optionalprecision follows, which starts with a period, ‘.’, and may befollowed by a decimal integer, representing the precision. If a decimalinteger is not specified after the period, the precision is taken to bezero. The character ‘*’ is not allowed. Finally, the format stringends with one of the following conversion specifiers: ‘a’, ‘A’,‘e’, ‘E’, ‘f’, ‘F’, ‘g’ or ‘G’ (seeTable of Output Conversions). Invalid format strings result in undefinedbehavior.
These functions return the number of characters that would have beenwritten tostring hadsize been sufficiently large, notcounting the terminating null character. Thus, the null-terminated outputhas been completely written if and only if the returned value is less thansize.
These functions were introduced by ISO/IEC TS 18661-1.
int
strfromfN(char *restrictstring, size_tsize, const char *restrictformat, _FloatNvalue)
¶int
strfromfNx(char *restrictstring, size_tsize, const char *restrictformat, _FloatNxvalue)
¶Preliminary:| MT-Safe locale| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
These functions are likestrfromd
, except for the type ofvalue
.
They were introduced in ISO/IEC TS 18661-3 and are available on machinesthat support the related types; seeMathematics.
Previous:Printing of Floats, Up:Arithmetic Functions [Contents][Index]
The old System V C library provided three functions to convertnumbers to strings, with unusual and hard-to-use semantics. The GNU C Libraryalso provides these functions and some natural extensions.
These functions are only available in the GNU C Library and on systems descendedfrom AT&T Unix. Therefore, unless these functions do precisely what youneed, it is better to usesprintf
, which is standard.
All these functions are defined instdlib.h.
char *
ecvt(doublevalue, intndigit, int *decpt, int *neg)
¶Preliminary:| MT-Unsafe race:ecvt| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
The functionecvt
converts the floating-point numbervalueto a string with at mostndigit decimal digits. Thereturned string contains no decimal point or sign. The first digit ofthe string is non-zero (unlessvalue is actually zero) and thelast digit is rounded to nearest.*decpt
is set to theindex in the string of the first digit after the decimal point.*neg
is set to a nonzero value ifvalue is negative,zero otherwise.
Ifndigit decimal digits would exceed the precision of adouble
it is reduced to a system-specific value.
The returned string is statically allocated and overwritten by each calltoecvt
.
Ifvalue is zero, it is implementation defined whether*decpt
is0
or1
.
For example:ecvt (12.3, 5, &d, &n)
returns"12300"
and setsd to2
andn to0
.
char *
fcvt(doublevalue, intndigit, int *decpt, int *neg)
¶Preliminary:| MT-Unsafe race:fcvt| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
The functionfcvt
is likeecvt
, butndigit specifiesthe number of digits after the decimal point. Ifndigit is lessthan zero,value is rounded to thendigit+1’th place to theleft of the decimal point. For example, ifndigit is-1
,value will be rounded to the nearest 10. Ifndigit isnegative and larger than the number of digits to the left of the decimalpoint invalue,value will be rounded to one significant digit.
Ifndigit decimal digits would exceed the precision of adouble
it is reduced to a system-specific value.
The returned string is statically allocated and overwritten by each calltofcvt
.
char *
gcvt(doublevalue, intndigit, char *buf)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
gcvt
is functionally equivalent to ‘sprintf(buf, "%*g",ndigit, value)’. It is provided only for compatibility’s sake. Itreturnsbuf.
Ifndigit decimal digits would exceed the precision of adouble
it is reduced to a system-specific value.
As extensions, the GNU C Library provides versions of these threefunctions that takelong double
arguments.
char *
qecvt(long doublevalue, intndigit, int *decpt, int *neg)
¶Preliminary:| MT-Unsafe race:qecvt| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
This function is equivalent toecvt
except that it takes along double
for the first parameter and thatndigit isrestricted by the precision of along double
.
char *
qfcvt(long doublevalue, intndigit, int *decpt, int *neg)
¶Preliminary:| MT-Unsafe race:qfcvt| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function is equivalent tofcvt
except that ittakes along double
for the first parameter and thatndigit isrestricted by the precision of along double
.
char *
qgcvt(long doublevalue, intndigit, char *buf)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is equivalent togcvt
except that it takes along double
for the first parameter and thatndigit isrestricted by the precision of along double
.
Theecvt
andfcvt
functions, and theirlong double
equivalents, all return a string located in a static buffer which isoverwritten by the next call to the function. The GNU C Libraryprovides another set of extended functions which write the convertedstring into a user-supplied buffer. These have the conventional_r
suffix.
gcvt_r
is not necessary, becausegcvt
already uses auser-supplied buffer.
int
ecvt_r(doublevalue, intndigit, int *decpt, int *neg, char *buf, size_tlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theecvt_r
function is the same asecvt
, exceptthat it places its result into the user-specified buffer pointed to bybuf, with lengthlen. The return value is-1
incase of an error and zero otherwise.
This function is a GNU extension.
int
fcvt_r(doublevalue, intndigit, int *decpt, int *neg, char *buf, size_tlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thefcvt_r
function is the same asfcvt
, except that itplaces its result into the user-specified buffer pointed to bybuf, with lengthlen. The return value is-1
incase of an error and zero otherwise.
This function is a GNU extension.
int
qecvt_r(long doublevalue, intndigit, int *decpt, int *neg, char *buf, size_tlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theqecvt_r
function is the same asqecvt
, exceptthat it places its result into the user-specified buffer pointed to bybuf, with lengthlen. The return value is-1
incase of an error and zero otherwise.
This function is a GNU extension.
int
qfcvt_r(long doublevalue, intndigit, int *decpt, int *neg, char *buf, size_tlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theqfcvt_r
function is the same asqfcvt
, exceptthat it places its result into the user-specified buffer pointed to bybuf, with lengthlen. The return value is-1
incase of an error and zero otherwise.
This function is a GNU extension.
Next:Date and Time, Previous:Arithmetic Functions, Up:Main Menu [Contents][Index]
This chapter contains information about functions and macros fordetermining the endianness of integer types and manipulating the bitsof unsigned integers. These functions and macros are from ISO C23 andare declared in the header filestdbit.h.
The following macros describe the endianness of integer types. Theyhave values that are integer constant expressions.
This macro represents little-endian storage.
This macro represents big-endian storage.
This macro equals__STDC_ENDIAN_LITTLE__
if integer types arestored in memory in little-endian format, and equals__STDC_ENDIAN_BIG__
if integer types are stored in memory inbig-endian format.
The following functions manipulate the bits of unsigned integers.Each function family has functions for the typesunsigned char
,unsigned short
,unsigned int
,unsigned long int
andunsigned long long int
. In addition, there is acorresponding type-generic macro (not listed below), named the same asthe functions but without any suffix such as ‘_uc’. Thetype-generic macro can only be used with an argument of an unsignedinteger type with a width of 8, 16, 32 or 64 bits, or when usinga compiler with support for__builtin_stdc_bit_ceil
,etc., built-in functions such as GCC 14.1 or laterany unsigned integer type those built-in functions support.In GCC 14.1 that includes support forunsigned __int128
andunsigned _BitInt(n)
if supported by the target.
unsigned int
stdc_leading_zeros_uc(unsigned charx)
¶unsigned int
stdc_leading_zeros_us(unsigned shortx)
¶unsigned int
stdc_leading_zeros_ui(unsigned intx)
¶unsigned int
stdc_leading_zeros_ul(unsigned long intx)
¶unsigned int
stdc_leading_zeros_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_leading_zeros
functions count the number of leading(most significant) zero bits inx, starting from the mostsignificant bit of the argument type. Ifx is zero, they returnthe width ofx in bits.
unsigned int
stdc_leading_ones_uc(unsigned charx)
¶unsigned int
stdc_leading_ones_us(unsigned shortx)
¶unsigned int
stdc_leading_ones_ui(unsigned intx)
¶unsigned int
stdc_leading_ones_ul(unsigned long intx)
¶unsigned int
stdc_leading_ones_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_leading_ones
functions count the number of leading(most significant) one bits inx, starting from the mostsignificant bit of the argument type.
unsigned int
stdc_trailing_zeros_uc(unsigned charx)
¶unsigned int
stdc_trailing_zeros_us(unsigned shortx)
¶unsigned int
stdc_trailing_zeros_ui(unsigned intx)
¶unsigned int
stdc_trailing_zeros_ul(unsigned long intx)
¶unsigned int
stdc_trailing_zeros_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_trailing_zeros
functions count the number of trailing(least significant) zero bits inx, starting from the leastsignificant bit of the argument type. Ifx is zero, they returnthe width ofx in bits.
unsigned int
stdc_trailing_ones_uc(unsigned charx)
¶unsigned int
stdc_trailing_ones_us(unsigned shortx)
¶unsigned int
stdc_trailing_ones_ui(unsigned intx)
¶unsigned int
stdc_trailing_ones_ul(unsigned long intx)
¶unsigned int
stdc_trailing_ones_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_trailing_ones
functions count the number of trailing(least significant) one bits inx, starting from the leastsignificant bit of the argument type.
unsigned int
stdc_first_leading_zero_uc(unsigned charx)
¶unsigned int
stdc_first_leading_zero_us(unsigned shortx)
¶unsigned int
stdc_first_leading_zero_ui(unsigned intx)
¶unsigned int
stdc_first_leading_zero_ul(unsigned long intx)
¶unsigned int
stdc_first_leading_zero_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_first_leading_zero
functions return the position ofthe most significant zero bit inx, counting from the mostsignificant bit ofx as 1, or zero if there is no zero bit inx.
unsigned int
stdc_first_leading_one_uc(unsigned charx)
¶unsigned int
stdc_first_leading_one_us(unsigned shortx)
¶unsigned int
stdc_first_leading_one_ui(unsigned intx)
¶unsigned int
stdc_first_leading_one_ul(unsigned long intx)
¶unsigned int
stdc_first_leading_one_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_first_leading_one
functions return the position of themost significant one bit inx, counting from the mostsignificant bit ofx as 1, or zero if there is no one bit inx.
unsigned int
stdc_first_trailing_zero_uc(unsigned charx)
¶unsigned int
stdc_first_trailing_zero_us(unsigned shortx)
¶unsigned int
stdc_first_trailing_zero_ui(unsigned intx)
¶unsigned int
stdc_first_trailing_zero_ul(unsigned long intx)
¶unsigned int
stdc_first_trailing_zero_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_first_trailing_zero
functions return the position ofthe least significant zero bit inx, counting from the leastsignificant bit ofx as 1, or zero if there is no zero bit inx.
unsigned int
stdc_first_trailing_one_uc(unsigned charx)
¶unsigned int
stdc_first_trailing_one_us(unsigned shortx)
¶unsigned int
stdc_first_trailing_one_ui(unsigned intx)
¶unsigned int
stdc_first_trailing_one_ul(unsigned long intx)
¶unsigned int
stdc_first_trailing_one_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_first_trailing_one
functions return the position ofthe least significant one bit inx, counting from the leastsignificant bit ofx as 1, or zero if there is no one bit inx.
unsigned int
stdc_count_zeros_uc(unsigned charx)
¶unsigned int
stdc_count_zeros_us(unsigned shortx)
¶unsigned int
stdc_count_zeros_ui(unsigned intx)
¶unsigned int
stdc_count_zeros_ul(unsigned long intx)
¶unsigned int
stdc_count_zeros_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_count_zeros
functions count the number of zero bits inx.
unsigned int
stdc_count_ones_uc(unsigned charx)
¶unsigned int
stdc_count_ones_us(unsigned shortx)
¶unsigned int
stdc_count_ones_ui(unsigned intx)
¶unsigned int
stdc_count_ones_ul(unsigned long intx)
¶unsigned int
stdc_count_ones_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_count_ones
functions count the number of one bits inx.
_Bool
stdc_has_single_bit_uc(unsigned charx)
¶_Bool
stdc_has_single_bit_us(unsigned shortx)
¶_Bool
stdc_has_single_bit_ui(unsigned intx)
¶_Bool
stdc_has_single_bit_ul(unsigned long intx)
¶_Bool
stdc_has_single_bit_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_has_single_bit
functions return whetherx hasexactly one bit set to one.
unsigned int
stdc_bit_width_uc(unsigned charx)
¶unsigned int
stdc_bit_width_us(unsigned shortx)
¶unsigned int
stdc_bit_width_ui(unsigned intx)
¶unsigned int
stdc_bit_width_ul(unsigned long intx)
¶unsigned int
stdc_bit_width_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_bit_width
functions return the minimum number of bitsneeded to storex, not counting leading zero bits. Ifxis zero, they return zero.
unsigned char
stdc_bit_floor_uc(unsigned charx)
¶unsigned short
stdc_bit_floor_us(unsigned shortx)
¶unsigned int
stdc_bit_floor_ui(unsigned intx)
¶unsigned long int
stdc_bit_floor_ul(unsigned long intx)
¶unsigned long long int
stdc_bit_floor_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_bit_floor
functions return the largest integer powerof two that is less than or equal tox. Ifx is zero,they return zero.
unsigned char
stdc_bit_ceil_uc(unsigned charx)
¶unsigned short
stdc_bit_ceil_us(unsigned shortx)
¶unsigned int
stdc_bit_ceil_ui(unsigned intx)
¶unsigned long int
stdc_bit_ceil_ul(unsigned long intx)
¶unsigned long long int
stdc_bit_ceil_ull(unsigned long long intx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thestdc_bit_ceil
functions return the smallest integer powerof two that is greater than or equal tox. If this cannot berepresented in the return type, they return zero.
Next:Resource Usage And Limitation, Previous:Bit Manipulation, Up:Main Menu [Contents][Index]
This chapter describes functions for manipulating dates and times,including functions for determining what time it is and conversionbetween different time representations.
Next:Time Types, Up:Date and Time [Contents][Index]
Discussing time in a technical manual can be difficult because the word“time” in English refers to lots of different things. In this manual,we use a rigorous terminology to avoid confusion, and the only thing weuse the simple word “time” for is to talk about the abstract concept.
Acalendar time, sometimes called “absolute time”,is a point in the Earth’s time continuum, for exampleJune 9, 2024, at 13:50:06.5 Coordinated Universal Time (UTC).UTC, formerly called Greenwich Mean Time, is the primary timestandard on Earth, and is the basis for civil time and time zones.
We don’t speak of a “date”, because that is inherent in a calendartime.
Aninterval is a contiguous part of the time continuum between twocalendar times, for example the hour on June 9, 2024,between 13:00 and 14:00 UTC.
Anelapsed time is the length of an interval, for example, 35minutes. People sometimes sloppily use the word “interval” to referto the elapsed time of some interval.
Anamount of time is a sum of elapsed times, which need not be ofany specific intervals. For example, the amount of time it takes toread a book might be 9 hours, independently of when and in how manysittings it is read.
Aperiod is the elapsed time of an interval between two events,especially when they are part of a sequence of regularly repeatingevents.
Asimple calendar time is a calendar time represented as anelapsed time since a fixed, implementation-specific calendar timecalled theepoch. This representation is convenient for doingcalculations on calendar times, such as finding the elapsed timebetween two calendar times. Simple calendar times are independent oftime zone; they represent the same instant in time regardless of whereon the globe the computer is.
POSIX says that simple calendar times do not include leap seconds, butsome (otherwise POSIX-conformant) systems can be configured to includeleap seconds in simple calendar times.
Abroken-down time is a calendar time represented by itscomponents in the Gregorian calendar: year, month, day, hour, minute,and second. A broken-down time value is relative to a specific timezone, and so it is also sometimes called alocal time.Broken-down times are most useful for input and output, as they areeasier for people to understand, but more difficult to calculate with.
Atime zone is a single fixed offset from UTC, along withatime zone abbreviation that is a string of charactersthat can include ASCII alphanumerics, ‘+’, and ‘-’.For example, the current time zone in Japan is9 hours ahead (east) of the Prime Meridian with abbreviation"JST"
.
Atime zone ruleset maps each simple calendar time to a singletime zone. For example, Paris’s time zone ruleset might list over adozen time zones that Paris has experienced during its history.
CPU time measures the amount of time that a single process hasactively used a CPU to perform computations. It does not include thetime that process has spent waiting for external events. The systemtracks the CPU time used by each process separately.
Processor time measures the amount of timeany CPU hasbeen in use byany process. It is a basic system resource,since there’s a limit to how much can exist in any given interval (theelapsed time of the interval times the number of CPUs in the computer)
People often call this CPU time, but we reserve the latter term inthis manual for the definition above.
Next:Calculating Elapsed Time, Previous:Time Basics, Up:Date and Time [Contents][Index]
ISO C and POSIX define several data types for representing elapsedtimes, simple calendar times, and broken-down times.
clock_t
is used to measure processor and CPU time.It may be an integer or a floating-point type.Its values are counts ofclock ticks since some arbitrary eventin the past.The number of clock ticks per second is system-specific.SeeProcessor And CPU Time, for further detail.
time_t
is the simplest data type used to represent simplecalendar time.
In ISO C,time_t
can be either an integer or a real floatingtype, and the meaning oftime_t
values is not specified. Theonly things a strictly conforming program can do withtime_t
values are: pass them todifftime
to get the elapsed timebetween two simple calendar times (seeCalculating Elapsed Time),and pass them to the functions that convert them to broken-down time(seeBroken-down Time).
On POSIX-conformant systems,time_t
is an integer type and itsvalues represent the number of seconds elapsed since thePOSIX Epoch,which is January 1, 1970, at 00:00:00 Coordinated Universal Time (UTC).The count of seconds ignores leap seconds. Additionally, POSIX.1-2024added the requirement thattime_t
be at least 64 bits wide.
The GNU C Library additionally guarantees thattime_t
is a signedtype, and that all of its functions operate correctly on negativetime_t
values, which are interpreted as times before the POSIX Epoch.Functions likelocaltime
assume the Gregorian calendar and UTCeven though this is historically inaccurate for dates before 1582,for times before 1960, and for timestamps after the Gregorian calendarand UTC will become obsolete.The GNU C Library also supports leap seconds as an option, in which casetime_t
counts leap seconds instead of ignoring them.Currently thetime_t
type is 64 bits wide on all platformssupported by the GNU C Library, except that it is 32 bits wide on a fewolder platforms unless you define_TIME_BITS
to 64.SeeFeature Test Macros.
struct timespec
represents a simple calendar time, or anelapsed time, with sub-second resolution. It is declared intime.h and has the following members:
time_t tv_sec
The number of whole seconds elapsed since the epoch (for a simplecalendar time) or since some other starting point (for an elapsedtime).
long int tv_nsec
The number of nanoseconds elapsed since the time given by thetv_sec
member.
Whenstruct timespec
values are produced by GNU C Libraryfunctions, the value in this field will always be greater than orequal to zero, and less than 1,000,000,000.Whenstruct timespec
values are supplied to GNU C Libraryfunctions, the value in this field must be in the same range.
struct timeval
is an older type for representing a simplecalendar time, or an elapsed time, with sub-second resolution. It isalmost the same asstruct timespec
, but provides onlymicrosecond resolution. It is declared insys/time.h and hasthe following members:
time_t tv_sec
The number of whole seconds elapsed since the epoch (for a simplecalendar time) or since some other starting point (for an elapsedtime).
long int tv_usec
The number of microseconds elapsed since the time given by thetv_sec
member.
Whenstruct timeval
values are produced by GNU C Libraryfunctions, the value in this field will always be greater than orequal to zero, and less than 1,000,000.Whenstruct timeval
values are supplied to GNU C Libraryfunctions, the value in this field must be in the same range.
This is the data type used to represent a broken-down time. It hasseparate fields for year, month, day, and so on.SeeBroken-down Time, for further details.
Next:Processor And CPU Time, Previous:Time Types, Up:Date and Time [Contents][Index]
Often, one wishes to calculate an elapsed time as the differencebetween two simple calendar times. The GNU C Library provides only onefunction for this purpose.
double
difftime(time_tend, time_tbegin)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thedifftime
function returns the number of seconds of elapsedtime from calendar timebegin to calendar timeend, asa value of typedouble
.
On POSIX-conformant systems, the advantage of using‘difftime (end,begin)’ over ‘end -begin’is that it will not overflow even ifend andbegin are so far apart that a simple subtractionwould overflow. However, if they are so far apart that adouble
cannot exactly represent the difference, the result will be inexact.
On other systems,time_t
values might be encoded in a way thatprevents subtraction from working directly, and thendifftime
would be the only way to compute their difference.
The GNU C Library does not provide any functions for computing thedifference between two values of typestruct timespec
orstruct timeval
. Here is one way to do thiscalculation by hand. It works even on peculiar operating systemswhere thetv_sec
member has an unsigned type.
#include <stdckdint.h>#include <time.h>/*Put into *R the difference between X and Y. Return true if overflow occurs, false otherwise. */booltimespec_subtract (struct timespec *r, struct timespec x, struct timespec y){ /*Compute nanoseconds, settingborrow to 1 or 0 for propagation into seconds. */ long int nsec_diff = x.tv_nsec - y.tv_nsec; bool borrow = nsec_diff < 0; r->tv_nsec = nsec_diff + 1000000000 * borrow; /*Compute seconds, returning true if this overflows. */ bool v = ckd_sub (&r->tv_sec, x.tv_sec, y.tv_sec); return v ^ ckd_sub (&r->tv_sec, r->tv_sec, borrow);}
Next:Calendar Time, Previous:Calculating Elapsed Time, Up:Date and Time [Contents][Index]
If you’re trying to optimize your program or measure its efficiency,it’s very useful to know how much processor time it uses. For that,calendar time and elapsed times are useless because a process may spendtime waiting for I/O or for other processes to use the CPU. However,you can get the information with the functions in this section.
CPU time (seeTime Basics) is represented by the data typeclock_t
, which is a number ofclock ticks. It gives thetotal amount of time a process has actively used a CPU since somearbitrary event. On GNU systems, that event is the creation of theprocess. While arbitrary in general, the event is always the same eventfor any particular process, so you can always measure how much time onthe CPU a particular computation takes by examining the process’ CPUtime before and after the computation.
The number of clock ticks per second.
On GNU/Linux and GNU/Hurd systems,clock_t
is equivalent tolong int
andCLOCKS_PER_SEC
is an integer value. But in other systems, bothclock_t
and the macroCLOCKS_PER_SEC
can be either integeror floating-point types. Converting CPU time values todouble
can help code be more portable no matter what the underlyingrepresentation is.
Note that the clock can wrap around. On a 32bit system withCLOCKS_PER_SEC
set to one million this function will return thesame value approximately every 72 minutes.
For additional functions to examine a process’ use of processor time,and to control it, seeResource Usage And Limitation.
Next:Processor Time Inquiry, Up:Processor And CPU Time [Contents][Index]
To get a process’ CPU time, you can use theclock
function. Thisfacility is declared in the header filetime.h.
In typical usage, you call theclock
function at the beginningand end of the interval you want to time, subtract the values, and thendivide byCLOCKS_PER_SEC
(the number of clock ticks per second)to get processor time, like this:
#include <time.h>clock_t start, end;double cpu_time_used;start = clock();... /*Do the work. */end = clock();cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
Do not use a single CPU time as an amount of time; it doesn’t work thatway. Either do a subtraction as shown above or query processor timedirectly. SeeProcessor Time Inquiry.
Different computers and operating systems vary wildly in how they keeptrack of CPU time. It’s common for the internal processor clockto have a resolution somewhere between a hundredth and millionth of asecond.
int
CLOCKS_PER_SEC ¶The value of this macro is the number of clock ticks per second measuredby theclock
function. POSIX requires that this value be onemillion independent of the actual resolution.
clock_t
clock(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the calling process’ current CPU time. If the CPUtime is not available or cannot be represented,clock
returns thevalue(clock_t)(-1)
.
Previous:CPU Time Inquiry, Up:Processor And CPU Time [Contents][Index]
Thetimes
function returns information about a process’consumption of processor time in astruct tms
object, inaddition to the process’ CPU time. SeeTime Basics. You shouldinclude the header filesys/times.h to use this facility.
Thetms
structure is used to return information about processtimes. It contains at least the following members:
clock_t tms_utime
This is the total processor time the calling process has used inexecuting the instructions of its program.
clock_t tms_stime
This is the processor time the system has used on behalf of the callingprocess.
clock_t tms_cutime
This is the sum of thetms_utime
values and thetms_cutime
values of all terminated child processes of the calling process, whosestatus has been reported to the parent process bywait
orwaitpid
; seeProcess Completion. In other words, itrepresents the total processor time used in executing the instructionsof all the terminated child processes of the calling process, excludingchild processes which have not yet been reported bywait
orwaitpid
.
clock_t tms_cstime
This is similar totms_cutime
, but represents the total processortime the system has used on behalf of all the terminated child processesof the calling process.
All of the times are given in numbers of clock ticks. Unlike CPU time,these are the actual amounts of time; not relative to any event.SeeCreating a Process.
int
CLK_TCK ¶This is an obsolete name for the number of clock ticks per second. Usesysconf (_SC_CLK_TCK)
instead.
clock_t
times(struct tms *buffer)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thetimes
function stores the processor time information forthe calling process inbuffer.
The return value is the number of clock ticks since an arbitrary pointin the past, e.g. since system start-up.times
returns(clock_t)(-1)
to indicate failure.
Portability Note: Theclock
function described inCPU Time Inquiry is specified by the ISO C standard. Thetimes
function is a feature of POSIX.1. On GNU systems, theCPU time is defined to be equivalent to the sum of thetms_utime
andtms_stime
fields returned bytimes
.
Next:Setting an Alarm, Previous:Processor And CPU Time, Up:Date and Time [Contents][Index]
This section describes the functions for getting, setting, andmanipulating calendar times.
TZ
Next:Setting and Adjusting the Time, Up:Calendar Time [Contents][Index]
The GNU C Library provides several functions for getting the currentcalendar time, with different levels of resolution.
time_t
time(time_t *result)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is the simplest function for getting the current calendar time.It returns the calendar time as a value of typetime_t
; onPOSIX systems, that means it has a resolution of one second. Ituses the same clock as ‘clock_gettime (CLOCK_REALTIME_COARSE)’,when the clock is available or ‘clock_gettime (CLOCK_REALTIME)’otherwise.
If the argumentresult is not a null pointer, the calendar timevalue is also stored in*result
.
This function cannot fail.
Some applications need more precise timekeeping than is possible withatime_t
alone. Some applications also need more control overwhat is meant by “the current time.” For these applications,POSIX and ISO C provide functions to retrieve the timewith up to nanosecond precision, from a variety of different clocks.Clocks can be system-wide, measuring time the same for all processes;or they can be per-process or per-thread, measuring CPU time consumedby a particular process, or some other similar resource. Each clockhas its own resolution and epoch. POSIX and ISO C also provide functionsfor finding the resolution of a clock. There is no function toget the epoch for a clock; either it is fixed and documented, or theclock is not meant to be used to measure absolute times.
The typeclockid_t
is used for constants that indicate which ofseveral POSIX system clocks one wishes to use.
All systems that support the POSIX functions will define at leastthis clock constant:
clockid_t
CLOCK_REALTIME ¶This POSIX clock uses the POSIX Epoch, 1970-01-01 00:00:00 UTC.It is close to, but not necessarily in lock-step with, theclocks oftime
(above) and ofgettimeofday
(below).
A second clock constant which is not universal, but still very common,is for a clock measuringmonotonic time. Monotonic time isuseful for measuring elapsed times, because it guarantees that thosemeasurements are not affected by changes to the system clock.
clockid_t
CLOCK_MONOTONIC ¶This system-wide POSIX clock continuously measures the advancement ofcalendar time, ignoring discontinuous changes to the system’ssetting for absolute calendar time.
The epoch for this clock is an unspecified point in the past.The epoch may change if the system is rebooted or suspended.Therefore,CLOCK_MONOTONIC
cannot be used to measureabsolute time, only elapsed time.
The following clocks are defined by POSIX, but may not be supported byall POSIX systems:
clockid_t
CLOCK_PROCESS_CPUTIME_ID ¶This POSIX clock measures the amount of CPU time used by the callingprocess.
clockid_t
CLOCK_THREAD_CPUTIME_ID ¶This POSIX clock measures the amount of CPU time used by the callingthread.
The following clocks are Linux extensions:
clockid_t
CLOCK_MONOTONIC_RAW ¶clockid_t
CLOCK_REALTIME_COARSE ¶clockid_t
CLOCK_MONOTONIC_COARSE ¶clockid_t
CLOCK_BOOTTIME ¶clockid_t
CLOCK_REALTIME_ALARM ¶clockid_t
CLOCK_BOOTTIME_ALARM ¶clockid_t
CLOCK_TAI ¶For details of these clocks, see the manual pageclock_gettime(2)SeeLinux (The Linux Kernel).
Systems may support additional clocks beyond those listed here.
int
clock_gettime(clockid_tclock, struct timespec *ts)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Get the current time according to the clock identified byclock,storing it as seconds and nanoseconds in*ts
.SeeTime Types, for a description ofstruct timespec
.
The return value is0
on success and-1
on failure. Thefollowingerrno
error condition is defined for this function:
EINVAL
The clock identified byclock is not supported.
clock_gettime
reports the time scaled to seconds andnanoseconds, but the actual resolution of each clock may not be asfine as one nanosecond, and may not be the same for all clocks. POSIXalso provides a function for finding out the actual resolution of aclock:
int
clock_getres(clockid_tclock, struct timespec *res)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Get the actual resolution of the clock identified byclock,storing it in*ts
.
For instance, if the clock hardware forCLOCK_REALTIME
uses a quartz crystal that oscillates at 32.768 kHz,then its resolution would be 30.518 microseconds,and ‘clock_getres (CLOCK_REALTIME, &r)’ would setr.tv_sec
to 0 andr.tv_nsec
to 30518.
The return value is0
on success and-1
on failure. Thefollowingerrno
error condition is defined for this function:
EINVAL
The clock identified byclock is not supported.
Portability Note: On some systems, including systems that useolder versions of the GNU C Library, programs that useclock_gettime
orclock_setres
must be linked with the-lrt
library.This has not been necessary with the GNU C Library since version 2.17.
The following ISO C macros and functions for higher-resolutiontimestamps were standardized more recently than the POSIX functions,so they are less portable to older POSIX systems. However, the ISO C functions are portable to C platforms that do not support POSIX.
int
TIME_UTC ¶This is a positive integer constant designating a simple calendar time base.In the GNU C Library and other POSIX systems,this is equivalent to the POSIXCLOCK_REALTIME
clock.On non-POSIX systems, though, the epoch is implementation-defined.
Systems may support more than just this ISO C clock.
int
timespec_get(struct timespec *ts, intbase)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Store into*ts
the current time according to the ISO C timebase.
The return value isbase on success and0
on failure.
int
timespec_getres(struct timespec *res, intbase)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Ifts is non-null, store into*ts
the resolution ofthe time provided bytimespec_get
function for the ISO Ctimebase.
The return value isbase on success and0
on failure.
The previous functions, data types and constants are declared intime.h.The GNU C Library also provides an older functionfor getting the current time with a resolution of microseconds. Thisfunction is declared insys/time.h.
int
gettimeofday(struct timeval *tp, void *tzp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Get the current calendar time, storing it as seconds and microsecondsin*tp
. SeeTime Types, for a description ofstruct timeval
. The clock ofgettimeofday
is close to,but not necessarily in lock-step with, the clocks oftime
and of‘clock_gettime (CLOCK_REALTIME)’ (see above).
On some historic systems, iftzp was not a null pointer,information about a system-wide time zone would be written to*tzp
. This feature is obsolete and not supported onGNU systems. You should always supply a null pointer for thisargument. Instead, use the facilities described inBroken-down Time for working with time zones.
This function cannot fail, and its return value is always0
.
Portability Note: POSIX.1-2024 removed this function.Although the GNU C Library will continue to provide it indefinitely,portable programs should useclock_gettime
ortimespec_get
instead.
Next:Broken-down Time, Previous:Getting the Time, Up:Calendar Time [Contents][Index]
The clock hardware inside a modern computer is quite reliable, but itcan still be wrong. The functions in this section allow one to setthe system’s idea of the current calendar time, and to adjust the rateat which the system counts seconds, so that the calendar time willboth be accurate, and remain accurate.
The functions in this section require special privileges to use.SeeUsers and Groups.
int
clock_settime(clockid_tclock, const struct timespec *ts)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Change the current calendar time, according to the clock identified byclock, to be the simple calendar time in*ts
.
Not all of the system’s clocks can be changed. For instance, theCLOCK_REALTIME
clock can be changed (with the appropriateprivileges), but theCLOCK_MONOTONIC
clock cannot.
Because simple calendar times are independent of time zone, thisfunction should not be used when the time zone changes (e.g. if thecomputer is physically moved from one zone to another). Instead, usethe facilities described inState Variables for Time Zones.
clock_settime
causes the clock to jump forwards or backwards,which can cause a variety of problems. Changing theCLOCK_REALTIME
clock withclock_settime
does not affectwhen timers expire (seeSetting an Alarm) or when sleepingprocesses wake up (seeSleeping), which avoids some of theproblems. Still, for small changes made while the system is running,it is better to usentp_adjtime
(below) to make a smoothtransition from one time to another.
The return value is0
on success and-1
on failure. Thefollowingerrno
error conditions are defined for this function:
EINVAL
The clock identified byclock is not supported or cannot be setat all, or the simple calendar time in*ts
is invalid(for instance,ts->tv_nsec
is negative or greater than 999,999,999).
EPERM
This process does not have the privileges required to set the clockidentified byclock.
Portability Note: On some systems, including systems that useolder versions of the GNU C Library, programs that useclock_settime
must be linked with the-lrt
library. This has not beennecessary with the GNU C Library since version 2.17.
For systems that remain up and running for long periods, it is notenough to set the time once; one should alsodiscipline theclock so that it does not drift away from the true calendar time.
Thentp_gettime
andntp_adjtime
functions provide aninterface to monitor and discipline the system clock. For example,you can fine-tune the rate at which the clock “ticks,” and makesmall adjustments to the current reported calendar time smoothly, bytemporarily speeding up or slowing down the clock.
These functions’ names begin with ‘ntp_’ because they weredesigned for use by programs implementing the Network Time Protocol tosynchronize a system’s clock with other systems’ clocks and/or withexternal high-precision clock hardware.
These functions, and the constants and structures they use, aredeclared insys/timex.h.
This structure is used to report information about the system clock.It contains the following members:
struct timeval time
The current calendar time, as if retrieved bygettimeofday
.Thestruct timeval
data type is described inTime Types.
long int maxerror
This is the maximum error, measured in microseconds. Unless updatedviantp_adjtime
periodically, this value will reach someplatform-specific maximum value.
long int esterror
This is the estimated error, measured in microseconds. This value canbe set byntp_adjtime
to indicate the estimated offset of thesystem clock from the true calendar time.
int
ntp_gettime(struct ntptimeval *tptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thentp_gettime
function sets the structure pointed to bytptr to current values. The elements of the structure afterwardscontain the values the timer implementation in the kernel assumes. Theymight or might not be correct. If they are not, anntp_adjtime
call is necessary.
The return value is0
on success and other values on failure. Thefollowingerrno
error conditions are defined for this function:
TIME_ERROR
¶The precision clock model is not properly set up at the moment, thus theclock must be considered unsynchronized, and the values should betreated with care.
This structure is used to control and monitor the system clock. Itcontains the following members:
unsigned int modes
This variable controls whether and which values are set. Severalsymbolic constants have to be combined withbinary or to specifythe effective mode. These constants start withMOD_
.
long int offset
This value indicates the current offset of the system clock from the truecalendar time. The value is given in microseconds. If bitMOD_OFFSET
is set inmodes
, the offset (and possibly otherdependent values) can be set. The offset’s absolute value must notexceedMAXPHASE
.
long int frequency
This value indicates the difference in frequency between the truecalendar time and the system clock. The value is expressed as scaledPPM (parts per million, 0.0001%). The scaling is1 <<SHIFT_USEC
. The value can be set with bitMOD_FREQUENCY
, butthe absolute value must not exceedMAXFREQ
.
long int maxerror
This is the maximum error, measured in microseconds. A new value can beset using bitMOD_MAXERROR
. Unless updated viantp_adjtime
periodically, this value will increase steadilyand reach some platform-specific maximum value.
long int esterror
This is the estimated error, measured in microseconds. This value canbe set using bitMOD_ESTERROR
.
int status
This variable reflects the various states of the clock machinery. Thereare symbolic constants for the significant bits, starting withSTA_
. Some of these flags can be updated using theMOD_STATUS
bit.
long int constant
This value represents the bandwidth or stiffness of the PLL (phaselocked loop) implemented in the kernel. The value can be changed usingbitMOD_TIMECONST
.
long int precision
This value represents the accuracy or the maximum error when reading thesystem clock. The value is expressed in microseconds.
long int tolerance
This value represents the maximum frequency error of the system clock inscaled PPM. This value is used to increase themaxerror
everysecond.
struct timeval time
The current calendar time.
long int tick
The elapsed time between clock ticks in microseconds. A clock tick is aperiodic timer interrupt on which the system clock is based.
long int ppsfreq
This is the first of a few optional variables that are present only ifthe system clock can use a PPS (pulse per second) signal to disciplinethe system clock. The value is expressed in scaled PPM and it denotesthe difference in frequency between the system clock and the PPS signal.
long int jitter
This value expresses a median filtered average of the PPS signal’sdispersion in microseconds.
int shift
This value is a binary exponent for the duration of the PPS calibrationinterval, ranging fromPPS_SHIFT
toPPS_SHIFTMAX
.
long int stabil
This value represents the median filtered dispersion of the PPSfrequency in scaled PPM.
long int jitcnt
This counter represents the number of pulses where the jitter exceededthe allowed maximumMAXTIME
.
long int calcnt
This counter reflects the number of successful calibration intervals.
long int errcnt
This counter represents the number of calibration errors (caused bylarge offsets or jitter).
long int stbcnt
This counter denotes the number of calibrations where the stabilityexceeded the threshold.
int
ntp_adjtime(struct timex *tptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thentp_adjtime
function sets the structure specified bytptr to current values.
In addition,ntp_adjtime
updates some settings to match whatyou pass to it in*tptr
. Use themodes
element of*tptr
to select what settings to update. You can setoffset
,freq
,maxerror
,esterror
,status
,constant
, andtick
.
modes
= zero means set nothing.
Only the superuser can update settings.
The return value is0
on success and other values on failure. Thefollowingerrno
error conditions are defined for this function:
TIME_ERROR
The high accuracy clock model is not properly set up at the moment, thus theclock must be considered unsynchronized, and the values should betreated with care. Another reason could be that the specified new valuesare not allowed.
EPERM
The process specified a settings update, but is not superuser.
For more details see RFC 5905 (Network Time Protocol, Version 4) andrelated documents.
Portability note: Early versions of the GNU C Library did nothave this function, but did have the synonymousadjtimex
.
int
adjtime(const struct timeval *delta, struct timeval *olddelta)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This simpler version ofntp_adjtime
speeds up or slows down thesystem clock for a short time, in order to correct it by a smallamount. This avoids a discontinuous change in the calendar timereported by theCLOCK_REALTIME
clock, at the price of having towait longer for the time to become correct.
Thedelta argument specifies a relative adjustment to be made tothe clock time. If negative, the system clock is slowed down for awhile until it has lost this much elapsed time. If positive, the systemclock is sped up for a while.
If theolddelta argument is not a null pointer, theadjtime
function returns information about any previous time adjustment thathas not yet completed.
The return value is0
on success and-1
on failure. Thefollowingerrno
error condition is defined for this function:
EPERM
This process does not have the privileges required to adjust theCLOCK_REALTIME
clock.
For compatibility, the GNU C Library also provides several older functionsfor controlling the system time. New programs should prefer to usethe functions above.
int
stime(const time_t *newtime)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Change theCLOCK_REALTIME
calendar time to be the simplecalendar time in*newtime
. Calling this function isexactly the same as calling ‘clock_settime (CLOCK_REALTIME)’,except that the new time can only be set to a precision of one second.
This function is no longer available on GNU systems, but it may betheonly way to set the time on very old Unix systems, so wecontinue to document it. If it is available, it is declared intime.h.
The return value is0
on success and-1
on failure. Thefollowingerrno
error condition is defined for this function:
EPERM
This process does not have the privileges required to adjust theCLOCK_REALTIME
clock.
int
adjtimex(struct timex *timex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
adjtimex
is an older name forntp_adjtime
.This function is only available on GNU/Linux systems.It is declared insys/timex.h.
int
settimeofday(const struct timeval *tp, const void *tzp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Change theCLOCK_REALTIME
calendar time to be the simplecalendar time in*newtime
. This function is declared insys/time.h.
Whentzp is a null pointer, calling this function is exactly thesame as calling ‘clock_settime (CLOCK_REALTIME)’, except thatthe new time can only be set to a precision of one microsecond.
Whentzp is not a null pointer, the data it points tomaybe used to set a system-wide idea of the current time zone. Thisfeature is obsolete and not supported on GNU systems. Instead, usethe facilities described inState Variables for Time Zones and inBroken-down Time for working with time zones.
The return value is0
on success and-1
on failure. Thefollowingerrno
error conditions are defined for this function:
EPERM
This process does not have the privileges required to set theCLOCK_REALTIME
clock.
EINVAL
Neithertp nortzp is a null pointer. (For historicalreasons, it is not possible to set the current time and the currenttime zone in the same call.)
ENOSYS
The operating system does not support setting time zone information, andtzp is not a null pointer.
Next:Formatting Calendar Time, Previous:Setting and Adjusting the Time, Up:Calendar Time [Contents][Index]
Simple calendar times represent absolute times as elapsed times sincean epoch. This is convenient for computation, but has no relation tothe way people normally think of calendar time. By contrast,broken-down time is a binary representation of calendar timeseparated into year, month, day, and so on. Although broken-down timevalues are painful to calculate with, they are useful for printinghuman readable time information.
A broken-down time value is always relative to a choice of timezone, and it also indicates which time zone that is.
The symbols in this section are declared in the header filetime.h.
This is the data type used to represent a broken-down time. The structurecontains at least the following members, which can appear in any order.
int tm_sec
This is the number of full seconds since the top of the minute (normallyin the range0
through59
, but the actual upper limit is60
, to allow for leap seconds if leap second support isavailable).
int tm_min
This is the number of full minutes since the top of the hour (in therange0
through59
).
int tm_hour
This is the number of full hours past midnight (in the range0
through23
).
int tm_mday
This is the ordinal day of the month (in the range1
through31
).Watch out for this one! As the only ordinal number in the structure, it isinconsistent with the rest of the structure.
int tm_mon
This is the number of full calendar months since the beginning of theyear (in the range0
through11
). Watch out for this one!People usually use ordinal numbers for month-of-year (where January = 1).
int tm_year
This is the number of full calendar years since 1900.
int tm_wday
This is the number of full days since Sunday (in the range0
through6
).
int tm_yday
This is the number of full days since the beginning of the year (in therange0
through365
).
int tm_isdst
¶This is a flag that indicates whether daylight saving time is (or was, orwill be) in effect at the time described. The value is positive ifdaylight saving time is in effect, zero if it is not, and negative if theinformation is not available.Although this flag is useful when passing a broken-down time to themktime
function, for other uses this flag should be ignored andthetm_gmtoff
andtm_zone
fields should be inspected instead.
long int tm_gmtoff
This field describes the time zone that was used to compute thisbroken-down time value, including any adjustment for daylight saving; itis the number of seconds that you must add to UTC to get local time.You can also think of this as the number of seconds east of the Prime Meridian.For example, for U.S. Eastern Standard Time, the value is-5*60*60
.
const char *tm_zone
This field is the abbreviation for the time zone that was used to compute thisbroken-down time value.
Portability note: Thetm_gmtoff
andtm_zone
fieldsare derived from BSD and are POSIX extensions to ISO C.Code intended to be portable to operating systems that lackthese fields can instead use time zone state variables, althoughthose variables are unreliable when theTZ
environment variablehas a geographical format. SeeState Variables for Time Zones.
struct tm *
localtime(const time_t *time)
¶Preliminary:| MT-Unsafe race:tmbuf env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
Thelocaltime
function converts the simple time pointed to bytime to broken-down time representation, expressed relative to theuser’s specified time zone.
The return value is a pointer to a static broken-down time structure, whichmight be overwritten by subsequent calls togmtime
orlocaltime
. (No other library function overwrites the contentsof this object.) In the GNU C Library, the structure’stm_zone
points to a string with a storage lifetime that lasts indefinitely;on other platforms, the lifetime may expire when theTZ
environment variable is changed.
The return value is the null pointer iftime cannot be representedas a broken-down time; typically this is because the year cannot fit intoanint
.
Callinglocaltime
also sets the time zone state as iftzset
were called. SeeState Variables for Time Zones.
Using thelocaltime
function is a big problem in multi-threadedprograms. The result is returned in a static buffer and this is used inall threads. A variant function avoids this problem.
struct tm *
localtime_r(const time_t *time, struct tm *resultp)
¶Preliminary:| MT-Safe env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
Thelocaltime_r
function works just like thelocaltime
function. It takes a pointer to a variable containing a simple timeand converts it to the broken-down time format.
But the result is not placed in a static buffer. Instead it is placedin the object of typestruct tm
to which the parameterresultp points. Also, the time zone state is not necessarilyset as iftzset
were called.
If the conversion is successful the function returns a pointer to theobject the result was written into, i.e., it returnsresultp.
struct tm *
gmtime(const time_t *time)
¶Preliminary:| MT-Unsafe race:tmbuf env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
This function is similar tolocaltime
, except that the broken-downtime is expressed as UTC rather than relative to a local time zone.The broken-down time’stm_gmtoff
is 0, and itstm_zone
is a string"UTC"
with static storage duration.
As for thelocaltime
function we have the problem that the resultis placed in a static variable. A thread-safe replacement is also provided forgmtime
.
struct tm *
gmtime_r(const time_t *time, struct tm *resultp)
¶Preliminary:| MT-Safe env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
This function is similar tolocaltime_r
, except that it convertsjust likegmtime
the given time as UTC.
If the conversion is successful the function returns a pointer to theobject the result was written into, i.e., it returnsresultp.
time_t
mktime(struct tm *brokentime)
¶Preliminary:| MT-Safe env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
Themktime
function converts a broken-down time structure to asimple time representation. It also normalizes the contents of thebroken-down time structure, and fills in some components based on thevalues of the others.
Themktime
function ignores the specified contents of thetm_wday
,tm_yday
,tm_gmtoff
, andtm_zone
members of the broken-down timestructure. It uses the values of the other components to determine thecalendar time; it’s permissible for these components to haveunnormalized values outside their normal ranges. The last thing thatmktime
does is adjust the components of thebrokentimestructure, including the members that were initially ignored.
If the specified broken-down time cannot be represented as a simple time,mktime
returns a value of(time_t)(-1)
and does not modifythe contents ofbrokentime.
Callingmktime
also sets the time zone state as iftzset
were called;mktime
uses this information insteadofbrokentime’s initialtm_gmtoff
andtm_zone
members. SeeState Variables for Time Zones.
time_t
timelocal(struct tm *brokentime)
¶Preliminary:| MT-Safe env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
timelocal
is functionally identical tomktime
, but moremnemonically named. Note that it is the inverse of thelocaltime
function.
Portability note:mktime
is essentially universallyavailable.timelocal
is rather rare.
time_t
timegm(struct tm *brokentime)
¶Preliminary:| MT-Safe env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
timegm
is functionally identical tomktime
except italways takes the input values to be UTCregardless of any local time zone setting.
Note thattimegm
is the inverse ofgmtime
.
Portability note:mktime
is essentially universallyavailable. Althoughtimegm
is standardized by C23, someother systems lack it; to be portable to them, you can settheTZ
environment variable to UTC, callmktime
, then setTZ
back.
Next:Convert textual time and date information back, Previous:Broken-down Time, Up:Calendar Time [Contents][Index]
The functions described in this section format calendar time values asstrings. These functions are declared in the header filetime.h.
size_t
strftime(char *s, size_tsize, const char *template, const struct tm *brokentime)
¶Preliminary:| MT-Safe env locale| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
This function is similar to thesprintf
function (seeFormatted Input), but the conversion specifications that can appear in the formattemplatetemplate are specialized for printing components ofbrokentime according to the locale currently specified fortime conversion (seeLocales and Internationalization) and the current time zone(seeState Variables for Time Zones).
Ordinary characters appearing in thetemplate are copied to theoutput strings; this can include multibyte character sequences.Conversion specifiers are introduced by a ‘%’ character, followedby an optional flag which can be one of the following. These flagsare all GNU extensions. The first three affect only the output ofnumbers:
_
The number is padded with spaces.
-
The number is not padded at all.
0
The number is padded with zeros even if the format specifies paddingwith spaces.
^
The output uses uppercase characters, but only if this is possible(seeCase Conversion).
The default action is to pad the number with zeros to keep it a constantwidth. Numbers that do not have a range indicated below are neverpadded, since there is no natural width for them.
Following the flag an optional specification of the width is possible.This is specified in decimal notation. If the natural size of theoutput of the field has less than the specified number of characters,the result is written right adjusted and space padded to the givensize.
An optional modifier can follow the optional flag and widthspecification. The modifiers are:
E
Use the locale’s alternative representation for date and time. Thismodifier applies to the%c
,%C
,%x
,%X
,%y
and%Y
format specifiers. In a Japanese locale, forexample,%Ex
might yield a date format based on the JapaneseEmperors’ reigns.
O
With all format specifiers that produce numbers: use the locale’salternative numeric symbols.
With%B
,%b
, and%h
: use the grammatical form formonth names that is appropriate when the month is named by itself,rather than the form that is appropriate when the month is used aspart of a complete date. The%OB
and%Ob
formats are aC23 feature, specified in C23 to use the locale’s ‘alternative’ monthname; the GNU C Library extends this specification to say that the form usedin a complete date is the default and the form naming the month byitself is the alternative.
If the format supports the modifier but no alternative representationis available, it is ignored.
The conversion specifier ends with a format specifier taken from thefollowing list. The whole ‘%’ sequence is replaced in the outputstring as follows:
%a
The abbreviated weekday name according to the current locale.
%A
The full weekday name according to the current locale.
%b
The abbreviated month name according to the current locale, in thegrammatical form used when the month is part of a complete date.As a C23 feature (with a more detailed specification in the GNU C Library),theO
modifier can be used (%Ob
) to get the grammaticalform used when the month is named by itself.
%B
The full month name according to the current locale, in thegrammatical form used when the month is part of a complete date.As a C23 feature (with a more detailed specification in the GNU C Library),theO
modifier can be used (%OB
) to get the grammaticalform used when the month is named by itself.
Note that not all languages need two different forms of the monthnames, so the text produced by%B
and%OB
, and by%b
and%Ob
, may or may not be the same, depending onthe locale.
%c
The preferred calendar time representation for the current locale.
%C
The century of the year. This is equivalent to the greatest integer notgreater than the year divided by 100.
If theE
modifier is specified (%EC
), instead producesthe name of the period for the year (e.g. an era name) in thelocale’s alternative calendar.
%d
The day of the month as a decimal number (range01
through31
).
%D
The date using the format%m/%d/%y
.
%e
The day of the month like with%d
, but padded with spaces (range 1
through31
).
%F
The date using the format%Y-%m-%d
. This is the form specifiedin the ISO 8601 standard and is the preferred form for all uses.
%g
The year corresponding to the ISO week number, but without the century(range00
through99
). This has the same format and valueas%y
, except that if the ISO week number (see%V
) belongsto the previous or next year, that year is used instead.
%G
The year corresponding to the ISO week number. This has the same formatand value as%Y
, except that if the ISO week number (see%V
) belongs to the previous or next year, that year is usedinstead.
%h
The abbreviated month name according to the current locale. The actionis the same as for%b
.
%H
The hour as a decimal number, using a 24-hour clock (range00
through23
).
%I
The hour as a decimal number, using a 12-hour clock (range01
through12
).
%j
The day of the year as a decimal number (range001
through366
).
%k
The hour as a decimal number, using a 24-hour clock like%H
, butpadded with spaces (range 0
through23
).
This format is a GNU extension.
%l
The hour as a decimal number, using a 12-hour clock like%I
, butpadded with spaces (range 1
through12
).
This format is a GNU extension.
%m
The month as a decimal number (range01
through12
).
%M
The minute as a decimal number (range00
through59
).
%n
A single ‘\n’ (newline) character.
%p
Either ‘AM’ or ‘PM’, according to the given time value; or thecorresponding strings for the current locale. Noon is treated as‘PM’ and midnight as ‘AM’. In most locales‘AM’/‘PM’ format is not supported, in such cases"%p"
yields an empty string.
%P
Either ‘am’ or ‘pm’, according to the given time value; or thecorresponding strings for the current locale, printed in lowercasecharacters. Noon is treated as ‘pm’ and midnight as ‘am’. Inmost locales ‘AM’/‘PM’ format is not supported, in such cases"%P"
yields an empty string.
This format is a GNU extension.
%r
The complete calendar time using the AM/PM format of the current locale.
In the POSIX locale, this format is equivalent to%I:%M:%S %p
.
%R
The hour and minute in decimal numbers using the format%H:%M
.
%s
The number of seconds since the POSIX Epoch,i.e., since 1970-01-01 00:00:00 UTC.Leap seconds are not counted unless leap second support is available.
This format is a GNU extension.
%S
The seconds as a decimal number (range00
through60
).
%t
A single ‘\t’ (tabulator) character.
%T
The time of day using decimal numbers using the format%H:%M:%S
.
%u
The day of the week as a decimal number (range1
through7
), Monday being1
.
%U
The week number of the current year as a decimal number (range00
through53
), starting with the first Sunday as the first day ofthe first week. Days preceding the first Sunday in the year areconsidered to be in week00
.
%V
The ISO 8601 week number as a decimal number (range01
through53
). ISO weeks start with Monday and end with Sunday.Week01
of a year is the first week which has the majority of itsdays in that year; this is equivalent to the week containing the year’sfirst Thursday, and it is also equivalent to the week containing January4. Week01
of a year can contain days from the previous year.The week before week01
of a year is the last week (52
or53
) of the previous year even if it contains days from the newyear.
%w
The day of the week as a decimal number (range0
through6
), Sunday being0
.
%W
The week number of the current year as a decimal number (range00
through53
), starting with the first Monday as the first day ofthe first week. All days preceding the first Monday in the year areconsidered to be in week00
.
%x
The preferred date representation for the current locale.
%X
The preferred time of day representation for the current locale.
%y
The year without a century as a decimal number (range00
through99
). This is equivalent to the year modulo 100.
If theE
modifier is specified (%Ey
), instead producesthe year number according to a locale-specific alternative calendar.Unlike%y
, the number isnot reduced modulo 100.However, by default it is zero-padded to a minimum of two digits (thiscan be overridden by an explicit field width or by the_
and-
flags).
%Y
The year as a decimal number, using the Gregorian calendar. Yearsbefore the year1
are numbered0
,-1
, and so on.
If theE
modifier is specified (%EY
), instead produces acomplete representation of the year according to the locale’salternative calendar. Generally this will be some combination of theinformation produced by%EC
and%Ey
. As a GNUextension, the formatting flags_
or-
may be used withthis conversion specifier; they affect how the year number is printed.
%z
RFC 5322/ISO 8601 style numeric time zone (e.g.,-0600
or+0100
), or nothing if no time zone isdeterminable.
In the POSIX locale, a full RFC 5322 timestamp is generated by the format"%a, %d %b %Y %H:%M:%S %z"
(or the equivalent"%a, %d %b %Y %T %z"
).
%Z
The time zone abbreviation (empty if the time zone can’t be determined).
%%
A literal ‘%’ character.
Thesize parameter can be used to specify the maximum number ofcharacters to be stored in the arrays, including the terminatingnull character. If the formatted time requires more thansizecharacters,strftime
returns zero and the contents of the arrays are undefined. Otherwise the return value indicates thenumber of characters placed in the arrays, not including theterminating null character.
Warning: This convention for the return value which is prescribedin ISO C can lead to problems in some situations. For certainformat strings and certain locales the output really can be the emptystring and this cannot be discovered by testing the return value only.E.g., in most locales the AM/PM time format is not supported (most ofthe world uses the 24 hour time representation). In such locales"%p"
will return the empty string, i.e., the return value iszero. To detect situations like this something similar to the followingcode should be used:
buf[0] = '\1';len = strftime (buf, bufsize, format, tp);if (len == 0 && buf[0] != '\0') { /* Something went wrong in the strftime call. */ ... }
Ifs is a null pointer,strftime
does not actually writeanything, but instead returns the number of characters it would have written.
Callingstrftime
also sets the time zone state as iftzset
were called. SeeState Variables for Time Zones.
For an example ofstrftime
, seeTime Functions Example.
size_t
strftime_l(char *restricts, size_tsize, const char *restricttemplate, const struct tm *brokentime, locale_tlocale)
¶Preliminary:| MT-Safe env locale| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thestrftime_l
function is equivalent to thestrftime
function except that it operates inlocale rather than inthe current locale.
size_t
wcsftime(wchar_t *s, size_tsize, const wchar_t *template, const struct tm *brokentime)
¶Preliminary:| MT-Safe env locale| AS-Unsafe corrupt heap lock dlopen| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
Thewcsftime
function is equivalent to thestrftime
function with the difference that it operates on wide characterstrings. The buffer where the result is stored, pointed to bys,must be an array of wide characters. The parametersize whichspecifies the size of the output buffer gives the number of widecharacters, not the number of bytes.
Also the format stringtemplate is a wide character string. Sinceall characters needed to specify the format string are in the basiccharacter set it is portably possible to write format strings in the Csource code using theL"…"
notation. The parameterbrokentime has the same meaning as in thestrftime
call.
Thewcsftime
function supports the same flags, modifiers, andformat specifiers as thestrftime
function.
The return value ofwcsftime
is the number of wide charactersstored ins
. When more characters would have to be written thancan be placed in the buffers the return value is zero, with thesame problems indicated in thestrftime
documentation.
char *
asctime(const struct tm *brokentime)
¶Preliminary:| MT-Unsafe race:asctime locale| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
Theasctime
function converts the broken-down time value thatbrokentime points to into a string in a standard format:
"Tue May 21 13:46:22 1991\n"
The abbreviations for the days of week are: ‘Sun’, ‘Mon’,‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, and ‘Sat’.
The abbreviations for the months are: ‘Jan’, ‘Feb’,‘Mar’, ‘Apr’, ‘May’, ‘Jun’, ‘Jul’, ‘Aug’,‘Sep’, ‘Oct’, ‘Nov’, and ‘Dec’.
Behavior is undefined if the calculated year would be less than 1000or greater than 9999.
The return value points to a statically allocated string, which might beoverwritten by subsequent calls toasctime
orctime
.(No other library function overwrites the contents of thisstring.)
Portability note:This obsolescent function is deprecated in C23.Programs should instead usestrftime
or evensprintf
.
char *
asctime_r(const struct tm *brokentime, char *buffer)
¶Preliminary:| MT-Safe locale| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar toasctime
but instead of placing theresult in a static buffer it writes the string in the buffer pointed toby the parameterbuffer. This buffer should have roomfor at least 26 bytes, including the terminating null.Behavior is undefined if the calculated year would be less than 1000or greater than 9999.
If no error occurred the function returns a pointer to the string theresult was written into, i.e., it returnsbuffer. Otherwiseit returnsNULL
.
Portability Note:POSIX.1-2024 removed this obsolescent function.Programs should instead usestrftime
or evensprintf
.
char *
ctime(const time_t *time)
¶Preliminary:| MT-Unsafe race:tmbuf race:asctime env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
Thectime
function is similar toasctime
, except that youspecify the calendar time argument as atime_t
simple time valuerather than in broken-down local time format. It is equivalent to
asctime (localtime (time))
Behavior is undefined if the calculated year would be less than 1000or greater than 9999.
Callingctime
also sets the time zone state as iftzset
were called. SeeState Variables for Time Zones.
Portability note:This obsolescent function is deprecated in C23.Programs should instead usestrftime
or evensprintf
.
char *
ctime_r(const time_t *time, char *buffer)
¶Preliminary:| MT-Safe env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
This function is similar toctime
, but places the result in thestring pointed to bybuffer, and the time zone state is notnecessarily set as iftzset
were called. It is equivalent to:
asctime_r (localtime_r (time, &(struct tm) {0}),buffer)
Behavior is undefined if the calculated year would be less than 1000or greater than 9999.
If no error occurred the function returns a pointer to the string theresult was written into, i.e., it returnsbuffer. Otherwiseit returnsNULL
.
Portability Note:POSIX.1-2024 removed this obsolescent function.Programs should instead usestrftime
or evensprintf
.
Next:Specifying the Time Zone withTZ
, Previous:Formatting Calendar Time, Up:Calendar Time [Contents][Index]
The ISO C standard does not specify any functions which can convertthe output of thestrftime
function back into a binary format.This led to a variety of more-or-less successful implementations withdifferent interfaces over the years. Then the Unix standard wasextended by the addition of two functions:strptime
andgetdate
. Both have strange interfaces but at least they arewidely available.
Next:A More User-friendly Way to Parse Times and Dates, Up:Convert textual time and date information back [Contents][Index]
The first function is rather low-level. It is nevertheless frequentlyused in software since it is better known. Its interface andimplementation are heavily influenced by thegetdate
function,which is defined and implemented in terms of calls tostrptime
.
char *
strptime(const char *s, const char *fmt, struct tm *tp)
¶Preliminary:| MT-Safe env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
Thestrptime
function parses the input strings accordingto the format stringfmt and stores its results in thestructuretp.
The input string could be generated by astrftime
call orobtained any other way. It does not need to be in a human-recognizableformat; e.g. a date passed as"02:1999:9"
is acceptable, eventhough it is ambiguous without context. As long as the format stringfmt matches the input string the function will succeed.
The user has to make sure, though, that the input can be parsed in aunambiguous way. The string"1999112"
can be parsed using theformat"%Y%m%d"
as 1999-1-12, 1999-11-2, or even 19991-1-2. Itis necessary to add appropriate separators to reliably get results.
The format string consists of the same components as the format stringof thestrftime
function. The only difference is that the flags_
,-
,0
, and^
are not allowed.Several of the distinct formats ofstrftime
do the same work instrptime
since differences like case of the input do not matter.For reasons of symmetry all formats are supported, though.
The modifiersE
andO
are also allowed everywhere thestrftime
function allows them.
The formats are:
%a
%A
The weekday name according to the current locale, in abbreviated form orthe full name.
%b
%B
%h
A month name according to the current locale. All three specifierswill recognize both abbreviated and full month names. If thelocale provides two different grammatical forms of month names,all three specifiers will recognize both forms.
As a GNU extension, theO
modifier can be used with thesespecifiers; it has no effect, as both grammatical forms of monthnames are recognized.
%c
The date and time representation for the current locale.
%Ec
Like%c
but the locale’s alternative date and time format is used.
%C
The century of the year.
It makes sense to use this format only if the format string alsocontains the%y
format.
%EC
The locale’s representation of the period.
Unlike%C
it sometimes makes sense to use this format since somecultures represent years relative to the beginning of eras instead ofusing the Gregorian years.
%d
%e
The day of the month as a decimal number (range1
through31
).Leading zeroes are permitted but not required.
%Od
%Oe
Same as%d
but using the locale’s alternative numeric symbols.
Leading zeroes are permitted but not required.
%D
Equivalent to%m/%d/%y
.
%F
Equivalent to%Y-%m-%d
, which is the ISO 8601 dateformat.
This is a GNU extension following an ISO C99 extension tostrftime
.
%g
The year corresponding to the ISO week number, but without the century(range00
through99
).
Note: Currently, this is not fully implemented. The format isrecognized, input is consumed but no field intm is set.
This format is a GNU extension following a GNU extension ofstrftime
.
%G
The year corresponding to the ISO week number.
Note: Currently, this is not fully implemented. The format isrecognized, input is consumed but no field intm is set.
This format is a GNU extension following a GNU extension ofstrftime
.
%H
%k
The hour as a decimal number, using a 24-hour clock (range00
through23
).
%k
is a GNU extension following a GNU extension ofstrftime
.
%OH
Same as%H
but using the locale’s alternative numeric symbols.
%I
%l
The hour as a decimal number, using a 12-hour clock (range01
through12
).
%l
is a GNU extension following a GNU extension ofstrftime
.
%OI
Same as%I
but using the locale’s alternative numeric symbols.
%j
The day of the year as a decimal number (range1
through366
).
Leading zeroes are permitted but not required.
%m
The month as a decimal number (range1
through12
).
Leading zeroes are permitted but not required.
%Om
Same as%m
but using the locale’s alternative numeric symbols.
%M
The minute as a decimal number (range0
through59
).
Leading zeroes are permitted but not required.
%OM
Same as%M
but using the locale’s alternative numeric symbols.
%n
%t
Matches any whitespace.
%p
%P
The locale-dependent equivalent to ‘AM’ or ‘PM’.
This format is not useful unless%I
or%l
is also used.Another complication is that the locale might not define these values atall and therefore the conversion fails.
%P
is a GNU extension following a GNU extension tostrftime
.
%r
The complete time using the AM/PM format of the current locale.
A complication is that the locale might not define this format at alland therefore the conversion fails.
%R
The hour and minute in decimal numbers using the format%H:%M
.
%R
is a GNU extension following a GNU extension tostrftime
.
%s
The number of seconds since the POSIX Epoch,i.e., since 1970-01-01 00:00:00 UTC.Leap seconds are not counted unless leap second support is available.
%s
is a GNU extension following a GNU extension tostrftime
.
%S
The seconds as a decimal number (range0
through60
).
Leading zeroes are permitted but not required.
NB: The Unix specification says the upper bound on this valueis61
, a result of a decision to allow double leap seconds. Youwill not see the value61
because no minute has more than oneleap second, but the myth persists.
%OS
Same as%S
but using the locale’s alternative numeric symbols.
%T
Equivalent to the use of%H:%M:%S
in this place.
%u
The day of the week as a decimal number (range1
through7
), Monday being1
.
Leading zeroes are permitted but not required.
Note: Currently, this is not fully implemented. The format isrecognized, input is consumed but no field intm is set.
%U
The week number of the current year as a decimal number (range0
through53
).
Leading zeroes are permitted but not required.
%OU
Same as%U
but using the locale’s alternative numeric symbols.
%V
The ISO 8601 week number as a decimal number (range1
through53
).
Leading zeroes are permitted but not required.
Note: Currently, this is not fully implemented. The format isrecognized, input is consumed but no field intm is set.
%w
The day of the week as a decimal number (range0
through6
), Sunday being0
.
Leading zeroes are permitted but not required.
Note: Currently, this is not fully implemented. The format isrecognized, input is consumed but no field intm is set.
%Ow
Same as%w
but using the locale’s alternative numeric symbols.
%W
The week number of the current year as a decimal number (range0
through53
).
Leading zeroes are permitted but not required.
Note: Currently, this is not fully implemented. The format isrecognized, input is consumed but no field intm is set.
%OW
Same as%W
but using the locale’s alternative numeric symbols.
%x
The date using the locale’s date format.
%Ex
Like%x
but the locale’s alternative data representation is used.
%X
The time using the locale’s time format.
%EX
Like%X
but the locale’s alternative time representation is used.
%y
The year without a century as a decimal number (range0
through99
).
Leading zeroes are permitted but not required.
Note that it is questionable to use this format withoutthe%C
format. Thestrptime
function does regard inputvalues in the range68 to99 as the years1969 to1999 and the values0 to68 as the years2000 to2068. But maybe this heuristic fails for someinput data.
Therefore it is best to avoid%y
completely and use%Y
instead.
%Ey
The offset from%EC
in the locale’s alternative representation.
%Oy
The offset of the year (from%C
) using the locale’s alternativenumeric symbols.
%Y
The year as a decimal number, using the Gregorian calendar.
%EY
The full alternative year representation.
%z
The offset from UTC in ISO 8601/RFC 5322 format.
%Z
The time zone abbreviation.
Note: Currently, this is not fully implemented. The format isrecognized, input is consumed but no field intm is set.
%%
A literal ‘%’ character.
All other characters in the format string must have a matching characterin the input string. Exceptions are whitespace characters in the input stringwhich can match zero or more whitespace characters in the format string.
Portability Note: The XPG standard advises applications to useat least one whitespace character (as specified byisspace
) orother non-alphanumeric characters between any two conversionspecifications. The GNU C Library does not have this limitation butother libraries might have trouble parsing formats like"%d%m%Y%H%M%S"
.
Thestrptime
function processes the input string from right toleft. Each of the three possible input elements (whitespace, literal,or format) are handled one after the other. If the input cannot bematched to the format string the function stops. The remainder of theformat and input strings are not processed.
The function returns a pointer to the first character it was unable toprocess. If the input string contains more characters than required bythe format string the return value points right after the last consumedinput character. If the whole input string is consumed the return valuepoints to theNULL
byte at the end of the string. If an erroroccurs, i.e.,strptime
fails to match all of the format string,the function returnsNULL
.
The specification of the function in the XPG standard is rather vague,leaving out a few important pieces of information. Most importantly, itdoes not specify what happens to those elements oftm which arenot directly initialized by the different formats. Theimplementations on different Unix systems vary here.
The GNU C Library implementation does not touch those fields which are notdirectly initialized. Exceptions are thetm_wday
andtm_yday
elements, which are recomputed if any of the year, month,or date elements changed. This has two implications:
strptime
function for a new input string, youshould prepare thetm structure you pass. Normally this will meaninitializing all values to zero. Alternatively, you can set allfields to values likeINT_MAX
, allowing you to determine whichelements were set by the function call. Zero does not work here sinceit is a valid value for many of the fields.Careful initialization is necessary if you want to find out whether acertain field intm was initialized by the function call.
struct tm
value with several consecutivestrptime
calls. A useful application of this is e.g. the parsingof two separate strings, one containing date information and the othertime information. By parsing one after the other without clearing thestructure in-between, you can construct a complete broken-down time.The following example shows a function which parses a string whichcontains the date information in either US style or ISO 8601 form:
const char *parse_date (const char *input, struct tm *tm){ const char *cp; /*First clear the result structure. */ memset (tm, '\0', sizeof (*tm)); /*Try the ISO format first. */ cp = strptime (input, "%F", tm); if (cp == NULL) { /*Does not match. Try the US form. */ cp = strptime (input, "%D", tm); } return cp;}
Previous:Interpret string according to given format, Up:Convert textual time and date information back [Contents][Index]
The Unix standard defines another function for parsing date strings.The interface is weird, but if the function happens to suit yourapplication it is just fine. It is problematic to use this functionin multi-threaded programs or libraries, since it returns a pointer toa static variable, and uses a global variable and global state basedon an environment variable.
This variable of typeint
contains the error code of the lastunsuccessful call togetdate
. Defined values are:
The environment variableDATEMSK
is not defined or null.
The template file denoted by theDATEMSK
environment variablecannot be opened.
Information about the template file cannot retrieved.
The template file is not a regular file.
An I/O error occurred while reading the template file.
Not enough memory available to execute the function.
The template file contains no matching template.
The input date is invalid, but would match a template otherwise. Thisincludes dates like February 31st, and dates which cannot be representedin atime_t
variable.
struct tm *
getdate(const char *string)
¶Preliminary:| MT-Unsafe race:getdate env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
The interface togetdate
is the simplest possible for a functionto parse a string and return the value.string is the inputstring and the result is returned in a statically-allocated variable.
The details about how the string is processed are hidden from the user.In fact, they can be outside the control of the program. Which formatsare recognized is controlled by the file named by the environmentvariableDATEMSK
. This file should containlines of valid format strings which could be passed tostrptime
.
Thegetdate
function reads these format strings one after theother and tries to match the input string. The first line whichcompletely matches the input string is used.
Elements not initialized through the format string retain the valuespresent at the time of thegetdate
function call.
The formats recognized bygetdate
are the same as forstrptime
. See above for an explanation. There are only a fewextensions to thestrptime
behavior:
%Z
format is given the broken-down time is based on thecurrent time of the time zone matched, not of the current time zone of theruntime environment.Note: This is not implemented (currently). The problem is thattime zone abbreviations are not unique. If a fixed time zone is assumed for agiven string (sayEST
meaning US East Coast time), then uses forcountries other than the USA will fail. So far we have found no goodsolution to this.
tm_wday
value the current week’s day is chosen, otherwise the day next week is chosen.It should be noted that the format in the template file need not onlycontain format elements. The following is a list of possible formatstrings (taken from the Unix standard):
%m%A %B %d, %Y %H:%M:%S%A%B%m/%d/%y %I %p%d,%m,%Y %H:%Mat %A the %dst of %B in %Yrun job at %I %p,%B %dnd%A den %d. %B %Y %H.%M Uhr
As you can see, the template list can contain very specific strings likerun job at %I %p,%B %dnd
. Using the above list of templates andassuming the current time is Mon Sep 22 12:19:47 EDT 1986, we can obtain thefollowing results for the given input.
Input | Match | Result |
Mon | %a | Mon Sep 22 12:19:47 EDT 1986 |
Sun | %a | Sun Sep 28 12:19:47 EDT 1986 |
Fri | %a | Fri Sep 26 12:19:47 EDT 1986 |
September | %B | Mon Sep 1 12:19:47 EDT 1986 |
January | %B | Thu Jan 1 12:19:47 EST 1987 |
December | %B | Mon Dec 1 12:19:47 EST 1986 |
Sep Mon | %b %a | Mon Sep 1 12:19:47 EDT 1986 |
Jan Fri | %b %a | Fri Jan 2 12:19:47 EST 1987 |
Dec Mon | %b %a | Mon Dec 1 12:19:47 EST 1986 |
Jan Wed 1989 | %b %a %Y | Wed Jan 4 12:19:47 EST 1989 |
Fri 9 | %a %H | Fri Sep 26 09:00:00 EDT 1986 |
Feb 10:30 | %b %H:%S | Sun Feb 1 10:00:30 EST 1987 |
10:30 | %H:%M | Tue Sep 23 10:30:00 EDT 1986 |
13:30 | %H:%M | Mon Sep 22 13:30:00 EDT 1986 |
The return value of the function is a pointer to a static variable oftypestruct tm
, or a null pointer if an error occurred. Theresult is only valid until the nextgetdate
call, making thisfunction unusable in multi-threaded applications.
Theerrno
variable isnot changed. Error conditions arestored in the global variablegetdate_err
. See thedescription above for a list of the possible error values.
Warning: Thegetdate
function shouldnever beused in SUID-programs. The reason is obvious: using theDATEMSK
environment variable you can get the function to openany arbitrary file and chances are high that with some bogus input(such as a binary file) the program will crash.
int
getdate_r(const char *string, struct tm *tp)
¶Preliminary:| MT-Safe env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
Thegetdate_r
function is the reentrant counterpart ofgetdate
. It does not use the global variablegetdate_err
to signal an error, but instead returns an error code. The same errorcodes as described in thegetdate_err
documentation above areused, with 0 meaning success.
Moreover,getdate_r
stores the broken-down time in the variableof typestruct tm
pointed to by the second argument, rather thanin a static variable.
This function is not defined in the Unix standard. Nevertheless it isavailable on some other Unix systems as well.
The warning against usinggetdate
in SUID-programs applies togetdate_r
as well.
Next:State Variables for Time Zones, Previous:Convert textual time and date information back, Up:Calendar Time [Contents][Index]
TZ
¶In POSIX systems, a user can specify the time zone by means of theTZ
environment variable. For information about how to setenvironment variables, seeEnvironment Variables. The functionsfor accessing the time zone are declared intime.h.
You should not normally need to setTZ
. If the system isconfigured properly, the default time zone will be correct. You mightsetTZ
if you are using a computer over a network from adifferent time zone, and would like times reported to you in the timezone local to you, rather than what is local to the computer.
The value ofTZ
can be in one of the following formats:
TZ
.Here are some examples:Asia/TokyoAmerica/New_York/usr/share/zoneinfo/America/Nuuk
TZ
.Here are some examples:JST-9EST+5EDT,M3.2.0/2,M11.1.0/2<-02>+2<-01>,M3.5.0/-1,M10.5.0/0
:/etc/localtime
Each operating system can interpret this format differently;in the GNU C Library, the ‘:’ is ignored andcharactersare treated as if they specified the geographical or proleptic format.
TZ
is the empty string,the GNU C Library uses UTC.If theTZ
environment variable does not have a value, theimplementation chooses a time zone by default. In the GNU C Library, thedefault time zone is like the specification ‘TZ=/etc/localtime’(or ‘TZ=/usr/local/etc/localtime’, depending on how the GNU C Librarywas configured; seeInstalling the GNU C Library). Other C libraries use their ownrule for choosing the default time zone, so there is little we can sayabout them.
TZ
¶The geographical format names a time zone ruleset maintained by theTime Zone Database of time zone and daylight saving timeinformation for most regions of the world.This public-domain database is maintained by a community of volunteers.
If the format’scharacters begin with ‘/’it is an absolute file name;otherwise the library looks for the file/usr/share/zoneinfo/characters. Thezoneinfodirectory contains data files describing time zone rulesets in manydifferent parts of the world. The names represent major cities, withsubdirectories for geographical areas; for example,America/New_York,Europe/London,Asia/Tokyo.These data files are installed by the system administrator, who alsosets/etc/localtime to point to the data file for the local timezone ruleset.
If the file corresponding tocharacters cannot be read or hasinvalid data, andcharacters are not in the proleptic format,then the GNU C Library silently defaults to UTC. However, applicationsshould not depend on this, asTZ
formats may be extended in thefuture.
Previous:Geographical Format forTZ
, Up:Specifying the Time Zone withTZ
[Contents][Index]
TZ
¶Although the proleptic format is cumbersome and inaccurate for old timestamps,POSIX.1-2017 and earlier specified details only for the proleptic format,and you may need to use it on small systems that lack a time zoneinformation database.
The proleptic format is:
stdoffset[dst[offset][,
start[/
time],
end[/
time]]]
Thestd string specifies the time zone abbreviation,which must be at least three bytes long,and which can appear in unquoted or quoted form.The unquoted form can contain only ASCII alphabetic characters.The quoted form can also contain ASCII digits, ‘+’, and ‘-’;it is quoted by surrounding it by ‘<’ and ‘>’,which are not part of the abbreviation. There is no spacecharacter separating the time zone abbreviation from theoffset, so theserestrictions are necessary to parse the specification correctly.
Theoffset specifies the time value you must add to the local timeto get a UTC value. It has syntax like:
[+
|-
]hh[:
mm[:
ss]]
Thisis positive if the local time zone is west of the Prime Meridian andnegative if it is east; this is opposite from the usual conventionthat positive time zone offsets are east of the Prime Meridian.The hourhh must be between 0 and 24and may be a single digit, and the minutesmm and secondsss, if present, must be between 0 and 59.
For example, to specify time in Panama, which is Eastern Standard Timewithout any daylight saving time alternative:
EST+5
When daylight saving time is used, the proleptic format is more complicated.The initialstd andoffset specify the standard time zone, asdescribed above. Thedst string andoffset are the abbreviationand offset for the corresponding daylight saving time zone; if theoffset is omitted, it defaults to one hour ahead of standard time.
The remainder of the proleptic format, which starts with the first comma,describes when daylight saving time is in effect. This remainder isoptional and if omitted, the GNU C Library defaults to the daylight savingrules that would be used ifTZ
had the value"posixrules"
.However, other POSIX implementations default to different daylightsaving rules, so portableTZ
settings should not omit theremainder.
In the remainder, thestart field is when daylight saving time goes intoeffect and theend field is when the change is made back to standardtime. The following formats are recognized for these fields:
Jn
This specifies the Julian day, withn between1
and365
.February 29 is never counted, even in leap years.
n
This specifies the Julian day, withn between0
and365
.February 29 is counted in leap years.
Mm.w.d
This specifies dayd of weekw of monthm. The dayd must be between0
(Sunday) and6
. The weekw must be between1
and5
; week1
is thefirst week in which dayd occurs, and week5
specifies thelastd day in the month. The monthm should bebetween1
and12
.
Thetime fields specify when, in the local time currently ineffect, the change to the other time occurs. They have the sameformat asoffset except the hours part can range from−167 through 167; for example,-22:30
stands for 01:30the previous day and25:30
stands for 01:30 the next day. Ifomitted,time defaults to02:00:00
.
Here are exampleTZ
values with daylight saving time rules.
In North American Eastern Standard Time (EST) and Eastern Daylight Time (EDT),the normal offset from UTC is 5 hours; since this iswest of the Prime Meridian, the sign is positive. Summer time begins onMarch’s second Sunday at 2:00am, and ends on November’s first Sundayat 2:00am.
Israel Standard Time (IST) and Israel Daylight Time (IDT) are 2 hoursahead of the prime meridian in winter, springing forward an hour onMarch’s fourth Thursday at 26:00 (i.e., 02:00 on the first Friday on orafter March 23), and falling back on October’s last Sunday at 02:00.
Irish Standard Time (IST) is 1 hour behind the Prime Meridian insummer, falling forward to Greenwich Mean Time (GMT, the PrimeMeridian’s time), on October’s last Sunday at 00:00 and springing backon March’s last Sunday at 01:00. This is an example of “negativedaylight saving”; here, daylight saving time is one hour west ofstandard time instead of the more usual one hour east.
Most of Greenland is 2 hours behind UTC in winter. Clocks follow the EuropeanUnion rules of springing forward by one hour on March’s last Sunday at01:00 UTC (−01:00 local time) and falling back on October’slast Sunday at 01:00 UTC (00:00 local time).The numeric abbreviations ‘-02’ and ‘-01’ standfor standard and daylight saving time, respectively.
The schedule of daylight saving time in any particular jurisdiction haschanged over the years. To be strictly correct, the conversion of datesand times in the past should be based on the schedule that was in effectthen. However, the proleptic format does not let you specify how theschedule has changed from year to year. The most you can do is specifyone particular schedule—usually the present day schedule—and this isused to convert any date, no matter when. For precise time zonespecifications, it is best to use the geographical format.SeeGeographical Format forTZ
.
Next:Time Functions Example, Previous:Specifying the Time Zone withTZ
, Up:Calendar Time [Contents][Index]
For compatibility with POSIX, the GNU C Library defines global statevariables that depend on time zone rules specified by theTZ
environment variable. However, these state variables are obsolescentand are planned to be removed in a future version of POSIX,and programs generally should avoid them because they are notthread-safe and their values are specified only whenTZ
uses theproleptic format. SeeSpecifying the Time Zone withTZ
.Programs should instead use thetm_gmtoff
andtm_zone
members ofstruct tm
. SeeBroken-down Time.
void
tzset(void)
¶Preliminary:| MT-Safe env locale| AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
Thetzset
function initializes the state variables fromthe value of theTZ
environment variable.It is not usually necessary for your program to call this function,partly because your program should not use the state variables,and partly because this function is called automaticallywhen you use the time conversion functionslocaltime
,mktime
,strftime
,strftime_l
, andwcsftime
, or the deprecated functionctime
.Behavior is undefined if one thread accesses any of these variables directlywhile another thread is callingtzset
or any other functionthat is required or allowed to behave as if it calledtzset
.
char *
tzname[2]
¶The arraytzname
contains two strings, which areabbreviations of time zones (standard and DaylightSaving) that the user has selected.tzname[0]
abbreviatesa standard time zone (for example,"EST"
), andtzname[1]
abbreviates a time zone when daylight saving time is in use (forexample,"EDT"
). These correspond to thestd anddststrings (respectively) when theTZ
environment variableuses the proleptic format.The string values are unspecified ifTZ
uses the geographical format,so it is generally better to use the broken-down time structure’stm_zone
member instead.
In the GNU C Library, the strings have a storage lifetime that lasts indefinitely;on some other platforms, the lifetime lasts only untilTZ
is changed.
Thetzname
array is initialized bytzset
.Though the strings are declared aschar *
the user must refrain from modifying them.Modifying the strings will almost certainly lead to trouble.
long int
timezone ¶This contains the difference between UTC and local standardtime, in seconds west of the Prime Meridian.For example, in the U.S. Eastern timezone, the value is5*60*60
. Unlike thetm_gmtoff
memberof the broken-down time structure, this value is not adjusted fordaylight saving, and its sign is reversed.The value is unspecified ifTZ
uses the geographical format,so it is generally better to use the broken-down time structure’stm_gmtoff
member instead.
int
daylight ¶This variable is nonzero if daylight saving time rules apply.A nonzero value does not necessarily mean that daylight saving time isnow in effect; it means only that daylight saving time is sometimes in effect.This variable has little or no practical use;it is present for POSIX compatibility.
Previous:State Variables for Time Zones, Up:Calendar Time [Contents][Index]
Here is an example program showing the use of some of the calendar timefunctions.
#include <time.h>#include <stdio.h>intmain (void){ /*This buffer is big enough that the strftime calls below cannot possibly exhaust it. */ char buf[256]; /*Get the current time. */ time_t curtime = time (NULL); /*Convert it to local time representation. */ struct tm *lt = localtime (&curtime); if (!lt) return 1; /*Print the date and time in a simple format that is independent of locale. */ strftime (buf, sizeof buf, "%Y-%m-%d %H:%M:%S", lt); puts (buf);
/*Print it in a nicer English format. */ strftime (buf, sizeof buf, "Today is %A, %B %d.", lt); puts (buf); strftime (buf, sizeof buf, "The time is %I:%M %p.", lt); puts (buf); return 0;}
It produces output like this:
2024-06-09 13:50:06Today is Sunday, June 09.The time is 01:50 PM.
Next:Sleeping, Previous:Calendar Time, Up:Date and Time [Contents][Index]
Thealarm
andsetitimer
functions provide a mechanism for aprocess to interrupt itself in the future. They do this by setting atimer; when the timer expires, the process receives a signal.
Each process has three independent interval timers available:
SIGALRM
signal to the process when it expires.SIGVTALRM
signal to the process when it expires.SIGPROF
signal to the process when it expires.This timer is useful for profiling in interpreters. The interval timermechanism does not have the fine granularity necessary for profilingnative code.
You can only have one timer of each kind set at any given time. If youset a timer that has not yet expired, that timer is simply reset to thenew value.
You should establish a handler for the appropriate alarm signal usingsignal
orsigaction
before issuing a call tosetitimer
oralarm
. Otherwise, an unusual chain of eventscould cause the timer to expire before your program establishes thehandler. In this case it would be terminated, since termination is thedefault action for the alarm signals. SeeSignal Handling.
To be able to use the alarm function to interrupt a system call whichmight block otherwise indefinitely it is important tonot set theSA_RESTART
flag when registering the signal handler usingsigaction
. When not usingsigaction
things get evenuglier: thesignal
function has fixed semantics with respectto restarts. The BSD semantics for this function is to set the flag.Therefore, ifsigaction
for whatever reason cannot be used, it isnecessary to usesysv_signal
and notsignal
.
Thesetitimer
function is the primary means for setting an alarm.This facility is declared in the header filesys/time.h. Thealarm
function, declared inunistd.h, provides a somewhatsimpler interface for setting the real-time timer.
This structure is used to specify when a timer should expire. It containsthe following members:
struct timeval it_interval
This is the period between successive timer interrupts. If zero, thealarm will only be sent once.
struct timeval it_value
This is the period between now and the first timer interrupt. If zero,the alarm is disabled.
Thestruct timeval
data type is described inTime Types.
int
setitimer(intwhich, const struct itimerval *new, struct itimerval *old)
¶Preliminary:| MT-Safe timer| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thesetitimer
function sets the timer specified bywhichaccording tonew. Thewhich argument can have a value ofITIMER_REAL
,ITIMER_VIRTUAL
, orITIMER_PROF
.
Ifold is not a null pointer,setitimer
returns informationabout any previous unexpired timer of the same kind in the structure itpoints to.
The return value is0
on success and-1
on failure. Thefollowingerrno
error conditions are defined for this function:
EINVAL
The timer period is too large.
int
getitimer(intwhich, struct itimerval *old)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetitimer
function stores information about the timer specifiedbywhich in the structure pointed at byold.
The return value and error conditions are the same as forsetitimer
.
ITIMER_REAL
¶This constant can be used as thewhich argument to thesetitimer
andgetitimer
functions to specify the real-timetimer.
ITIMER_VIRTUAL
¶This constant can be used as thewhich argument to thesetitimer
andgetitimer
functions to specify the virtualtimer.
ITIMER_PROF
¶This constant can be used as thewhich argument to thesetitimer
andgetitimer
functions to specify the profilingtimer.
unsigned int
alarm(unsigned intseconds)
¶Preliminary:| MT-Safe timer| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thealarm
function sets the real-time timer to expire inseconds seconds. If you want to cancel any existing alarm, youcan do this by callingalarm
with aseconds argument ofzero.
The return value indicates how many seconds remain before the previousalarm would have been sent. If there was no previous alarm,alarm
returns zero.
Thealarm
function could be defined in terms ofsetitimer
like this:
unsigned intalarm (unsigned int seconds){ struct itimerval old, new; new.it_interval.tv_usec = 0; new.it_interval.tv_sec = 0; new.it_value.tv_usec = 0; new.it_value.tv_sec = (long int) seconds; if (setitimer (ITIMER_REAL, &new, &old) < 0) return 0; else return old.it_value.tv_sec;}
There is an example showing the use of thealarm
function inSignal Handlers that Return.
If you simply want your process to wait for a given number of seconds,you should use thesleep
function. SeeSleeping.
You shouldn’t count on the signal arriving precisely when the timerexpires. In a multiprocessing environment there is typically someamount of delay involved.
Portability Note: Thesetitimer
andgetitimer
functions are derived from BSD Unix, while thealarm
function isspecified by POSIX.setitimer
is more powerful thanalarm
, butalarm
is more widely used.
Previous:Setting an Alarm, Up:Date and Time [Contents][Index]
The functionsleep
gives a simple way to make the program waitfor a short interval. If your program doesn’t use signals (except toterminate), then you can expectsleep
to wait reliably throughoutthe specified interval. Otherwise,sleep
can return sooner if asignal arrives; if you want to wait for a given interval regardless ofsignals, useselect
(seeWaiting for Input or Output) and don’t specifyany descriptors to wait for.
unsigned int
sleep(unsigned intseconds)
¶Preliminary:| MT-Unsafe sig:SIGCHLD/linux| AS-Unsafe | AC-Unsafe | SeePOSIX Safety Concepts.
Thesleep
function waits forseconds seconds or until a signalis delivered, whichever happens first.
Ifsleep
returns because the requested interval is over,it returns a value of zero. If it returns because of delivery of asignal, its return value is the remaining time in the sleep interval.
Thesleep
function is declared inunistd.h.
Resist the temptation to implement a sleep for a fixed amount of time byusing the return value ofsleep
, when nonzero, to callsleep
again. This will work with a certain amount of accuracy aslong as signals arrive infrequently. But each signal can cause theeventual wakeup time to be off by an additional second or so. Suppose afew signals happen to arrive in rapid succession by bad luck—there isno limit on how much this could shorten or lengthen the wait.
Instead, compute the calendar time at which the program should stopwaiting, and keep trying to wait until that calendar time. This won’tbe off by more than a second. With just a little more work, you can useselect
and make the waiting period quite accurate. (Of course,heavy system load can cause additional unavoidable delays—unless themachine is dedicated to one application, there is no way you can avoidthis.)
On some systems,sleep
can do strange things if your program usesSIGALRM
explicitly. Even ifSIGALRM
signals are beingignored or blocked whensleep
is called,sleep
mightreturn prematurely on delivery of aSIGALRM
signal. If you haveestablished a handler forSIGALRM
signals and aSIGALRM
signal is delivered while the process is sleeping, the action takenmight be just to causesleep
to return instead of invoking yourhandler. And, ifsleep
is interrupted by delivery of a signalwhose handler requests an alarm or alters the handling ofSIGALRM
,this handler andsleep
will interfere.
On GNU systems, it is safe to usesleep
andSIGALRM
inthe same program, becausesleep
does not work by means ofSIGALRM
.
int
nanosleep(const struct timespec *requested_time, struct timespec *remaining_time)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
If resolution to seconds is not enough, thenanosleep
function canbe used. As the name suggests the sleep interval can be specified innanoseconds. The actual elapsed time of the sleep interval might belonger since the system rounds the elapsed time you request up to thenext integer multiple of the actual resolution the system can deliver.
*requested_time
is the elapsed time of the interval youwant to sleep.
Ifremaining_time is not the null pointer, the function returns as*remaining_time
the elapsed time left in the interval for whichyou requested to sleep. If the interval completed without gettinginterrupted by a signal, this is zero.
struct timespec
is described inTime Types.
If the function returns because the interval is over, it returns zero.Otherwise it returns-1 and sets the global variableerrno
toone of the following values:
EINTR
The call was interrupted because a signal was delivered to the thread.If theremaining_time parameter is not the null pointer, the structurepointed to byremaining_time is updated to contain the remainingelapsed time.
EINVAL
The nanosecond value in therequested_time parameter contains aninvalid value. Either the value is negative or greater than or equal to1000 million.
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timenanosleep
iscalled. If the thread gets canceled, these resources stay allocateduntil the program ends. To avoid this, calls tonanosleep
shouldbe protected using cancellation handlers.
Thenanosleep
function is declared intime.h.
int
clock_nanosleep(clockid_tclock, intflags, const struct timespec *requested_time, struct timespec *remaining_time)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar tonanosleep
while additionally providingthe caller with a way to specify the clock to be used to measure elapsedtime and express the sleep interval in absolute or relative terms. Itreturns zero when returning because the interval is over, and a positiveerror number corresponding to the error encountered otherwise. This isdifferent fromnanosleep
, which returns-1 upon failure andsets the global variableerrno
according to the error encounteredinstead.
Except for the return value convention and the way to communicate an errorcondition the call:
nanosleep (requested_time,remaining_time)
is analogous to:
clock_nanosleep (CLOCK_REALTIME, 0,requested_time,remaining_time)
Theclock argument specifies the clock to use.SeeGetting the Time, for theclockid_t
type and possible valuesofclock. Not all clocks listed are supported for use withclock_nanosleep
. For details, see the manual pageclock_nanosleep(2)SeeLinux (The Linux Kernel).
Theflags argument is either0
orTIMER_ABSTIME
. Ifflags is0
, thenclock_nanosleep
interpretsrequested_time as an interval relative to the current time specifiedbyclock. If it isTIMER_ABSTIME
instead,requested_timespecifies an absolute time measured byclock; if at the time of thecall the value requested is less than or equal to the clock specified, thenthe function returns right away. Whenflags isTIMER_ABSTIME
,remaining_time is not updated.
Theclock_nanosleep
function returns error codes as positive returnvalues. The error conditions forclock_nanosleep
are the same as fornanosleep
, with the following conditions additionally defined:
EINVAL
Theclock argument is not a valid clock.
EOPNOTSUPP
Theclock argument is not supported by the kernel forclock_nanosleep
.
Theclock_nanosleep
function is declared intime.h.
Next:Non-Local Exits, Previous:Date and Time, Up:Main Menu [Contents][Index]
This chapter describes functions for examining how much of various kinds ofresources (CPU time, memory, etc.) a process has used and getting and settinglimits on future usage.
The functiongetrusage
and the data typestruct rusage
are used to examine the resource usage of a process. They are declaredinsys/resource.h.
int
getrusage(intprocesses, struct rusage *rusage)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function reports resource usage totals for processes specified byprocesses, storing the information in*rusage
.
In most systems,processes has only two valid values:
RUSAGE_SELF
¶Just the current process.
RUSAGE_CHILDREN
¶All child processes (direct and indirect) that have already terminated.
The return value ofgetrusage
is zero for success, and-1
for failure.
EINVAL
The argumentprocesses is not valid.
One way of getting resource usage for a particular child process is withthe functionwait4
, which returns totals for a child when itterminates. SeeBSD Process Wait Function.
This data type stores various resource usage statistics. It has thefollowing members, and possibly others:
struct timeval ru_utime
Time spent executing user instructions.
struct timeval ru_stime
Time spent in operating system code on behalf ofprocesses.
long int ru_maxrss
The maximum resident set size used, in kilobytes. That is, the maximumnumber of kilobytes of physical memory thatprocesses usedsimultaneously.
long int ru_ixrss
An integral value expressed in kilobytes times ticks of execution, whichindicates the amount of memory used by text that was shared with otherprocesses.
long int ru_idrss
An integral value expressed the same way, which is the amount ofunshared memory used for data.
long int ru_isrss
An integral value expressed the same way, which is the amount ofunshared memory used for stack space.
long int ru_minflt
The number of page faults which were serviced without requiring any I/O.
long int ru_majflt
The number of page faults which were serviced by doing I/O.
long int ru_nswap
The number of timesprocesses was swapped entirely out of main memory.
long int ru_inblock
The number of times the file system had to read from the disk on behalfofprocesses.
long int ru_oublock
The number of times the file system had to write to the disk on behalfofprocesses.
long int ru_msgsnd
Number of IPC messages sent.
long int ru_msgrcv
Number of IPC messages received.
long int ru_nsignals
Number of signals received.
long int ru_nvcsw
The number of timesprocesses voluntarily invoked a context switch(usually to wait for some service).
long int ru_nivcsw
The number of times an involuntary context switch took place (becausea time slice expired, or another process of higher priority wasscheduled).
Next:Process CPU Priority And Scheduling, Previous:Resource Usage, Up:Resource Usage And Limitation [Contents][Index]
You can specify limits for the resource usage of a process. When theprocess tries to exceed a limit, it may get a signal, or the system callby which it tried to do so may fail, depending on the resource. Eachprocess initially inherits its limit values from its parent, but it cansubsequently change them.
There are two per-process limits associated with a resource:
The current limit is the value the system will not allow usage toexceed. It is also called the “soft limit” because the process beinglimited can generally raise the current limit at will.
The maximum limit is the maximum value to which a process is allowed toset its current limit. It is also called the “hard limit” becausethere is no way for a process to get around it. A process may lowerits own maximum limit, but only the superuser may increase a maximumlimit.
The symbols for use withgetrlimit
,setrlimit
,getrlimit64
, andsetrlimit64
are defined insys/resource.h.
int
getrlimit(intresource, struct rlimit *rlp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Read the current and maximum limits for the resourceresourceand store them in*rlp
.
The return value is0
on success and-1
on failure. Theonly possibleerrno
error condition isEFAULT
.
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32-bit system this function is in factgetrlimit64
. Thus, theLFS interface transparently replaces the old interface.
int
getrlimit64(intresource, struct rlimit64 *rlp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar togetrlimit
but its second parameter isa pointer to a variable of typestruct rlimit64
, which allows itto read values which wouldn’t fit in the member of astructrlimit
.
If the sources are compiled with_FILE_OFFSET_BITS == 64
on a32-bit machine, this function is available under the namegetrlimit
and so transparently replaces the old interface.
int
setrlimit(intresource, const struct rlimit *rlp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Change the current and maximum limits of the process for the resourceresource to the values provided in*rlp
.
The return value is0
on success and-1
on failure. Thefollowingerrno
error condition is possible:
EPERM
When the sources are compiled with_FILE_OFFSET_BITS == 64
on a32-bit system this function is in factsetrlimit64
. Thus, theLFS interface transparently replaces the old interface.
int
setrlimit64(intresource, const struct rlimit64 *rlp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar tosetrlimit
but its second parameter isa pointer to a variable of typestruct rlimit64
which allows itto set values which wouldn’t fit in the member of astructrlimit
.
If the sources are compiled with_FILE_OFFSET_BITS == 64
on a32-bit machine this function is available under the namesetrlimit
and so transparently replaces the old interface.
This structure is used withgetrlimit
to receive limit values,and withsetrlimit
to specify limit values for a particular processand resource. It has two fields:
rlim_t rlim_cur
The current limit
rlim_t rlim_max
The maximum limit.
Forgetrlimit
, the structure is an output; it receives the currentvalues. Forsetrlimit
, it specifies the new values.
For the LFS functions a similar type is defined insys/resource.h.
This structure is analogous to therlimit
structure above, butits components have wider ranges. It has two fields:
rlim64_t rlim_cur
This is analogous torlimit.rlim_cur
, but with a different type.
rlim64_t rlim_max
This is analogous torlimit.rlim_max
, but with a different type.
Here is a list of resources for which you can specify a limit. Memoryand file sizes are measured in bytes.
RLIMIT_CPU
¶The maximum amount of CPU time the process can use. If it runs forlonger than this, it gets a signal:SIGXCPU
. The value ismeasured in seconds. SeeOperation Error Signals.
RLIMIT_FSIZE
¶The maximum size of file the process can create. Trying to write alarger file causes a signal:SIGXFSZ
. SeeOperation Error Signals.
RLIMIT_DATA
¶The maximum size of data memory for the process. If the process triesto allocate data memory beyond this amount, the allocation functionfails.
RLIMIT_STACK
¶The maximum stack size for the process. If the process tries to extendits stack past this size, it gets aSIGSEGV
signal.SeeProgram Error Signals.
RLIMIT_CORE
¶The maximum size core file that this process can create. If the processterminates and would dump a core file larger than this, then no corefile is created. So setting this limit to zero prevents core files fromever being created.
RLIMIT_RSS
¶The maximum amount of physical memory that this process should get.This parameter is a guide for the system’s scheduler and memoryallocator; the system may give the process more memory when there is asurplus.
RLIMIT_MEMLOCK
¶The maximum amount of memory that can be locked into physical memory (soit will never be paged out).
RLIMIT_NPROC
¶The maximum number of processes that can be created with the same user ID.If you have reached the limit for your user ID,fork
will failwithEAGAIN
. SeeCreating a Process.
RLIMIT_NOFILE
¶RLIMIT_OFILE
¶The maximum number of files that the process can open. If it tries toopen more files than this, its open attempt fails witherrno
EMFILE
. SeeError Codes. Not all systems support this limit;GNU does, and 4.4 BSD does.
RLIMIT_AS
¶The maximum size of total memory that this process should get. If theprocess tries to allocate more memory beyond this amount with, forexample,brk
,malloc
,mmap
orsbrk
, theallocation function fails.
RLIM_NLIMITS
¶The number of different resource limits. Any validresourceoperand must be less thanRLIM_NLIMITS
.
rlim_t
RLIM_INFINITY ¶This constant stands for a value of “infinity” when supplied asthe limit value insetrlimit
.
The following are historical functions to do some of what the functionsabove do. The functions above are better choices.
ulimit
and the command symbols are declared inulimit.h.
long int
ulimit(intcmd, …)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
ulimit
gets the current limit or sets the current and maximumlimit for a particular resource for the calling process according to thecommandcmd.
If you are getting a limit, the command argument is the only argument.If you are setting a limit, there is a second argument:long int
limit which is the value to which you are settingthe limit.
Thecmd values and the operations they specify are:
GETFSIZE
¶Get the current limit on the size of a file, in units of 512 bytes.
SETFSIZE
¶Set the current and maximum limit on the size of a file tolimit *512 bytes.
There are also some othercmd values that may do things on somesystems, but they are not supported.
Only the superuser may increase a maximum limit.
When you successfully get a limit, the return value ofulimit
isthat limit, which is never negative. When you successfully set a limit,the return value is zero. When the function fails, the return value is-1
anderrno
is set according to the reason:
EPERM
A process tried to increase a maximum limit, but is not superuser.
vlimit
and its resource symbols are declared insys/vlimit.h.
int
vlimit(intresource, intlimit)
¶Preliminary:| MT-Unsafe race:setrlimit| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
vlimit
sets the current limit for a resource for a process.
resource identifies the resource:
LIM_CPU
¶Maximum CPU time. Same asRLIMIT_CPU
forsetrlimit
.
LIM_FSIZE
¶Maximum file size. Same asRLIMIT_FSIZE
forsetrlimit
.
LIM_DATA
¶Maximum data memory. Same asRLIMIT_DATA
forsetrlimit
.
LIM_STACK
¶Maximum stack size. Same asRLIMIT_STACK
forsetrlimit
.
LIM_CORE
¶Maximum core file size. Same asRLIMIT_COR
forsetrlimit
.
LIM_MAXRSS
¶Maximum physical memory. Same asRLIMIT_RSS
forsetrlimit
.
The return value is zero for success, and-1
witherrno
setaccordingly for failure:
EPERM
The process tried to set its current limit beyond its maximum limit.
Next:Querying memory available resources, Previous:Limiting Resource Usage, Up:Resource Usage And Limitation [Contents][Index]
When multiple processes simultaneously require CPU time, the system’sscheduling policy and process CPU priorities determine which processesget it. This section describes how that determination is made andGNU C Library functions to control it.
It is common to refer to CPU scheduling simply as scheduling and aprocess’ CPU priority simply as the process’ priority, with the CPUresource being implied. Bear in mind, though, that CPU time is not theonly resource a process uses or that processes contend for. In somecases, it is not even particularly important. Giving a process a high“priority” may have very little effect on how fast a process runs withrespect to other processes. The priorities discussed in this sectionapply only to CPU time.
CPU scheduling is a complex issue and different systems do it in wildlydifferent ways. New ideas continually develop and find their way intothe intricacies of the various systems’ scheduling algorithms. Thissection discusses the general concepts, some specifics of systemsthat commonly use the GNU C Library, and some standards.
For simplicity, we talk about CPU contention as if there is only one CPUin the system. But all the same principles apply when a processor hasmultiple CPUs, and knowing that the number of processes that can run atany one time is equal to the number of CPUs, you can easily extrapolatethe information.
The functions described in this section are all defined by the POSIX.1and POSIX.1b standards (thesched…
functions are POSIX.1b).However, POSIX does not define any semantics for the values that thesefunctions get and set. In this chapter, the semantics are based on theLinux kernel’s implementation of the POSIX standard. As you will see,the Linux implementation is quite the inverse of what the authors of thePOSIX syntax had in mind.
Every process has an absolute priority, and it is represented by a number.The higher the number, the higher the absolute priority.
On systems of the past, and most systems today, all processes haveabsolute priority 0 and this section is irrelevant. In that case,SeeTraditional Scheduling. Absolute priorities were invented toaccommodate realtime systems, in which it is vital that certain processesbe able to respond to external events happening in real time, whichmeans they cannot wait around while some other process thatwantsto, but doesn’tneed to run occupies the CPU.
When two processes are in contention to use the CPU at any instant, theone with the higher absolute priority always gets it. This is true even if theprocess with the lower priority is already using the CPU (i.e., thescheduling is preemptive). Of course, we’re only talking aboutprocesses that are running or “ready to run,” which means they areready to execute instructions right now. When a process blocks to waitfor something like I/O, its absolute priority is irrelevant.
NB: The term “runnable” is a synonym for “ready to run.”
When two processes are running or ready to run and both have the sameabsolute priority, it’s more interesting. In that case, who gets theCPU is determined by the scheduling policy. If the processes haveabsolute priority 0, the traditional scheduling policy described inTraditional Scheduling applies. Otherwise, the policies describedinRealtime Scheduling apply.
You normally give an absolute priority above 0 only to a process thatcan be trusted not to hog the CPU. Such processes are designed to block(or terminate) after relatively short CPU runs.
A process begins life with the same absolute priority as its parentprocess. Functions described inBasic Scheduling Functions canchange it.
Only a privileged process can change a process’ absolute priority tosomething other than0
. Only a privileged process or thetarget process’ owner can change its absolute priority at all.
POSIX requires absolute priority values used with the realtimescheduling policies to be consecutive with a range of at least 32. OnLinux, they are 1 through 99. The functionssched_get_priority_max
andsched_set_priority_min
portablytell you what the range is on a particular system.
One thing you must keep in mind when designing real time applications isthat having higher absolute priority than any other process doesn’tguarantee the process can run continuously. Two things that can wreck agood CPU run are interrupts and page faults.
Interrupt handlers live in that limbo between processes. The CPU isexecuting instructions, but they aren’t part of any process. Aninterrupt will stop even the highest priority process. So you mustallow for slight delays and make sure that no device in the system hasan interrupt handler that could cause too long a delay betweeninstructions for your process.
Similarly, a page fault causes what looks like a straightforwardsequence of instructions to take a long time. The fact that otherprocesses get to run while the page faults in is of no consequence,because as soon as the I/O is complete, the higher priority process willkick them out and run again, but the wait for the I/O itself could be aproblem. To neutralize this threat, usemlock
ormlockall
.
There are a few ramifications of the absoluteness of this priority on asingle-CPU system that you need to keep in mind when you choose to set apriority and also when you’re working on a program that runs with highabsolute priority. Consider a process that has higher absolute prioritythan any other process in the system and due to a bug in its program, itgets into an infinite loop. It will never cede the CPU. You can’t runa command to kill it because your command would need to get the CPU inorder to run. The errant program is in complete control. It controlsthe vertical, it controls the horizontal.
There are two ways to avoid this: 1) keep a shell running somewhere witha higher absolute priority or 2) keep a controlling terminal attached tothe high priority process group. All the priority in the world won’tstop an interrupt handler from running and delivering a signal to theprocess if you hit Control-C.
Some systems use absolute priority as a means of allocating a fixedpercentage of CPU time to a process. To do this, a super high priorityprivileged process constantly monitors the process’ CPU usage and raisesits absolute priority when the process isn’t getting its entitled shareand lowers it when the process is exceeding it.
NB: The absolute priority is sometimes called the “staticpriority.” We don’t use that term in this manual because it misses themost important feature of the absolute priority: its absoluteness.
Next:Basic Scheduling Functions, Previous:Absolute Priority, Up:Process CPU Priority And Scheduling [Contents][Index]
Whenever two processes with the same absolute priority are ready to run,the kernel has a decision to make, because only one can run at a time.If the processes have absolute priority 0, the kernel makes this decisionas described inTraditional Scheduling. Otherwise, the decisionis as described in this section.
If two processes are ready to run but have different absolute priorities,the decision is much simpler, and is described inAbsolute Priority.
Each process has a scheduling policy. For processes with absolutepriority other than zero, there are two available:
The most sensible case is where all the processes with a certainabsolute priority have the same scheduling policy. We’ll discuss thatfirst.
In Round Robin, processes share the CPU, each one running for a smallquantum of time (“time slice”) and then yielding to another in acircular fashion. Of course, only processes that are ready to run andhave the same absolute priority are in this circle.
In First Come First Served, the process that has been waiting thelongest to run gets the CPU, and it keeps it until it voluntarilyrelinquishes the CPU, runs out of things to do (blocks), or getspreempted by a higher priority process.
First Come First Served, along with maximal absolute priority andcareful control of interrupts and page faults, is the one to use when aprocess absolutely, positively has to run at full CPU speed or not atall.
Judicious use ofsched_yield
function invocations by processeswith First Come First Served scheduling policy forms a good compromisebetween Round Robin and First Come First Served.
To understand how scheduling works when processes of different schedulingpolicies occupy the same absolute priority, you have to know the nittygritty details of how processes enter and exit the ready to run list.
In both cases, the ready to run list is organized as a true queue, wherea process gets pushed onto the tail when it becomes ready to run and ispopped off the head when the scheduler decides to run it. Note thatready to run and running are two mutually exclusive states. When thescheduler runs a process, that process is no longer ready to run and nolonger in the ready to run list. When the process stops running, itmay go back to being ready to run again.
The only difference between a process that is assigned the Round Robinscheduling policy and a process that is assigned First Come First Serveis that in the former case, the process is automatically booted off theCPU after a certain amount of time. When that happens, the process goesback to being ready to run, which means it enters the queue at the tail.The time quantum we’re talking about is small. Really small. This isnot your father’s timesharing. For example, with the Linux kernel, theround robin time slice is a thousand times shorter than its typicaltime slice for traditional scheduling.
A process begins life with the same scheduling policy as its parent process.Functions described inBasic Scheduling Functions can change it.
Only a privileged process can set the scheduling policy of a processthat has absolute priority higher than 0.
Next:Extensible Scheduling, Previous:Realtime Scheduling, Up:Process CPU Priority And Scheduling [Contents][Index]
This section describes functions in the GNU C Library for setting theabsolute priority and scheduling policy of a process.
Portability Note: On systems that have the functions in thissection, the macro _POSIX_PRIORITY_SCHEDULING is defined in<unistd.h>.
For the case that the scheduling policy is traditional scheduling, morefunctions to fine tune the scheduling are inTraditional Scheduling.
Don’t try to make too much out of the naming and structure of thesefunctions. They don’t match the concepts described in this manualbecause the functions are as defined by POSIX.1b, but the implementationon systems that use the GNU C Library is the inverse of what the POSIXstructure contemplates. The POSIX scheme assumes that the primaryscheduling parameter is the scheduling policy and that the priorityvalue, if any, is a parameter of the scheduling policy. In theimplementation, though, the priority value is king and the schedulingpolicy, if anything, only fine tunes the effect of that priority.
The symbols in this section are declared by including filesched.h.
Portability Note: In POSIX, thepid_t
arguments of thefunctions below refer to process IDs. On Linux, they are actuallythread IDs, and control how specific threads are scheduled withregards to the entire system. The resulting behavior does not conformto POSIX. This is why the following description refers to tasks andtasks IDs, and not processes and process IDs.
This structure describes an absolute priority.
int sched_priority
absolute priority value
int
sched_setscheduler(pid_tpid, intpolicy, const struct sched_param *param)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function sets both the absolute priority and the scheduling policyfor a task.
It assigns the absolute priority value given byparam and thescheduling policypolicy to the task with IDpid,or the calling task ifpid is zero. Ifpolicy isnegative,sched_setscheduler
keeps the existing scheduling policy.
The following macros represent the valid values forpolicy:
On success, the return value is0
. Otherwise, it is-1
andERRNO
is set accordingly. Theerrno
values specificto this function are:
EPERM
CAP_SYS_NICE
permission andpolicy is notSCHED_OTHER
(or it’s negative and theexisting policy is notSCHED_OTHER
.CAP_SYS_NICE
permission and itsowner is not the target task’s owner. I.e., the effective uid of thecalling task is neither the effective nor the real uid of taskpid.ESRCH
There is no task with pidpid andpid is not zero.
EINVAL
sched_get_priority_max
andsched_get_priority_min
tell you what the valid range is.int
sched_getscheduler(pid_tpid)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the scheduling policy assigned to the task withIDpid, or the calling task ifpid is zero.
The return value is the scheduling policy. Seesched_setscheduler
for the possible values.
If the function fails, the return value is instead-1
anderrno
is set accordingly.
Theerrno
values specific to this function are:
ESRCH
There is no task with pidpid and it is not zero.
EINVAL
pid is negative.
Note that this function is not an exact mate tosched_setscheduler
because while that function sets the scheduling policy and the absolutepriority, this function gets only the scheduling policy. To get theabsolute priority, usesched_getparam
.
int
sched_setparam(pid_tpid, const struct sched_param *param)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function sets a task’s absolute priority.
It is functionally identical tosched_setscheduler
withpolicy =-1
.
int
sched_getparam(pid_tpid, struct sched_param *param)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns a task’s absolute priority.
pid is the task ID of the task whose absolute priority you wantto know.
param is a pointer to a structure in which the function stores theabsolute priority of the task.
On success, the return value is0
. Otherwise, it is-1
anderrno
is set accordingly. Theerrno
values specificto this function are:
ESRCH
There is no task with IDpid and it is not zero.
EINVAL
pid is negative.
int
sched_get_priority_min(intpolicy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the lowest absolute priority value that isallowable for a task with scheduling policypolicy.
On Linux, it is 0 for SCHED_OTHER and 1 for everything else.
On success, the return value is0
. Otherwise, it is-1
andERRNO
is set accordingly. Theerrno
values specificto this function are:
EINVAL
policy does not identify an existing scheduling policy.
int
sched_get_priority_max(intpolicy)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the highest absolute priority value that isallowable for a task that with scheduling policypolicy.
On Linux, it is 0 for SCHED_OTHER and 99 for everything else.
On success, the return value is0
. Otherwise, it is-1
andERRNO
is set accordingly. Theerrno
values specificto this function are:
EINVAL
policy does not identify an existing scheduling policy.
int
sched_rr_get_interval(pid_tpid, struct timespec *interval)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the length of the quantum (time slice) used withthe Round Robin scheduling policy, if it is used, for the task withtask IDpid.
It returns the length of time asinterval.
With a Linux kernel, the round robin time slice is always 150microseconds, andpid need not even be a real pid.
The return value is0
on success and in the pathological casethat it fails, the return value is-1
anderrno
is setaccordingly. There is nothing specific that can go wrong with thisfunction, so there are no specificerrno
values.
int
sched_yield(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function voluntarily gives up the task’s claim on the CPU.Depending on the scheduling policy in effect and the tasks ready to runon the system, another task may be scheduled to run instead.
A call tosched_yield
does not guarantee that a different taskfrom the calling task is scheduled as a result; it depends on thescheduling policy used on the target system. It is possible that thecall may not result in any visible effect, i.e., the same task getsscheduled again.
For example on Linux systems, when a simple priority-based FIFOscheduling policy (SCHED_FIFO
) is in effect, the calling task ismade immediately ready to run (as opposed to running, which is what itwas before). This means that if it has absolute priority higher than 0,it gets pushed onto the tail of the queue of tasks that share itsabsolute priority and are ready to run, and it will run again when itsturn next arrives. If its absolute priority is 0, it is morecomplicated, but still has the effect of yielding the CPU to othertasks. If there are no other tasks that share the calling task’sabsolute priority, it will be scheduled again as ifsched_yield
was never called.
Another example could be a time slice based preemptive round-robinpolicy, such as theSCHED_RR
policy on Linux. It is possiblewith this policy that the calling task is scheduled again because itstill has time left in its slice.
To the extent that the containing program is oblivious to what otherprocesses in the system are doing and how fast it executes, thisfunction appears as a no-op.
The return value is0
on success and in the pathological casethat it fails, the return value is-1
anderrno
is setaccordingly. There is nothing specific that can go wrong with thisfunction, so there are no specificerrno
values.
Next:Traditional Scheduling, Previous:Basic Scheduling Functions, Up:Process CPU Priority And Scheduling [Contents][Index]
The typestruct sched_attr
and the functionssched_setattr
andsched_getattr
are used to implement scheduling policies withmultiple parameters (not just priority and niceness).
It is expected that these interfaces will be compatible with all futurescheduling policies.
For additional information about scheduling policies, consultthe manual pagessched(7)SeeLinux (The Linux Kernel) andsched_setattr(2)SeeLinux (The Linux Kernel).
Note: Calling thesched_setattr
function is incompatiblewith support forPTHREAD_PRIO_PROTECT
mutexes.
Thesched_attr
structure describes a parameterized scheduling policy.
Portability note: In the future, additional fields can be addedtostruct sched_attr
at the end, so that the size of this datatype changes. Do not use it in places where this matters, such asstructure fields in installed header files, where such a change couldimpact the application binary interface (ABI).
The following generic fields are available.
size
The actually used size of the data structure. See the description ofthe functionssched_setattr
andsched_getattr
below how thisfield is used to support extension ofstruct sched_attr
withmore fields.
sched_policy
The scheduling policy. This field determines which fields in thestructure are used, and how thesched_flags
field is interpreted.
sched_flags
Scheduling flags associated with the scheduling policy.
In addition to the generic fields, policy-specific fields are available.For additional information, consult the manual pagesched_setattr(2)SeeLinux (The Linux Kernel).
int
sched_setattr(pid_ttid, struct sched_attr *attr, unsigned int flags)
¶| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This functions applies the scheduling policy described by*attr
to the threadtid (the value zero denotes thecurrent thread).
It is recommended to initialize unused fields to zero, either usingmemset
, or using a structure initializer. Theattr->size
field should be set tosizeof (structsched_attr)
, to inform the kernel of the structure version in use.
Theflags argument must be zero. Other values may becomeavailable in the future.
On failure,sched_setattr
returns-1 and setserrno
. The following errors are related the wayextensibility is handled.
E2BIG
A field in*attr
has a non-zero value, but is unknown tothe kernel. The application could try to apply a modified policy, wheremore fields are zero.
EINVAL
The policy inattr->sched_policy
is unknown to the kernel,or flags are set inattr->sched_flags
that the kernel doesnot know how to interpret. The application could try with fewer flagsset, or a different scheduling policy.
This error also occurs ifattr isNULL
orflags isnot zero.
EPERM
The current thread is not sufficiently privileged to assign the policy,either because access to the policy is restricted in general, or becausethe current thread does not have the rights to change the schedulingpolicy of the threadtid.
Other error codes depend on the scheduling policy.
int
sched_getattr(pid_ttid, struct sched_attr *attr, unsigned int size, unsigned int flags)
¶| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function obtains the scheduling policy of the threadtid(zero denotes the current thread) and store it in*attr
,which must have space for at leastsize bytes.
Theflags argument must be zero. Other values may becomeavailable in the future.
Upon success,attr->size
contains the size of the structureversion used by the kernel. Fields with offsets greater or equal toattr->size
may not be overwritten by the kernel. To obtainpredictable values for unknown fields, usememset
to set allsize bytes to zero prior to callingsched_getattr
.
On failure,sched_getattr
returns-1 and setserrno
.Iferrno
isE2BIG
, this means that the buffer is not largelarge enough, and the application could retry with a larger buffer.
Next:Limiting execution to certain CPUs, Previous:Extensible Scheduling, Up:Process CPU Priority And Scheduling [Contents][Index]
This section is about the scheduling among processes whose absolutepriority is 0. When the system hands out the scraps of CPU time thatare left over after the processes with higher absolute priority havetaken all they want, the scheduling described herein determines whoamong the great unwashed processes gets them.
Long before there was absolute priority (SeeAbsolute Priority),Unix systems were scheduling the CPU using this system. When POSIX camein like the Romans and imposed absolute priorities to accommodate theneeds of realtime processing, it left the indigenous Absolute PriorityZero processes to govern themselves by their own familiar schedulingpolicy.
Indeed, absolute priorities higher than zero are not available on manysystems today and are not typically used when they are, being intendedmainly for computers that do realtime processing. So this sectiondescribes the only scheduling many programmers need to be concernedabout.
But just to be clear about the scope of this scheduling: Any time aprocess with an absolute priority of 0 and a process with an absolutepriority higher than 0 are ready to run at the same time, the one withabsolute priority 0 does not run. If it’s already running when thehigher priority ready-to-run process comes into existence, it stopsimmediately.
In addition to its absolute priority of zero, every process has anotherpriority, which we will refer to as "dynamic priority" because it changesover time. The dynamic priority is meaningless for processes withan absolute priority higher than zero.
The dynamic priority sometimes determines who gets the next turn on theCPU. Sometimes it determines how long turns last. Sometimes itdetermines whether a process can kick another off the CPU.
In Linux, the value is a combination of these things, but mostly itjust determines the length of the time slice. The higher a process’dynamic priority, the longer a shot it gets on the CPU when it gets one.If it doesn’t use up its time slice before giving up the CPU to dosomething like wait for I/O, it is favored for getting the CPU back whenit’s ready for it, to finish out its time slice. Other than that,selection of processes for new time slices is basically round robin.But the scheduler does throw a bone to the low priority processes: Aprocess’ dynamic priority rises every time it is snubbed in thescheduling process. In Linux, even the fat kid gets to play.
The fluctuation of a process’ dynamic priority is regulated by anothervalue: The “nice” value. The nice value is an integer, usually in therange -20 to 20, and represents an upper limit on a process’ dynamicpriority. The higher the nice number, the lower that limit.
On a typical Linux system, for example, a process with a nice value of20 can get only 10 milliseconds on the CPU at a time, whereas a processwith a nice value of -20 can achieve a high enough priority to get 400milliseconds.
The idea of the nice value is deferential courtesy. In the beginning,in the Unix garden of Eden, all processes shared equally in the bountyof the computer system. But not all processes really need the sameshare of CPU time, so the nice value gave a courteous process theability to refuse its equal share of CPU time that others might prosper.Hence, the higher a process’ nice value, the nicer the process is.(Then a snake came along and offered some process a negative nice valueand the system became the crass resource allocation system we knowtoday.)
Dynamic priorities tend upward and downward with an objective ofsmoothing out allocation of CPU time and giving quick response time toinfrequent requests. But they never exceed their nice limits, so on aheavily loaded CPU, the nice value effectively determines how fast aprocess runs.
In keeping with the socialistic heritage of Unix process priority, aprocess begins life with the same nice value as its parent process andcan raise it at will. A process can also raise the nice value of anyother process owned by the same user (or effective user). But only aprivileged process can lower its nice value. A privileged process canalso raise or lower another process’ nice value.
GNU C Library functions for getting and setting nice values are described inSeeFunctions For Traditional Scheduling.
Previous:Introduction To Traditional Scheduling, Up:Traditional Scheduling [Contents][Index]
This section describes how you can read and set the nice value of aprocess. All these symbols are declared insys/resource.h.
The function and macro names are defined by POSIX, and refer to"priority," but the functions actually have to do with nice values, asthe terms are used both in the manual and POSIX.
The range of valid nice values depends on the kernel, but typically itruns from-20
to20
. A lower nice value corresponds tohigher priority for the process. These constants describe the range ofpriority values:
int
getpriority(intclass, intid)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Return the nice value of a set of processes;class andidspecify which ones (see below). If the processes specified do not allhave the same nice value, this returns the lowest value that any of themhas.
On success, the return value is0
. Otherwise, it is-1
anderrno
is set accordingly. Theerrno
values specificto this function are:
ESRCH
The combination ofclass andid does not match any existingprocess.
EINVAL
The value ofclass is not valid.
If the return value is-1
, it could indicate failure, or it couldbe the nice value. The only way to make certain is to seterrno =0
before callinggetpriority
, then useerrno != 0
afterward as the criterion for failure.
int
setpriority(intclass, intid, intniceval)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Set the nice value of a set of processes toniceval;classandid specify which ones (see below).
The return value is0
on success, and-1
onfailure. The followingerrno
error condition are possible forthis function:
ESRCH
The combination ofclass andid does not match any existingprocess.
EINVAL
The value ofclass is not valid.
EPERM
The call would set the nice value of a process which is owned by a differentuser than the calling process (i.e., the target process’ real or effectiveuid does not match the calling process’ effective uid) and the callingprocess does not haveCAP_SYS_NICE
permission.
EACCES
The call would lower the process’ nice value and the process does not haveCAP_SYS_NICE
permission.
The argumentsclass andid together specify a set ofprocesses in which you are interested. These are the possible values ofclass:
PRIO_PROCESS
¶One particular process. The argumentid is a process ID (pid).
PRIO_PGRP
¶All the processes in a particular process group. The argumentid isa process group ID (pgid).
PRIO_USER
¶All the processes owned by a particular user (i.e., whose real uidindicates the user). The argumentid is a user ID (uid).
If the argumentid is 0, it stands for the calling process, itsprocess group, or its owner (real uid), according toclass.
int
nice(intincrement)
¶Preliminary:| MT-Unsafe race:setpriority| AS-Unsafe | AC-Safe | SeePOSIX Safety Concepts.
Increment the nice value of the calling process byincrement.The return value is the new nice value on success, and-1
onfailure. In the case of failure,errno
will be set to thesame values as forsetpriority
.
Here is an equivalent definition ofnice
:
intnice (int increment){ int result, old = getpriority (PRIO_PROCESS, 0); result = setpriority (PRIO_PROCESS, 0, old + increment); if (result != -1) return old + increment; else return -1;}
Previous:Traditional Scheduling, Up:Process CPU Priority And Scheduling [Contents][Index]
On a multi-processor system the operating system usually distributesthe different processes which are runnable on all available CPUs in away which allows the system to work most efficiently. Which processesand threads run can to some extend be controlled with the schedulingfunctionality described in the last sections. But which CPU finallyexecutes which process or thread is not covered.
There are a number of reasons why a program might want to have controlover this aspect of the system as well:
The POSIX standard up to this date is of not much help to solve thisproblem. The Linux kernel provides a set of interfaces to allowspecifyingaffinity sets for a process. The scheduler willschedule the thread or process on CPUs specified by the affinitymasks. The interfaces which the GNU C Library define follow to someextent the Linux kernel interface.
This data set is a bitset where each bit represents a CPU. How thesystem’s CPUs are mapped to bits in the bitset is system dependent.The data type has a fixed size; it is strongly recommended to allocatea dynamically sized set based on the actual number of CPUs detected,such as viaget_nprocs_conf()
, and use theCPU_*_S
variants instead of the fixed-size ones.
This type is a GNU extension and is defined insched.h.
To manipulate the bitset, to set and reset bits, and thus add andremove CPUs from the sets, a number of macros are defined. Some ofthe macros take a CPU number as a parameter. Here it is important tonever exceed the size of the bitset, eitherCPU_SETSIZE
forfixed sets or the allocated size for dynamic sets. For each macrothere is a fixed-size version (documented below) and a dynamic-sizedversion (with a_S
suffix).
int
CPU_SETSIZE ¶The value of this macro is the maximum number of CPUs which can behandled with a fixedcpu_set_t
object.
For applications that require CPU sets larger than the built-in size,a set of macros that support dynamically-sized sets are defined.
size_t
CPU_ALLOC_SIZE(size_tcount)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Given a count of CPUs to hold, returns the size of the set toallocate. This return value is appropriate to be used in the *_S macros.
This macro is a GNU extension and is defined insched.h.
cpu_set_t *
CPU_ALLOC(size_tcount)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Given the count of CPUs to hold, returns a set large enough to holdthem; that is, the resulting set will be valid for CPUs numbered 0throughcount-1, inclusive. This set must be freed viaCPU_FREE
to avoid memory leaks. Warning: the argument is theCPUcount and not the size returned byCPU_ALLOC_SIZE
.
This macro is a GNU extension and is defined insched.h.
void
CPU_FREE(cpu_set_t *set)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Frees a CPU set previously allocated byCPU_ALLOC
.
This macro is a GNU extension and is defined insched.h.
The typecpu_set_t
should be considered opaque; allmanipulation should happen via theCPU_*
macros describedbelow.
void
CPU_ZERO(cpu_set_t *set)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro initializes the CPU setset to be the empty set.
This macro is a GNU extension and is defined insched.h.
void
CPU_SET(intcpu, cpu_set_t *set)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro addscpu to the CPU setset.
Thecpu parameter must not have side effects since it isevaluated more than once.
This macro is a GNU extension and is defined insched.h.
void
CPU_CLR(intcpu, cpu_set_t *set)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro removescpu from the CPU setset.
Thecpu parameter must not have side effects since it isevaluated more than once.
This macro is a GNU extension and is defined insched.h.
cpu_set_t *
CPU_AND(cpu_set_t *dest, cpu_set_t *src1, cpu_set_t *src2)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro populatesdest with only those CPUs included in bothsrc1 andsrc2. Its value isdest.
This macro is a GNU extension and is defined insched.h.
cpu_set_t *
CPU_OR(cpu_set_t *dest, cpu_set_t *src1, cpu_set_t *src2)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro populatesdest with those CPUs included in eithersrc1 orsrc2. Its value isdest.
This macro is a GNU extension and is defined insched.h.
cpu_set_t *
CPU_XOR(cpu_set_t *dest, cpu_set_t *src1, cpu_set_t *src2)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro populatesdest with those CPUs included in eithersrc1 orsrc2, but not both. Its value isdest.
This macro is a GNU extension and is defined insched.h.
int
CPU_ISSET(intcpu, const cpu_set_t *set)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value (true) ifcpu is a memberof the CPU setset, and zero (false) otherwise.
Thecpu parameter must not have side effects since it isevaluated more than once.
This macro is a GNU extension and is defined insched.h.
int
CPU_COUNT(const cpu_set_t *set)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns the count of CPUs (bits) set inset.
This macro is a GNU extension and is defined insched.h.
int
CPU_EQUAL(cpu_set_t *src1, cpu_set_t *src2)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns nonzero if the two setsset1 andset2have the same contents; that is, the set of CPUs represented by bothsets is identical.
This macro is a GNU extension and is defined insched.h.
void
CPU_ZERO_S(size_tsize, cpu_set_t *set)
¶void
CPU_SET_S(intcpu, size_tsize, cpu_set_t *set)
¶void
CPU_CLR_S(intcpu, size_tsize, cpu_set_t *set)
¶cpu_set_t *
CPU_AND_S(size_tsize, cpu_set_t *dest, cpu_set_t *src1, cpu_set_t *src2)
¶cpu_set_t *
CPU_OR_S(size_tsize, cpu_set_t *dest, cpu_set_t *src1, cpu_set_t *src2)
¶cpu_set_t *
CPU_XOR_S(size_tsize, cpu_set_t *dest, cpu_set_t *src1, cpu_set_t *src2)
¶int
CPU_ISSET_S(intcpu, size_tsize, const cpu_set_t *set)
¶int
CPU_COUNT_S(size_tsize, const cpu_set_t *set)
¶int
CPU_EQUAL_S(size_tsize, cpu_set_t *src1, cpu_set_t *src2)
¶Each of these macros performs the same action as its non-_S
variant,but takes asize argument to specify the set size. Thissize argument is as returned by theCPU_ALLOC_SIZE
macro,defined above.
CPU bitsets can be constructed from scratch or the currently installedaffinity mask can be retrieved from the system.
int
sched_getaffinity(pid_tpid, size_tcpusetsize, cpu_set_t *cpuset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function stores the CPU affinity mask for the process or threadwith the IDpid in thecpusetsize bytes long bitmappointed to bycpuset. If successful, the function alwaysinitializes all bits in thecpu_set_t
object and returns zero.
Ifpid does not correspond to a process or thread on the systemthe or the function fails for some other reason, it returns-1
anderrno
is set to represent the error condition.
ESRCH
No process or thread with the given ID found.
EFAULT
The pointercpuset does not point to a valid object.
This function is a GNU extension and is declared insched.h.
Note that it is not portably possible to use this information toretrieve the information for different POSIX threads. A separateinterface must be provided for that.
int
sched_setaffinity(pid_tpid, size_tcpusetsize, const cpu_set_t *cpuset)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function installs thecpusetsize bytes long affinity maskpointed to bycpuset for the process or thread with the IDpid.If successful the function returns zero and the scheduler will in the futuretake the affinity information into account.
If the function fails it will return-1
anderrno
is setto the error code:
ESRCH
No process or thread with the given ID found.
EFAULT
The pointercpuset does not point to a valid object.
EINVAL
The bitset is not valid. This might mean that the affinity set mightnot leave a processor for the process or thread to run on.
This function is a GNU extension and is declared insched.h.
int
getcpu(unsigned int *cpu, unsigned int *node)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetcpu
function identifies the processor and node on whichthe calling thread or process is currently running and writes them intothe integers pointed to by thecpu andnode arguments. Theprocessor is a unique nonnegative integer identifying a CPU. The nodeis a unique nonnegative integer identifying a NUMA node. When eithercpu ornode isNULL
, nothing is written to therespective pointer.
The return value is0
on success and-1
on failure. Thefollowingerrno
error condition is defined for this function:
ENOSYS
The operating system does not support this function.
This function is Linux-specific and is declared insched.h.
int
sched_getcpu(void)
¶Similar togetcpu
but with a simpler interface. On success,returns a nonnegative number identifying the CPU on which the currentthread is running. Returns-1
on failure. The followingerrno
error condition is defined for this function:
ENOSYS
The operating system does not support this function.
This function is Linux-specific and is declared insched.h.
Here’s an example of how to use most of the above to limit the numberof CPUs a process runs on, not including error handling or good logicon CPU choices:
#define _GNU_SOURCE#include <sched.h>#include <sys/sysinfo.h>#include <unistd.h>voidlimit_cpus (void){ unsigned int mycpu; size_t nproc, cssz, cpu; cpu_set_t *cs; getcpu (&mycpu, NULL); nproc = get_nprocs_conf (); cssz = CPU_ALLOC_SIZE (nproc); cs = CPU_ALLOC (nproc); sched_getaffinity (0, cssz, cs); if (CPU_COUNT_S (cssz, cs) > nproc / 2) { for (cpu = nproc / 2; cpu < nproc; cpu ++) if (cpu != mycpu) CPU_CLR_S (cpu, cssz, cs); sched_setaffinity (0, cssz, cs); } CPU_FREE (cs);}
Next:Learn about the processors available, Previous:Process CPU Priority And Scheduling, Up:Resource Usage And Limitation [Contents][Index]
The amount of memory available in the system and the way it is organizeddetermines oftentimes the way programs can and have to work. Forfunctions likemmap
it is necessary to know about the size ofindividual memory pages and knowing how much memory is available enablesa program to select appropriate sizes for, say, caches. Before we getinto these details a few words about memory subsystems in traditionalUnix systems will be given.
Next:How to get information about the memory subsystem?, Up:Querying memory available resources [Contents][Index]
Unix systems normally provide processes virtual address spaces. Thismeans that the addresses of the memory regions do not have to corresponddirectly to the addresses of the actual physical memory which stores thedata. An extra level of indirection is introduced which translatesvirtual addresses into physical addresses. This is normally done by thehardware of the processor.
Using a virtual address space has several advantages. The most importantis process isolation. The different processes running on the systemcannot interfere directly with each other. No process can write intothe address space of another process (except when shared memory is usedbut then it is wanted and controlled).
Another advantage of virtual memory is that the address space theprocesses see can actually be larger than the physical memory available.The physical memory can be extended by storage on an external mediawhere the content of currently unused memory regions is stored. Theaddress translation can then intercept accesses to these memory regionsand make memory content available again by loading the data back intomemory. This concept makes it necessary that programs which have to uselots of memory know the difference between available virtual addressspace and available physical memory. If the working set of virtualmemory of all the processes is larger than the available physical memorythe system will slow down dramatically due to constant swapping ofmemory content from the memory to the storage media and back. This iscalled “thrashing”.
A final aspect of virtual memory which is important and follows fromwhat is said in the last paragraph is the granularity of the virtualaddress space handling. When we said that the virtual address handlingstores memory content externally it cannot do this on a byte-by-bytebasis. The administrative overhead does not allow this (leaving alonethe processor hardware). Instead several thousand bytes are handledtogether and form apage. The size of each page is always a powerof two bytes. The smallest page size in use today is 4096, with 8192,16384, and 65536 being other popular sizes.
Previous:Overview about traditional Unix memory handling, Up:Querying memory available resources [Contents][Index]
The page size of the virtual memory the process sees is essential toknow in several situations. Some programming interfaces (e.g.,mmap
, seeMemory-mapped I/O) require the user to provideinformation adjusted to the page size. In the case ofmmap
it isnecessary to provide a length argument which is a multiple of the pagesize. Another place where the knowledge about the page size is usefulis in memory allocation. If one allocates pieces of memory in largerchunks which are then subdivided by the application code it is useful toadjust the size of the larger blocks to the page size. If the totalmemory requirement for the block is close (but not larger) to a multipleof the page size the kernel’s memory handling can work more effectivelysince it only has to allocate memory pages which are fully used. (To dothis optimization it is necessary to know a bit about the memoryallocator which will require a bit of memory itself for each block andthis overhead must not push the total size over the page size multiple.)
The page size traditionally was a compile time constant. But recentdevelopment of processors changed this. Processors now supportdifferent page sizes and they can possibly even vary among differentprocesses on the same system. Therefore the system should be queried atruntime about the current page size and no assumptions (except about itbeing a power of two) should be made.
The correct interface to query about the page size issysconf
(seeDefinition ofsysconf
) with the parameter_SC_PAGESIZE
.There is a much older interface available, too.
int
getpagesize(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetpagesize
function returns the page size of the process.This value is fixed for the runtime of the process but can vary indifferent runs of the application.
The function is declared inunistd.h.
Widely available on System V derived systems is a method to getinformation about the physical memory the system has. The call
sysconf (_SC_PHYS_PAGES)
returns the total number of pages of physical memory the system has.This does not mean all this memory is available. This information canbe found using
sysconf (_SC_AVPHYS_PAGES)
These two values help to optimize applications. The value returned for_SC_AVPHYS_PAGES
is the amount of memory the application can usewithout hindering any other process (given that no other processincreases its memory usage). The value returned for_SC_PHYS_PAGES
is more or less a hard limit for the working set.If all applications together constantly use more than that amount ofmemory the system is in trouble.
The GNU C Library provides in addition to these already described way toget this information two functions. They are declared in the filesys/sysinfo.h. Programmers should prefer to use thesysconf
method described above.
long int
get_phys_pages(void)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Theget_phys_pages
function returns the total number of pages ofphysical memory the system has. To get the amount of memory this number has tobe multiplied by the page size.
This function is a GNU extension.
long int
get_avphys_pages(void)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Theget_avphys_pages
function returns the number of available pages ofphysical memory the system has. To get the amount of memory this number has tobe multiplied by the page size.
This function is a GNU extension.
The use of threads or processes with shared memory allows an applicationto take advantage of all the processing power a system can provide. Ifthe task can be parallelized the optimal way to write an application isto have at any time as many processes running as there are processors.To determine the number of processors available to the system one canrun
sysconf (_SC_NPROCESSORS_CONF)
which returns the number of processors the operating system configured.But it might be possible for the operating system to disable individualprocessors and so the call
sysconf (_SC_NPROCESSORS_ONLN)
returns the number of processors which are currently online (i.e.,available).
For these two pieces of information the GNU C Library also providesfunctions to get the information directly. The functions are declaredinsys/sysinfo.h.
int
get_nprocs_conf(void)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Theget_nprocs_conf
function returns the number of processors theoperating system configured.
This function is a GNU extension.
int
get_nprocs(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
Theget_nprocs
function returns the number of available processors.
This function is a GNU extension.
Before starting more threads it should be checked whether the processorsare not already overused. Unix systems calculate something called theload average. This is a number indicating how many processes wererunning. This number is an average over different periods of time(normally 1, 5, and 15 minutes).
int
getloadavg(doubleloadavg[], intnelem)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe fd| SeePOSIX Safety Concepts.
This function gets the 1, 5 and 15 minute load averages of thesystem. The values are placed inloadavg.getloadavg
willplace at mostnelem elements into the array but never more thanthree elements. The return value is the number of elements written toloadavg, or -1 on error.
This function is declared instdlib.h.
Next:Signal Handling, Previous:Resource Usage And Limitation, Up:Main Menu [Contents][Index]
Sometimes when your program detects an unusual situation inside a deeplynested set of function calls, you would like to be able to immediatelyreturn to an outer level of control. This section describes how you cando suchnon-local exits using thesetjmp
andlongjmp
functions.
Next:Details of Non-Local Exits, Up:Non-Local Exits [Contents][Index]
As an example of a situation where a non-local exit can be useful,suppose you have an interactive program that has a “main loop” thatprompts for and executes commands. Suppose the “read” command readsinput from a file, doing some lexical analysis and parsing of the inputwhile processing it. If a low-level input error is detected, it wouldbe useful to be able to return immediately to the “main loop” insteadof having to make each of the lexical analysis, parsing, and processingphases all have to explicitly deal with error situations initiallydetected by nested calls.
(On the other hand, if each of these phases has to do a substantialamount of cleanup when it exits—such as closing files, deallocatingbuffers or other data structures, and the like—then it can be moreappropriate to do a normal return and have each phase do its owncleanup, because a non-local exit would bypass the intervening phases andtheir associated cleanup code entirely. Alternatively, you could use anon-local exit but do the cleanup explicitly either before or afterreturning to the “main loop”.)
In some ways, a non-local exit is similar to using the ‘return’statement to return from a function. But while ‘return’ abandonsonly a single function call, transferring control back to the point atwhich it was called, a non-local exit can potentially abandon manylevels of nested function calls.
You identify return points for non-local exits by calling the functionsetjmp
. This function saves information about the executionenvironment in which the call tosetjmp
appears in an object oftypejmp_buf
. Execution of the program continues normally afterthe call tosetjmp
, but if an exit is later made to this returnpoint by callinglongjmp
with the correspondingjmp_buf
object, control is transferred back to the point wheresetjmp
wascalled. The return value fromsetjmp
is used to distinguishbetween an ordinary return and a return made by a call tolongjmp
, so calls tosetjmp
usually appear in an ‘if’statement.
Here is how the example program described above might be set up:
#include <setjmp.h>#include <stdlib.h>#include <stdio.h>jmp_buf main_loop;voidabort_to_main_loop (int status){ longjmp (main_loop, status);}intmain (void){ while (1) if (setjmp (main_loop)) puts ("Back at main loop...."); else do_command ();}voiddo_command (void){ char buffer[128]; if (fgets (buffer, 128, stdin) == NULL) abort_to_main_loop (-1); else exit (EXIT_SUCCESS);}
The functionabort_to_main_loop
causes an immediate transfer ofcontrol back to the main loop of the program, no matter where it iscalled from.
The flow of control inside themain
function may appear a littlemysterious at first, but it is actually a common idiom withsetjmp
. A normal call tosetjmp
returns zero, so the“else” clause of the conditional is executed. Ifabort_to_main_loop
is called somewhere within the execution ofdo_command
, then it actually appears as if thesame calltosetjmp
inmain
were returning a second time with a valueof-1
.
So, the general pattern for usingsetjmp
looks something like:
if (setjmp (buffer)) /*Code to clean up after premature return. */ ...else /*Code to be executed normally after setting up the return point. */ ...
Next:Non-Local Exits and Signals, Previous:Introduction to Non-Local Exits, Up:Non-Local Exits [Contents][Index]
Here are the details on the functions and data structures used forperforming non-local exits. These facilities are declared insetjmp.h.
Objects of typejmp_buf
hold the state information tobe restored by a non-local exit. The contents of ajmp_buf
identify a specific place to return to.
int
setjmp(jmp_bufstate)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
When called normally,setjmp
stores information about theexecution state of the program instate and returns zero. Iflongjmp
is later used to perform a non-local exit to thisstate,setjmp
returns a nonzero value.
void
longjmp(jmp_bufstate, intvalue)
¶Preliminary:| MT-Safe | AS-Unsafe plugin corrupt lock/hurd| AC-Unsafe corrupt lock/hurd| SeePOSIX Safety Concepts.
This function restores current execution to the state saved instate, and continues execution from the call tosetjmp
thatestablished that return point. Returning fromsetjmp
by means oflongjmp
returns thevalue argument that was passed tolongjmp
, rather than0
. (But ifvalue is given as0
,setjmp
returns1
).
There are a lot of obscure but important restrictions on the use ofsetjmp
andlongjmp
. Most of these restrictions arepresent because non-local exits require a fair amount of magic on thepart of the C compiler and can interact with other parts of the languagein strange ways.
Thesetjmp
function is actually a macro without an actualfunction definition, so you shouldn’t try to ‘#undef’ it or takeits address. In addition, calls tosetjmp
are safe in only thefollowing contexts:
Return points are valid only during the dynamic extent of the functionthat calledsetjmp
to establish them. If youlongjmp
toa return point that was established in a function that has alreadyreturned, unpredictable and disastrous things are likely to happen.
You should use a nonzerovalue argument tolongjmp
. Whilelongjmp
refuses to pass back a zero argument as the return valuefromsetjmp
, this is intended as a safety net against accidentalmisuse and is not really good programming style.
When you perform a non-local exit, accessible objects generally retainwhatever values they had at the timelongjmp
was called. Theexception is that the values of automatic variables local to thefunction containing thesetjmp
call that have been changed sincethe call tosetjmp
are indeterminate, unless you have declaredthemvolatile
.
Next:Complete Context Control, Previous:Details of Non-Local Exits, Up:Non-Local Exits [Contents][Index]
In BSD Unix systems,setjmp
andlongjmp
also save andrestore the set of blocked signals; seeBlocking Signals. However,the POSIX.1 standard requiressetjmp
andlongjmp
not tochange the set of blocked signals, and provides an additional pair offunctions (sigsetjmp
andsiglongjmp
) to get the BSDbehavior.
The behavior ofsetjmp
andlongjmp
in the GNU C Library iscontrolled by feature test macros; seeFeature Test Macros. Thedefault in the GNU C Library is the POSIX.1 behavior rather than the BSDbehavior.
The facilities in this section are declared in the header filesetjmp.h.
This is similar tojmp_buf
, except that it can also store stateinformation about the set of blocked signals.
int
sigsetjmp(sigjmp_bufstate, intsavesigs)
¶Preliminary:| MT-Safe | AS-Unsafe lock/hurd| AC-Unsafe lock/hurd| SeePOSIX Safety Concepts.
This is similar tosetjmp
. Ifsavesigs is nonzero, the setof blocked signals is saved instate and will be restored if asiglongjmp
is later performed with thisstate.
void
siglongjmp(sigjmp_bufstate, intvalue)
¶Preliminary:| MT-Safe | AS-Unsafe plugin corrupt lock/hurd| AC-Unsafe corrupt lock/hurd| SeePOSIX Safety Concepts.
This is similar tolongjmp
except for the type of itsstateargument. If thesigsetjmp
call that set thisstate used anonzerosavesigs flag,siglongjmp
also restores the set ofblocked signals.
Previous:Non-Local Exits and Signals, Up:Non-Local Exits [Contents][Index]
The Unix standard provides one more set of functions to control theexecution path and these functions are more powerful than thosediscussed in this chapter so far. These functions were part of theoriginal System V API and by this route were added to the UnixAPI. Besides on branded Unix implementations these interfaces are notwidely available. Not all platforms and/or architectures the GNU C Libraryis available on provide this interface. Useconfigure todetect the availability.
Similar to thejmp_buf
andsigjmp_buf
types used for thevariables to contain the state of thelongjmp
functions theinterfaces of interest here have an appropriate type as well. Objectsof this type are normally much larger since more information iscontained. The type is also used in a few more places as we will see.The types and functions described in this section are all defined anddeclared respectively in theucontext.h header file.
Theucontext_t
type is defined as a structure with at least thefollowing elements:
ucontext_t *uc_link
This is a pointer to the next context structure which is used if thecontext described in the current structure returns.
sigset_t uc_sigmask
Set of signals which are blocked when this context is used.
stack_t uc_stack
Stack used for this context. The value need not be (and normally isnot) the stack pointer. SeeUsing a Separate Signal Stack.
mcontext_t uc_mcontext
This element contains the actual state of the process. Themcontext_t
type is also defined in this header but the definitionshould be treated as opaque. Any use of knowledge of the type makesapplications less portable.
Objects of this type have to be created by the user. The initializationand modification happens through one of the following functions:
int
getcontext(ucontext_t *ucp)
¶Preliminary:| MT-Safe race:ucp| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetcontext
function initializes the variable pointed to byucp with the context of the calling thread. The context containsthe content of the registers, the signal mask, and the current stack.Executing the contents would start at the point where thegetcontext
call just returned.
Compatibility Note: Depending on the operating system,information about the current context’s stack may be in theuc_stack
field ofucp, or it may instead be inarchitecture-specific subfields of theuc_mcontext
field.
The function returns0
if successful. Otherwise it returns-1
and setserrno
accordingly.
Thegetcontext
function is similar tosetjmp
but it doesnot provide an indication of whethergetcontext
is returning forthe first time or whether an initialized context has just been restored.If this is necessary the user has to determine this herself. This mustbe done carefully since the context contains registers which might containregister variables. This is a good situation to define variables withvolatile
.
Once the context variable is initialized it can be used as is or it canbe modified using themakecontext
function. The latter is normallydone when implementing co-routines or similar constructs.
void
makecontext(ucontext_t *ucp, void (*func) (void), intargc, …)
¶Preliminary:| MT-Safe race:ucp| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theucp parameter passed tomakecontext
shall beinitialized by a call togetcontext
. The context will bemodified in a way such that if the context is resumed it will start bycalling the functionfunc
which getsargc integer argumentspassed. The integer arguments which are to be passed should follow theargc parameter in the call tomakecontext
.
Before the call to this function theuc_stack
anduc_link
element of theucp structure should be initialized. Theuc_stack
element describes the stack which is used for thiscontext. No two contexts which are used at the same time should use thesame memory region for a stack.
Theuc_link
element of the object pointed to byucp shouldbe a pointer to the context to be executed when the functionfuncreturns or it should be a null pointer. Seesetcontext
for moreinformation about the exact use.
While allocating the memory for the stack one has to be careful. Mostmodern processors keep track of whether a certain memory region isallowed to contain code which is executed or not. Data segments andheap memory are normally not tagged to allow this. The result is thatprograms would fail. Examples for such code include the callingsequences the GNU C compiler generates for calls to nested functions.Safe ways to allocate stacks correctly include using memory on theoriginal thread’s stack or explicitly allocating memory tagged forexecution using (seeMemory-mapped I/O).
Compatibility note: The current Unix standard is very impreciseabout the way the stack is allocated. All implementations seem to agreethat theuc_stack
element must be used but the values stored inthe elements of thestack_t
value are unclear. The GNU C Libraryand most other Unix implementations require thess_sp
value oftheuc_stack
element to point to the base of the memory regionallocated for the stack and the size of the memory region is stored inss_size
. There are implementations out there which requiress_sp
to be set to the value the stack pointer will have (whichcan, depending on the direction the stack grows, be different). Thisdifference makes themakecontext
function hard to use and itrequires detection of the platform at compile time.
int
setcontext(const ucontext_t *ucp)
¶Preliminary:| MT-Safe race:ucp| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Thesetcontext
function restores the context described byucp. The context is not modified and can be reused as often aswanted.
If the context was created bygetcontext
execution resumes withthe registers filled with the same values and the same stack as if thegetcontext
call just returned.
If the context was modified with a call tomakecontext
executioncontinues with the function passed tomakecontext
which gets thespecified parameters passed. If this function returns execution isresumed in the context which was referenced by theuc_link
element of the context structure passed tomakecontext
at thetime of the call. Ifuc_link
was a null pointer the applicationterminates normally with an exit status value ofEXIT_SUCCESS
(seeProgram Termination).
If the context was created by a call to a signal handler or from anyother source then the behaviour ofsetcontext
is unspecified.
Since the context contains information about the stack no two threadsshould use the same context at the same time. The result in most caseswould be disastrous.
Thesetcontext
function does not return unless an error occurredin which case it returns-1
.
Thesetcontext
function simply replaces the current context withthe one described by theucp parameter. This is often useful butthere are situations where the current context has to be preserved.
int
swapcontext(ucontext_t *restrictoucp, const ucontext_t *restrictucp)
¶Preliminary:| MT-Safe race:oucp race:ucp| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theswapcontext
function is similar tosetcontext
butinstead of just replacing the current context the latter is first savedin the object pointed to byoucp as if this was a call togetcontext
. The saved context would resume after the call toswapcontext
.
Once the current context is saved the context described inucp isinstalled and execution continues as described in this context.
Ifswapcontext
succeeds the function does not return unless thecontextoucp is used without prior modification bymakecontext
. The return value in this case is0
. If thefunction fails it returns-1
and setserrno
accordingly.
The easiest way to use the context handling functions is as areplacement forsetjmp
andlongjmp
. The context containson most platforms more information which may lead to fewer surprisesbut this also means using these functions is more expensive (besidesbeing less portable).
intrandom_search (int n, int (*fp) (int, ucontext_t *)){ volatile int cnt = 0; ucontext_t uc; /*Safe current context. */ if (getcontext (&uc) < 0) return -1; /*If we have not triedn times try again. */ if (cnt++ < n) /*Call the function with a new random numberand the context. */ if (fp (rand (), &uc) != 0) /*We found what we were looking for. */ return 1; /*Not found. */ return 0;}
Using contexts in such a way enables emulating exception handling. Thesearch functions passed in thefp parameter could be very large,nested, and complex which would make it complicated (or at least wouldrequire a lot of code) to leave the function with an error value whichhas to be passed down to the caller. By using the context it ispossible to leave the search function in one step and allow restartingthe search which also has the nice side effect that it can besignificantly faster.
Something which is harder to implement withsetjmp
andlongjmp
is to switch temporarily to a different execution pathand then resume where execution was stopped.
#include <signal.h>#include <stdio.h>#include <stdlib.h>#include <ucontext.h>#include <sys/time.h>/*Set by the signal handler. */static volatile int expired;/*The contexts. */static ucontext_t uc[3];/*We do only a certain number of switches. */static int switches;/*This is the function doing the work. It is just a skeleton, real code has to be filled in. */static voidf (int n){ int m = 0; while (1) { /*This is where the work would be done. */ if (++m % 100 == 0) { putchar ('.'); fflush (stdout); } /*Regularly theexpire variable must be checked. */ if (expired) { /*We do not want the program to run forever. */ if (++switches == 20) return; printf ("\nswitching from %d to %d\n", n, 3 - n); expired = 0; /*Switch to the other context, saving the current one. */ swapcontext (&uc[n], &uc[3 - n]); } }}/*This is the signal handler which simply set the variable. */voidhandler (int signal){ expired = 1;}intmain (void){ struct sigaction sa; struct itimerval it; char st1[8192]; char st2[8192]; /*Initialize the data structures for the interval timer. */ sa.sa_flags = SA_RESTART; sigfillset (&sa.sa_mask); sa.sa_handler = handler; it.it_interval.tv_sec = 0; it.it_interval.tv_usec = 1; it.it_value = it.it_interval; /*Install the timer and get the context we can manipulate. */ if (sigaction (SIGPROF, &sa, NULL) < 0 || setitimer (ITIMER_PROF, &it, NULL) < 0 || getcontext (&uc[1]) == -1 || getcontext (&uc[2]) == -1) abort (); /*Create a context with a separate stack which causes the functionf
to be call with the parameter1
. Note that theuc_link
points to the main context which will cause the program to terminate once the function return. */ uc[1].uc_link = &uc[0]; uc[1].uc_stack.ss_sp = st1; uc[1].uc_stack.ss_size = sizeof st1; makecontext (&uc[1], (void (*) (void)) f, 1, 1); /*Similarly, but2
is passed as the parameter tof
. */ uc[2].uc_link = &uc[0]; uc[2].uc_stack.ss_sp = st2; uc[2].uc_stack.ss_size = sizeof st2; makecontext (&uc[2], (void (*) (void)) f, 1, 2); /*Start running. */ swapcontext (&uc[0], &uc[1]); putchar ('\n'); return 0;}
This an example how the context functions can be used to implementco-routines or cooperative multi-threading. All that has to be done isto call every once in a whileswapcontext
to continue running adifferent context. It is not recommended to do the context switching fromthe signal handler directly since leaving the signal handler viasetcontext
if the signal was delivered during code that was notasynchronous signal safe could lead to problems. Setting a variable inthe signal handler and checking it in the body of the functions whichare executed is a safer approach. Sinceswapcontext
is saving thecurrent context it is possible to have multiple different scheduling pointsin the code. Execution will always resume where it was left.
Next:The Basic Program/System Interface, Previous:Non-Local Exits, Up:Main Menu [Contents][Index]
Asignal is a software interrupt delivered to a process. Theoperating system uses signals to report exceptional situations to anexecuting program. Some signals report errors such as references toinvalid memory addresses; others report asynchronous events, such asdisconnection of a phone line.
The GNU C Library defines a variety of signal types, each for aparticular kind of event. Some kinds of events make it inadvisable orimpossible for the program to proceed as usual, and the correspondingsignals normally abort the program. Other kinds of signals that reportharmless events are ignored by default.
If you anticipate an event that causes signals, you can define a handlerfunction and tell the operating system to run it when that particulartype of signal arrives.
Finally, one process can send a signal to another process; this allows aparent process to abort a child, or two related processes to communicateand synchronize.
Next:Standard Signals, Up:Signal Handling [Contents][Index]
This section explains basic concepts of how signals are generated, whathappens after a signal is delivered, and how programs can handlesignals.
A signal reports the occurrence of an exceptional event. These are someof the events that can cause (orgenerate, orraise) asignal:
kill
orraise
by the same process.kill
from another process. Signals are a limited butuseful form of interprocess communication.Each of these kinds of events (excepting explicit calls tokill
andraise
) generates its own particular kind of signal. Thevarious kinds of signals are listed and described in detail inStandard Signals.
Next:How Signals Are Delivered, Previous:Some Kinds of Signals, Up:Basic Concepts of Signals [Contents][Index]
In general, the events that generate signals fall into three majorcategories: errors, external events, and explicit requests.
An error means that a program has done something invalid and cannotcontinue execution. But not all kinds of errors generate signals—infact, most do not. For example, opening a nonexistent file is an error,but it does not raise a signal; instead,open
returns-1
.In general, errors that are necessarily associated with certain libraryfunctions are reported by returning a value that indicates an error.The errors which raise signals are those which can happen anywhere inthe program, not just in library calls. These include division by zeroand invalid memory addresses.
An external event generally has to do with I/O or other processes.These include the arrival of input, the expiration of a timer, and thetermination of a child process.
An explicit request means the use of a library function such askill
whose purpose is specifically to generate a signal.
Signals may be generatedsynchronously orasynchronously. Asynchronous signal pertains to a specific action in the program, and isdelivered (unless blocked) during that action. Most errors generatesignals synchronously, and so do explicit requests by a process togenerate a signal for that same process. On some machines, certainkinds of hardware errors (usually floating-point exceptions) are notreported completely synchronously, but may arrive a few instructionslater.
Asynchronous signals are generated by events outside the control of theprocess that receives them. These signals arrive at unpredictable timesduring execution. External events generate signals asynchronously, andso do explicit requests that apply to some other process.
A given type of signal is either typically synchronous or typicallyasynchronous. For example, signals for errors are typically synchronousbecause errors generate signals synchronously. But any type of signalcan be generated synchronously or asynchronously with an explicitrequest.
Previous:Concepts of Signal Generation, Up:Basic Concepts of Signals [Contents][Index]
When a signal is generated, it becomespending. Normally itremains pending for just a short period of time and then isdelivered to the process that was signaled. However, if that kindof signal is currentlyblocked, it may remain pendingindefinitely—until signals of that kind areunblocked. Onceunblocked, it will be delivered immediately. SeeBlocking Signals.
When the signal is delivered, whether right away or after a long delay,thespecified action for that signal is taken. For certainsignals, such asSIGKILL
andSIGSTOP
, the action is fixed,but for most signals, the program has a choice: ignore the signal,specify ahandler function, or accept thedefault action forthat kind of signal. The program specifies its choice using functionssuch assignal
orsigaction
(seeSpecifying Signal Actions). Wesometimes say that a handlercatches the signal. While thehandler is running, that particular signal is normally blocked.
If the specified action for a kind of signal is to ignore it, then anysuch signal which is generated is discarded immediately. This happenseven if the signal is also blocked at the time. A signal discarded inthis way will never be delivered, not even if the program subsequentlyspecifies a different action for that kind of signal and then unblocksit.
If a signal arrives which the program has neither handled nor ignored,itsdefault action takes place. Each kind of signal has its owndefault action, documented below (seeStandard Signals). For most kindsof signals, the default action is to terminate the process. For certainkinds of signals that represent “harmless” events, the default actionis to do nothing.
When a signal terminates a process, its parent process can determine thecause of termination by examining the termination status code reportedby thewait
orwaitpid
functions. (This is discussed inmore detail inProcess Completion.) The information it can getincludes the fact that termination was due to a signal and the kind ofsignal involved. If a program you run from a shell is terminated by asignal, the shell typically prints some kind of error message.
The signals that normally represent program errors have a specialproperty: when one of these signals terminates the process, it alsowrites acore dump file which records the state of the process atthe time of termination. You can examine the core dump with a debuggerto investigate what caused the error.
If you raise a “program error” signal by explicit request, and thisterminates the process, it makes a core dump file just as if the signalhad been due directly to an error.
Next:Specifying Signal Actions, Previous:Basic Concepts of Signals, Up:Signal Handling [Contents][Index]
This section lists the names for various standard kinds of signals anddescribes what kind of event they mean. Each signal name is a macrowhich stands for a positive integer—thesignal number for thatkind of signal. Your programs should never make assumptions about thenumeric code for a particular kind of signal, but rather refer to themalways by the names defined here. This is because the number for agiven kind of signal can vary from system to system, but the meanings ofthe names are standardized and fairly uniform.
The signal names are defined in the header filesignal.h.
int
NSIG ¶The value of this symbolic constant is the total number of signalsdefined. Since the signal numbers are allocated consecutively,NSIG
is also one greater than the largest defined signal number.
Next:Termination Signals, Up:Standard Signals [Contents][Index]
The following signals are generated when a serious program error isdetected by the operating system or the computer itself. In general,all of these signals are indications that your program is seriouslybroken in some way, and there’s usually no way to continue thecomputation which encountered the error.
Some programs handle program error signals in order to tidy up beforeterminating; for example, programs that turn off echoing of terminalinput should handle program error signals in order to turn echoing backon. The handler should end by specifying the default action for thesignal that happened and then reraising it; this will cause the programto terminate with that signal, as if it had not had a handler.(SeeHandlers That Terminate the Process.)
Termination is the sensible ultimate outcome from a program error inmost programs. However, programming systems such as Lisp that can loadcompiled user programs might need to keep executing even if a userprogram incurs an error. These programs have handlers which uselongjmp
to return control to the command level.
The default action for all of these signals is to cause the process toterminate. If you block or ignore these signals or establish handlersfor them that return normally, your program will probably break horriblywhen such signals happen, unless they are generated byraise
orkill
instead of a real error.
When one of these program error signals terminates a process, it alsowrites acore dump file which records the state of the process atthe time of termination. The core dump file is namedcore and iswritten in whichever directory is current in the process at the time.(On GNU/Hurd systems, you can specify the file name for core dumps withthe environment variableCOREFILE
.) The purpose of core dumpfiles is so that you can examine them with a debugger to investigatewhat caused the error.
int
SIGFPE ¶TheSIGFPE
signal reports a fatal arithmetic error. Although thename is derived from “floating-point exception”, this signal actuallycovers all arithmetic errors, including division by zero and overflow.If a program stores integer data in a location which is then used in afloating-point operation, this often causes an “invalid operation”exception, because the processor cannot recognize the data as afloating-point number.
Actual floating-point exceptions are a complicated subject because thereare many types of exceptions with subtly different meanings, and theSIGFPE
signal doesn’t distinguish between them. TheIEEEStandard for Binary Floating-Point Arithmetic (ANSI/IEEE Std 754-1985and ANSI/IEEE Std 854-1987)defines various floating-point exceptions and requires conformingcomputer systems to report their occurrences. However, this standarddoes not specify how the exceptions are reported, or what kinds ofhandling and control the operating system can offer to the programmer.
BSD systems provide theSIGFPE
handler with an extra argumentthat distinguishes various causes of the exception. In order to accessthis argument, you must define the handler to accept two arguments,which means you must cast it to a one-argument function type in order toestablish the handler. The GNU C Library does provide this extraargument, but the value is meaningful only on operating systems thatprovide the information (BSD systems and GNU systems).
FPE_INTOVF_TRAP
¶Integer overflow (impossible in a C program unless you enable overflowtrapping in a hardware-specific fashion).
FPE_INTDIV_TRAP
¶Integer division by zero.
FPE_SUBRNG_TRAP
¶Subscript-range (something that C programs never check for).
FPE_FLTOVF_TRAP
¶Floating overflow trap.
FPE_FLTDIV_TRAP
¶Floating/decimal division by zero.
FPE_FLTUND_TRAP
¶Floating underflow trap. (Trapping on floating underflow is notnormally enabled.)
FPE_DECOVF_TRAP
¶Decimal overflow trap. (Only a few machines have decimal arithmetic andC never uses it.)
int
SIGILL ¶The name of this signal is derived from “illegal instruction”; itusually means your program is trying to execute garbage or a privilegedinstruction. Since the C compiler generates only valid instructions,SIGILL
typically indicates that the executable file is corrupted,or that you are trying to execute data. Some common ways of gettinginto the latter situation are by passing an invalid object where apointer to a function was expected, or by writing past the end of anautomatic array (or similar problems with pointers to automaticvariables) and corrupting other data on the stack such as the returnaddress of a stack frame.
SIGILL
can also be generated when the stack overflows, or whenthe system has trouble running the handler for a signal.
int
SIGSEGV ¶This signal is generated when a program tries to read or write outsidethe memory that is allocated for it, or to write memory that can only beread. (Actually, the signals only occur when the program goes farenough outside to be detected by the system’s memory protectionmechanism.) The name is an abbreviation for “segmentation violation”.
Common ways of getting aSIGSEGV
condition include dereferencinga null or uninitialized pointer, or when you use a pointer to stepthrough an array, but fail to check for the end of the array. It variesamong systems whether dereferencing a null pointer generatesSIGSEGV
orSIGBUS
.
int
SIGBUS ¶This signal is generated when an invalid pointer is dereferenced. LikeSIGSEGV
, this signal is typically the result of dereferencing anuninitialized pointer. The difference between the two is thatSIGSEGV
indicates an invalid access to valid memory, whileSIGBUS
indicates an access to an invalid address. In particular,SIGBUS
signals often result from dereferencing a misalignedpointer, such as referring to a four-word integer at an address notdivisible by four. (Each kind of computer has its own requirements foraddress alignment.)
The name of this signal is an abbreviation for “bus error”.
int
SIGABRT ¶This signal indicates an error detected by the program itself andreported by callingabort
. SeeAborting a Program.
int
SIGIOT ¶Generated by the PDP-11 “iot” instruction. On most machines, this isjust another name forSIGABRT
.
int
SIGTRAP ¶Generated by the machine’s breakpoint instruction, and possibly othertrap instructions. This signal is used by debuggers. Your program willprobably only seeSIGTRAP
if it is somehow executing badinstructions.
int
SIGEMT ¶Emulator trap; this results from certain unimplemented instructionswhich might be emulated in software, or the operating system’sfailure to properly emulate them.
int
SIGSYS ¶System call event. This signal may be generated by a valid systemcall which requested an invalid sub-function, and also by the SECCOMPfilter when it filters or traps a system call.
If the system call itself is invalid or unsupported by the kernel, thecall will not raise this signal, but will returnENOSYS
.
int
SIGSTKFLT ¶Coprocessor stack fault. Obsolete, no longer generated. This signalmay be used by applications in much the waySIGUSR1
andSIGUSR2
are.
Next:Alarm Signals, Previous:Program Error Signals, Up:Standard Signals [Contents][Index]
These signals are all used to tell a process to terminate, in one wayor another. They have different names because they’re used for slightlydifferent purposes, and programs might want to handle them differently.
The reason for handling these signals is usually so your program cantidy up as appropriate before actually terminating. For example, youmight want to save state information, delete temporary files, or restorethe previous terminal modes. Such a handler should end by specifyingthe default action for the signal that happened and then reraising it;this will cause the program to terminate with that signal, as if it hadnot had a handler. (SeeHandlers That Terminate the Process.)
The (obvious) default action for all of these signals is to cause theprocess to terminate.
int
SIGTERM ¶TheSIGTERM
signal is a generic signal used to cause programtermination. UnlikeSIGKILL
, this signal can be blocked,handled, and ignored. It is the normal way to politely ask a program toterminate.
int
SIGINT ¶TheSIGINT
(“program interrupt”) signal is sent when the usertypes the INTR character (normallyC-c). SeeSpecial Characters, for information about terminal driver support forC-c.
int
SIGQUIT ¶TheSIGQUIT
signal is similar toSIGINT
, except that it’scontrolled by a different key—the QUIT character, usuallyC-\—and produces a core dump when it terminates the process,just like a program error signal. You can think of this as aprogram error condition “detected” by the user.
SeeProgram Error Signals, for information about core dumps.SeeSpecial Characters, for information about terminal driversupport.
Certain kinds of cleanups are best omitted in handlingSIGQUIT
.For example, if the program creates temporary files, it should handlethe other termination requests by deleting the temporary files. But itis better forSIGQUIT
not to delete them, so that the user canexamine them in conjunction with the core dump.
int
SIGKILL ¶TheSIGKILL
signal is used to cause immediate program termination.It cannot be handled or ignored, and is therefore always fatal. It isalso not possible to block this signal.
This signal is usually generated only by explicit request. Since itcannot be handled, you should generate it only as a last resort, afterfirst trying a less drastic method such asC-c orSIGTERM
.If a process does not respond to any other termination signals, sendingit aSIGKILL
signal will almost always cause it to go away.
In fact, ifSIGKILL
fails to terminate a process, that by itselfconstitutes an operating system bug which you should report.
The system will generateSIGKILL
for a process itself under someunusual conditions where the program cannot possibly continue to run(even to run a signal handler).
int
SIGHUP ¶TheSIGHUP
(“hang-up”) signal is used to report that the user’sterminal is disconnected, perhaps because a network or telephoneconnection was broken. For more information about this, seeControl Modes.
This signal is also used to report the termination of the controllingprocess on a terminal to jobs associated with that session; thistermination effectively disconnects all processes in the session fromthe controlling terminal. For more information, seeTermination Internals.
Next:Asynchronous I/O Signals, Previous:Termination Signals, Up:Standard Signals [Contents][Index]
These signals are used to indicate the expiration of timers.SeeSetting an Alarm, for information about functions that causethese signals to be sent.
The default behavior for these signals is to cause program termination.This default is rarely useful, but no other default would be useful;most of the ways of using these signals would require handler functionsin any case.
int
SIGALRM ¶This signal typically indicates expiration of a timer that measures realor clock time. It is used by thealarm
function, for example.
int
SIGVTALRM ¶This signal typically indicates expiration of a timer that measures CPUtime used by the current process. The name is an abbreviation for“virtual time alarm”.
int
SIGPROF ¶This signal typically indicates expiration of a timer that measuresboth CPU time used by the current process, and CPU time expended onbehalf of the process by the system. Such a timer is used to implementcode profiling facilities, hence the name of this signal.
Next:Job Control Signals, Previous:Alarm Signals, Up:Standard Signals [Contents][Index]
The signals listed in this section are used in conjunction withasynchronous I/O facilities. You have to take explicit action bycallingfcntl
to enable a particular file descriptor to generatethese signals (seeInterrupt-Driven Input). The default action for thesesignals is to ignore them.
int
SIGIO ¶This signal is sent when a file descriptor is ready to perform inputor output.
On most operating systems, terminals and sockets are the only kinds offiles that can generateSIGIO
; other kinds, including ordinaryfiles, never generateSIGIO
even if you ask them to.
On GNU systemsSIGIO
will always be generated properlyif you successfully set asynchronous mode withfcntl
.
int
SIGURG ¶This signal is sent when “urgent” or out-of-band data arrives on asocket. SeeOut-of-Band Data.
int
SIGPOLL ¶This is a System V signal name, more or less similar toSIGIO
.It is defined only for compatibility.
Next:Operation Error Signals, Previous:Asynchronous I/O Signals, Up:Standard Signals [Contents][Index]
These signals are used to support job control. If your systemdoesn’t support job control, then these macros are defined but thesignals themselves can’t be raised or handled.
You should generally leave these signals alone unless you reallyunderstand how job control works. SeeJob Control.
int
SIGCHLD ¶This signal is sent to a parent process whenever one of its childprocesses terminates or stops.
The default action for this signal is to ignore it. If you establish ahandler for this signal while there are child processes that haveterminated but not reported their status viawait
orwaitpid
(seeProcess Completion), whether your new handlerapplies to those processes or not depends on the particular operatingsystem.
int
SIGCLD ¶This is an obsolete name forSIGCHLD
.
int
SIGCONT ¶You can send aSIGCONT
signal to a process to make it continue.This signal is special—it always makes the process continue if it isstopped, before the signal is delivered. The default behavior is to donothing else. You cannot block this signal. You can set a handler, butSIGCONT
always makes the process continue regardless.
Most programs have no reason to handleSIGCONT
; they simplyresume execution without realizing they were ever stopped. You can usea handler forSIGCONT
to make a program do something special whenit is stopped and continued—for example, to reprint a prompt when itis suspended while waiting for input.
int
SIGSTOP ¶TheSIGSTOP
signal stops the process. It cannot be handled,ignored, or blocked.
int
SIGTSTP ¶TheSIGTSTP
signal is an interactive stop signal. UnlikeSIGSTOP
, this signal can be handled and ignored.
Your program should handle this signal if you have a special need toleave files or system tables in a secure state when a process isstopped. For example, programs that turn off echoing should handleSIGTSTP
so they can turn echoing back on before stopping.
This signal is generated when the user types the SUSP character(normallyC-z). For more information about terminal driversupport, seeSpecial Characters.
int
SIGTTIN ¶A process cannot read from the user’s terminal while it is runningas a background job. When any process in a background job tries toread from the terminal, all of the processes in the job are sent aSIGTTIN
signal. The default action for this signal is tostop the process. For more information about how this interacts withthe terminal driver, seeAccess to the Controlling Terminal.
int
SIGTTOU ¶This is similar toSIGTTIN
, but is generated when a process in abackground job attempts to write to the terminal or set its modes.Again, the default action is to stop the process.SIGTTOU
isonly generated for an attempt to write to the terminal if theTOSTOP
output mode is set; seeOutput Modes.
While a process is stopped, no more signals can be delivered to it untilit is continued, exceptSIGKILL
signals and (obviously)SIGCONT
signals. The signals are marked as pending, but notdelivered until the process is continued. TheSIGKILL
signalalways causes termination of the process and can’t be blocked, handledor ignored. You can ignoreSIGCONT
, but it always causes theprocess to be continued anyway if it is stopped. Sending aSIGCONT
signal to a process causes any pending stop signals forthat process to be discarded. Likewise, any pendingSIGCONT
signals for a process are discarded when it receives a stop signal.
When a process in an orphaned process group (seeOrphaned Process Groups) receives aSIGTSTP
,SIGTTIN
, orSIGTTOU
signal and does not handle it, the process does not stop. Stopping theprocess would probably not be very useful, since there is no shellprogram that will notice it stop and allow the user to continue it.What happens instead depends on the operating system you are using.Some systems may do nothing; others may deliver another signal instead,such asSIGKILL
orSIGHUP
. On GNU/Hurd systems, the processdies withSIGKILL
; this avoids the problem of many stopped,orphaned processes lying around the system.
Next:Miscellaneous Signals, Previous:Job Control Signals, Up:Standard Signals [Contents][Index]
These signals are used to report various errors generated by anoperation done by the program. They do not necessarily indicate aprogramming error in the program, but an error that prevents anoperating system call from completing. The default action for all ofthem is to cause the process to terminate.
int
SIGPIPE ¶Broken pipe. If you use pipes or FIFOs, you have to design yourapplication so that one process opens the pipe for reading beforeanother starts writing. If the reading process never starts, orterminates unexpectedly, writing to the pipe or FIFO raises aSIGPIPE
signal. IfSIGPIPE
is blocked, handled orignored, the offending call fails withEPIPE
instead.
Pipes and FIFO special files are discussed in more detail inPipes and FIFOs.
Another cause ofSIGPIPE
is when you try to output to a socketthat isn’t connected. SeeSending Data.
int
SIGLOST ¶Resource lost. On GNU/Hurd systems,SIGLOST
is generated whenany server program dies unexpectedly. It is usually fine to ignorethe signal; whatever call was made to the server that died justreturns an error. This signal’s original purpose of signalling a lostNFS lock is obsolete.
int
SIGXCPU ¶CPU time limit exceeded. This signal is generated when the processexceeds its soft resource limit on CPU time. SeeLimiting Resource Usage.
int
SIGXFSZ ¶File size limit exceeded. This signal is generated when the processattempts to extend a file so it exceeds the process’s soft resourcelimit on file size. SeeLimiting Resource Usage.
Next:Signal Messages, Previous:Operation Error Signals, Up:Standard Signals [Contents][Index]
These signals are used for various other purposes. In general, theywill not affect your program unless it explicitly uses them for something.
int
SIGUSR1 ¶int
SIGUSR2 ¶TheSIGUSR1
andSIGUSR2
signals are set aside for you touse any way you want. They’re useful for simple interprocesscommunication, if you write a signal handler for them in the programthat receives the signal.
There is an example showing the use ofSIGUSR1
andSIGUSR2
inSignaling Another Process.
The default action is to terminate the process.
int
SIGWINCH ¶Window size change. This is generated on some systems (including GNU)when the terminal driver’s record of the number of rows and columns onthe screen is changed. The default action is to ignore it.
If a program does full-screen display, it should handleSIGWINCH
.When the signal arrives, it should fetch the new screen size andreformat its display accordingly.
This macro was originally a BSD extension, but was added inPOSIX.1-2024.
int
SIGINFO ¶Information request. On 4.4 BSD and GNU/Hurd systems, this signal is sentto all the processes in the foreground process group of the controllingterminal when the user types the STATUS character in canonical mode;seeCharacters that Cause Signals.
If the process is the leader of the process group, the default action isto print some status information about the system and what the processis doing. Otherwise the default is to do nothing.
int
SIGPWR ¶Power lost or restored. On s390x Linux systems, this signal isgenerated when a machine check warning is issued, and is sent to theprocess designated to receive ctrl-alt-del notifications. Otherwise,it is up to userspace applications to generate this signal and managenotifications as to the type of power event that happened.
The default action is to terminate the process.
Previous:Miscellaneous Signals, Up:Standard Signals [Contents][Index]
We mentioned above that the shell prints a message describing the signalthat terminated a child process. The clean way to print a messagedescribing a signal is to use the functionsstrsignal
andpsignal
. These functions use a signal number to specify whichkind of signal to describe. The signal number may come from thetermination status of a child process (seeProcess Completion) or itmay come from a signal handler in the same process.
char *
strsignal(intsignum)
¶Preliminary:| MT-Unsafe race:strsignal locale| AS-Unsafe init i18n corrupt heap| AC-Unsafe init corrupt mem| SeePOSIX Safety Concepts.
This function returns a pointer to a statically-allocated stringcontaining a message describing the signalsignum. Youshould not modify the contents of this string; and, since it can berewritten on subsequent calls, you should save a copy of it if you needto reference it later.
This function is a GNU extension, declared in the header filestring.h.
void
psignal(intsignum, const char *message)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt i18n heap| AC-Unsafe lock corrupt mem| SeePOSIX Safety Concepts.
This function prints a message describing the signalsignum to thestandard error output streamstderr
; seeStandard Streams.
If you callpsignal
with amessage that is either a nullpointer or an empty string,psignal
just prints the messagecorresponding tosignum, adding a trailing newline.
If you supply a non-nullmessage argument, thenpsignal
prefixes its output with this string. It adds a colon and a spacecharacter to separate themessage from the string correspondingtosignum.
This function is a BSD feature, declared in the header filesignal.h.
const char *
sigdescr_np(intsignum)
¶| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the message describing the signalsignum orNULL
for invalid signal number (e.g "Hangup" forSIGHUP
).Different thanstrsignal
the returned description is not translated.The message points to a static storage whose lifetime is the whole lifetimeof the program.
This function is a GNU extension, declared in the header filestring.h.
const char *
sigabbrev_np(intsignum)
¶| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the abbreviation describing the signalsignum orNULL
for invalid signal number. The message points to a staticstorage whose lifetime is the whole lifetime of the program.
This function is a GNU extension, declared in the header filestring.h.
Next:Defining Signal Handlers, Previous:Standard Signals, Up:Signal Handling [Contents][Index]
The simplest way to change the action for a signal is to use thesignal
function. You can specify a built-in action (such as toignore the signal), or you canestablish a handler.
The GNU C Library also implements the more versatilesigaction
facility. This section describes both facilities and gives suggestionson which to use when.
signal
andsigaction
sigaction
Function Examplesigaction
Thesignal
function provides a simple interface for establishingan action for a particular signal. The function and associated macrosare declared in the header filesignal.h.
This is the type of signal handler functions. Signal handlers take oneinteger argument specifying the signal number, and have return typevoid
. So, you should define handler functions like this:
voidhandler (intsignum
) { ... }
The namesighandler_t
for this data type is a GNU extension.
sighandler_t
signal(intsignum, sighandler_taction)
¶Preliminary:| MT-Safe sigintr| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thesignal
function establishesaction as the action forthe signalsignum.
The first argument,signum, identifies the signal whose behavioryou want to control, and should be a signal number. The proper way tospecify a signal number is with one of the symbolic signal names(seeStandard Signals)—don’t use an explicit number, becausethe numerical code for a given kind of signal may vary from operatingsystem to operating system.
The second argument,action, specifies the action to use for thesignalsignum. This can be one of the following:
SIG_DFL
¶SIG_DFL
specifies the default action for the particular signal.The default actions for various kinds of signals are stated inStandard Signals.
SIG_IGN
¶SIG_IGN
specifies that the signal should be ignored.
Your program generally should not ignore signals that represent seriousevents or that are normally used to request termination. You cannotignore theSIGKILL
orSIGSTOP
signals at all. You canignore program error signals likeSIGSEGV
, but ignoring the errorwon’t enable the program to continue executing meaningfully. Ignoringuser requests such asSIGINT
,SIGQUIT
, andSIGTSTP
is unfriendly.
When you do not wish signals to be delivered during a certain part ofthe program, the thing to do is to block them, not ignore them.SeeBlocking Signals.
handler
Supply the address of a handler function in your program, to specifyrunning this handler as the way to deliver the signal.
For more information about defining signal handler functions,seeDefining Signal Handlers.
If you set the action for a signal toSIG_IGN
, or if you set ittoSIG_DFL
and the default action is to ignore that signal, thenany pending signals of that type are discarded (even if they areblocked). Discarding the pending signals means that they will never bedelivered, not even if you subsequently specify another action andunblock this kind of signal.
Thesignal
function returns the action that was previously ineffect for the specifiedsignum. You can save this value andrestore it later by callingsignal
again.
Ifsignal
can’t honor the request, it returnsSIG_ERR
instead. The followingerrno
error conditions are defined forthis function:
EINVAL
You specified an invalidsignum; or you tried to ignore or providea handler forSIGKILL
orSIGSTOP
.
Compatibility Note: A problem encountered when working with thesignal
function is that it has different semantics on BSD andSVID systems. The difference is that on SVID systems the signal handleris deinstalled after signal delivery. On BSD systems thehandler must be explicitly deinstalled. In the GNU C Library we use theBSD version by default. To use the SVID version you can either use thefunctionsysv_signal
(see below) or use the_XOPEN_SOURCE
feature select macro (seeFeature Test Macros). In general, use of thesefunctions should be avoided because of compatibility problems. Itis better to usesigaction
if it is available since the resultsare much more reliable.
Here is a simple example of setting up a handler to delete temporaryfiles when certain fatal signals happen:
#include <signal.h>voidtermination_handler (int signum){ struct temp_file *p; for (p = temp_file_list; p; p = p->next) unlink (p->name);}intmain (void){ ... if (signal (SIGINT, termination_handler) == SIG_IGN) signal (SIGINT, SIG_IGN); if (signal (SIGHUP, termination_handler) == SIG_IGN) signal (SIGHUP, SIG_IGN); if (signal (SIGTERM, termination_handler) == SIG_IGN) signal (SIGTERM, SIG_IGN); ...}
Note that if a given signal was previously set to be ignored, this codeavoids altering that setting. This is because non-job-control shellsoften ignore certain signals when starting children, and it is importantfor the children to respect this.
We do not handleSIGQUIT
or the program error signals in thisexample because these are designed to provide information for debugging(a core dump), and the temporary files may give useful information.
sighandler_t
sysv_signal(intsignum, sighandler_taction)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thesysv_signal
implements the behavior of the standardsignal
function as found on SVID systems. The difference to BSDsystems is that the handler is deinstalled after a delivery of a signal.
Compatibility Note: As said above forsignal
, thisfunction should be avoided when possible.sigaction
is thepreferred method.
sighandler_t
ssignal(intsignum, sighandler_taction)
¶Preliminary:| MT-Safe sigintr| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thessignal
function does the same thing assignal
; it isprovided only for compatibility with SVID.
sighandler_t
SIG_ERR ¶The value of this macro is used as the return value fromsignal
to indicate an error.
Next:Interaction ofsignal
andsigaction
, Previous:Basic Signal Handling, Up:Specifying Signal Actions [Contents][Index]
Thesigaction
function has the same basic effect assignal
: to specify how a signal should be handled by the process.However,sigaction
offers more control, at the expense of morecomplexity. In particular,sigaction
allows you to specifyadditional flags to control when the signal is generated and how thehandler is invoked.
Thesigaction
function is declared insignal.h.
Structures of typestruct sigaction
are used in thesigaction
function to specify all the information about how tohandle a particular signal. This structure contains at least thefollowing members:
sighandler_t sa_handler
This is used in the same way as theaction argument to thesignal
function. The value can beSIG_DFL
,SIG_IGN
, or a function pointer. SeeBasic Signal Handling.
void (*sa_sigaction) (intsignum, siginfo_t *info, void *ucontext)
This is an alternate tosa_handler
that is used when thesa_flags
includes theflag SA_SIGINFO
. Note that thisandsa_handler
overlap; only ever set one at a time.
The contents of theinfo anducontext structures arekernel and architecture dependent. Please seesigaction(2)SeeLinux (The Linux Kernel) for details.
sigset_t sa_mask
This specifies a set of signals to be blocked while the handler runs.Blocking is explained inBlocking Signals for a Handler. Note that thesignal that was delivered is automatically blocked by default before itshandler is started; this is true regardless of the value insa_mask
. If you want that signal not to be blocked within itshandler, you must write code in the handler to unblock it.
int sa_flags
This specifies various flags which can affect the behavior ofthe signal. These are described in more detail inFlags forsigaction
.
int
sigaction(intsignum, const struct sigaction *restrictaction, struct sigaction *restrictold-action)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theaction argument is used to set up a new action for the signalsignum, while theold-action argument is used to returninformation about the action previously associated with this signal.(In other words,old-action has the same purpose as thesignal
function’s return value—you can check to see what theold action in effect for the signal was, and restore it later if youwant.)
Eitheraction orold-action can be a null pointer. Ifold-action is a null pointer, this simply suppresses the returnof information about the old action. Ifaction is a null pointer,the action associated with the signalsignum is unchanged; thisallows you to inquire about how a signal is being handled without changingthat handling.
The return value fromsigaction
is zero if it succeeds, and-1
on failure. The followingerrno
error conditions aredefined for this function:
EINVAL
Thesignum argument is not valid, or you are trying totrap or ignoreSIGKILL
orSIGSTOP
.
Next:sigaction
Function Example, Previous:Advanced Signal Handling, Up:Specifying Signal Actions [Contents][Index]
signal
andsigaction
¶It’s possible to use both thesignal
andsigaction
functions within a single program, but you have to be careful becausethey can interact in slightly strange ways.
Thesigaction
function specifies more information than thesignal
function, so the return value fromsignal
cannotexpress the full range ofsigaction
possibilities. Therefore, ifyou usesignal
to save and later reestablish an action, it maynot be able to reestablish properly a handler that was established withsigaction
.
To avoid having problems as a result, always usesigaction
tosave and restore a handler if your program usessigaction
at all.Sincesigaction
is more general, it can properly save andreestablish any action, regardless of whether it was establishedoriginally withsignal
orsigaction
.
On some systems if you establish an action withsignal
and thenexamine it withsigaction
, the handler address that you get maynot be the same as what you specified withsignal
. It may noteven be suitable for use as an action argument withsignal
. Butyou can rely on using it as an argument tosigaction
. Thisproblem never happens on GNU systems.
So, you’re better off using one or the other of the mechanismsconsistently within a single program.
Portability Note: The basicsignal
function is a featureof ISO C, whilesigaction
is part of the POSIX.1 standard. Ifyou are concerned about portability to non-POSIX systems, then youshould use thesignal
function instead.
Next:Flags forsigaction
, Previous:Interaction ofsignal
andsigaction
, Up:Specifying Signal Actions [Contents][Index]
sigaction
Function Example ¶InBasic Signal Handling, we gave an example of establishing asimple handler for termination signals usingsignal
. Here is anequivalent example usingsigaction
:
#include <signal.h>voidtermination_handler (int signum){ struct temp_file *p; for (p = temp_file_list; p; p = p->next) unlink (p->name);}intmain (void){ ... struct sigaction new_action, old_action; /*Set up the structure to specify the new action. */ new_action.sa_handler = termination_handler; sigemptyset (&new_action.sa_mask); new_action.sa_flags = 0; sigaction (SIGINT, NULL, &old_action); if (old_action.sa_handler != SIG_IGN) sigaction (SIGINT, &new_action, NULL); sigaction (SIGHUP, NULL, &old_action); if (old_action.sa_handler != SIG_IGN) sigaction (SIGHUP, &new_action, NULL); sigaction (SIGTERM, NULL, &old_action); if (old_action.sa_handler != SIG_IGN) sigaction (SIGTERM, &new_action, NULL); ...}
The program just loads thenew_action
structure with the desiredparameters and passes it in thesigaction
call. The usage ofsigemptyset
is described later; seeBlocking Signals.
As in the example usingsignal
, we avoid handling signalspreviously set to be ignored. Here we can avoid altering the signalhandler even momentarily, by using the feature ofsigaction
thatlets us examine the current action without specifying a new one.
Here is another example. It retrieves information about the currentaction forSIGINT
without changing that action.
struct sigaction query_action;if (sigaction (SIGINT, NULL, &query_action) < 0) /*sigaction
returns -1 in case of error. */else if (query_action.sa_handler == SIG_DFL) /*SIGINT
is handled in the default, fatal manner. */else if (query_action.sa_handler == SIG_IGN) /*SIGINT
is ignored. */else /*A programmer-defined signal handler is in effect. */
Next:Initial Signal Actions, Previous:sigaction
Function Example, Up:Specifying Signal Actions [Contents][Index]
sigaction
¶Thesa_flags
member of thesigaction
structure is acatch-all for special features. Most of the time,SA_RESTART
isa good value to use for this field.
The value ofsa_flags
is interpreted as a bit mask. Thus, youshould choose the flags you want to set,OR those flags together,and store the result in thesa_flags
member of yoursigaction
structure.
Each signal number has its own set of flags. Each call tosigaction
affects one particular signal number, and the flagsthat you specify apply only to that particular signal.
In the GNU C Library, establishing a handler withsignal
sets allthe flags to zero except forSA_RESTART
, whose value depends onthe settings you have made withsiginterrupt
. SeePrimitives Interrupted by Signals, to see what this is about.
These macros are defined in the header filesignal.h.
int
SA_NOCLDSTOP ¶This flag is meaningful only for theSIGCHLD
signal. When theflag is set, the system delivers the signal for a terminated childprocess but not for one that is stopped. By default,SIGCHLD
isdelivered for both terminated children and stopped children.
Setting this flag for a signal other thanSIGCHLD
has no effect.
int
SA_NOCLDWAIT ¶This flag is meaningful only for theSIGCHLD
signal. When theflag is set, the terminated child will not wait for the parent to reapit, or become a zombie if not reaped. The child will instead bereaped by the kernel immediately on termination, similar to settingSIGCHLD to SIG_IGN.
Setting this flag for a signal other thanSIGCHLD
has no effect.
int
SA_NODEFER ¶Normally a signal is added to the signal mask while running its ownhandler; this negates that, so that the same signal can be receivedwhile it’s handler is running. Note that if the signal is included insa_mask
, it is masked regardless of this flag. Only useful whenassigning a function as a signal handler.
int
SA_ONSTACK ¶If this flag is set for a particular signal number, the system uses thesignal stack when delivering that kind of signal. SeeUsing a Separate Signal Stack.If a signal with this flag arrives and you have not set a signal stack,the normal user stack is used instead, as if the flag had not been set.
int
SA_RESETHAND ¶Resets the handler for a signal to SIG_DFL, at the moment specifiedhandler function begins. I.e. the handler is called once, then theaction resets.
int
SA_RESTART ¶This flag controls what happens when a signal is delivered duringcertain primitives (such asopen
,read
orwrite
),and the signal handler returns normally. There are two alternatives:the library function can resume, or it can return failure with errorcodeEINTR
.
The choice is controlled by theSA_RESTART
flag for theparticular kind of signal that was delivered. If the flag is set,returning from a handler resumes the library function. If the flag isclear, returning from a handler makes the function fail.SeePrimitives Interrupted by Signals.
int
SA_SIGINFO ¶Indicates that thesa_sigaction
three-argument form of thehandler should be used in setting up a handler instead of theone-argumentsa_handler
form.
Previous:Flags forsigaction
, Up:Specifying Signal Actions [Contents][Index]
When a new process is created (seeCreating a Process), it inheritshandling of signals from its parent process. However, when you load anew process image using theexec
function (seeExecuting a File), any signals that you’ve defined your own handlers for revert totheirSIG_DFL
handling. (If you think about it a little, thismakes sense; the handler functions from the old program are specific tothat program, and aren’t even present in the address space of the newprogram image.) Of course, the new program can establish its ownhandlers.
When a program is run by a shell, the shell normally sets the initialactions for the child process toSIG_DFL
orSIG_IGN
, asappropriate. It’s a good idea to check to make sure that the shell hasnot set up an initial action ofSIG_IGN
before you establish yourown signal handlers.
Here is an example of how to establish a handler forSIGHUP
, butnot ifSIGHUP
is currently ignored:
...struct sigaction temp;sigaction (SIGHUP, NULL, &temp);if (temp.sa_handler != SIG_IGN) { temp.sa_handler = handle_sighup; sigemptyset (&temp.sa_mask); sigaction (SIGHUP, &temp, NULL); }
Next:Primitives Interrupted by Signals, Previous:Specifying Signal Actions, Up:Signal Handling [Contents][Index]
This section describes how to write a signal handler function that canbe established with thesignal
orsigaction
functions.
A signal handler is just a function that you compile together with therest of the program. Instead of directly invoking the function, you usesignal
orsigaction
to tell the operating system to callit when a signal arrives. This is known asestablishing thehandler. SeeSpecifying Signal Actions.
There are two basic strategies you can use in signal handler functions:
You need to take special care in writing handler functions because theycan be called asynchronously. That is, a handler might be called at anypoint in the program, unpredictably. If two signals arrive during avery short interval, one handler can run within another. This sectiondescribes what your handler should do, and what you should avoid.
Handlers which return normally are usually used for signals such asSIGALRM
and the I/O and interprocess communication signals. Buta handler forSIGINT
might also return normally after setting aflag that tells the program to exit at a convenient time.
It is not safe to return normally from the handler for a program errorsignal, because the behavior of the program when the handler functionreturns is not defined after a program error. SeeProgram Error Signals.
Handlers that return normally must modify some global variable in orderto have any effect. Typically, the variable is one that is examinedperiodically by the program during normal operation. Its data typeshould besig_atomic_t
for reasons described inAtomic Data Access and Signal Handling.
Here is a simple example of such a program. It executes the body ofthe loop until it has noticed that aSIGALRM
signal has arrived.This technique is useful because it allows the iteration in progresswhen the signal arrives to complete before the loop exits.
#include <signal.h>#include <stdio.h>#include <stdlib.h>/*This flag controls termination of the main loop. */volatile sig_atomic_t keep_going = 1;/*The signal handler just clears the flag and re-enables itself. */voidcatch_alarm (int sig){ keep_going = 0; signal (sig, catch_alarm);}voiddo_stuff (void){ puts ("Doing stuff while waiting for alarm....");}intmain (void){ /*Establish a handler for SIGALRM signals. */ signal (SIGALRM, catch_alarm); /*Set an alarm to go off in a little while. */ alarm (2); /*Check the flag once in a while to see when to quit. */ while (keep_going) do_stuff (); return EXIT_SUCCESS;}
Next:Nonlocal Control Transfer in Handlers, Previous:Signal Handlers that Return, Up:Defining Signal Handlers [Contents][Index]
Handler functions that terminate the program are typically used to causeorderly cleanup or recovery from program error signals and interactiveinterrupts.
The cleanest way for a handler to terminate the process is to raise thesame signal that ran the handler in the first place. Here is how to dothis:
volatile sig_atomic_t fatal_error_in_progress = 0;voidfatal_error_signal (int sig){
/*Since this handler is established for more than one kind of signal,it might still get invoked recursively by delivery of some other kindof signal. Use a static variable to keep track of that. */ if (fatal_error_in_progress) raise (sig); fatal_error_in_progress = 1;
/*Now do the clean up actions:- reset terminal modes- kill child processes- remove lock files */ ...
/*Now reraise the signal. We reactivate the signal’sdefault handling, which is to terminate the process.We could just callexit
orabort
,but reraising the signal sets the return statusfrom the process correctly. */ signal (sig, SIG_DFL); raise (sig);}
Next:Signals Arriving While a Handler Runs, Previous:Handlers That Terminate the Process, Up:Defining Signal Handlers [Contents][Index]
You can do a nonlocal transfer of control out of a signal handler usingthesetjmp
andlongjmp
facilities (seeNon-Local Exits).
When the handler does a nonlocal control transfer, the part of theprogram that was running will not continue. If this part of the programwas in the middle of updating an important data structure, the datastructure will remain inconsistent. Since the program does notterminate, the inconsistency is likely to be noticed later on.
There are two ways to avoid this problem. One is to block the signalfor the parts of the program that update important data structures.Blocking the signal delays its delivery until it is unblocked, once thecritical updating is finished. SeeBlocking Signals.
The other way is to re-initialize the crucial data structures in thesignal handler, or to make their values consistent.
Here is a rather schematic example showing the reinitialization of oneglobal variable.
#include <signal.h>#include <setjmp.h>jmp_buf return_to_top_level;volatile sig_atomic_t waiting_for_input;voidhandle_sigint (int signum){ /*We may have been waiting for input when the signal arrived,but we are no longer waiting once we transfer control. */ waiting_for_input = 0; longjmp (return_to_top_level, 1);}
intmain (void){ ... signal (SIGINT, sigint_handler); ... while (1) { prepare_for_command (); if (setjmp (return_to_top_level) == 0) read_and_execute_command (); }}
/*Imagine this is a subroutine used by various commands. */char *read_data (){ if (input_from_terminal) { waiting_for_input = 1; ... waiting_for_input = 0; } else { ... }}
Next:Signals Close Together Merge into One, Previous:Nonlocal Control Transfer in Handlers, Up:Defining Signal Handlers [Contents][Index]
What happens if another signal arrives while your signal handlerfunction is running?
When the handler for a particular signal is invoked, that signal isautomatically blocked until the handler returns. That means that if twosignals of the same kind arrive close together, the second one will beheld until the first has been handled. (The handler can explicitlyunblock the signal usingsigprocmask
, if you want to allow moresignals of this type to arrive; seeProcess Signal Mask.)
However, your handler can still be interrupted by delivery of anotherkind of signal. To avoid this, you can use thesa_mask
member ofthe action structure passed tosigaction
to explicitly specifywhich signals should be blocked while the signal handler runs. Thesesignals are in addition to the signal for which the handler was invoked,and any other signals that are normally blocked by the process.SeeBlocking Signals for a Handler.
When the handler returns, the set of blocked signals is restored to thevalue it had before the handler ran. So usingsigprocmask
insidethe handler only affects what signals can arrive during the execution ofthe handler itself, not what signals can arrive once the handler returns.
Portability Note: Always usesigaction
to establish ahandler for a signal that you expect to receive asynchronously, if youwant your program to work properly on System V Unix. On this system,the handling of a signal whose handler was established withsignal
automatically sets the signal’s action back toSIG_DFL
, and the handler must re-establish itself each time itruns. This practice, while inconvenient, does work when signals cannotarrive in succession. However, if another signal can arrive right away,it may arrive before the handler can re-establish itself. Then thesecond signal would receive the default handling, which could terminatethe process.
Next:Signal Handling and Nonreentrant Functions, Previous:Signals Arriving While a Handler Runs, Up:Defining Signal Handlers [Contents][Index]
If multiple signals of the same type are delivered to your processbefore your signal handler has a chance to be invoked at all, thehandler may only be invoked once, as if only a single signal hadarrived. In effect, the signals merge into one. This situation canarise when the signal is blocked, or in a multiprocessing environmentwhere the system is busy running some other processes while the signalsare delivered. This means, for example, that you cannot reliably use asignal handler to count signals. The only distinction you can reliablymake is whether at least one signal has arrived since a given time inthe past.
Here is an example of a handler forSIGCHLD
that compensates forthe fact that the number of signals received may not equal the number ofchild processes that generate them. It assumes that the program keeps trackof all the child processes with a chain of structures as follows:
struct process{ struct process *next; /*The process ID of this child. */ int pid; /*The descriptor of the pipe or pseudo terminalon which output comes from this child. */ int input_descriptor; /*Nonzero if this process has stopped or terminated. */ sig_atomic_t have_status; /*The status of this child; 0 if running,otherwise a status value fromwaitpid
. */ int status;};struct process *process_list;
This example also uses a flag to indicate whether signals have arrivedsince some time in the past—whenever the program last cleared it tozero.
/*Nonzero means some child’s status has changedso look atprocess_list
for the details. */int process_status_change;
Here is the handler itself:
voidsigchld_handler (int signo){ int old_errno = errno; while (1) { register int pid; int w; struct process *p; /*Keep asking for a status until we get a definitive result. */ do { errno = 0; pid = waitpid (WAIT_ANY, &w, WNOHANG | WUNTRACED); } while (pid <= 0 && errno == EINTR); if (pid <= 0) { /*A real failure means there are no morestopped or terminated child processes, so return. */ errno = old_errno; return; } /*Find the process that signaled us, and record its status. */ for (p = process_list; p; p = p->next) if (p->pid == pid) { p->status = w; /*Indicate that thestatus
fieldhas data to look at. We do this only after storing it. */ p->have_status = 1; /*If process has terminated, stop waiting for its output. */ if (WIFSIGNALED (w) || WIFEXITED (w)) if (p->input_descriptor) FD_CLR (p->input_descriptor, &input_wait_mask); /*The program should check this flag from time to timeto see if there is any news inprocess_list
. */ ++process_status_change; } /*Loop around to handle all the processesthat have something to tell us. */ }}
Here is the proper way to check the flagprocess_status_change
:
if (process_status_change) { struct process *p; process_status_change = 0; for (p = process_list; p; p = p->next) if (p->have_status) { ...Examinep->status
... }}
It is vital to clear the flag before examining the list; otherwise, if asignal were delivered just before the clearing of the flag, and afterthe appropriate element of the process list had been checked, the statuschange would go unnoticed until the next signal arrived to set the flagagain. You could, of course, avoid this problem by blocking the signalwhile scanning the list, but it is much more elegant to guaranteecorrectness by doing things in the right order.
The loop which checks process status avoids examiningp->status
until it sees that status has been validly stored. This is to make surethat the status cannot change in the middle of accessing it. Oncep->have_status
is set, it means that the child process is stoppedor terminated, and in either case, it cannot stop or terminate againuntil the program has taken notice. SeeAtomic Usage Patterns, for moreinformation about coping with interruptions during accesses of avariable.
Here is another way you can test whether the handler has run since thelast time you checked. This technique uses a counter which is neverchanged outside the handler. Instead of clearing the count, the programremembers the previous value and sees whether it has changed since theprevious check. The advantage of this method is that different parts ofthe program can check independently, each part checking whether therehas been a signal since that part last checked.
sig_atomic_t process_status_change;sig_atomic_t last_process_status_change;...{ sig_atomic_t prev = last_process_status_change; last_process_status_change = process_status_change; if (last_process_status_change != prev) { struct process *p; for (p = process_list; p; p = p->next) if (p->have_status) { ...Examinep->status
... } }}
Next:Atomic Data Access and Signal Handling, Previous:Signals Close Together Merge into One, Up:Defining Signal Handlers [Contents][Index]
Handler functions usually don’t do very much. The best practice is towrite a handler that does nothing but set an external variable that theprogram checks regularly, and leave all serious work to the program.This is best because the handler can be called asynchronously, atunpredictable times—perhaps in the middle of a primitive function, oreven between the beginning and the end of a C operator that requiresmultiple instructions. The data structures being manipulated mighttherefore be in an inconsistent state when the handler function isinvoked. Even copying oneint
variable into another can take twoinstructions on most machines.
This means you have to be very careful about what you do in a signalhandler.
volatile
. This tells the compiler thatthe value of the variable might change asynchronously, and inhibitscertain optimizations that would be invalidated by such modifications.A function can be non-reentrant if it uses memory that is not on thestack.
For example, suppose that the signal handler usesgethostbyname
.This function returns its value in a static object, reusing the sameobject each time. If the signal happens to arrive during a call togethostbyname
, or even after one (while the program is stillusing the value), it will clobber the value that the program asked for.
However, if the program does not usegethostbyname
or any otherfunction that returns information in the same object, or if it alwaysblocks signals around each use, then you are safe.
There are a large number of library functions that return values in afixed object, always reusing the same object in this fashion, and all ofthem cause the same problem. Function descriptions in this manualalways mention this behavior.
This case arises when you do I/O using streams. Suppose that thesignal handler prints a message withfprintf
. Suppose that theprogram was in the middle of anfprintf
call using the samestream when the signal was delivered. Both the signal handler’s messageand the program’s data could be corrupted, because both calls operate onthe same data structure—the stream itself.
However, if you know that the stream that the handler uses cannotpossibly be used by the program at a time when signals can arrive, thenyou are safe. It is no problem if the program uses some other stream.
malloc
andfree
are not reentrant,because they use a static data structure which records what memoryblocks are free. As a result, no library functions that allocate orfree memory are reentrant. This includes functions that allocate spaceto store a result.The best way to avoid the need to allocate memory in a handler is toallocate in advance space for signal handlers to use.
The best way to avoid freeing memory in a handler is to flag or recordthe objects to be freed, and have the program check from time to timewhether anything is waiting to be freed. But this must be done withcare, because placing an object on a chain is not atomic, and if it isinterrupted by another signal handler that does the same thing, youcould “lose” one of the objects.
errno
is non-reentrant, but you cancorrect for this: in the handler, save the original value oferrno
and restore it before returning normally. This preventserrors that occur within the signal handler from being confused witherrors from system calls at the point the program is interrupted to runthe handler.This technique is generally applicable; if you want to call in a handlera function that modifies a particular object in memory, you can makethis safe by saving and restoring that object.
Whether the data in your application concerns atoms, or mere text, youhave to be careful about the fact that access to a single datum is notnecessarilyatomic. This means that it can take more than oneinstruction to read or write a single object. In such cases, a signalhandler might be invoked in the middle of reading or writing the object.
There are three ways you can cope with this problem. You can use datatypes that are always accessed atomically; you can carefully arrangethat nothing untoward happens if an access is interrupted, or you canblock all signals around any access that had better not be interrupted(seeBlocking Signals).
Here is an example which shows what can happen if a signal handler runsin the middle of modifying a variable. (Interrupting the reading of avariable can also lead to paradoxical results, but here we only showwriting.)
#include <signal.h>#include <stdio.h>volatile struct two_words { int a, b; } memory;voidhandler(int signum){ printf ("%d,%d\n", memory.a, memory.b); alarm (1);}
intmain (void){ static struct two_words zeros = { 0, 0 }, ones = { 1, 1 }; signal (SIGALRM, handler); memory = zeros; alarm (1); while (1) { memory = zeros; memory = ones; }}
This program fillsmemory
with zeros, ones, zeros, ones,alternating forever; meanwhile, once per second, the alarm signal handlerprints the current contents. (Callingprintf
in the handler issafe in this program because it is certainly not being called outsidethe handler when the signal happens.)
Clearly, this program can print a pair of zeros or a pair of ones. Butthat’s not all it can do! On most machines, it takes severalinstructions to store a new value inmemory
, and the value isstored one word at a time. If the signal is delivered in between theseinstructions, the handler might find thatmemory.a
is zero andmemory.b
is one (or vice versa).
On some machines it may be possible to store a new value inmemory
with just one instruction that cannot be interrupted. Onthese machines, the handler will always print two zeros or two ones.
Next:Atomic Usage Patterns, Previous:Problems with Non-Atomic Access, Up:Atomic Data Access and Signal Handling [Contents][Index]
To avoid uncertainty about interrupting access to a variable, you canuse a particular data type for which access is always atomic:sig_atomic_t
. Reading and writing this data type is guaranteedto happen in a single instruction, so there’s no way for a handler torun “in the middle” of an access.
The typesig_atomic_t
is always an integer data type, but whichone it is, and how many bits it contains, may vary from machine tomachine.
This is an integer data type. Objects of this type are always accessedatomically.
In practice, you can assume thatint
is atomic.You can also assume that pointertypes are atomic; that is very convenient. Both of these assumptionsare true on all of the machines that the GNU C Library supports and onall POSIX systems we know of.
Previous:Atomic Types, Up:Atomic Data Access and Signal Handling [Contents][Index]
Certain patterns of access avoid any problem even if an access isinterrupted. For example, a flag which is set by the handler, andtested and cleared by the main program from time to time, is always safeeven if access actually requires two instructions. To show that this isso, we must consider each access that could be interrupted, and showthat there is no problem if it is interrupted.
An interrupt in the middle of testing the flag is safe because either it’srecognized to be nonzero, in which case the precise value doesn’tmatter, or it will be seen to be nonzero the next time it’s tested.
An interrupt in the middle of clearing the flag is no problem becauseeither the value ends up zero, which is what happens if a signal comesin just before the flag is cleared, or the value ends up nonzero, andsubsequent events occur as if the signal had come in just after the flagwas cleared. As long as the code handles both of these cases properly,it can also handle a signal in the middle of clearing the flag. (Thisis an example of the sort of reasoning you need to do to figure outwhether non-atomic usage is safe.)
Sometimes you can ensure uninterrupted access to one object byprotecting its use with another object, perhaps one whose typeguarantees atomicity. SeeSignals Close Together Merge into One, for an example.
Next:Generating Signals, Previous:Defining Signal Handlers, Up:Signal Handling [Contents][Index]
A signal can arrive and be handled while an I/O primitive such asopen
orread
is waiting for an I/O device. If the signalhandler returns, the system faces the question: what should happen next?
POSIX specifies one approach: make the primitive fail right away. Theerror code for this kind of failure isEINTR
. This is flexible,but usually inconvenient. Typically, POSIX applications that use signalhandlers must check forEINTR
after each library function thatcan return it, in order to try the call again. Often programmers forgetto check, which is a common source of error.
The GNU C Library provides a convenient way to retry a call after atemporary failure, with the macroTEMP_FAILURE_RETRY
:
This macro evaluatesexpression once, and examines its value astypelong int
. If the value equals-1
, that indicates afailure anderrno
should be set to show what kind of failure.If it fails and reports error codeEINTR
,TEMP_FAILURE_RETRY
evaluates it again, and over and over untilthe result is not a temporary failure.
The value returned byTEMP_FAILURE_RETRY
is whatever valueexpression produced.
BSD avoidsEINTR
entirely and provides a more convenientapproach: to restart the interrupted primitive, instead of making itfail. If you choose this approach, you need not be concerned withEINTR
.
You can choose either approach with the GNU C Library. If you usesigaction
to establish a signal handler, you can specify how thathandler should behave. If you specify theSA_RESTART
flag,return from that handler will resume a primitive; otherwise, return fromthat handler will causeEINTR
. SeeFlags forsigaction
.
Another way to specify the choice is with thesiginterrupt
function. SeeBSD Signal Handling.
When you don’t specify withsigaction
orsiginterrupt
whata particular handler should do, it uses a default choice. The defaultchoice in the GNU C Library is to make primitives fail withEINTR
.
The description of each primitive affected by this issuelistsEINTR
among the error codes it can return.
There is one situation where resumption never happens no matter whichchoice you make: when a data-transfer function such asread
orwrite
is interrupted by a signal after transferring part of thedata. In this case, the function returns the number of bytes alreadytransferred, indicating partial success.
This might at first appear to cause unreliable behavior onrecord-oriented devices (including datagram sockets; seeDatagram Socket Operations),where splitting oneread
orwrite
into two would read orwrite two records. Actually, there is no problem, because interruptionafter a partial transfer cannot happen on such devices; they alwaystransfer an entire record in one burst, with no waiting once datatransfer has started.
Next:Blocking Signals, Previous:Primitives Interrupted by Signals, Up:Signal Handling [Contents][Index]
Besides signals that are generated as a result of a hardware trap orinterrupt, your program can explicitly send signals to itself or toanother process.
Next:Signaling Another Process, Up:Generating Signals [Contents][Index]
A process can send itself a signal with theraise
function. Thisfunction is declared insignal.h.
int
raise(intsignum)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theraise
function sends the signalsignum to the callingprocess. It returns zero if successful and a nonzero value if it fails.About the only reason for failure would be if the value ofsignumis invalid.
int
gsignal(intsignum)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegsignal
function does the same thing asraise
; it isprovided only for compatibility with SVID.
One convenient use forraise
is to reproduce the default behaviorof a signal that you have trapped. For instance, suppose a user of yourprogram types the SUSP character (usuallyC-z; seeSpecial Characters) to send it an interactive stop signal(SIGTSTP
), and you want to clean up some internal data buffersbefore stopping. You might set this up like this:
#include <signal.h>/*When a stop signal arrives, set the action back to the default and then resend the signal after doing cleanup actions. */voidtstp_handler (int sig){ signal (SIGTSTP, SIG_DFL); /*Do cleanup actions here. */ ... raise (SIGTSTP);}/*When the process is continued again, restore the signal handler. */voidcont_handler (int sig){ signal (SIGCONT, cont_handler); signal (SIGTSTP, tstp_handler);}
/*Enable both handlers during program initialization. */intmain (void){ signal (SIGCONT, cont_handler); signal (SIGTSTP, tstp_handler); ...}
Portability note:raise
was invented by the ISO Ccommittee. Older systems may not support it, so usingkill
maybe more portable. SeeSignaling Another Process.
Next:Permission for usingkill
, Previous:Signaling Yourself, Up:Generating Signals [Contents][Index]
Thekill
function can be used to send a signal to another process.In spite of its name, it can be used for a lot of things other thancausing a process to terminate. Some examples of situations where youmight want to send signals between processes are:
This section assumes that you know a little bit about how processeswork. For more information on this subject, seeProcesses.
Thekill
function is declared insignal.h.
int
kill(pid_tpid, intsignum)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thekill
function sends the signalsignum to the processor process group specified bypid. Besides the signals listed inStandard Signals,signum can also have a value of zero tocheck the validity of thepid.
Thepid specifies the process or process group to receive thesignal:
pid > 0
The process whose identifier ispid. (On Linux, the signal issent to the entire process even ifpid is a thread ID distinctfrom the process ID.)
pid == 0
All processes in the same process group as the sender.
pid < -1
The process group whose identifier is −pid.
pid == -1
If the process is privileged, send the signal to all processes exceptfor some special system processes. Otherwise, send the signal to allprocesses with the same effective user ID.
A process can send a signal to itself with a call likekill (getpid(), signum)
. Ifkill
is used by a process to senda signal to itself, and the signal is not blocked, thenkill
delivers at least one signal (which might be some other pendingunblocked signal instead of the signalsignum) to that processbefore it returns.
The return value fromkill
is zero if the signal can be sentsuccessfully. Otherwise, no signal is sent, and a value of-1
isreturned. Ifpid specifies sending a signal to several processes,kill
succeeds if it can send the signal to at least one of them.There’s no way you can tell which of the processes got the signalor whether all of them did.
The followingerrno
error conditions are defined for this function:
EINVAL
Thesignum argument is an invalid or unsupported number.
EPERM
You do not have the privilege to send a signal to the process or any ofthe processes in the process group named bypid.
ESRCH
Thepid argument does not refer to an existing process or group.
int
tgkill(pid_tpid, pid_ttid, intsignum)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thetgkill
function sends the signalsignum to the threador process with IDtid, like thekill
function, but onlyif the process ID of the threadtid is equal topid. Ifthe target thread belongs to another process, the function fails withESRCH
.
Thetgkill
function can be used to avoid sending a signal to athread in the wrong process if the caller ensures that the passedpid value is not reused by the kernel (for example, if it is theprocess ID of the current process, as returned bygetpid
).
int
killpg(intpgid, intsignum)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is similar tokill
, but sends signalsignum to theprocess grouppgid. This function is provided for compatibilitywith BSD; usingkill
to do this is more portable.
As a simple example ofkill
, the callkill (getpid (), sig)
has the same effect asraise (sig)
.
Next:Usingkill
for Communication, Previous:Signaling Another Process, Up:Generating Signals [Contents][Index]
kill
¶There are restrictions that prevent you from usingkill
to sendsignals to any random process. These are intended to prevent antisocialbehavior such as arbitrarily killing off processes belonging to anotheruser. In typical use,kill
is used to pass signals betweenparent, child, and sibling processes, and in these situations younormally do have permission to send signals. The only common exceptionis when you run a setuid program in a child process; if the programchanges its real UID as well as its effective UID, you may not havepermission to send a signal. Thesu
program does this.
Whether a process has permission to send a signal to another processis determined by the user IDs of the two processes. This concept isdiscussed in detail inThe Persona of a Process.
Generally, for a process to be able to send a signal to another process,either the sending process must belong to a privileged user (like‘root’), or the real or effective user ID of the sending processmust match the real or effective user ID of the receiving process. Ifthe receiving process has changed its effective user ID from theset-user-ID mode bit on its process image file, then the owner of theprocess image file is used in place of its current effective user ID.In some implementations, a parent process might be able to send signalsto a child process even if the user ID’s don’t match, and otherimplementations might enforce other restrictions.
TheSIGCONT
signal is a special case. It can be sent if thesender is part of the same session as the receiver, regardless ofuser IDs.
Previous:Permission for usingkill
, Up:Generating Signals [Contents][Index]
kill
for Communication ¶Here is a longer example showing how signals can be used forinterprocess communication. This is what theSIGUSR1
andSIGUSR2
signals are provided for. Since these signals are fatalby default, the process that is supposed to receive them must trap themthroughsignal
orsigaction
.
In this example, a parent process forks a child process and then waitsfor the child to complete its initialization. The child process tellsthe parent when it is ready by sending it aSIGUSR1
signal, usingthekill
function.
#include <signal.h>#include <stdio.h>#include <sys/types.h>#include <unistd.h>
/*When aSIGUSR1
signal arrives, set this variable. */volatile sig_atomic_t usr_interrupt = 0;voidsynch_signal (int sig){ usr_interrupt = 1;}/*The child process executes this function. */voidchild_function (void){ /*Perform initialization. */ printf ("I'm here!!! My pid is %d.\n", (int) getpid ()); /*Let parent know you’re done. */ kill (getppid (), SIGUSR1); /*Continue with execution. */ puts ("Bye, now...."); exit (0);}intmain (void){ struct sigaction usr_action; sigset_t block_mask; pid_t child_id; /*Establish the signal handler. */ sigfillset (&block_mask); usr_action.sa_handler = synch_signal; usr_action.sa_mask = block_mask; usr_action.sa_flags = 0; sigaction (SIGUSR1, &usr_action, NULL); /*Create the child process. */ child_id = fork (); if (child_id == 0) child_function (); /*Does not return. */
/*Busy wait for the child to send a signal. */ while (!usr_interrupt) ;
/*Now continue execution. */ puts ("That's all, folks!"); return 0;}
This example uses a busy wait, which is bad, because it wastes CPUcycles that other programs could otherwise use. It is better to ask thesystem to wait until the signal arrives. See the example inWaiting for a Signal.
Next:Waiting for a Signal, Previous:Generating Signals, Up:Signal Handling [Contents][Index]
Blocking a signal means telling the operating system to hold it anddeliver it later. Generally, a program does not block signalsindefinitely—it might as well ignore them by setting their actions toSIG_IGN
. But it is useful to block signals briefly, to preventthem from interrupting sensitive operations. For instance:
sigprocmask
function to block signals while youmodify global variables that are also modified by the handlers for thesesignals.sa_mask
in yoursigaction
call to blockcertain signals while a particular signal handler runs. This way, thesignal handler can run without being interrupted itself by signals.Next:Signal Sets, Up:Blocking Signals [Contents][Index]
Temporary blocking of signals withsigprocmask
gives you a way toprevent interrupts during critical parts of your code. If signalsarrive in that part of the program, they are delivered later, after youunblock them.
One example where this is useful is for sharing data between a signalhandler and the rest of the program. If the type of the data is notsig_atomic_t
(seeAtomic Data Access and Signal Handling), then the signalhandler could run when the rest of the program has only half finishedreading or writing the data. This would lead to confusing consequences.
To make the program reliable, you can prevent the signal handler fromrunning while the rest of the program is examining or modifying thatdata—by blocking the appropriate signal around the parts of theprogram that touch the data.
Blocking signals is also necessary when you want to perform a certainaction only if a signal has not arrived. Suppose that the handler forthe signal sets a flag of typesig_atomic_t
; you would like totest the flag and perform the action if the flag is not set. This isunreliable. Suppose the signal is delivered immediately after you testthe flag, but before the consequent action: then the program willperform the action even though the signal has arrived.
The only way to test reliably for whether a signal has yet arrived is totest while the signal is blocked.
Next:Process Signal Mask, Previous:Why Blocking Signals is Useful, Up:Blocking Signals [Contents][Index]
All of the signal blocking functions use a data structure called asignal set to specify what signals are affected. Thus, everyactivity involves two stages: creating the signal set, and then passingit as an argument to a library function.
These facilities are declared in the header filesignal.h.
Thesigset_t
data type is used to represent a signal set.Internally, it may be implemented as either an integer or structuretype.
For portability, use only the functions described in this section toinitialize, change, and retrieve information fromsigset_t
objects—don’t try to manipulate them directly.
There are two ways to initialize a signal set. You can initiallyspecify it to be empty withsigemptyset
and then add specifiedsignals individually. Or you can specify it to be full withsigfillset
and then delete specified signals individually.
You must always initialize the signal set with one of these twofunctions before using it in any other way. Don’t try to set all thesignals explicitly because thesigset_t
object might include someother information (like a version field) that needs to be initialized aswell. (In addition, it’s not wise to put into your program anassumption that the system has no signals aside from the ones you knowabout.)
int
sigemptyset(sigset_t *set)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function initializes the signal setset to exclude all of thedefined signals. It always returns0
.
int
sigfillset(sigset_t *set)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function initializes the signal setset to includeall of the defined signals. Again, the return value is0
.
int
sigaddset(sigset_t *set, intsignum)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function adds the signalsignum to the signal setset.Allsigaddset
does is modifyset; it does not block orunblock any signals.
The return value is0
on success and-1
on failure.The followingerrno
error condition is defined for this function:
EINVAL
Thesignum argument doesn’t specify a valid signal.
int
sigdelset(sigset_t *set, intsignum)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function removes the signalsignum from the signal setset. Allsigdelset
does is modifyset; it does notblock or unblock any signals. The return value and error conditions arethe same as forsigaddset
.
Finally, there is a function to test what signals are in a signal set:
int
sigismember(const sigset_t *set, intsignum)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thesigismember
function tests whether the signalsignum isa member of the signal setset. It returns1
if the signalis in the set,0
if not, and-1
if there is an error.
The followingerrno
error condition is defined for this function:
EINVAL
Thesignum argument doesn’t specify a valid signal.
Next:Blocking to Test for Delivery of a Signal, Previous:Signal Sets, Up:Blocking Signals [Contents][Index]
The collection of signals that are currently blocked is called thesignal mask. Each process has its own signal mask. When youcreate a new process (seeCreating a Process), it inherits itsparent’s mask. You can block or unblock signals with total flexibilityby modifying the signal mask.
The prototype for thesigprocmask
function is insignal.h.
Note that you must not usesigprocmask
in multi-threaded processes,because each thread has its own signal mask and there is no single processsignal mask. According to POSIX, the behavior ofsigprocmask
in amulti-threaded process is “unspecified”.Instead, usepthread_sigmask
.
int
sigprocmask(inthow, const sigset_t *restrictset, sigset_t *restrictoldset)
¶Preliminary:| MT-Unsafe race:sigprocmask/bsd(SIG_UNBLOCK)| AS-Unsafe lock/hurd| AC-Unsafe lock/hurd| SeePOSIX Safety Concepts.
Thesigprocmask
function is used to examine or change the callingprocess’s signal mask. Thehow argument determines how the signalmask is changed, and must be one of the following values:
SIG_BLOCK
¶Block the signals inset
—add them to the existing mask. Inother words, the new mask is the union of the existing mask andset.
SIG_UNBLOCK
¶Unblock the signals inset—remove them from the existing mask.
SIG_SETMASK
¶Useset for the mask; ignore the previous value of the mask.
The last argument,oldset, is used to return information about theold process signal mask. If you just want to change the mask withoutlooking at it, pass a null pointer as theoldset argument.Similarly, if you want to know what’s in the mask without changing it,pass a null pointer forset (in this case thehow argumentis not significant). Theoldset argument is often used toremember the previous signal mask in order to restore it later. (Sincethe signal mask is inherited overfork
andexec
calls, youcan’t predict what its contents are when your program starts running.)
If invokingsigprocmask
causes any pending signals to beunblocked, at least one of those signals is delivered to the processbeforesigprocmask
returns. The order in which pending signalsare delivered is not specified, but you can control the order explicitlyby making multiplesigprocmask
calls to unblock various signalsone at a time.
Thesigprocmask
function returns0
if successful, and-1
to indicate an error. The followingerrno
error conditions aredefined for this function:
EINVAL
Thehow argument is invalid.
You can’t block theSIGKILL
andSIGSTOP
signals, butif the signal set includes these,sigprocmask
just ignoresthem instead of returning an error status.
Remember, too, that blocking program error signals such asSIGFPE
leads to undesirable results for signals generated by an actual programerror (as opposed to signals sent withraise
orkill
).This is because your program may be too broken to be able to continueexecuting to a point where the signal is unblocked again.SeeProgram Error Signals.
Next:Blocking Signals for a Handler, Previous:Process Signal Mask, Up:Blocking Signals [Contents][Index]
Now for a simple example. Suppose you establish a handler forSIGALRM
signals that sets a flag whenever a signal arrives, andyour main program checks this flag from time to time and then resets it.You can prevent additionalSIGALRM
signals from arriving in themeantime by wrapping the critical part of the code with calls tosigprocmask
, like this:
/*This variable is set by the SIGALRM signal handler. */volatile sig_atomic_t flag = 0;intmain (void){ sigset_t block_alarm; ... /*Initialize the signal mask. */ sigemptyset (&block_alarm); sigaddset (&block_alarm, SIGALRM);
while (1) { /*Check if a signal has arrived; if so, reset the flag. */ sigprocmask (SIG_BLOCK, &block_alarm, NULL); if (flag) {actions-if-not-arrived flag = 0; } sigprocmask (SIG_UNBLOCK, &block_alarm, NULL); ... }}
Next:Checking for Pending Signals, Previous:Blocking to Test for Delivery of a Signal, Up:Blocking Signals [Contents][Index]
When a signal handler is invoked, you usually want it to be able tofinish without being interrupted by another signal. From the moment thehandler starts until the moment it finishes, you must block signals thatmight confuse it or corrupt its data.
When a handler function is invoked on a signal, that signal isautomatically blocked (in addition to any other signals that are alreadyin the process’s signal mask) during the time the handler is running.If you set up a handler forSIGTSTP
, for instance, then thearrival of that signal forces furtherSIGTSTP
signals to waitduring the execution of the handler.
However, by default, other kinds of signals are not blocked; they canarrive during handler execution.
The reliable way to block other kinds of signals during the execution ofthe handler is to use thesa_mask
member of thesigaction
structure.
Here is an example:
#include <signal.h>#include <stddef.h>void catch_stop ();voidinstall_handler (void){ struct sigaction setup_action; sigset_t block_mask; sigemptyset (&block_mask); /*Block other terminal-generated signals while handler runs. */ sigaddset (&block_mask, SIGINT); sigaddset (&block_mask, SIGQUIT); setup_action.sa_handler = catch_stop; setup_action.sa_mask = block_mask; setup_action.sa_flags = 0; sigaction (SIGTSTP, &setup_action, NULL);}
This is more reliable than blocking the other signals explicitly in thecode for the handler. If you block signals explicitly in the handler,you can’t avoid at least a short interval at the beginning of thehandler where they are not yet blocked.
You cannot remove signals from the process’s current mask using thismechanism. However, you can make calls tosigprocmask
withinyour handler to block or unblock signals as you wish.
In any case, when the handler returns, the system restores the mask thatwas in place before the handler was entered. If any signals that becomeunblocked by this restoration are pending, the process will receivethose signals immediately, before returning to the code that wasinterrupted.
Next:Remembering a Signal to Act On Later, Previous:Blocking Signals for a Handler, Up:Blocking Signals [Contents][Index]
You can find out which signals are pending at any time by callingsigpending
. This function is declared insignal.h.
int
sigpending(sigset_t *set)
¶Preliminary:| MT-Safe | AS-Unsafe lock/hurd| AC-Unsafe lock/hurd| SeePOSIX Safety Concepts.
Thesigpending
function stores information about pending signalsinset. If there is a pending signal that is blocked fromdelivery, then that signal is a member of the returned set. (You cantest whether a particular signal is a member of this set usingsigismember
; seeSignal Sets.)
The return value is0
if successful, and-1
on failure.
Testing whether a signal is pending is not often useful. Testing whenthat signal is not blocked is almost certainly bad design.
Here is an example.
#include <signal.h>#include <stddef.h>sigset_t base_mask, waiting_mask;sigemptyset (&base_mask);sigaddset (&base_mask, SIGINT);sigaddset (&base_mask, SIGTSTP);/*Block user interrupts while doing other processing. */sigprocmask (SIG_SETMASK, &base_mask, NULL);.../*After a while, check to see whether any signals are pending. */sigpending (&waiting_mask);if (sigismember (&waiting_mask, SIGINT)) { /*User has tried to kill the process. */}else if (sigismember (&waiting_mask, SIGTSTP)) { /*User has tried to stop the process. */}
Remember that if there is a particular signal pending for your process,additional signals of that same type that arrive in the meantime mightbe discarded. For example, if aSIGINT
signal is pending whenanotherSIGINT
signal arrives, your program will probably onlysee one of them when you unblock this signal.
Portability Note: Thesigpending
function is new inPOSIX.1. Older systems have no equivalent facility.
Previous:Checking for Pending Signals, Up:Blocking Signals [Contents][Index]
Instead of blocking a signal using the library facilities, you can getalmost the same results by making the handler set a flag to be testedlater, when you “unblock”. Here is an example:
/*If this flag is nonzero, don’t handle the signal right away. */volatile sig_atomic_t signal_pending;/*This is nonzero if a signal arrived and was not handled. */volatile sig_atomic_t defer_signal;voidhandler (int signum){ if (defer_signal) signal_pending = signum; else ... /*“Really” handle the signal. */}...voidupdate_mumble (int frob){ /*Prevent signals from having immediate effect. */ defer_signal++; /*Now updatemumble
, without worrying about interruption. */ mumble.a = 1; mumble.b = hack (); mumble.c = frob; /*We have updatedmumble
. Handle any signal that came in. */ defer_signal--; if (defer_signal == 0 && signal_pending != 0) raise (signal_pending);}
Note how the particular signal that arrives is stored insignal_pending
. That way, we can handle several types ofinconvenient signals with the same mechanism.
We increment and decrementdefer_signal
so that nested criticalsections will work properly; thus, ifupdate_mumble
were calledwithsignal_pending
already nonzero, signals would be deferrednot only withinupdate_mumble
, but also within the caller. Thisis also why we do not checksignal_pending
ifdefer_signal
is still nonzero.
The incrementing and decrementing ofdefer_signal
each require morethan one instruction; it is possible for a signal to happen in themiddle. But that does not cause any problem. If the signal happensearly enough to see the value from before the increment or decrement,that is equivalent to a signal which came before the beginning of theincrement or decrement, which is a case that works properly.
It is absolutely vital to decrementdefer_signal
before testingsignal_pending
, because this avoids a subtle bug. If we didthese things in the other order, like this,
if (defer_signal == 1 && signal_pending != 0) raise (signal_pending); defer_signal--;
then a signal arriving in between theif
statement and the decrementwould be effectively “lost” for an indefinite amount of time. Thehandler would merely setdefer_signal
, but the program havingalready tested this variable, it would not test the variable again.
Bugs like these are calledtiming errors. They are especially badbecause they happen only rarely and are nearly impossible to reproduce.You can’t expect to find them with a debugger as you would find areproducible bug. So it is worth being especially careful to avoidthem.
(You would not be tempted to write the code in this order, given the useofdefer_signal
as a counter which must be tested along withsignal_pending
. After all, testing for zero is cleaner thantesting for one. But if you did not usedefer_signal
as acounter, and gave it values of zero and one only, then either ordermight seem equally simple. This is a further advantage of using acounter fordefer_signal
: it will reduce the chance you willwrite the code in the wrong order and create a subtle bug.)
Next:Using a Separate Signal Stack, Previous:Blocking Signals, Up:Signal Handling [Contents][Index]
If your program is driven by external events, or uses signals forsynchronization, then when it has nothing to do it should probably waituntil a signal arrives.
Next:Problems withpause
, Up:Waiting for a Signal [Contents][Index]
pause
¶The simple way to wait until a signal arrives is to callpause
.Please read about its disadvantages, in the following section, beforeyou use it.
int
pause(void)
¶Preliminary:| MT-Unsafe race:sigprocmask/!bsd!linux| AS-Unsafe lock/hurd| AC-Unsafe lock/hurd| SeePOSIX Safety Concepts.
Thepause
function suspends program execution until a signalarrives whose action is either to execute a handler function, or toterminate the process.
If the signal causes a handler function to be executed, thenpause
returns. This is considered an unsuccessful return (since“successful” behavior would be to suspend the program forever), so thereturn value is-1
. Even if you specify that other primitivesshould resume when a system handler returns (seePrimitives Interrupted by Signals), this has no effect onpause
; it always fails when asignal is handled.
The followingerrno
error conditions are defined for this function:
EINTR
The function was interrupted by delivery of a signal.
If the signal causes program termination,pause
doesn’t return(obviously).
This function is a cancellation point in multithreaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timepause
iscalled. If the thread gets cancelled these resources stay allocateduntil the program ends. To avoid this calls topause
should beprotected using cancellation handlers.
Thepause
function is declared inunistd.h.
Next:Usingsigsuspend
, Previous:Usingpause
, Up:Waiting for a Signal [Contents][Index]
pause
¶The simplicity ofpause
can conceal serious timing errors thatcan make a program hang mysteriously.
It is safe to usepause
if the real work of your program is doneby the signal handlers themselves, and the “main program” does nothingbut callpause
. Each time a signal is delivered, the handlerwill do the next batch of work that is to be done, and then return, sothat the main loop of the program can callpause
again.
You can’t safely usepause
to wait until one more signal arrives,and then resume real work. Even if you arrange for the signal handlerto cooperate by setting a flag, you still can’t usepause
reliably. Here is an example of this problem:
/*usr_interrupt
is set by the signal handler. */if (!usr_interrupt) pause ();/*Do work once the signal arrives. */...
This has a bug: the signal could arrive after the variableusr_interrupt
is checked, but before the call topause
.If no further signals arrive, the process would never wake up again.
You can put an upper limit on the excess waiting by usingsleep
in a loop, instead of usingpause
. (SeeSleeping, for moreaboutsleep
.) Here is what this looks like:
/*usr_interrupt
is set by the signal handler.while (!usr_interrupt) sleep (1);/*Do work once the signal arrives. */...
For some purposes, that is good enough. But with a little morecomplexity, you can wait reliably until a particular signal handler isrun, usingsigsuspend
.
Previous:Problems withpause
, Up:Waiting for a Signal [Contents][Index]
sigsuspend
¶The clean and reliable way to wait for a signal to arrive is to block itand then usesigsuspend
. By usingsigsuspend
in a loop,you can wait for certain kinds of signals, while letting other kinds ofsignals be handled by their handlers.
int
sigsuspend(const sigset_t *set)
¶Preliminary:| MT-Unsafe race:sigprocmask/!bsd!linux| AS-Unsafe lock/hurd| AC-Unsafe lock/hurd| SeePOSIX Safety Concepts.
This function replaces the process’s signal mask withset and thensuspends the process until a signal is delivered whose action is eitherto terminate the process or invoke a signal handling function. In otherwords, the program is effectively suspended until one of the signals thatis not a member ofset arrives.
If the process is woken up by delivery of a signal that invokes a handlerfunction, and the handler function returns, thensigsuspend
alsoreturns.
The mask remainsset only as long assigsuspend
is waiting.The functionsigsuspend
always restores the previous signal maskwhen it returns.
The return value and error conditions are the same as forpause
.
Withsigsuspend
, you can replace thepause
orsleep
loop in the previous section with something completely reliable:
sigset_t mask, oldmask;.../*Set up the mask of signals to temporarily block. */sigemptyset (&mask);sigaddset (&mask, SIGUSR1);.../*Wait for a signal to arrive. */sigprocmask (SIG_BLOCK, &mask, &oldmask);while (!usr_interrupt) sigsuspend (&oldmask);sigprocmask (SIG_UNBLOCK, &mask, NULL);
This last piece of code is a little tricky. The key point to rememberhere is that whensigsuspend
returns, it resets the process’ssignal mask to the original value, the value from before the call tosigsuspend
—in this case, theSIGUSR1
signal is onceagain blocked. The second call tosigprocmask
isnecessary to explicitly unblock this signal.
One other point: you may be wondering why thewhile
loop isnecessary at all, since the program is apparently only waiting for oneSIGUSR1
signal. The answer is that the mask passed tosigsuspend
permits the process to be woken up by the delivery ofother kinds of signals, as well—for example, job control signals. Ifthe process is woken up by a signal that doesn’t setusr_interrupt
, it just suspends itself again until the “right”kind of signal eventually arrives.
This technique takes a few more lines of preparation, but that is neededjust once for each kind of wait criterion you want to use. The codethat actually waits is just four lines.
Next:BSD Signal Handling, Previous:Waiting for a Signal, Up:Signal Handling [Contents][Index]
A signal stack is a special area of memory to be used as the executionstack during signal handlers. It should be fairly large, to avoid anydanger that it will overflow in turn; the macroSIGSTKSZ
isdefined to a canonical size for signal stacks. You can usemalloc
to allocate the space for the stack. Then callsigaltstack
orsigstack
to tell the system to use thatspace for the signal stack.
You don’t need to write signal handlers differently in order to use asignal stack. Switching from one stack to the other happensautomatically. (Some non-GNU debuggers on some machines may getconfused if you examine a stack trace while a handler that uses thesignal stack is running.)
There are two interfaces for telling the system to use a separate signalstack.sigstack
is the older interface, which comes from 4.2BSD.sigaltstack
is the newer interface, and comes from 4.4BSD. Thesigaltstack
interface has the advantage that it doesnot require your program to know which direction the stack grows, whichdepends on the specific machine and operating system.
This structure describes a signal stack. It contains the following members:
void *ss_sp
This points to the base of the signal stack.
size_t ss_size
This is the size (in bytes) of the signal stack which ‘ss_sp’ points to.You should set this to however much space you allocated for the stack.
There are two macros defined insignal.h that you should use incalculating this size:
SIGSTKSZ
¶This is the canonical size for a signal stack. It is judged to besufficient for normal uses.
MINSIGSTKSZ
¶This is the amount of signal stack space the operating system needs justto implement signal delivery. The size of a signal stackmustbe greater than this.
For most cases, just usingSIGSTKSZ
forss_size
issufficient. But if you know how much stack space your program’s signalhandlers will need, you may want to use a different size. In this case,you should allocateMINSIGSTKSZ
additional bytes for the signalstack and increasess_size
accordingly.
int ss_flags
This field contains the bitwiseOR of these flags:
int
sigaltstack(const stack_t *restrictstack, stack_t *restrictoldstack)
¶Preliminary:| MT-Safe | AS-Unsafe lock/hurd| AC-Unsafe lock/hurd| SeePOSIX Safety Concepts.
Thesigaltstack
function specifies an alternate stack for useduring signal handling. When a signal is received by the process andits action indicates that the signal stack is used, the system arrangesa switch to the currently installed signal stack while the handler forthat signal is executed.
Ifoldstack is not a null pointer, information about the currentlyinstalled signal stack is returned in the location it points to. Ifstack is not a null pointer, then this is installed as the newstack for use by signal handlers.
The return value is0
on success and-1
on failure. Ifsigaltstack
fails, it setserrno
to one of these values:
EINVAL
You tried to disable a stack that was in fact currently in use.
ENOMEM
The size of the alternate stack was too small.It must be greater thanMINSIGSTKSZ
.
Here is the oldersigstack
interface. You should usesigaltstack
instead on systems that have it.
This structure describes a signal stack. It contains the following members:
void *ss_sp
This is the stack pointer. If the stack grows downwards on yourmachine, this should point to the top of the area you allocated. If thestack grows upwards, it should point to the bottom.
int ss_onstack
This field is true if the process is currently using this stack.
int
sigstack(struct sigstack *stack, struct sigstack *oldstack)
¶Preliminary:| MT-Safe | AS-Unsafe lock/hurd| AC-Unsafe lock/hurd| SeePOSIX Safety Concepts.
Thesigstack
function specifies an alternate stack for use duringsignal handling. When a signal is received by the process and itsaction indicates that the signal stack is used, the system arranges aswitch to the currently installed signal stack while the handler forthat signal is executed.
Ifoldstack is not a null pointer, information about the currentlyinstalled signal stack is returned in the location it points to. Ifstack is not a null pointer, then this is installed as the newstack for use by signal handlers.
The return value is0
on success and-1
on failure.
Previous:Using a Separate Signal Stack, Up:Signal Handling [Contents][Index]
This section describes alternative signal handling functions derivedfrom BSD Unix. These facilities were an advance, in their time; today,they are mostly obsolete, and supported mainly for compatibility withBSD Unix.
There are many similarities between the BSD and POSIX signal handlingfacilities, because the POSIX facilities were inspired by the BSDfacilities. Besides having different names for all the functions toavoid conflicts, the main difference between the two is that BSD Unixrepresents signal masks as anint
bit mask, rather than as asigset_t
object.
The BSD facilities are declared insignal.h.
int
siginterrupt(intsignum, intfailflag)
¶Preliminary:| MT-Unsafe const:sigintr| AS-Unsafe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function specifies which approach to use when certain primitivesare interrupted by handling signalsignum. Iffailflag isfalse, signalsignum restarts primitives. Iffailflag istrue, handlingsignum causes these primitives to fail with errorcodeEINTR
. SeePrimitives Interrupted by Signals.
This function has been replaced by theSA_RESTART
flag of thesigaction
function. SeeAdvanced Signal Handling.
int
sigmask(intsignum)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a signal mask that has the bit for signalsignumset. You can bitwise-OR the results of several calls tosigmask
together to specify more than one signal. For example,
(sigmask (SIGTSTP) | sigmask (SIGSTOP) | sigmask (SIGTTIN) | sigmask (SIGTTOU))
specifies a mask that includes all the job-control stop signals.
This macro has been replaced by thesigset_t
type and theassociated signal set manipulation functions. SeeSignal Sets.
int
sigblock(intmask)
¶Preliminary:| MT-Safe | AS-Unsafe lock/hurd| AC-Unsafe lock/hurd| SeePOSIX Safety Concepts.
This function is equivalent tosigprocmask
(seeProcess Signal Mask) with ahow argument ofSIG_BLOCK
: it adds thesignals specified bymask to the calling process’s set of blockedsignals. The return value is the previous set of blocked signals.
int
sigsetmask(intmask)
¶Preliminary:| MT-Safe | AS-Unsafe lock/hurd| AC-Unsafe lock/hurd| SeePOSIX Safety Concepts.
This function is equivalent tosigprocmask
(seeProcess Signal Mask) with ahow argument ofSIG_SETMASK
: it setsthe calling process’s signal mask tomask. The return value isthe previous set of blocked signals.
int
sigpause(intmask)
¶Preliminary:| MT-Unsafe race:sigprocmask/!bsd!linux| AS-Unsafe lock/hurd| AC-Unsafe lock/hurd| SeePOSIX Safety Concepts.
This function is the equivalent ofsigsuspend
(seeWaiting for a Signal): it sets the calling process’s signal mask tomask,and waits for a signal to arrive. On return the previous set of blockedsignals is restored.
Next:Processes, Previous:Signal Handling, Up:Main Menu [Contents][Index]
Processes are the primitive units for allocation of systemresources. Each process has its own address space and (usually) onethread of control. A process executes a program; you can have multipleprocesses executing the same program, but each process has its own copyof the program within its own address space and executes itindependently of the other copies. Though it may have multiple threadsof control within the same program and a program may be composed ofmultiple logically separate modules, a process always executes exactlyone program.
Note that we are using a specific definition of “program” for thepurposes of this manual, which corresponds to a common definition in thecontext of Unix systems. In popular usage, “program” enjoys a muchbroader definition; it can refer for example to a system’s kernel, aneditor macro, a complex package of software, or a discrete section ofcode executing within a process.
Writing the program is what this manual is all about. This chapterexplains the most basic interface between your program and the systemthat runs, or calls, it. This includes passing of parameters (argumentsand environment) from the system, requesting basic services from thesystem, and telling the system the program is done.
A program starts another program with theexec
family of system calls.This chapter looks at program startup from the execee’s point of view. Tosee the event from the execor’s point of view, seeExecuting a File.
getopt
The system starts a C program by calling the functionmain
. Itis up to you to write a function namedmain
—otherwise, youwon’t even be able to link your program without errors.
In ISO C you can definemain
either to take no arguments, or totake two arguments that represent the command line arguments to theprogram, like this:
int main (intargc, char *argv[])
The command line arguments are the whitespace-separated tokens given inthe shell command used to invoke the program; thus, in ‘cat foobar’, the arguments are ‘foo’ and ‘bar’. The only way aprogram can look at its command line arguments is via the arguments ofmain
. Ifmain
doesn’t take arguments, then you cannot getat the command line.
The value of theargc argument is the number of command linearguments. Theargv argument is a vector of C strings; itselements are the individual command line argument strings. The filename of the program being run is also included in the vector as thefirst element; the value ofargc counts this element. A nullpointer always follows the last element:argv[argc]
is this null pointer.
For the command ‘cat foo bar’,argc is 3 andargv hasthree elements,"cat"
,"foo"
and"bar"
.
In Unix systems you can definemain
a third way, using three arguments:
int main (intargc, char *argv[], char *envp[])
The first two arguments are just the same. The third argumentenvp gives the program’s environment; it is the same as the valueofenviron
. SeeEnvironment Variables. POSIX.1 does notallow this three-argument form, so to be portable it is best to writemain
to take two arguments, and use the value ofenviron
.
Next:Parsing Program Arguments, Up:Program Arguments [Contents][Index]
POSIX recommends these conventions for command line arguments.getopt
(seeParsing program options usinggetopt
) andargp_parse
(seeParsing Program Options with Argp) makeit easy to implement them.
isalnum
;seeClassification of Characters).ld
command requires an argument—an output file name.The implementations ofgetopt
andargp_parse
in the GNU C Librarynormally make it appear as if all the option arguments werespecified before all the non-option arguments for the purposes ofparsing, even if the user of your program intermixed option andnon-option arguments. They do this by reordering the elements of theargv array. This behavior is nonstandard; if you want to suppressit, define the_POSIX_OPTION_ORDER
environment variable.SeeStandard Environment Variables.
GNU addslong options to these conventions. Long options consistof-- followed by a name made of alphanumeric characters anddashes. Option names are typically one to three words long, withhyphens to separate words. Users can abbreviate the option names aslong as the abbreviations are unique.
To specify an argument for a long option, write--name=value. This syntax enables a long option toaccept an argument that is itself optional.
Eventually, GNU systems will provide completion for long option namesin the shell.
Previous:Program Argument Syntax Conventions, Up:Program Arguments [Contents][Index]
If the syntax for the command line arguments to your program is simpleenough, you can simply pick the arguments off fromargv by hand.But unless your program takes a fixed number of arguments, or all of thearguments are interpreted in the same way (as file names, for example),you are usually better off usinggetopt
(seeParsing program options usinggetopt
) orargp_parse
(seeParsing Program Options with Argp) to do the parsing.
getopt
is more standard (the short-option only version of it is apart of the POSIX standard), but usingargp_parse
is ofteneasier, both for very simple and very complex option structures, becauseit does more of the dirty work for you.
getopt
¶Thegetopt
andgetopt_long
functions automate some of thechore involved in parsing typical unix command line options.
getopt
functiongetopt
getopt_long
getopt_long
Next:Example of Parsing Arguments withgetopt
, Up:Parsing program options usinggetopt
[Contents][Index]
getopt
function ¶Here are the details about how to call thegetopt
function. Touse this facility, your program must include the header fileunistd.h.
int
opterr ¶If the value of this variable is nonzero, thengetopt
prints anerror message to the standard error stream if it encounters an unknownoption character or an option with a missing required argument. This isthe default behavior. If you set this variable to zero,getopt
does not print any messages, but it still returns the character?
to indicate an error.
int
optopt ¶Whengetopt
encounters an unknown option character or an optionwith a missing required argument, it stores that option character inthis variable. You can use this for providing your own diagnosticmessages.
int
optind ¶This variable is set bygetopt
to the index of the next elementof theargv array to be processed. Oncegetopt
has foundall of the option arguments, you can use this variable to determinewhere the remaining non-option arguments begin. The initial value ofthis variable is1
.
char *
optarg ¶This variable is set bygetopt
to point at the value of theoption argument, for those options that accept arguments.
int
getopt(intargc, char *const *argv, const char *options)
¶Preliminary:| MT-Unsafe race:getopt env| AS-Unsafe heap i18n lock corrupt| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
Thegetopt
function gets the next option argument from theargument list specified by theargv andargc arguments.Normally these values come directly from the arguments received bymain
.
Theoptions argument is a string that specifies the optioncharacters that are valid for this program. An option character in thisstring can be followed by a colon (‘:’) to indicate that it takes arequired argument. If an option character is followed by two colons(‘::’), its argument is optional; this is a GNU extension.
getopt
has three ways to deal with options that follownon-optionsargv elements. The special argument ‘--’ forcesin all cases the end of option scanning.
POSIXLY_CORRECT
or beginning theoptions argumentstring with a plus sign (‘+’).Thegetopt
function returns the option character for the nextcommand line option. When no more option arguments are available, itreturns-1
. There may still be more non-option arguments; youmust compare the external variableoptind
against theargcparameter to check this.
If the option has an argument,getopt
returns the argument bystoring it in the variableoptarg. You don’t ordinarily need tocopy theoptarg
string, since it is a pointer into the originalargv array, not into a static area that might be overwritten.
Ifgetopt
finds an option character inargv that was notincluded inoptions, or a missing option argument, it returns‘?’ and sets the external variableoptopt
to the actualoption character. If the first character ofoptions is a colon(‘:’), thengetopt
returns ‘:’ instead of ‘?’ toindicate a missing option argument. In addition, if the externalvariableopterr
is nonzero (which is the default),getopt
prints an error message.
Next:Parsing Long Options withgetopt_long
, Previous:Using thegetopt
function, Up:Parsing program options usinggetopt
[Contents][Index]
getopt
¶Here is an example showing howgetopt
is typically used. Thekey points to notice are:
getopt
is called in a loop. Whengetopt
returns-1
, indicating no more options are present, the loop terminates.switch
statement is used to dispatch on the return value fromgetopt
. In typical use, each case just sets a variable thatis used later in the program.#include <ctype.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>intmain (int argc, char **argv){ int aflag = 0; int bflag = 0; char *cvalue = NULL; int index; int c; opterr = 0;
while ((c = getopt (argc, argv, "abc:")) != -1) switch (c) { case 'a': aflag = 1; break; case 'b': bflag = 1; break; case 'c': cvalue = optarg; break; case '?': if (optopt == 'c') fprintf (stderr, "Option -%c requires an argument.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); }
printf ("aflag = %d, bflag = %d, cvalue = %s\n", aflag, bflag, cvalue); for (index = optind; index < argc; index++) printf ("Non-option argument %s\n", argv[index]); return 0;}
Here are some examples showing what this program prints with differentcombinations of arguments:
% testoptaflag = 0, bflag = 0, cvalue = (null)% testopt -a -baflag = 1, bflag = 1, cvalue = (null)% testopt -abaflag = 1, bflag = 1, cvalue = (null)% testopt -c fooaflag = 0, bflag = 0, cvalue = foo% testopt -cfooaflag = 0, bflag = 0, cvalue = foo% testopt arg1aflag = 0, bflag = 0, cvalue = (null)Non-option argument arg1% testopt -a arg1aflag = 1, bflag = 0, cvalue = (null)Non-option argument arg1% testopt -c foo arg1aflag = 0, bflag = 0, cvalue = fooNon-option argument arg1% testopt -a -- -baflag = 1, bflag = 0, cvalue = (null)Non-option argument -b% testopt -a -aflag = 1, bflag = 0, cvalue = (null)Non-option argument -
Next:Example of Parsing Long Options withgetopt_long
, Previous:Example of Parsing Arguments withgetopt
, Up:Parsing program options usinggetopt
[Contents][Index]
getopt_long
¶To accept GNU-style long options as well as single-character options,usegetopt_long
instead ofgetopt
. This function isdeclared ingetopt.h, notunistd.h. You should make everyprogram accept long options if it uses any options, for this takeslittle extra work and helps beginners remember how to use the program.
This structure describes a single long option name for the sake ofgetopt_long
. The argumentlongopts must be an array ofthese structures, one for each long option. Terminate the array with anelement containing all zeros.
Thestruct option
structure has these fields:
const char *name
This field is the name of the option. It is a string.
int has_arg
This field says whether the option takes an argument. It is an integer,and there are three legitimate values:no_argument
,required_argument
andoptional_argument
.
int *flag
int val
These fields control how to report or act on the option when it occurs.
Ifflag
is a null pointer, then theval
is a value whichidentifies this option. Often these values are chosen to uniquelyidentify particular long options.
Ifflag
is not a null pointer, it should be the address of anint
variable which is the flag for this option. The value inval
is the value to store in the flag to indicate that the optionwas seen.
int
getopt_long(intargc, char *const *argv, const char *shortopts, const struct option *longopts, int *indexptr)
¶Preliminary:| MT-Unsafe race:getopt env| AS-Unsafe heap i18n lock corrupt| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
Decode options from the vectorargv (whose length isargc).The argumentshortopts describes the short options to accept, just asit does ingetopt
. The argumentlongopts describes the longoptions to accept (see above).
Whengetopt_long
encounters a short option, it does the samething thatgetopt
would do: it returns the character code for theoption, and stores the option’s argument (if it has one) inoptarg
.
Whengetopt_long
encounters a long option, it takes actions basedon theflag
andval
fields of the definition of thatoption. The option name may be abbreviated as long as the abbreviation isunique.
Ifflag
is a null pointer, thengetopt_long
returns thecontents ofval
to indicate which option it found. You shouldarrange distinct values in theval
field for options withdifferent meanings, so you can decode these values aftergetopt_long
returns. If the long option is equivalent to a shortoption, you can use the short option’s character code inval
.
Ifflag
is not a null pointer, that means this option should justset a flag in the program. The flag is a variable of typeint
that you define. Put the address of the flag in theflag
field.Put in theval
field the value you would like this option tostore in the flag. In this case,getopt_long
returns0
.
For any long option,getopt_long
tells you the index in the arraylongopts of the options definition, by storing it into*indexptr
. You can get the name of the option withlongopts[*indexptr].name
. So you can distinguish amonglong options either by the values in theirval
fields or by theirindices. You can also distinguish in this way among long options thatset flags.
When a long option has an argument,getopt_long
puts the argumentvalue in the variableoptarg
before returning. When the optionhas no argument, the value inoptarg
is a null pointer. This ishow you can tell whether an optional argument was supplied.
Whengetopt_long
has no more options to handle, it returns-1
, and leaves in the variableoptind
the index inargv of the next remaining argument.
Since long option names were used beforegetopt_long
was invented there are program interfaces which require programsto recognize options like ‘-option value’ instead of‘--option value’. To enable these programs to use the GNUgetopt functionality there is one more function available.
int
getopt_long_only(intargc, char *const *argv, const char *shortopts, const struct option *longopts, int *indexptr)
¶Preliminary:| MT-Unsafe race:getopt env| AS-Unsafe heap i18n lock corrupt| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
Thegetopt_long_only
function is equivalent to thegetopt_long
function but it allows the user of theapplication to pass long options with only ‘-’ instead of‘--’. The ‘--’ prefix is still recognized but instead oflooking through the short options if a ‘-’ is seen it is firsttried whether this parameter names a long option. If not, it is parsedas a short option. In case both short and long options could bematched (this can happen with single letter long options), the shortoption is preferred (with some caveats). For long options,abbreviations are detected as well.
Assuminggetopt_long_only
is used starting an application with
app -foo
thegetopt_long_only
will first look for a long option named‘foo’. If this is not found, the short options ‘f’, ‘o’,and again ‘o’ are recognized.
It gets more interesting with single letter long options. If wedefine options in the following way
static struct option long_options[] = { {"f", no_argument, 0, 0 }, {"foo", no_argument, 0, 0 }, {0, 0, 0, 0 }, };
use"f"
(as a C string) as an option string and start theapplication with-f, the short option will be matched.--f will match the long one. And both-fo and-foo will match the long option"foo"
.
Be aware that if the option string would be"f:"
(thus theshort option requires an argument), using just-f leads to anerror. But using-fo results in the long option beingmatched. For passing an argument in this situation, you need to do itas two arguments (-f,o). Though any other valuewould work in a single argument (e.g.,-f1), since it wouldnot match a long option (or its abbreviation).
Previous:Parsing Long Options withgetopt_long
, Up:Parsing program options usinggetopt
[Contents][Index]
getopt_long
¶#include <stdio.h>#include <stdlib.h>#include <getopt.h>/*Flag set by ‘--verbose’. */static int verbose_flag;intmain (int argc, char **argv){ int c; while (1) { static struct option long_options[] = { /*These options set a flag. */ {"verbose", no_argument, &verbose_flag, 1}, {"brief", no_argument, &verbose_flag, 0}, /*These options don’t set a flag. We distinguish them by their indices. */ {"add", no_argument, 0, 'a'}, {"append", no_argument, 0, 'b'}, {"delete", required_argument, 0, 'd'}, {"create", required_argument, 0, 'c'}, {"file", required_argument, 0, 'f'}, {0, 0, 0, 0} }; /*getopt_long
stores the option index here. */ int option_index = 0; c = getopt_long (argc, argv, "abc:d:f:", long_options, &option_index); /*Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: /*If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) break; printf ("option %s", long_options[option_index].name); if (optarg) printf (" with arg %s", optarg); printf ("\n"); break; case 'a': puts ("option -a"); break; case 'b': puts ("option -b"); break; case 'c': printf ("option -c with value '%s'\n", optarg); break; case 'd': printf ("option -d with value '%s'\n", optarg); break; case 'f': printf ("option -f with value '%s'\n", optarg); break; case '?': /*getopt_long
already printed an error message. */ break; default: abort (); } } /*Instead of reporting ‘--verbose’ and ‘--brief’ as they are encountered, we report the final status resulting from them. */ if (verbose_flag) puts ("verbose flag is set"); /*Print any remaining command line arguments (not options). */ if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); putchar ('\n'); } exit (0);}
Next:Parsing of Suboptions, Previous:Parsing program options usinggetopt
, Up:Parsing Program Arguments [Contents][Index]
Argp is an interface for parsing unix-style argument vectors.SeeProgram Arguments.
Argp provides features unavailable in the more commonly usedgetopt
interface. These features include automatically producingoutput in response to the ‘--help’ and ‘--version’ options, asdescribed in the GNU coding standards. Using argp makes it less likelythat programmers will neglect to implement these additional options orkeep them up to date.
Argp also provides the ability to merge several independently definedoption parsers into one, mediating conflicts between them and making theresult appear seamless. A library can export an argp option parser thatuser programs might employ in conjunction with their own option parsers,resulting in less work for the user programs. Some programs may use onlyargument parsers exported by libraries, thereby achieving consistent andefficient option-parsing for abstractions implemented by the libraries.
The header file<argp.h> should be included to use argp.
argp_parse
Functionargp_parse
argp_help
Functionargp_help
Functionargp_parse
Function ¶The main interface to argp is theargp_parse
function. In manycases, callingargp_parse
is the only argument-parsing codeneeded inmain
.SeeProgram Arguments.
error_t
argp_parse(const struct argp *argp, intargc, char **argv, unsignedflags, int *arg_index, void *input)
¶Preliminary:| MT-Unsafe race:argpbuf locale env| AS-Unsafe heap i18n lock corrupt| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
Theargp_parse
function parses the arguments inargv, oflengthargc, using the argp parserargp. SeeSpecifying Argp Parsers. Passing a null pointer forargp is the same as usingastruct argp
containing all zeros.
flags is a set of flag bits that modify the parsing behavior.SeeFlags forargp_parse
.input is passed through to the argp parserargp, and has meaning defined byargp. A typical usage isto pass a pointer to a structure which is used for specifyingparameters to the parser and passing back the results.
Unless theARGP_NO_EXIT
orARGP_NO_HELP
flags are includedinflags, callingargp_parse
may result in the programexiting. This behavior is true if an error is detected, or when anunknown option is encountered. SeeProgram Termination.
Ifarg_index is non-null, the index of the first unparsed optioninargv is returned as a value.
The return value is zero for successful parsing, or an error code(seeError Codes) if an error is detected. Different argp parsersmay return arbitrary error codes, but the standard error codes are:ENOMEM
if a memory allocation error occurred, orEINVAL
ifan unknown option or option argument is encountered.
These variables make it easy for user programs to implement the‘--version’ option and provide a bug-reporting address in the‘--help’ output. These are implemented in argp by default.
const char *
argp_program_version ¶If defined or set by the user program to a non-zero value, then a‘--version’ option is added when parsing withargp_parse
,which will print the ‘--version’ string followed by a newline andexit. The exception to this is if theARGP_NO_EXIT
flag is used.
const char *
argp_program_bug_address ¶If defined or set by the user program to a non-zero value,argp_program_bug_address
should point to a string that will beprinted at the end of the standard output for the ‘--help’ option,embedded in a sentence that says ‘Report bugs toaddress.’.
If defined or set by the user program to a non-zero value, a‘--version’ option is added when parsing witharg_parse
,which prints the program version and exits with a status of zero. Thisis not the case if theARGP_NO_HELP
flag is used. If theARGP_NO_EXIT
flag is set, the exit behavior of the program issuppressed or modified, as when the argp parser is going to be used byother programs.
It should point to a function with this type of signature:
voidprint-version (FILE *stream, struct argp_state *state)
SeeArgp Parsing State, for an explanation ofstate.
This variable takes precedence overargp_program_version
, and isuseful if a program has version information not easily expressed in asimple string.
error_t
argp_err_exit_status ¶This is the exit status used when argp exits due to a parsing error. Ifnot defined or set by the user program, this defaults to:EX_USAGE
from<sysexits.h>.
Next:Flags forargp_parse
, Previous:Argp Global Variables, Up:Parsing Program Options with Argp [Contents][Index]
The first argument to theargp_parse
function is a pointer to astruct argp
, which is known as anargp parser:
This structure specifies how to parse a given set of options andarguments, perhaps in conjunction with other argp parsers. It has thefollowing fields:
const struct argp_option *options
A pointer to a vector ofargp_option
structures specifying whichoptions this argp parser understands; it may be zero if there are nooptions at all. SeeSpecifying Options in an Argp Parser.
argp_parser_t parser
A pointer to a function that defines actions for this parser; it iscalled for each option parsed, and at other well-defined points in theparsing process. A value of zero is the same as a pointer to a functionthat always returnsARGP_ERR_UNKNOWN
. SeeArgp Parser Functions.
const char *args_doc
If non-zero, a string describing what non-option arguments are called bythis parser. This is only used to print the ‘Usage:’ message. Ifit contains newlines, the strings separated by them are consideredalternative usage patterns and printed on separate lines. Lines afterthe first are prefixed by ‘ or:’ instead of ‘Usage:’.
const char *doc
If non-zero, a string containing extra text to be printed before andafter the options in a long help message, with the two sectionsseparated by a vertical tab ('\v'
,'\013'
) character. Byconvention, the documentation before the options is just a short stringexplaining what the program does. Documentation printed after theoptions describe behavior in more detail.
const struct argp_child *children
A pointer to a vector ofargp_child
structures. This pointerspecifies which additional argp parsers should be combined with thisone. SeeCombining Multiple Argp Parsers.
char *(*help_filter)(intkey, const char *text, void *input)
If non-zero, a pointer to a function that filters the output of helpmessages. SeeCustomizing Argp Help Output.
const char *argp_domain
If non-zero, the strings used in the argp library are translated usingthe domain described by this string. If zero, the current default domainis used.
Of the above group,options
,parser
,args_doc
, andthedoc
fields are usually all that are needed. If an argpparser is defined as an initialized C variable, only the fields usedneed be specified in the initializer. The rest will default to zero dueto the way C structure initialization works. This design is exploited inmost argp structures; the most-used fields are grouped near thebeginning, the unused fields left unspecified.
Next:Argp Parser Functions, Previous:Specifying Argp Parsers, Up:Specifying Argp Parsers [Contents][Index]
Theoptions
field in astruct argp
points to a vector ofstruct argp_option
structures, each of which specifies an optionthat the argp parser supports. Multiple entries may be used for a singleoption provided it has multiple names. This should be terminated by anentry with zero in all fields. Note that when using an initialized Carray for options, writing{ 0 }
is enough to achieve this.
This structure specifies a single option that an argp parserunderstands, as well as how to parse and document that option. It hasthe following fields:
const char *name
The long name for this option, corresponding to the long option‘--name’; this field may be zero if this optiononlyhas a short name. To specify multiple names for an option, additionalentries may follow this one, with theOPTION_ALIAS
flagset. SeeFlags for Argp Options.
int key
The integer key provided by the current option to the option parser. Ifkey has a value that is a printableASCII character (i.e.,isascii (key)
is true), italso specifies a shortoption ‘-char’, wherechar is theASCII characterwith the codekey.
const char *arg
If non-zero, this is the name of an argument associated with thisoption, which must be provided (e.g., with the‘--name=value’ or ‘-charvalue’syntaxes), unless theOPTION_ARG_OPTIONAL
flag (seeFlags for Argp Options) is set, in which case itmay be provided.
int flags
Flags associated with this option, some of which are referred to above.SeeFlags for Argp Options.
const char *doc
A documentation string for this option, for printing in help messages.
If both thename
andkey
fields are zero, this stringwill be printed tabbed left from the normal option column, making ituseful as a group header. This will be the first thing printed in itsgroup. In this usage, it’s conventional to end the string with a‘:’ character.
int group
Group identity for this option.
In a long help message, options are sorted alphabetically within eachgroup, and the groups presented in the order 0, 1, 2, …,n,−m, …, −2, −1.
Every entry in an options array with this field 0 will inherit the groupnumber of the previous entry, or zero if it’s the first one. If it’s agroup header withname
andkey
fields both zero, theprevious entry + 1 is the default. Automagic options such as‘--help’ are put into group −1.
Note that because of C structure initialization rules, this field oftenneed not be specified, because 0 is the correct value.
The following flags may be or’d together in theflags
field of astruct argp_option
. These flags control various aspects of howthat option is parsed or displayed in help messages:
OPTION_ARG_OPTIONAL
¶The argument associated with this option is optional.
OPTION_HIDDEN
¶This option isn’t displayed in any help messages.
OPTION_ALIAS
¶This option is an alias for the closest previous non-alias option. Thismeans that it will be displayed in the same help entry, and will inheritfields other thanname
andkey
from the option beingaliased.
OPTION_DOC
¶This option isn’t actually an option and should be ignored by the actualoption parser. It is an arbitrary section of documentation that shouldbe displayed in much the same manner as the options. This is known as adocumentation option.
If this flag is set, then the optionname
field is displayedunmodified (e.g., no ‘--’ prefix is added) at the left-margin whereashort option would normally be displayed, and thisdocumentation string is left in its usual place. For purposes ofsorting, any leading whitespace and punctuation is ignored, unless thefirst non-whitespace character is ‘-’. This entry is displayedafter all options, afterOPTION_DOC
entries with a leading‘-’, in the same group.
OPTION_NO_USAGE
¶This option shouldn’t be included in ‘long’ usage messages, but shouldstill be included in other help messages. This is intended for optionsthat are completely documented in an argp’sargs_doc
field. SeeSpecifying Argp Parsers. Including this option in the generic usagelist would be redundant, and should be avoided.
For instance, ifargs_doc
is"FOO BAR\n-x BLAH"
, and the‘-x’ option’s purpose is to distinguish these two cases, ‘-x’should probably be markedOPTION_NO_USAGE
.
Next:Combining Multiple Argp Parsers, Previous:Specifying Options in an Argp Parser, Up:Specifying Argp Parsers [Contents][Index]
The function pointed to by theparser
field in astructargp
(seeSpecifying Argp Parsers) defines what actions take place in responseto each option or argument parsed. It is also used as a hook, allowing aparser to perform tasks at certain other points during parsing.
Argp parser functions have the following type signature:
error_tparser (intkey, char *arg, struct argp_state *state)
where the arguments are as follows:
For each option that is parsed,parser is called with a value ofkey from that option’skey
field in the optionvector. SeeSpecifying Options in an Argp Parser.parser is also called atother times with special reserved keys, such asARGP_KEY_ARG
fornon-option arguments. SeeSpecial Keys for Argp Parser Functions.
Ifkey is an option,arg is its given value. This defaultsto zero if no value is specified. Only options that have a non-zeroarg
field can ever have a value. These mustalways have avalue unless theOPTION_ARG_OPTIONAL
flag is specified. If theinput being parsed specifies a value for an option that doesn’t allowone, an error results beforeparser ever gets called.
Ifkey isARGP_KEY_ARG
,arg is a non-optionargument. Other special keys always have a zeroarg.
state points to astruct argp_state
, containing usefulinformation about the current parsing state for use byparser. SeeArgp Parsing State.
Whenparser is called, it should perform whatever action isappropriate forkey, and return0
for success,ARGP_ERR_UNKNOWN
if the value ofkey is not handled by thisparser function, or a unix error code if a real erroroccurred. SeeError Codes.
int
ARGP_ERR_UNKNOWN ¶Argp parser functions should returnARGP_ERR_UNKNOWN
for anykey value they do not recognize, or for non-option arguments(key == ARGP_KEY_ARG
) that they are not equipped to handle.
A typical parser function uses a switch statement onkey:
error_tparse_opt (int key, char *arg, struct argp_state *state){ switch (key) { caseoption_key:action break; ... default: return ARGP_ERR_UNKNOWN; } return 0;}
Next:Argp Parsing State, Up:Argp Parser Functions [Contents][Index]
In addition to key values corresponding to user options, thekeyargument to argp parser functions may have a number of other specialvalues. In the following examplearg andstate refer toparser function arguments. SeeArgp Parser Functions.
ARGP_KEY_ARG
¶This is not an option at all, but rather a command line argument, whosevalue is pointed to byarg.
When there are multiple parser functions in play due to argp parsersbeing combined, it’s impossible to know which one will handle a specificargument. Each is called until one returns 0 or an error other thanARGP_ERR_UNKNOWN
; if an argument is not handled,argp_parse
immediately returns success, without parsing any morearguments.
Once a parser function returns success for this key, that fact isrecorded, and theARGP_KEY_NO_ARGS
case won’t beused.However, if while processing the argument a parser functiondecrements thenext
field of itsstate argument, the optionwon’t be considered processed; this is to allow you to actually modifythe argument, perhaps into an option, and have it processed again.
ARGP_KEY_ARGS
¶If a parser function returnsARGP_ERR_UNKNOWN
forARGP_KEY_ARG
, it is immediately called again with the keyARGP_KEY_ARGS
, which has a similar meaning, but is slightly moreconvenient for consuming all remaining arguments.arg is 0, andthe tail of the argument vector may be found atstate->argv+state->next
. If success is returned for this key, andstate->next
is unchanged, all remaining arguments areconsidered to have been consumed. Otherwise, the amount by whichstate->next
has been adjusted indicates how many were used.Here’s an example that uses both, for different args:
...case ARGP_KEY_ARG: if (state->arg_num == 0) /* First argument */ first_arg =arg; else /* Let the next case parse it. */ return ARGP_KEY_UNKNOWN; break;case ARGP_KEY_ARGS: remaining_args =state->argv +state->next; num_remaining_args =state->argc -state->next; break;
ARGP_KEY_END
¶This indicates that there are no more command line arguments. Parserfunctions are called in a different order, children first. This allowseach parser to clean up its state for the parent.
ARGP_KEY_NO_ARGS
¶Because it’s common to do some special processing if there aren’t anynon-option args, parser functions are called with this key if theydidn’t successfully process any non-option arguments. This is calledjust beforeARGP_KEY_END
, where more general validity checks onpreviously parsed arguments take place.
ARGP_KEY_INIT
¶This is passed in before any parsing is done. Afterwards, the values ofeach element of thechild_input
field ofstate, if any, arecopied to each child’s state to be the initial value of theinput
whentheir parsers are called.
ARGP_KEY_SUCCESS
¶Passed in when parsing has successfully been completed, even ifarguments remain.
ARGP_KEY_ERROR
¶Passed in if an error has occurred and parsing is terminated. In thiscase a call with a key ofARGP_KEY_SUCCESS
is never made.
ARGP_KEY_FINI
¶The final key ever seen by any parser, even afterARGP_KEY_SUCCESS
andARGP_KEY_ERROR
. Any resourcesallocated byARGP_KEY_INIT
may be freed here. At times, certainresources allocated are to be returned to the caller after a successfulparse. In that case, those particular resources can be freed in theARGP_KEY_ERROR
case.
In all cases,ARGP_KEY_INIT
is the first key seen by parserfunctions, andARGP_KEY_FINI
the last, unless an error wasreturned by the parser forARGP_KEY_INIT
. Other keys can occurin one the following orders.opt refers to an arbitrary optionkey:
ARGP_KEY_NO_ARGS
ARGP_KEY_END
ARGP_KEY_SUCCESS
The arguments being parsed did not contain any non-option arguments.
ARGP_KEY_ARG
)…ARGP_KEY_END
ARGP_KEY_SUCCESS
All non-option arguments were successfully handled by a parserfunction. There may be multiple parser functions if multiple argpparsers were combined.
ARGP_KEY_ARG
)…ARGP_KEY_SUCCESS
Some non-option argument went unrecognized.
This occurs when every parser function returnsARGP_KEY_UNKNOWN
for an argument, in which case parsing stops at that argument ifarg_index is a null pointer. Otherwise an error occurs.
In all cases, if a non-null value forarg_index gets passed toargp_parse
, the index of the first unparsed command-line argumentis passed back in that value.
If an error occurs and is either detected by argp or because a parserfunction returned an error value, each parser is called withARGP_KEY_ERROR
. No further calls are made, except the final callwithARGP_KEY_FINI
.
Next:Functions For Use in Argp Parsers, Previous:Special Keys for Argp Parser Functions, Up:Argp Parser Functions [Contents][Index]
The third argument to argp parser functions (seeArgp Parser Functions) is a pointer to astruct argp_state
, which containsinformation about the state of the option parsing.
This structure has the following fields, which may be modified as noted:
const struct argp *const root_argp
The top level argp parser being parsed. Note that this is oftennot the samestruct argp
passed intoargp_parse
bythe invoking program. SeeParsing Program Options with Argp. It is an internal argp parser thatcontains options implemented byargp_parse
itself, such as‘--help’.
int argc
char **argv
The argument vector being parsed. This may be modified.
int next
The index inargv
of the next argument to be parsed. This may bemodified.
One way to consume all remaining arguments in the input is to setstate->next =state->argc
, perhaps after recordingthe value of thenext
field to find the consumed arguments. Thecurrent option can be re-parsed immediately by decrementing this field,then modifyingstate->argv[state->next]
to reflectthe option that should be reexamined.
unsigned flags
The flags supplied toargp_parse
. These may be modified, althoughsome flags may only take effect whenargp_parse
is firstinvoked. SeeFlags forargp_parse
.
unsigned arg_num
While calling a parsing function with thekey argumentARGP_KEY_ARG
, this represents the number of the current arg,starting at 0. It is incremented after eachARGP_KEY_ARG
callreturns. At all other times, this is the number ofARGP_KEY_ARG
arguments that have been processed.
int quoted
If non-zero, the index inargv
of the first argument following aspecial ‘--’ argument. This prevents anything that follows frombeing interpreted as an option. It is only set after argument parsinghas proceeded past this point.
void *input
An arbitrary pointer passed in from the caller ofargp_parse
, intheinput argument.
void **child_inputs
These are values that will be passed to child parsers. This vector willbe the same length as the number of children in the current parser. Eachchild parser will be given the value ofstate->child_inputs[i]
asitsstate->input
field, wherei is the index of the childin the this parser’schildren
field. SeeCombining Multiple Argp Parsers.
void *hook
For the parser function’s use. Initialized to 0, but otherwise ignoredby argp.
char *name
The name used when printing messages. This is initialized toargv[0]
, orprogram_invocation_name
ifargv[0]
isunavailable.
FILE *err_stream
FILE *out_stream
The stdio streams used when argp prints. Error messages are printed toerr_stream
, all other output, such as ‘--help’ output) toout_stream
. These are initialized tostderr
andstdout
respectively. SeeStandard Streams.
void *pstate
Private, for use by the argp implementation.
Previous:Argp Parsing State, Up:Argp Parser Functions [Contents][Index]
Argp provides a number of functions available to the user of argp(seeArgp Parser Functions), mostly for producing error messages.These take as their first argument thestate argument to theparser function. SeeArgp Parsing State.
void
argp_usage(const struct argp_state *state)
¶Preliminary:| MT-Unsafe race:argpbuf env locale| AS-Unsafe heap i18n corrupt| AC-Unsafe mem corrupt lock| SeePOSIX Safety Concepts.
Outputs the standard usage message for the argp parser referred to bystate tostate->err_stream
and terminates the programwithexit (argp_err_exit_status)
. SeeArgp Global Variables.
void
argp_error(const struct argp_state *state, const char *fmt, …)
¶Preliminary:| MT-Unsafe race:argpbuf env locale| AS-Unsafe heap i18n corrupt| AC-Unsafe mem corrupt lock| SeePOSIX Safety Concepts.
Prints the printf format stringfmt and following args, precededby the program name and ‘:’, and followed by a ‘Try … --help’ message, and terminates the program with an exit status ofargp_err_exit_status
. SeeArgp Global Variables.
void
argp_failure(const struct argp_state *state, intstatus, interrnum, const char *fmt, …)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap| AC-Unsafe lock corrupt mem| SeePOSIX Safety Concepts.
Similar to the standard GNU error-reporting functionerror
, thisprints the program name and ‘:’, the printf format stringfmt, and the appropriate following args. If it is non-zero, thestandard unix error text forerrnum is printed. Ifstatus isnon-zero, it terminates the program with that value as its exit status.
The difference betweenargp_failure
andargp_error
is thatargp_error
is forparsing errors, whereasargp_failure
is for other problems that occur during parsing butdon’t reflect a syntactic problem with the input, such as illegal valuesfor options, bad phase of the moon, etc.
void
argp_state_help(const struct argp_state *state, FILE *stream, unsignedflags)
¶Preliminary:| MT-Unsafe race:argpbuf env locale| AS-Unsafe heap i18n corrupt| AC-Unsafe mem corrupt lock| SeePOSIX Safety Concepts.
Outputs a help message for the argp parser referred to bystate,tostream. Theflags argument determines what sort of helpmessage is produced. SeeFlags for theargp_help
Function.
Error output is sent tostate->err_stream
, and the programname printed isstate->name
.
The output or program termination behavior of these functions may besuppressed if theARGP_NO_EXIT
orARGP_NO_ERRS
flags arepassed toargp_parse
. SeeFlags forargp_parse
.
This behavior is useful if an argp parser is exported for use by otherprograms (e.g., by a library), and may be used in a context where it isnot desirable to terminate the program in response to parsing errors. Inargp parsers intended for such general use, and for the case where theprogramdoesn’t terminate, calls to any of these functions shouldbe followed by code that returns the appropriate error code:
if (bad argument syntax) { argp_usage (state); return EINVAL; }
If a parser function willonly be used whenARGP_NO_EXIT
is not set, the return may be omitted.
Next:Customizing Argp Help Output, Previous:Argp Parser Functions, Up:Specifying Argp Parsers [Contents][Index]
Thechildren
field in astruct argp
enables other argpparsers to be combined with the referencing one for the parsing of asingle set of arguments. This field should point to a vector ofstruct argp_child
, which is terminated by an entry having a valueof zero in theargp
field.
Where conflicts between combined parsers arise, as when two specify anoption with the same name, the parser conflicts are resolved in favor ofthe parent argp parser(s), or the earlier of the argp parsers in thelist of children.
An entry in the list of subsidiary argp parsers pointed to by thechildren
field in astruct argp
. The fields are asfollows:
const struct argp *argp
The child argp parser, or zero to end of the list.
int flags
Flags for this child.
const char *header
If non-zero, this is an optional header to be printed within help outputbefore the child options. As a side-effect, a non-zero value forces thechild options to be grouped together. To achieve this effect withoutactually printing a header string, use a value of""
. As withheader strings specified in an option entry, the conventional value ofthe last character is ‘:’. SeeSpecifying Options in an Argp Parser.
int group
This is where the child options are grouped relative to the other‘consolidated’ options in the parent argp parser. The values are thesame as thegroup
field instruct argp_option
. SeeSpecifying Options in an Argp Parser. All child-groupings follow parent options at aparticular group level. If both this field andheader
are zero,then the child’s options aren’t grouped together, they are merged withparent options at the parent option group level.
Next:Theargp_help
Function, Previous:Specifying Argp Parsers, Up:Parsing Program Options with Argp [Contents][Index]
argp_parse
¶The default behavior ofargp_parse
is designed to be convenientfor the most common case of parsing program command line argument. Tomodify these defaults, the following flags may be or’d together in theflags argument toargp_parse
:
ARGP_PARSE_ARGV0
¶Don’t ignore the first element of theargv argument toargp_parse
. UnlessARGP_NO_ERRS
is set, the first elementof the argument vector is skipped for option parsing purposes, as itcorresponds to the program name in a command line.
ARGP_NO_ERRS
¶Don’t print error messages for unknown options tostderr
; unlessthis flag is set,ARGP_PARSE_ARGV0
is ignored, asargv[0]
is used as the program name in the error messages. This flag impliesARGP_NO_EXIT
. This is based on the assumption that silent exitingupon errors is bad behavior.
ARGP_NO_ARGS
¶Don’t parse any non-option args. Normally these are parsed by callingthe parse functions with a key ofARGP_KEY_ARG
, the actualargument being the value. This flag needn’t normally be set, as thedefault behavior is to stop parsing as soon as an argument fails to beparsed. SeeArgp Parser Functions.
ARGP_IN_ORDER
¶Parse options and arguments in the same order they occur on the commandline. Normally they’re rearranged so that all options come first.
ARGP_NO_HELP
¶Don’t provide the standard long option ‘--help’, which ordinarilycauses usage and option help information to be output tostdout
andexit (0)
.
ARGP_NO_EXIT
¶Don’t exit on errors, although they may still result in error messages.
ARGP_LONG_ONLY
¶Use the GNU getopt ‘long-only’ rules for parsing arguments. This allowslong-options to be recognized with only a single ‘-’(i.e., ‘-help’). This results in a less useful interface, and itsuse is discouraged as it conflicts with the way most GNU programs workas well as the GNU coding standards.
ARGP_SILENT
¶Turns off any message-printing/exiting options, specificallyARGP_NO_EXIT
,ARGP_NO_ERRS
, andARGP_NO_HELP
.
Previous:Combining Multiple Argp Parsers, Up:Specifying Argp Parsers [Contents][Index]
Thehelp_filter
field in astruct argp
is a pointer to afunction that filters the text of help messages before displayingthem. They have a function signature like:
char *help-filter (intkey, const char *text, void *input)
Wherekey is either a key from an option, in which casetextis that option’s help text. SeeSpecifying Options in an Argp Parser. Alternately, oneof the special keys with names beginning with ‘ARGP_KEY_HELP_’might be used, describing which other help texttext will contain.SeeSpecial Keys for Argp Help Filter Functions.
The function should return eithertext if it remains as-is, or areplacement string allocated usingmalloc
. This will be either befreed by argp or zero, which prints nothing. The value oftext issuppliedafter any translation has been done, so if any of thereplacement text needs translation, it will be done by the filterfunction.input is either the input supplied toargp_parse
or it is zero, ifargp_help
was called directly by the user.
The following special values may be passed to an argp help filterfunction as the first argument in addition to key values for useroptions. They specify which help text thetext argument contains:
ARGP_KEY_HELP_PRE_DOC
¶The help text preceding options.
ARGP_KEY_HELP_POST_DOC
¶The help text following options.
ARGP_KEY_HELP_HEADER
¶The option header string.
ARGP_KEY_HELP_EXTRA
¶This is used after all other documentation;text is zero for this key.
ARGP_KEY_HELP_DUP_ARGS_NOTE
¶The explanatory note printed when duplicate option arguments have been suppressed.
ARGP_KEY_HELP_ARGS_DOC
¶The argument doc string; formally theargs_doc
field from the argp parser. SeeSpecifying Argp Parsers.
Next:Argp Examples, Previous:Flags forargp_parse
, Up:Parsing Program Options with Argp [Contents][Index]
argp_help
Function ¶Normally programs using argp need not be written with particularprinting argument-usage-type help messages in mind as the standard‘--help’ option is handled automatically by argp. Typical errorcases can be handled usingargp_usage
andargp_error
. SeeFunctions For Use in Argp Parsers. However, if it’sdesirable to print a help message in some context other than parsing theprogram options, argp offers theargp_help
interface.
void
argp_help(const struct argp *argp, FILE *stream, unsignedflags, char *name)
¶Preliminary:| MT-Unsafe race:argpbuf env locale| AS-Unsafe heap i18n corrupt| AC-Unsafe mem corrupt lock| SeePOSIX Safety Concepts.
This outputs a help message for the argp parserargp tostream. The type of messages printed will be determined byflags.
Any options such as ‘--help’ that are implemented automatically byargp itself willnot be present in the help output; for thisreason it is best to useargp_state_help
if calling from withinan argp parser function. SeeFunctions For Use in Argp Parsers.
argp_help
Function ¶When callingargp_help
(seeTheargp_help
Function) orargp_state_help
(seeFunctions For Use in Argp Parsers) the exact outputis determined by theflags argument. This should consist of any ofthe following flags, or’d together:
ARGP_HELP_USAGE
¶A unix ‘Usage:’ message that explicitly lists all options.
ARGP_HELP_SHORT_USAGE
¶A unix ‘Usage:’ message that displays an appropriate placeholder toindicate where the options go; useful for showing the non-optionargument syntax.
ARGP_HELP_SEE
¶A ‘Try … for more help’ message; ‘…’ contains theprogram name and ‘--help’.
ARGP_HELP_LONG
¶A verbose option help message that gives each option available alongwith its documentation string.
ARGP_HELP_PRE_DOC
¶The part of the argp parser doc string preceding the verbose option help.
ARGP_HELP_POST_DOC
¶The part of the argp parser doc string that following the verbose option help.
ARGP_HELP_DOC
¶(ARGP_HELP_PRE_DOC | ARGP_HELP_POST_DOC)
ARGP_HELP_BUG_ADDR
¶A message that prints where to report bugs for this program, if theargp_program_bug_address
variable contains this information.
ARGP_HELP_LONG_ONLY
¶This will modify any output to reflect theARGP_LONG_ONLY
mode.
The following flags are only understood when used withargp_state_help
. They control whether the function returns afterprinting its output, or terminates the program:
ARGP_HELP_EXIT_ERR
¶This will terminate the program withexit (argp_err_exit_status)
.
ARGP_HELP_EXIT_OK
¶This will terminate the program withexit (0)
.
The following flags are combinations of the basic flags for printingstandard messages:
ARGP_HELP_STD_ERR
¶Assuming that an error message for a parsing error has printed, thisprints a message on how to get help, and terminates the program with anerror.
ARGP_HELP_STD_USAGE
¶This prints a standard usage message and terminates the program with anerror. This is used when no other specific error messages areappropriate or available.
ARGP_HELP_STD_HELP
¶This prints the standard response for a ‘--help’ option, andterminates the program successfully.
Next:Argp User Customization, Previous:Theargp_help
Function, Up:Parsing Program Options with Argp [Contents][Index]
These example programs demonstrate the basic usage of argp.
This is perhaps the smallest program possible that uses argp. It won’tdo much except give an error message and exit when there are anyarguments, and prints a rather pointless message for ‘--help’.
/*This is (probably) the smallest possible program that uses argp. It won’t do much except give an error messages and exit when there are any arguments, and print a (rather pointless) messages for –help. */#include <stdlib.h>#include <argp.h>intmain (int argc, char **argv){ argp_parse (0, argc, argv, 0, 0, 0); exit (0);}
Next:A Program Using Argp with User Options, Previous:A Minimal Program Using Argp, Up:Argp Examples [Contents][Index]
This program doesn’t use any options or arguments, it uses argp to becompliant with the GNU standard command line format.
In addition to giving no arguments and implementing a ‘--help’option, this example has a ‘--version’ option, which will put thegiven documentation string and bug address in the ‘--help’ output,as per GNU standards.
The variableargp
contains the argument parserspecification. Adding fields to this structure is the way mostparameters are passed toargp_parse
. The first three fields arenormally used, but they are not in this small program. There are alsotwo global variables that argp can use defined here,argp_program_version
andargp_program_bug_address
. Theyare considered global variables because they will almost always beconstant for a given program, even if they use different argumentparsers for various tasks.
/*This program doesn’t use any options or arguments, but uses argp to be compliant with the GNU standard command line format. In addition to making sure no arguments are given, and implementing a –help option, this example will have a –version option, and will put the given documentation string and bug address in the –help output, as per GNU standards. The variable ARGP contains the argument parser specification; adding fields to this structure is the way most parameters are passed to argp_parse (the first three fields are usually used, but not in this small program). There are also two global variables that argp knows about defined here, ARGP_PROGRAM_VERSION and ARGP_PROGRAM_BUG_ADDRESS (they are global variables because they will almost always be constant for a given program, even if it uses different argument parsers for various tasks). */#include <stdlib.h>#include <argp.h>const char *argp_program_version = "argp-ex2 1.0";const char *argp_program_bug_address = "<bug-gnu-utils@gnu.org>";/*Program documentation. */static char doc[] = "Argp example #2 -- a pretty minimal program using argp";/*Our argument parser. Theoptions
,parser
, andargs_doc
fields are zero because we have neither options or arguments;doc
andargp_program_bug_address
will be used in the output for ‘--help’, and the ‘--version’ option will print outargp_program_version
. */static struct argp argp = { 0, 0, 0, doc };intmain (int argc, char **argv){ argp_parse (&argp, argc, argv, 0, 0, 0); exit (0);}
Next:A Program Using Multiple Combined Argp Parsers, Previous:A Program Using Argp with Only Default Options, Up:Argp Examples [Contents][Index]
This program uses the same features as example 2, adding user optionsand arguments.
We now use the first four fields inargp
(seeSpecifying Argp Parsers)and specifyparse_opt
as the parser function. SeeArgp Parser Functions.
Note that in this example,main
uses a structure to communicatewith theparse_opt
function, a pointer to which it passes in theinput
argument toargp_parse
. SeeParsing Program Options with Argp. It is retrievedbyparse_opt
through theinput
field in itsstate
argument. SeeArgp Parsing State. Of course, it’s also possible touse global variables instead, but using a structure like this issomewhat more flexible and clean.
/*This program uses the same features as example 2, and uses options and arguments. We now use the first four fields in ARGP, so here’s a description of them: OPTIONS – A pointer to a vector of struct argp_option (see below) PARSER – A function to parse a single option, called by argp ARGS_DOC – A string describing how the non-option arguments should look DOC – A descriptive string about this program; if it contains a vertical tab character (\v), the part after it will be printed *following* the options The function PARSER takes the following arguments: KEY – An integer specifying which option this is (taken from the KEY field in each struct argp_option), or a special key specifying something else; the only special keys we use here are ARGP_KEY_ARG, meaning a non-option argument, and ARGP_KEY_END, meaning that all arguments have been parsed ARG – For an option KEY, the string value of its argument, or NULL if it has none STATE– A pointer to a struct argp_state, containing various useful information about the parsing state; used here are the INPUT field, which reflects the INPUT argument to argp_parse, and the ARG_NUM field, which is the number of the current non-option argument being parsed It should return either 0, meaning success, ARGP_ERR_UNKNOWN, meaning the given KEY wasn’t recognized, or an errno value indicating some other error. Note that in this example, main uses a structure to communicate with the parse_opt function, a pointer to which it passes in the INPUT argument to argp_parse. Of course, it’s also possible to use global variables instead, but this is somewhat more flexible. The OPTIONS field contains a pointer to a vector of struct argp_option’s; that structure has the following fields (if you assign your option structures using array initialization like this example, unspecified fields will be defaulted to 0, and need not be specified): NAME – The name of this option’s long option (may be zero) KEY – The KEY to pass to the PARSER function when parsing this option, *and* the name of this option’s short option, if it is a printable ascii character ARG – The name of this option’s argument, if any FLAGS – Flags describing this option; some of them are: OPTION_ARG_OPTIONAL – The argument to this option is optional OPTION_ALIAS – This option is an alias for the previous option OPTION_HIDDEN – Don’t show this option in –help output DOC – A documentation string for this option, shown in –help output An options vector should be terminated by an option with all fields zero. */#include <stdlib.h>#include <argp.h>const char *argp_program_version = "argp-ex3 1.0";const char *argp_program_bug_address = "<bug-gnu-utils@gnu.org>";/*Program documentation. */static char doc[] = "Argp example #3 -- a program with options and arguments using argp";/*A description of the arguments we accept. */static char args_doc[] = "ARG1 ARG2";/*The options we understand. */static struct argp_option options[] = { {"verbose", 'v', 0, 0, "Produce verbose output" }, {"quiet", 'q', 0, 0, "Don't produce any output" }, {"silent", 's', 0, OPTION_ALIAS }, {"output", 'o', "FILE", 0, "Output to FILE instead of standard output" }, { 0 }};/*Used bymain
to communicate withparse_opt
. */struct arguments{ char *args[2]; /*arg1 &arg2 */ int silent, verbose; char *output_file;};/*Parse a single option. */static error_tparse_opt (int key, char *arg, struct argp_state *state){ /*Get theinput argument fromargp_parse
, which we know is a pointer to our arguments structure. */ struct arguments *arguments = state->input; switch (key) { case 'q': case 's': arguments->silent = 1; break; case 'v': arguments->verbose = 1; break; case 'o': arguments->output_file = arg; break; case ARGP_KEY_ARG: if (state->arg_num >= 2) /*Too many arguments. */ argp_usage (state); arguments->args[state->arg_num] = arg; break; case ARGP_KEY_END: if (state->arg_num < 2) /*Not enough arguments. */ argp_usage (state); break; default: return ARGP_ERR_UNKNOWN; } return 0;}/*Our argp parser. */static struct argp argp = { options, parse_opt, args_doc, doc };intmain (int argc, char **argv){ struct arguments arguments; /*Default values. */ arguments.silent = 0; arguments.verbose = 0; arguments.output_file = "-"; /*Parse our arguments; every option seen byparse_opt
will be reflected inarguments
. */ argp_parse (&argp, argc, argv, 0, 0, &arguments); printf ("ARG1 = %s\nARG2 = %s\nOUTPUT_FILE = %s\n" "VERBOSE = %s\nSILENT = %s\n", arguments.args[0], arguments.args[1], arguments.output_file, arguments.verbose ? "yes" : "no", arguments.silent ? "yes" : "no"); exit (0);}
Previous:A Program Using Argp with User Options, Up:Argp Examples [Contents][Index]
This program uses the same features as example 3, but has more options,and presents more structure in the ‘--help’ output. It alsoillustrates how you can ‘steal’ the remainder of the input argumentspast a certain point for programs that accept a list of items. It alsoillustrates thekey valueARGP_KEY_NO_ARGS
, which is onlygiven if no non-option arguments were supplied to theprogram. SeeSpecial Keys for Argp Parser Functions.
For structuring help output, two features are used:headers and atwo part option string. Theheaders are entries in the optionsvector. SeeSpecifying Options in an Argp Parser. The first four fields are zero. Thetwo part documentation string are in the variabledoc
, whichallows documentation both before and after the options. SeeSpecifying Argp Parsers, the two parts ofdoc
are separated by a vertical-tabcharacter ('\v'
, or'\013'
). By convention, thedocumentation before the options is a short string stating what theprogram does, and after any options it is longer, describing thebehavior in more detail. All documentation strings are automaticallyfilled for output, although newlines may be included to force a linebreak at a particular point. In addition, documentation strings arepassed to thegettext
function, for possible translation into thecurrent locale.
/*This program uses the same features as example 3, but has more options, and somewhat more structure in the -help output. It also shows how you can ‘steal’ the remainder of the input arguments past a certain point, for programs that accept a list of items. It also shows the special argp KEY value ARGP_KEY_NO_ARGS, which is only given if no non-option arguments were supplied to the program. For structuring the help output, two features are used, *headers* which are entries in the options vector with the first four fields being zero, and a two part documentation string (in the variable DOC), which allows documentation both before and after the options; the two parts of DOC are separated by a vertical-tab character (’\v’, or ’\013’). By convention, the documentation before the options is just a short string saying what the program does, and that afterwards is longer, describing the behavior in more detail. All documentation strings are automatically filled for output, although newlines may be included to force a line break at a particular point. All documentation strings are also passed to the ‘gettext’ function, for possible translation into the current locale. */#include <stdlib.h>#include <error.h>#include <argp.h>const char *argp_program_version = "argp-ex4 1.0";const char *argp_program_bug_address = "<bug-gnu-utils@prep.ai.mit.edu>";/*Program documentation. */static char doc[] = "Argp example #4 -- a program with somewhat more complicated\options\\vThis part of the documentation comes *after* the options;\ note that the text is automatically filled, but it's possible\ to force a line-break, e.g.\n<-- here.";/*A description of the arguments we accept. */static char args_doc[] = "ARG1 [STRING...]";/*Keys for options without short-options. */#define OPT_ABORT 1 /*–abort *//*The options we understand. */static struct argp_option options[] = { {"verbose", 'v', 0, 0, "Produce verbose output" }, {"quiet", 'q', 0, 0, "Don't produce any output" }, {"silent", 's', 0, OPTION_ALIAS }, {"output", 'o', "FILE", 0, "Output to FILE instead of standard output" }, {0,0,0,0, "The following options should be grouped together:" }, {"repeat", 'r', "COUNT", OPTION_ARG_OPTIONAL, "Repeat the output COUNT (default 10) times"}, {"abort", OPT_ABORT, 0, 0, "Abort before showing any output"}, { 0 }};/*Used bymain
to communicate withparse_opt
. */struct arguments{ char *arg1; /*arg1 */ char **strings; /*[string...] */ int silent, verbose, abort; /*‘-s’, ‘-v’, ‘--abort’ */ char *output_file; /*file arg to ‘--output’ */ int repeat_count; /*count arg to ‘--repeat’ */};/*Parse a single option. */static error_tparse_opt (int key, char *arg, struct argp_state *state){ /*Get theinput
argument fromargp_parse
, which we know is a pointer to our arguments structure. */ struct arguments *arguments = state->input; switch (key) { case 'q': case 's': arguments->silent = 1; break; case 'v': arguments->verbose = 1; break; case 'o': arguments->output_file = arg; break; case 'r': arguments->repeat_count = arg ? atoi (arg) : 10; break; case OPT_ABORT: arguments->abort = 1; break; case ARGP_KEY_NO_ARGS: argp_usage (state); case ARGP_KEY_ARG: /*Here we know thatstate->arg_num == 0
, since we force argument parsing to end before any more arguments can get here. */ arguments->arg1 = arg; /*Now we consume all the rest of the arguments.state->next
is the index instate->argv
of the next argument to be parsed, which is the firststring we’re interested in, so we can just use&state->argv[state->next]
as the value for arguments->strings.In addition, by settingstate->next
to the end of the arguments, we can force argp to stop parsing here and return. */ arguments->strings = &state->argv[state->next]; state->next = state->argc; break; default: return ARGP_ERR_UNKNOWN; } return 0;}/*Our argp parser. */static struct argp argp = { options, parse_opt, args_doc, doc };intmain (int argc, char **argv){ int i, j; struct arguments arguments; /*Default values. */ arguments.silent = 0; arguments.verbose = 0; arguments.output_file = "-"; arguments.repeat_count = 1; arguments.abort = 0; /*Parse our arguments; every option seen byparse_opt
will be reflected inarguments
. */ argp_parse (&argp, argc, argv, 0, 0, &arguments); if (arguments.abort) error (10, 0, "ABORTED"); for (i = 0; i < arguments.repeat_count; i++) { printf ("ARG1 = %s\n", arguments.arg1); printf ("STRINGS = "); for (j = 0; arguments.strings[j]; j++) printf (j == 0 ? "%s" : ", %s", arguments.strings[j]); printf ("\n"); printf ("OUTPUT_FILE = %s\nVERBOSE = %s\nSILENT = %s\n", arguments.output_file, arguments.verbose ? "yes" : "no", arguments.silent ? "yes" : "no"); } exit (0);}
Previous:Argp Examples, Up:Parsing Program Options with Argp [Contents][Index]
The formatting of argp ‘--help’ output may be controlled to someextent by a program’s users, by setting theARGP_HELP_FMT
environment variable to a comma-separated list of tokens. Whitespace isignored:
These turnduplicate-argument-mode on or off. In duplicateargument mode, if an option that accepts an argument has multiple names,the argument is shown for each name. Otherwise, it is only shown for thefirst long option. A note is subsequently printed so the user knows thatit applies to other names as well. The default is ‘no-dup-args’,which is less consistent, but prettier.
These will enable or disable the note informing the user of suppressedoption argument duplication. The default is ‘dup-args-note’.
This prints the first short option in columnn. The default is 2.
This prints the first long option in columnn. The default is 6.
This prints ‘documentation options’ (seeFlags for Argp Options) incolumnn. The default is 2.
This prints the documentation for options starting in columnn. The default is 29.
This will indent the group headers that document groups of options tocolumnn. The default is 1.
This will indent continuation lines in ‘Usage:’ messages to columnn. The default is 12.
This will word wrap help output at or before columnn. The defaultis 79.
Next:Parsing of Suboptions Example, Previous:Parsing Program Options with Argp, Up:Parsing Program Arguments [Contents][Index]
Having a single level of options is sometimes not enough. There mightbe too many options which have to be available or a set of options isclosely related.
For this case some programs use suboptions. One of the most prominentprograms is certainlymount
(8). The-o
option take oneargument which itself is a comma separated list of options. To ease theprogramming of code like this the functiongetsubopt
isavailable.
int
getsubopt(char **optionp, char *const *tokens, char **valuep)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theoptionp parameter must be a pointer to a variable containingthe address of the string to process. When the function returns, thereference is updated to point to the next suboption or to theterminating ‘\0’ character if there are no more suboptions available.
Thetokens parameter references an array of strings containing theknown suboptions. All strings must be ‘\0’ terminated and to markthe end a null pointer must be stored. Whengetsubopt
finds apossible legal suboption it compares it with all strings available inthetokens array and returns the index in the string as theindicator.
In case the suboption has an associated value introduced by a ‘=’character, a pointer to the value is returned invaluep. Thestring is ‘\0’ terminated. If no argument is availablevaluep is set to the null pointer. By doing this the caller cancheck whether a necessary value is given or whether no unexpected valueis present.
In case the next suboption in the string is not mentioned in thetokens array the starting address of the suboption including apossible value is returned invaluep and the return value of thefunction is ‘-1’.
Previous:Parsing of Suboptions, Up:Parsing Program Arguments [Contents][Index]
The code which might appear in themount
(8) program is a perfectexample of the use ofgetsubopt
:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>int do_all;const char *type;int read_size;int write_size;int read_only;enum{ RO_OPTION = 0, RW_OPTION, READ_SIZE_OPTION, WRITE_SIZE_OPTION, THE_END};const char *mount_opts[] ={ [RO_OPTION] = "ro", [RW_OPTION] = "rw", [READ_SIZE_OPTION] = "rsize", [WRITE_SIZE_OPTION] = "wsize", [THE_END] = NULL};intmain (int argc, char **argv){ char *subopts, *value; int opt; while ((opt = getopt (argc, argv, "at:o:")) != -1) switch (opt) { case 'a': do_all = 1; break; case 't': type = optarg; break; case 'o': subopts = optarg; while (*subopts != '\0') switch (getsubopt (&subopts, mount_opts, &value)) { case RO_OPTION: read_only = 1; break; case RW_OPTION: read_only = 0; break; case READ_SIZE_OPTION: if (value == NULL) abort (); read_size = atoi (value); break; case WRITE_SIZE_OPTION: if (value == NULL) abort (); write_size = atoi (value); break; default: /*Unknown suboption. */ printf ("Unknown suboption `%s'\n", value); break; } break; default: abort (); } /*Do the real work. */ return 0;}
Next:Auxiliary Vector, Previous:Program Arguments, Up:The Basic Program/System Interface [Contents][Index]
When a program is executed, it receives information about the context inwhich it was invoked in two ways. The first mechanism uses theargv andargc arguments to itsmain
function, and isdiscussed inProgram Arguments. The second mechanism usesenvironment variables and is discussed in this section.
Theargv mechanism is typically used to pass command-linearguments specific to the particular program being invoked. Theenvironment, on the other hand, keeps track of information that isshared by many programs, changes infrequently, and that is lessfrequently used.
The environment variables discussed in this section are the sameenvironment variables that you set using assignments and theexport
command in the shell. Programs executed from the shellinherit all of the environment variables from the shell.
Standard environment variables are used for information about the user’shome directory, terminal type, current locale, and so on; you can defineadditional variables for other purposes. The set of all environmentvariables that have values is collectively known as theenvironment.
Names of environment variables are case-sensitive and must not containthe character ‘=’. System-defined environment variables areinvariably uppercase.
The values of environment variables can be anything that can berepresented as a string. A value must not contain an embedded nullcharacter, since this is assumed to terminate the string.
The value of an environment variable can be accessed with thegetenv
function. This is declared in the header filestdlib.h.
Libraries should usesecure_getenv
instead ofgetenv
, sothat they do not accidentally use untrusted environment variables.Modifications of environment variables are not allowed inmulti-threaded programs. Thegetenv
andsecure_getenv
functions can be safely used in multi-threaded programs.
char *
getenv(const char *name)
¶Preliminary:| MT-Safe env| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns a string that is the value of the environmentvariablename. You must not modify this string. In some non-Unixsystems not using the GNU C Library, it might be overwritten by subsequentcalls togetenv
(but not by any other library function). If theenvironment variablename is not defined, the value is a nullpointer.
char *
secure_getenv(const char *name)
¶Preliminary:| MT-Safe env| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is similar togetenv
, but it returns a nullpointer if the environment is untrusted. This happens when theprogram file has SUID or SGID bits set. General-purpose librariesshould always prefer this function overgetenv
to avoidvulnerabilities if the library is referenced from a SUID/SGID program.
This function was originally a GNU extension, but was added inPOSIX.1-2024.
int
putenv(char *string)
¶Preliminary:| MT-Unsafe const:env| AS-Unsafe heap lock| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Theputenv
function adds or removes definitions from the environment.If thestring is of the form ‘name=value’, thedefinition is added to the environment. Otherwise, thestring isinterpreted as the name of an environment variable, and any definitionfor this variable in the environment is removed.
If the function is successful it returns0
. Otherwise the returnvalue is nonzero anderrno
is set to indicate the error.
The difference to thesetenv
function is that the exact stringgiven as the parameterstring is put into the environment. If theuser should change the string after theputenv
call this willreflect automatically in the environment. This also requires thatstring not be an automatic variable whose scope is left before thevariable is removed from the environment. The same applies of course todynamically allocated variables which are freed later.
This function is part of the extended Unix interface. You should define_XOPEN_SOURCE before including any header.
int
setenv(const char *name, const char *value, intreplace)
¶Preliminary:| MT-Unsafe const:env| AS-Unsafe heap lock| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Thesetenv
function can be used to add a new definition to theenvironment. The entry with the namename is replaced by thevalue ‘name=value’. Please note that this is also trueifvalue is the empty string. To do this a new string is createdand the stringsname andvalue are copied. A null pointerfor thevalue parameter is illegal. If the environment alreadycontains an entry with keyname thereplace parametercontrols the action. If replace is zero, nothing happens. Otherwisethe old entry is replaced by the new one.
Please note that you cannot remove an entry completely using this function.
If the function is successful it returns0
. Otherwise theenvironment is unchanged and the return value is-1
anderrno
is set.
This function was originally part of the BSD library but is now part ofthe Unix standard.
int
unsetenv(const char *name)
¶Preliminary:| MT-Unsafe const:env| AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Using this function one can remove an entry completely from theenvironment. If the environment contains an entry with the keyname this whole entry is removed. A call to this function isequivalent to a call toputenv
when thevalue part of thestring is empty.
The function returns-1
ifname is a null pointer, points toan empty string, or points to a string containing a=
character.It returns0
if the call succeeded.
This function was originally part of the BSD library but is now part ofthe Unix standard. The BSD version had no return value, though.
There is one more function to modify the whole environment. Thisfunction is said to be used in the POSIX.9 (POSIX bindings for Fortran77) and so one should expect it did made it into POSIX.1. But thisnever happened. But we still provide this function as a GNU extensionto enable writing standard compliant Fortran environments.
int
clearenv(void)
¶Preliminary:| MT-Unsafe const:env| AS-Unsafe heap lock| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
Theclearenv
function removes all entries from the environment.Usingputenv
andsetenv
new entries can be added againlater.
If the function is successful it returns0
. Otherwise the returnvalue is nonzero.
You can deal directly with the underlying representation of environmentobjects to add more variables to the environment (for example, tocommunicate with another program you are about to execute;seeExecuting a File).
char **
environ ¶The environment is represented as an array of strings. Each string isof the format ‘name=value’. The order in whichstrings appear in the environment is not significant, but the samename must not appear more than once. The last element of thearray is a null pointer.
This variable is declared in the header fileunistd.h.
If you just want to get the value of an environment variable, usegetenv
.
Unix systems, and GNU systems, pass the initial value ofenviron
as the third argument tomain
.SeeProgram Arguments.
Previous:Environment Access, Up:Environment Variables [Contents][Index]
These environment variables have standard meanings. This doesn’t meanthat they are always present in the environment; but if these variablesare present, they have these meanings. You shouldn’t try to usethese environment variable names for some other purpose.
HOME
¶This is a string representing the user’shome directory, orinitial default working directory.
The user can setHOME
to any value.If you need to make sure to obtain the proper home directoryfor a particular user, you should not useHOME
; instead,look up the user’s name in the user database (seeUser Database).
For most purposes, it is better to useHOME
, precisely becausethis lets the user specify the value.
LOGNAME
¶This is the name that the user used to log in. Since the value in theenvironment can be tweaked arbitrarily, this is not a reliable way toidentify the user who is running a program; a function likegetlogin
(seeIdentifying Who Logged In) is better for that purpose.
For most purposes, it is better to useLOGNAME
, precisely becausethis lets the user specify the value.
PATH
¶Apath is a sequence of directory names which is used forsearching for a file. The variablePATH
holds a path usedfor searching for programs to be run.
Theexeclp
andexecvp
functions (seeExecuting a File)use this environment variable, as do many shells and other utilitieswhich are implemented in terms of those functions.
The syntax of a path is a sequence of directory names separated bycolons. An empty string instead of a directory name stands for thecurrent directory (seeWorking Directory).
A typical value for this environment variable might be a string like:
:/bin:/etc:/usr/bin:/usr/new/X11:/usr/new:/usr/local/bin
This means that if the user tries to execute a program namedfoo
,the system will look for files namedfoo,/bin/foo,/etc/foo, and so on. The first of these files that exists isthe one that is executed.
TERM
¶This specifies the kind of terminal that is receiving program output.Some programs can make use of this information to take advantage ofspecial escape sequences or terminal modes supported by particular kindsof terminals. Many programs which use the termcap library(seeFind inThe Termcap LibraryManual) use theTERM
environment variable, for example.
TZ
¶This specifies the time zone ruleset. SeeSpecifying the Time Zone withTZ
.
LANG
¶This specifies the default locale to use for attribute categories whereneitherLC_ALL
nor the specific environment variable for thatcategory is set. SeeLocales and Internationalization, for more information aboutlocales.
LC_ALL
¶If this environment variable is set it overrides the selection for allthe locales done using the otherLC_*
environment variables. Thevalue of the otherLC_*
environment variables is simply ignoredin this case.
LC_COLLATE
¶This specifies what locale to use for string sorting.
LC_CTYPE
¶This specifies what locale to use for character sets and characterclassification.
LC_MESSAGES
¶This specifies what locale to use for printing messages and to parseresponses.
LC_MONETARY
¶This specifies what locale to use for formatting monetary values.
LC_NUMERIC
¶This specifies what locale to use for formatting numbers.
LC_TIME
¶This specifies what locale to use for formatting date/time values.
NLSPATH
¶This specifies the directories in which thecatopen
functionlooks for message translation catalogs.
_POSIX_OPTION_ORDER
¶If this environment variable is defined, it suppresses the usualreordering of command line arguments bygetopt
andargp_parse
. SeeProgram Argument Syntax Conventions.
Next:System Calls, Previous:Environment Variables, Up:The Basic Program/System Interface [Contents][Index]
When a program is executed, it receives information from the operatingsystem about the environment in which it is operating. The form of thisinformation is a table of key-value pairs, where the keys are from theset of ‘AT_’ values inelf.h. Some of the data is providedby the kernel for libc consumption, and may be obtained by ordinaryinterfaces, such assysconf
. However, on a platform-by-platformbasis there may be information that is not available any other way.
getauxval
¶unsigned long int
getauxval(unsigned long inttype)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is used to inquire about the entries in the auxiliaryvector. Thetype argument should be one of the ‘AT_’ symbolsdefined inelf.h. If a matching entry is found, the value isreturned; if the entry is not found, zero is returned anderrno
is set toENOENT
.
Note: There is no relationship between the ‘AT_’ contantsdefined inelf.h and the file name lookup flags infcntl.h. SeeDescriptor-Relative Access.
For some platforms, the keyAT_HWCAP
is the easiest way to inquireabout any instruction set extensions available at runtime. In this case,there will (of necessity) be a platform-specific set of ‘HWCAP_’values masked together that describe the capabilities of the cpu on whichthe program is being executed.
Next:Program Termination, Previous:Auxiliary Vector, Up:The Basic Program/System Interface [Contents][Index]
A system call is a request for service that a program makes of thekernel. The service is generally something that only the kernel hasthe privilege to do, such as doing I/O. Programmers don’t normallyneed to be concerned with system calls because there are functions inthe GNU C Library to do virtually everything that system calls do.These functions work by making system calls themselves. For example,there is a system call that changes the permissions of a file, butyou don’t need to know about it because you can just use the GNU C Library’schmod
function.
System calls are sometimes called syscalls or kernel calls, and thisinterface is mostly a purely mechanical translation from the kernel’sABI to the C ABI. For the set of syscalls where we do not guaranteePOSIX Thread cancellation the wrappers only organize the incomingarguments from the C calling convention to the calling convention ofthe target kernel. For the set of syscalls where we provided POSIXThread cancellation the wrappers set some internal state in thelibrary to support cancellation, but this does not impact thebehaviour of the syscall provided by the kernel.
In some cases, if the GNU C Library detects that a system call has beensuperseded by a more capable one, the wrapper may map the old call tothe new one. For example,dup2
is implemented viadup3
by passing an additional empty flags argument, andopen
callsopenat
passing the additionalAT_FDCWD
. Sometimes evenmore is done, such as converting between 32-bit and 64-bit timevalues. In general, though, such processing is only to make thesystem call better match the C ABI, rather than change itsfunctionality.
However, there are times when you want to make a system call explicitly,and for that, the GNU C Library provides thesyscall
function.syscall
is harder to use and less portable than functions likechmod
, but easier and more portable than coding the system callin assembler instructions.
syscall
is most useful when you are working with a system callwhich is special to your system or is newer than the GNU C Library youare using.syscall
is implemented in an entirely generic way;the function does not know anything about what a particular systemcall does or even if it is valid.
The description ofsyscall
in this section assumes a certainprotocol for system calls on the various platforms on which the GNU C Libraryruns. That protocol is not defined by any strong authority, butwe won’t describe it here either because anyone who is codingsyscall
probably won’t accept anything less than kernel and Clibrary source code as a specification of the interface between themanyway.
syscall
does not provide cancellation logic, even if the systemcall you’re calling is listed as cancellable above.
syscall
is declared inunistd.h.
long int
syscall(long intsysno, …)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
syscall
performs a generic system call.
sysno is the system call number. Each kind of system call isidentified by a number. Macros for all the possible system call numbersare defined insys/syscall.h
The remaining arguments are the arguments for the system call, inorder, and their meanings depend on the kind of system call.If you code more arguments than the system call takes, the extra ones tothe right are ignored.
The return value is the return value from the system call, unless thesystem call failed. In that case,syscall
returns-1
andsetserrno
to an error code that the system call returned. Notethat system calls do not return-1
when they succeed.
If you specify an invalidsysno,syscall
returns-1
witherrno
=ENOSYS
.
Example:
#include <unistd.h>#include <sys/syscall.h>#include <errno.h>...int rc;rc = syscall(SYS_chmod, "/etc/passwd", 0444);if (rc == -1) fprintf(stderr, "chmod failed, errno = %d\n", errno);
This, if all the compatibility stars are aligned, is equivalent to thefollowing preferable code:
#include <sys/types.h>#include <sys/stat.h>#include <errno.h>...int rc;rc = chmod("/etc/passwd", 0444);if (rc == -1) fprintf(stderr, "chmod failed, errno = %d\n", errno);
Previous:System Calls, Up:The Basic Program/System Interface [Contents][Index]
The usual way for a program to terminate is simply for itsmain
function to return. Theexit status value returned from themain
function is used to report information back to the process’sparent process or shell.
A program can also terminate normally by calling theexit
function.
In addition, programs can be terminated by signals; this is discussed inmore detail inSignal Handling. Theabort
function causesa signal that kills the program.
Next:Exit Status, Up:Program Termination [Contents][Index]
A process terminates normally when its program signals it is done bycallingexit
. Returning frommain
is equivalent tocallingexit
, and the value thatmain
returns is used asthe argument toexit
.
void
exit(intstatus)
¶Preliminary:| MT-Unsafe race:exit| AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
Theexit
function tells the system that the program is done, whichcauses it to terminate the process.
status is the program’s exit status, which becomes part of theprocess’ termination status. This function does not return.
Normal termination causes the following actions:
atexit
oron_exit
functions are called in the reverse order of their registration. Thismechanism allows your application to specify its own “cleanup” actionsto be performed at program termination. Typically, this is used to dothings like saving program state information in a file, or unlockinglocks in shared data bases.tmpfile
function are removed; seeTemporary Files._exit
is called, terminating the program. SeeTermination Internals.Next:Cleanups on Exit, Previous:Normal Termination, Up:Program Termination [Contents][Index]
When a program exits, it can return to the parent process a smallamount of information about the cause of termination, using theexit status. This is a value between 0 and 255 that the exitingprocess passes as an argument toexit
.
Normally you should use the exit status to report very broad informationabout success or failure. You can’t provide a lot of detail about thereasons for the failure, and most parent processes would not want muchdetail anyway.
There are conventions for what sorts of status values certain programsshould return. The most common convention is simply 0 for success and 1for failure. Programs that perform comparison use a differentconvention: they use status 1 to indicate a mismatch, and status 2 toindicate an inability to compare. Your program should follow anexisting convention if an existing convention makes sense for it.
A general convention reserves status values 128 and up for specialpurposes. In particular, the value 128 is used to indicate failure toexecute another program in a subprocess. This convention is notuniversally obeyed, but it is a good idea to follow it in your programs.
Warning: Don’t try to use the number of errors as the exitstatus. This is actually not very useful; a parent process wouldgenerally not care how many errors occurred. Worse than that, it doesnot work, because the status value is truncated to eight bits.Thus, if the program tried to report 256 errors, the parent wouldreceive a report of 0 errors—that is, success.
For the same reason, it does not work to use the value oferrno
as the exit status—these can exceed 255.
Portability note: Some non-POSIX systems use differentconventions for exit status values. For greater portability, you canuse the macrosEXIT_SUCCESS
andEXIT_FAILURE
for theconventional status value for success and failure, respectively. Theyare declared in the filestdlib.h.
int
EXIT_SUCCESS ¶This macro can be used with theexit
function to indicatesuccessful program completion.
On POSIX systems, the value of this macro is0
. On othersystems, the value might be some other (possibly non-constant) integerexpression.
int
EXIT_FAILURE ¶This macro can be used with theexit
function to indicateunsuccessful program completion in a general sense.
On POSIX systems, the value of this macro is1
. On othersystems, the value might be some other (possibly non-constant) integerexpression. Other nonzero status values also indicate failures. Certainprograms use different nonzero status values to indicate particularkinds of "non-success". For example,diff
uses status value1
to mean that the files are different, and2
or more tomean that there was difficulty in opening the files.
Don’t confuse a program’s exit status with a process’ termination status.There are lots of ways a process can terminate besides having its programfinish. In the event that the process terminationis caused by programtermination (i.e.,exit
), though, the program’s exit status becomespart of the process’ termination status.
Next:Aborting a Program, Previous:Exit Status, Up:Program Termination [Contents][Index]
Your program can arrange to run its own cleanup functions if normaltermination happens. If you are writing a library for use in variousapplication programs, then it is unreliable to insist that allapplications call the library’s cleanup functions explicitly beforeexiting. It is much more robust to make the cleanup invisible to theapplication, by setting up a cleanup function in the library itselfusingatexit
oron_exit
.
int
atexit(void (*function) (void))
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
Theatexit
function registers the functionfunction to becalled at normal program termination. Thefunction is called withno arguments.
The return value fromatexit
is zero on success and nonzero ifthe function cannot be registered.
int
on_exit(void (*function)(intstatus, void *arg), void *arg)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
This function is a somewhat more powerful variant ofatexit
. Itaccepts two arguments, a functionfunction and an arbitrarypointerarg. At normal program termination, thefunction iscalled with two arguments: thestatus value passed toexit
,and thearg.
This function is included in the GNU C Library only for compatibilityfor SunOS, and may not be supported by other implementations.
Here’s a trivial program that illustrates the use ofexit
andatexit
:
#include <stdio.h>#include <stdlib.h>voidbye (void){ puts ("Goodbye, cruel world....");}intmain (void){ atexit (bye); exit (EXIT_SUCCESS);}
When this program is executed, it just prints the message and exits.
Next:Termination Internals, Previous:Cleanups on Exit, Up:Program Termination [Contents][Index]
You can abort your program using theabort
function. The prototypefor this function is instdlib.h.
void
abort(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theabort
function causes abnormal program termination. Thisdoes not execute cleanup functions registered withatexit
oron_exit
.
This function actually terminates the process by raising aSIGABRT
signal, and your program can include a handler tointercept this signal; seeSignal Handling.
If either the signal handler does not terminate the process, or if thesignal is blocked,abort
will reset the signal disposition to thedefaultSIG_DFL
action and raise the signal again.
Previous:Aborting a Program, Up:Program Termination [Contents][Index]
The_exit
function is the primitive used for process terminationbyexit
. It is declared in the header fileunistd.h.
void
_exit(intstatus)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The_exit
function is the primitive for causing a process toterminate with statusstatus. Calling this function does notexecute cleanup functions registered withatexit
oron_exit
.
void
_Exit(intstatus)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The_Exit
function is the ISO C equivalent to_exit
.The ISO C committee members were not sure whether the definitions of_exit
and_Exit
were compatible so they have not used thePOSIX name.
This function was introduced in ISO C99 and is declared instdlib.h.
When a process terminates for any reason—either because the programterminates, or as a result of a signal—thefollowing things happen:
wait
orwaitpid
; seeProcess Completion. If theprogram exited, this status includes as its low-order 8 bits the programexit status.init
process, with process ID 1.)SIGCHLD
signal is sent to the parent process.SIGHUP
signal is sent to each process in the foreground job,and the controlling terminal is disassociated from that session.SeeJob Control.SIGHUP
signal and aSIGCONT
signal are sent to each process in thegroup. SeeJob Control.Next:Inter-Process Communication, Previous:The Basic Program/System Interface, Up:Main Menu [Contents][Index]
Processes are the primitive units for allocation of systemresources. Each process has its own address space and (usually) onethread of control. A process executes a program; you can have multipleprocesses executing the same program, but each process has its own copyof the program within its own address space and executes itindependently of the other copies.
Processes are organized hierarchically. Each process has aparentprocess which explicitly arranged to create it. The processes createdby a given parent are called itschild processes. A childinherits many of its attributes from the parent process.
This chapter describes how a program can create, terminate, and controlchild processes. Actually, there are three distinct operationsinvolved: creating a new child process, causing the new process toexecute a program, and coordinating the completion of the child processwith the original program.
Thesystem
function provides a simple, portable mechanism forrunning another program; it does all three steps automatically. If youneed more control over the details of how this is done, you can use theprimitive functions to do each step individually instead.
Next:Process Creation Concepts, Up:Processes [Contents][Index]
The easy way to run another program is to use thesystem
function. This function does all the work of running a subprogram, butit doesn’t give you much control over the details: you have to waituntil the subprogram terminates before you can do anything else.
int
system(const char *command)
¶Preliminary:| MT-Safe | AS-Unsafe plugin heap lock| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
This function executescommand as a shell command. In the GNU C Library,it always uses the default shellsh
to run the command.In particular, it searches the directories inPATH
to findprograms to execute. The return value is-1
if it wasn’tpossible to create the shell process, and otherwise is the status of theshell process. SeeProcess Completion, for details on how thisstatus code can be interpreted.
If thecommand argument is a null pointer, a return value of zeroindicates that no command processor is available.
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timesystem
iscalled. If the thread gets canceled these resources stay allocateduntil the program ends. To avoid this calls tosystem
should beprotected using cancellation handlers.
Thesystem
function is declared in the header filestdlib.h.
Portability Note: Some C implementations may not have anynotion of a command processor that can execute other programs. You candetermine whether a command processor exists by executingsystem (NULL)
; if the return value is nonzero, a commandprocessor is available.
Thepopen
andpclose
functions (seePipe to a Subprocess) are closely related to thesystem
function. Theyallow the parent process to communicate with the standard input andoutput channels of the command being executed.
Next:Process Identification, Previous:Running a Command, Up:Processes [Contents][Index]
This section gives an overview of processes and of the steps involved increating a process and making it run another program.
A new processes is created when one of the functionsposix_spawn
,fork
,_Fork
,vfork
, orpidfd_spawn
is called. (Thesystem
andpopen
alsocreate new processes internally.) Due to the name of thefork
function, the act of creating a new process is sometimes calledforking a process. Each new process (thechild process orsubprocess) is allocated a process ID, distinct from the processID of the parent process. SeeProcess Identification.
After forking a child process, both the parent and child processescontinue to execute normally. If you want your program to wait for achild process to finish executing before continuing, you must do thisexplicitly after the fork operation, by callingwait
orwaitpid
(seeProcess Completion). These functions give youlimited information about why the child terminated—for example, itsexit status code.
A newly forked child process continues to execute the same program asits parent process, at the point where thefork
or_Fork
call returns. You can use the return value fromfork
or_Fork
to tell whether the program is running in the parent processor the child.
Having several processes run the same program is only occasionallyuseful. But the child can execute another program using one of theexec
functions; seeExecuting a File. The program that theprocess is executing is called itsprocess image. Startingexecution of a new program causes the process to forget all about itsprevious process image; when the new program exits, the process exitstoo, instead of returning to the previous process image.
Next:Creating a Process, Previous:Process Creation Concepts, Up:Processes [Contents][Index]
Each process is named by aprocess ID number, a value of typepid_t
. A process ID is allocated to each process when it iscreated. Process IDs are reused over time. The lifetime of a processends when the parent process of the corresponding process waits on theprocess ID after the process has terminated. SeeProcess Completion. (The parent process can arrange for such waiting tohappen implicitly.) A process ID uniquely identifies a process onlyduring the lifetime of the process. As a rule of thumb, this meansthat the process must still be running.
Process IDs can also denote process groups and sessions.SeeJob Control.
On Linux, threads created bypthread_create
also receive athread ID. The thread ID of the initial (main) thread is thesame as the process ID of the entire process. Thread IDs forsubsequently created threads are distinct. They are allocated fromthe same numbering space as process IDs. Process IDs and thread IDsare sometimes also referred to collectively astask IDs. Incontrast to processes, threads are never waited for explicitly, so athread ID becomes eligible for reuse as soon as a thread exits or iscanceled. This is true even for joinable threads, not just detachedthreads. Threads are assigned to athread group. Inthe GNU C Library implementation running on Linux, the process ID is thethread group ID of all threads in the process.
You can get the process ID of a process by callinggetpid
. Thefunctiongetppid
returns the process ID of the parent of thecurrent process (this is also known as theparent process ID).Your program should include the header filesunistd.h andsys/types.h to use these functions.
Thepid_t
data type is a signed integer type which is capableof representing a process ID. In the GNU C Library, this is anint
.
pid_t
getpid(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetpid
function returns the process ID of the current process.
pid_t
getppid(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetppid
function returns the process ID of the parent of thecurrent process.
pid_t
gettid(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegettid
function returns the thread ID of the currentthread. The returned value is obtained from the Linux kernel and isnot subject to caching. See the discussion of thread IDs above,especially regarding reuse of the IDs of threads which have exited.
This function is specific to Linux.
pid_t
pthread_gettid_np(pthread_tthread)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the same value thatgettid
would return ifexecuted on the running threadthread.
Ifthread is no longer running but it is joinable, it isunspecified whether this function returns −1, or if it returnsthe thread ID of the thread while it was running. Ifthread isnot running and is not joinable, the behavior is undefined.
Portability Note: Linux thread IDs can be reused rather quickly,so this function differs from thepthread_getunique_np
functionfound on other systems.
This function is specific to Linux.
Next:Querying a Process, Previous:Process Identification, Up:Processes [Contents][Index]
Thefork
function is the primitive for creating a process.It is declared in the header fileunistd.h.
pid_t
fork(void)
¶Preliminary:| MT-Safe | AS-Unsafe plugin| AC-Unsafe lock| SeePOSIX Safety Concepts.
Thefork
function creates a new process.
If the operation is successful, there are then both parent and childprocesses and both seefork
return, but with different values: itreturns a value of0
in the child process and returns the child’sprocess ID in the parent process.
If process creation failed,fork
returns a value of-1
inthe parent process. The followingerrno
error conditions aredefined forfork
:
EAGAIN
There aren’t enough system resources to create another process, or theuser already has too many processes running. This means exceeding theRLIMIT_NPROC
resource limit, which can usually be increased;seeLimiting Resource Usage.
ENOMEM
The process requires more space than the system can supply.
The specific attributes of the child process that differ from theparent process are:
pid_t
_Fork(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The_Fork
function is similar tofork
, but it does not invokeany callbacks registered withpthread_atfork
, nor does it resetany internal state or locks (such as themalloc
locks). In thenew subprocess, only async-signal-safe functions may be called, such asdup2
orexecve
.
The_Fork
function is an async-signal-safe replacement offork
.
This function was originally a GNU extension, but was added inPOSIX.1-2024.
pid_t
vfork(void)
¶Preliminary:| MT-Safe | AS-Unsafe plugin| AC-Unsafe lock| SeePOSIX Safety Concepts.
Thevfork
function is similar tofork
but on some systemsit is more efficient; however, there are restrictions you must follow touse it safely.
Whilefork
makes a complete copy of the calling process’s addressspace and allows both the parent and child to execute independently,vfork
does not make this copy. Instead, the child processcreated withvfork
shares its parent’s address space until itcalls_exit
or one of theexec
functions. In themeantime, the parent process suspends execution.
You must be very careful not to allow the child process created withvfork
to modify any global data or even local variables sharedwith the parent. Furthermore, the child process cannot return from (ordo a long jump out of) the function that calledvfork
! Thiswould leave the parent process’s control information very confused. Ifin doubt, usefork
instead.
Some operating systems don’t really implementvfork
. The GNU C Librarypermits you to usevfork
on all systems, but actuallyexecutesfork
ifvfork
isn’t available. If you followthe proper precautions for usingvfork
, your program will stillwork even if the system usesfork
instead.
Next:Executing a File, Previous:Creating a Process, Up:Processes [Contents][Index]
The file descriptor returned by thepidfd_fork
function can be used toquery process extra information.
pid_t
pidfd_getpid(intfd)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thepidfd_getpid
function retrieves the process ID associated with processfile descriptor created withpid_spawn
,pidfd_fork
, orpidfd_open
.
If the operation fails,pidfd_getpid
return-1
and the followingerrno
error conditionas are defined:
EBADF
The input file descriptor is invalid, does not have a pidfd associated, or anerror has occurred parsing the kernel data.
EREMOTE
There is no process ID to denote the process in the current namespace.
ESRCH
The process for which the file descriptor refers to is terminated.
ENOENT
The procfs is not mounted.
ENFILE.
Too many open files in system (pidfd_open
tries to open a procfs file andread its contents).
ENOMEM
Insufficient kernel memory was available.
This function is specific to Linux.
Next:Process Completion, Previous:Querying a Process, Up:Processes [Contents][Index]
This section describes theexec
family of functions, for executinga file as a process image. You can use these functions to make a childprocess execute a new program after it has been forked.
To see the effects ofexec
from the point of view of the calledprogram, seeThe Basic Program/System Interface.
The functions in this family differ in how you specify the arguments,but otherwise they all do the same thing. They are declared in theheader fileunistd.h.
int
execv(const char *filename, char *constargv[]
)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theexecv
function executes the file named byfilename as anew process image.
Theargv argument is an array of null-terminated strings that isused to provide a value for theargv
argument to themain
function of the program to be executed. The last element of this arraymust be a null pointer. By convention, the first element of this arrayis the file name of the program sans directory names. SeeProgram Arguments, for full details on how programs can access these arguments.
The environment for the new process image is taken from theenviron
variable of the current process image; seeEnvironment Variables, for information about environments.
int
execl(const char *filename, const char *arg0, …)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is similar toexecv
, but theargv strings arespecified individually instead of as an array. A null pointer must bepassed as the last such argument.
int
execve(const char *filename, char *constargv[]
, char *constenv[]
)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is similar toexecv
, but permits you to specify the environmentfor the new program explicitly as theenv argument. This shouldbe an array of strings in the same format as for theenviron
variable; seeEnvironment Access.
int
fexecve(intfd, char *constargv[]
, char *constenv[]
)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is similar toexecve
, but instead of identifying the programexecutable by its pathname, the file descriptorfd is used. Thedescriptor must have been opened with theO_RDONLY
flag or (onLinux) theO_PATH
flag.
On Linux,fexecve
can fail with an error ofENOSYS
if/proc has not been mounted and the kernel lacks support for theunderlyingexecveat
system call.
int
execle(const char *filename, const char *arg0, …, char *constenv[]
)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This is similar toexecl
, but permits you to specify theenvironment for the new program explicitly. The environment argument ispassed following the null pointer that marks the lastargvargument, and should be an array of strings in the same format as fortheenviron
variable.
int
execvp(const char *filename, char *constargv[]
)
¶Preliminary:| MT-Safe env| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Theexecvp
function is similar toexecv
, except that itsearches the directories listed in thePATH
environment variable(seeStandard Environment Variables) to find the full file name of afile fromfilename iffilename does not contain a slash.
This function is useful for executing system utility programs, becauseit looks for them in the places that the user has chosen. Shells use itto run the commands that users type.
int
execlp(const char *filename, const char *arg0, …)
¶Preliminary:| MT-Safe env| AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
This function is likeexecl
, except that it performs the samefile name searching as theexecvp
function.
The size of the argument list and environment list taken together mustnot be greater thanARG_MAX
bytes. SeeGeneral Capacity Limits. OnGNU/Hurd systems, the size (which compares againstARG_MAX
)includes, for each string, the number of characters in the string, plusthe size of achar *
, plus one, rounded up to a multiple of thesize of achar *
. Other systems may have somewhat differentrules for counting.
These functions normally don’t return, since execution of a new programcauses the currently executing program to go away completely. A valueof-1
is returned in the event of a failure. In addition to theusual file name errors (seeFile Name Errors), the followingerrno
error conditions are defined for these functions:
E2BIG
The combined size of the new program’s argument list and environmentlist is larger thanARG_MAX
bytes. GNU/Hurd systems have nospecific limit on the argument list size, so this error code cannotresult, but you may getENOMEM
instead if the arguments are toobig for available memory.
ENOEXEC
The specified file can’t be executed because it isn’t in the right format.
ENOMEM
Executing the specified file requires more storage than is available.
If execution of the new file succeeds, it updates the access time fieldof the file as if the file had been read. SeeFile Times, for moredetails about access times of files.
The point at which the file is closed again is not specified, butis at some point before the process exits or before another processimage is executed.
Executing a new process image completely changes the contents of memory,copying only the argument and environment strings to new locations. Butmany other attributes of the process are unchanged:
If the set-user-ID and set-group-ID mode bits of the process image fileare set, this affects the effective user ID and effective group ID(respectively) of the process. These concepts are discussed in detailinThe Persona of a Process.
Signals that are set to be ignored in the existing process image arealso set to be ignored in the new process image. All other signals areset to the default action in the new process image. For moreinformation about signals, seeSignal Handling.
File descriptors open in the existing process image remain open in thenew process image, unless they have theFD_CLOEXEC
(close-on-exec) flag set. The files that remain open inherit allattributes of the open file descriptors from the existing process image,including file locks. File descriptors are discussed inLow-Level Input/Output.
Streams, by contrast, cannot survive throughexec
functions,because they are located in the memory of the process itself. The newprocess image has no streams except those it creates afresh. Each ofthe streams in the pre-exec
process image has a descriptor insideit, and these descriptors do survive throughexec
(provided thatthey do not haveFD_CLOEXEC
set). The new process image canreconnect these to new streams usingfdopen
(seeDescriptors and Streams).
Next:Process Completion Status, Previous:Executing a File, Up:Processes [Contents][Index]
The functions described in this section are used to wait for a childprocess to terminate or stop, and determine its status. These functionsare declared in the header filesys/wait.h.
pid_t
waitpid(pid_tpid, int *status-ptr, intoptions)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thewaitpid
function is used to request status information from achild process whose process ID ispid. Normally, the callingprocess is suspended until the child process makes status informationavailable by terminating.
Other values for thepid argument have special interpretations. Avalue of-1
orWAIT_ANY
requests status information forany child process; a value of0
orWAIT_MYPGRP
requestsinformation for any child process in the same process group as thecalling process; and any other negative value −pgidrequests information for any child process whose process group ID ispgid.
If status information for a child process is available immediately, thisfunction returns immediately without waiting. If more than one eligiblechild process has status information available, one of them is chosenrandomly, and its status is returned immediately. To get the statusfrom the other eligible child processes, you need to callwaitpid
again.
Theoptions argument is a bit mask. Its value should be thebitwise OR (that is, the ‘|’ operator) of zero or more of theWNOHANG
andWUNTRACED
flags. You can use theWNOHANG
flag to indicate that the parent process shouldn’t wait;and theWUNTRACED
flag to request status information from stoppedprocesses as well as processes that have terminated.
The status information from the child process is stored in the objectthatstatus-ptr points to, unlessstatus-ptr is a null pointer.
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timewaitpid
iscalled. If the thread gets canceled these resources stay allocateduntil the program ends. To avoid this calls towaitpid
should beprotected using cancellation handlers.
The return value is normally the process ID of the child process whosestatus is reported. If there are child processes but none of them iswaiting to be noticed,waitpid
will block until one is. However,if theWNOHANG
option was specified,waitpid
will returnzero instead of blocking.
If a specific PID to wait for was given towaitpid
, it willignore all other children (if any). Therefore if there are childrenwaiting to be noticed but the child whose PID was specified is not oneof them,waitpid
will block or return zero as described above.
A value of-1
is returned in case of error. The followingerrno
error conditions are defined for this function:
EINTR
The function was interrupted by delivery of a signal to the callingprocess. SeePrimitives Interrupted by Signals.
ECHILD
There are no child processes to wait for, or the specifiedpidis not a child of the calling process.
EINVAL
An invalid value was provided for theoptions argument.
These symbolic constants are defined as values for thepid argumentto thewaitpid
function.
WAIT_ANY
¶This constant macro (whose value is-1
) specifies thatwaitpid
should return status information about any child process.
WAIT_MYPGRP
¶This constant (with value0
) specifies thatwaitpid
shouldreturn status information about any child process in the same processgroup as the calling process.
These symbolic constants are defined as flags for theoptionsargument to thewaitpid
function. You can bitwise-OR the flagstogether to obtain a value to use as the argument.
WNOHANG
¶This flag specifies thatwaitpid
should return immediatelyinstead of waiting, if there is no child process ready to be noticed.
WUNTRACED
¶This flag specifies thatwaitpid
should report the status of anychild processes that have been stopped as well as those that haveterminated.
pid_t
wait(int *status-ptr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is a simplified version ofwaitpid
, and is used to waituntil any one child process terminates. The call:
wait (&status)
is exactly equivalent to:
waitpid (-1, &status, 0)
This function is a cancellation point in multi-threaded programs. Thisis a problem if the thread allocates some resources (like memory, filedescriptors, semaphores or whatever) at the timewait
iscalled. If the thread gets canceled these resources stay allocateduntil the program ends. To avoid this calls towait
should beprotected using cancellation handlers.
pid_t
wait4(pid_tpid, int *status-ptr, intoptions, struct rusage *usage)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Ifusage is a null pointer,wait4
is equivalent towaitpid (pid,status-ptr,options)
.
Ifusage is not null,wait4
stores usage figures for thechild process in*rusage
(but only if the child hasterminated, not if it has stopped). SeeResource Usage.
This function is a BSD extension.
Here’s an example of how to usewaitpid
to get the status fromall child processes that have terminated, without ever waiting. Thisfunction is designed to be a handler forSIGCHLD
, the signal thatindicates that at least one child process has terminated.
voidsigchld_handler (int signum){ int pid, status, serrno; serrno = errno; while (1) { pid = waitpid (WAIT_ANY, &status, WNOHANG); if (pid < 0) { perror ("waitpid"); break; } if (pid == 0) break; notice_termination (pid, status); } errno = serrno;}
Next:BSD Process Wait Function, Previous:Process Completion, Up:Processes [Contents][Index]
If the exit status value (seeProgram Termination) of the childprocess is zero, then the status value reported bywaitpid
orwait
is also zero. You can test for other kinds of informationencoded in the returned status value using the following macros.These macros are defined in the header filesys/wait.h.
int
WIFEXITED(intstatus)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value if the child process terminatednormally withexit
or_exit
.
int
WEXITSTATUS(intstatus)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
IfWIFEXITED
is true ofstatus, this macro returns thelow-order 8 bits of the exit status value from the child process.SeeExit Status.
int
WIFSIGNALED(intstatus)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value if the child process terminatedbecause it received a signal that was not handled.SeeSignal Handling.
int
WTERMSIG(intstatus)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
IfWIFSIGNALED
is true ofstatus, this macro returns thesignal number of the signal that terminated the child process.
int
WCOREDUMP(intstatus)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value if the child process terminatedand produced a core dump.
This macro was originally a BSD extension, but was added inPOSIX.1-2024.
int
WIFSTOPPED(intstatus)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro returns a nonzero value if the child process is stopped.
int
WSTOPSIG(intstatus)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
IfWIFSTOPPED
is true ofstatus, this macro returns thesignal number of the signal that caused the child process to stop.
Next:Process Creation Example, Previous:Process Completion Status, Up:Processes [Contents][Index]
The GNU C Library also provides thewait3
function for compatibilitywith BSD. This function is declared insys/wait.h. It is thepredecessor towait4
, which is more flexible.wait3
isnow obsolete.
pid_t
wait3(int *status-ptr, intoptions, struct rusage *usage)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Ifusage is a null pointer,wait3
is equivalent towaitpid (-1,status-ptr,options)
.
Ifusage is not null,wait3
stores usage figures for thechild process in*rusage
(but only if the child hasterminated, not if it has stopped). SeeResource Usage.
Previous:BSD Process Wait Function, Up:Processes [Contents][Index]
Here is an example program showing how you might write a functionsimilar to the built-insystem
. It executes itscommandargument using the equivalent of ‘sh -ccommand’.
#include <stddef.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>/*Execute the command using this shell program. */#define SHELL "/bin/sh"
intmy_system (const char *command){ int status; pid_t pid;
pid = fork (); if (pid == 0) { /*This is the child process. Execute the shell command. */ execl (SHELL, SHELL, "-c", command, NULL); _exit (EXIT_FAILURE); } else if (pid < 0) /*The fork failed. Report failure. */ status = -1; else /*This is the parent process. Wait for the child to complete. */ if (waitpid (pid, &status, 0) != pid) status = -1; return status;}
There are a couple of things you should pay attention to in thisexample.
Remember that the firstargv
argument supplied to the programrepresents the name of the program being executed. That is why, in thecall toexecl
,SHELL
is supplied once to name the programto execute and a second time to supply a value forargv[0]
.
Theexecl
call in the child process doesn’t return if it issuccessful. If it fails, you must do something to make the childprocess terminate. Just returning a bad status code withreturn
would leave two processes running the original program. Instead, theright behavior is for the child process to report failure to its parentprocess.
Call_exit
to accomplish this. The reason for using_exit
instead ofexit
is to avoid flushing fully buffered streams suchasstdout
. The buffers of these streams probably contain datathat was copied from the parent process by thefork
, data thatwill be output eventually by the parent process. Callingexit
inthe child would output the data twice. SeeTermination Internals.
Next:Job Control, Previous:Processes, Up:Main Menu [Contents][Index]
This chapter describes the GNU C Library inter-process communication primitives.
The GNU C Library implements the semaphore APIs as defined in POSIX andSystem V. Semaphores can be used by multiple processes to coordinate sharedresources. The following is a complete list of the semaphore functions providedby the GNU C Library.
int
semctl(intsemid, intsemnum, intcmd)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe corrupt/linux| SeePOSIX Safety Concepts.
int
semget(key_tkey, intnsems, intsemflg)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
int
semop(intsemid, struct sembuf *sops, size_tnsops)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
int
semtimedop(intsemid, struct sembuf *sops, size_tnsops, const struct timespec *timeout)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
The GNU C Library provides POSIX semaphores as well. These functions’ names beginwithsem_
and they are declared insemaphore.h. SeePOSIX Semaphores.
Next:System Databases and Name Service Switch, Previous:Inter-Process Communication, Up:Main Menu [Contents][Index]
Job control refers to the protocol for allowing a user to movebetween multipleprocess groups (orjobs) within a singlelogin session. The job control facilities are set up so thatappropriate behavior for most programs happens automatically and theyneed not do anything special about job control. So you can probablyignore the material in this chapter unless you are writing a shell orlogin program.
You need to be familiar with concepts relating to process creation(seeProcess Creation Concepts) and signal handling (seeSignal Handling) in order to understand this material presented in thischapter.
Some old systems do not support job control, but GNU systems alwayshave, and it is a required feature in the 2001 revision of POSIX.1(seePOSIX (The Portable Operating System Interface)). If you need to be portable to old systems, you canuse the_POSIX_JOB_CONTROL
macro to test at compile-timewhether the system supports job control. SeeOverall System Options.
Next:Controlling Terminal of a Process, Up:Job Control [Contents][Index]
The fundamental purpose of an interactive shell is to readcommands from the user’s terminal and create processes to execute theprograms specified by those commands. It can do this using thefork
(seeCreating a Process) andexec
(seeExecuting a File) functions.
A single command may run just one process—but often one command usesseveral processes. If you use the ‘|’ operator in a shell command,you explicitly request several programs in their own processes. Buteven if you run just one program, it can use multiple processesinternally. For example, a single compilation command such as ‘cc-c foo.c’ typically uses four processes (though normally only two at anygiven time). If you runmake
, its job is to run other programsin separate processes.
The processes belonging to a single command are called aprocessgroup orjob. This is so that you can operate on all of them atonce. For example, typingC-c sends the signalSIGINT
toterminate all the processes in the foreground process group.
Asession is a larger group of processes. Normally all theprocesses that stem from a single login belong to the same session.
Every process belongs to a process group. When a process is created, itbecomes a member of the same process group and session as its parentprocess. You can put it in another process group using thesetpgid
function, provided the process group belongs to the samesession.
The only way to put a process in a different session is to make it theinitial process of a new session, or asession leader, using thesetsid
function. This also puts the session leader into a newprocess group, and you can’t move it out of that process group again.
Usually, new sessions are created by the system login program, and thesession leader is the process running the user’s login shell.
A shell that supports job control must arrange to control which job canuse the terminal at any time. Otherwise there might be multiple jobstrying to read from the terminal at once, and confusion about whichprocess should receive the input typed by the user. To prevent this,the shell must cooperate with the terminal driver using the protocoldescribed in this chapter.
The shell can give unlimited access to the controlling terminal to onlyone process group at a time. This is called theforeground job onthat controlling terminal. Other process groups managed by the shellthat are executing without such access to the terminal are calledbackground jobs.
If a background job needs to read from its controllingterminal, it isstopped by the terminal driver; if theTOSTOP
mode is set, likewise for writing. The user can stopa foreground job by typing the SUSP character (seeSpecial Characters) and a program can stop any job by sending it aSIGSTOP
signal. It’s the responsibility of the shell to noticewhen jobs stop, to notify the user about them, and to provide mechanismsfor allowing the user to interactively continue stopped jobs and switchjobs between foreground and background.
SeeAccess to the Controlling Terminal, for more information about I/O to thecontrolling terminal.
Next:Access to the Controlling Terminal, Previous:Concepts of Job Control, Up:Job Control [Contents][Index]
One of the attributes of a process is its controlling terminal. Childprocesses created withfork
inherit the controlling terminal fromtheir parent process. In this way, all the processes in a sessioninherit the controlling terminal from the session leader. A sessionleader that has control of a terminal is called thecontrollingprocess of that terminal.
You generally do not need to worry about the exact mechanism used toallocate a controlling terminal to a session, since it is done for youby the system when you log in.
An individual process disconnects from its controlling terminal when itcallssetsid
to become the leader of a new session.SeeProcess Group Functions.
Next:Orphaned Process Groups, Previous:Controlling Terminal of a Process, Up:Job Control [Contents][Index]
Processes in the foreground job of a controlling terminal haveunrestricted access to that terminal; background processes do not. Thissection describes in more detail what happens when a process in abackground job tries to access its controlling terminal.
When a process in a background job tries to read from its controllingterminal, the process group is usually sent aSIGTTIN
signal.This normally causes all of the processes in that group to stop (unlessthey handle the signal and don’t stop themselves). However, if thereading process is ignoring or blocking this signal, thenread
fails with anEIO
error instead.
Similarly, when a process in a background job tries to write to itscontrolling terminal, the default behavior is to send aSIGTTOU
signal to the process group. However, the behavior is modified by theTOSTOP
bit of the local modes flags (seeLocal Modes). Ifthis bit is not set (which is the default), then writing to thecontrolling terminal is always permitted without sending a signal.Writing is also permitted if theSIGTTOU
signal is being ignoredor blocked by the writing process.
Most other terminal operations that a program can do are treated asreading or as writing. (The description of each operation should saywhich.)
For more information about the primitiveread
andwrite
functions, seeInput and Output Primitives.
Next:Implementing a Job Control Shell, Previous:Access to the Controlling Terminal, Up:Job Control [Contents][Index]
When a controlling process terminates, its terminal becomes free and anew session can be established on it. (In fact, another user could login on the terminal.) This could cause a problem if any processes fromthe old session are still trying to use that terminal.
To prevent problems, process groups that continue running even after thesession leader has terminated are marked asorphaned processgroups.
When a process group becomes an orphan, its processes are sent aSIGHUP
signal. Ordinarily, this causes the processes toterminate. However, if a program ignores this signal or establishes ahandler for it (seeSignal Handling), it can continue running as inthe orphan process group even after its controlling process terminates;but it still cannot access the terminal any more.
Next:Functions for Job Control, Previous:Orphaned Process Groups, Up:Job Control [Contents][Index]
This section describes what a shell must do to implement job control, bypresenting an extensive sample program to illustrate the conceptsinvolved.
All of the program examples included in this chapter are part ofa simple shell program. This section presents data structuresand utility functions which are used throughout the example.
The sample shell deals mainly with two data structures. Thejob
type contains information about a job, which is aset of subprocesses linked together with pipes. Theprocess
typeholds information about a single subprocess. Here are the relevantdata structure declarations:
/*A process is a single process. */typedef struct process{ struct process *next; /*next process in pipeline */ char **argv; /*for exec */ pid_t pid; /*process ID */ char completed; /*true if process has completed */ char stopped; /*true if process has stopped */ int status; /*reported status value */} process;
/*A job is a pipeline of processes. */typedef struct job{ struct job *next; /*next active job */ char *command; /*command line, used for messages */ process *first_process; /*list of processes in this job */ pid_t pgid; /*process group ID */ char notified; /*true if user told about stopped job */ struct termios tmodes; /*saved terminal modes */ int stdin, stdout, stderr; /*standard i/o channels */} job;/*The active jobs are linked into a list. This is its head. */job *first_job = NULL;
Here are some utility functions that are used for operating onjob
objects.
/*Find the active job with the indicatedpgid. */job *find_job (pid_t pgid){ job *j; for (j = first_job; j; j = j->next) if (j->pgid == pgid) return j; return NULL;}
/*Return true if all processes in the job have stopped or completed. */intjob_is_stopped (job *j){ process *p; for (p = j->first_process; p; p = p->next) if (!p->completed && !p->stopped) return 0; return 1;}
/*Return true if all processes in the job have completed. */intjob_is_completed (job *j){ process *p; for (p = j->first_process; p; p = p->next) if (!p->completed) return 0; return 1;}
Next:Launching Jobs, Previous:Data Structures for the Shell, Up:Implementing a Job Control Shell [Contents][Index]
When a shell program that normally performs job control is started, ithas to be careful in case it has been invoked from another shell that isalready doing its own job control.
A subshell that runs interactively has to ensure that it has been placedin the foreground by its parent shell before it can enable job controlitself. It does this by getting its initial process group ID with thegetpgrp
function, and comparing it to the process group ID of thecurrent foreground job associated with its controlling terminal (whichcan be retrieved using thetcgetpgrp
function).
If the subshell is not running as a foreground job, it must stop itselfby sending aSIGTTIN
signal to its own process group. It may notarbitrarily put itself into the foreground; it must wait for the user totell the parent shell to do this. If the subshell is continued again,it should repeat the check and stop itself again if it is still not inthe foreground.
Once the subshell has been placed into the foreground by its parentshell, it can enable its own job control. It does this by callingsetpgid
to put itself into its own process group, and thencallingtcsetpgrp
to place this process group into theforeground.
When a shell enables job control, it should set itself to ignore all thejob control stop signals so that it doesn’t accidentally stop itself.You can do this by setting the action for all the stop signals toSIG_IGN
.
A subshell that runs non-interactively cannot and should not support jobcontrol. It must leave all processes it creates in the same processgroup as the shell itself; this allows the non-interactive shell and itschild processes to be treated as a single job by the parent shell. Thisis easy to do—just don’t use any of the job control primitives—butyou must remember to make the shell do it.
Here is the initialization code for the sample shell that shows how todo all of this.
/*Keep track of attributes of the shell. */#include <sys/types.h>#include <termios.h>#include <unistd.h>pid_t shell_pgid;struct termios shell_tmodes;int shell_terminal;int shell_is_interactive;/*Make sure the shell is running interactively as the foreground jobbefore proceeding. */voidinit_shell (){ /*See if we are running interactively. */ shell_terminal = STDIN_FILENO; shell_is_interactive = isatty (shell_terminal); if (shell_is_interactive) { /*Loop until we are in the foreground. */ while (tcgetpgrp (shell_terminal) != (shell_pgid = getpgrp ())) kill (- shell_pgid, SIGTTIN); /*Ignore interactive and job-control signals. */ signal (SIGINT, SIG_IGN); signal (SIGQUIT, SIG_IGN); signal (SIGTSTP, SIG_IGN); signal (SIGTTIN, SIG_IGN); signal (SIGTTOU, SIG_IGN); signal (SIGCHLD, SIG_IGN); /*Put ourselves in our own process group. */ shell_pgid = getpid (); if (setpgid (shell_pgid, shell_pgid) < 0) { perror ("Couldn't put the shell in its own process group"); exit (1); } /*Grab control of the terminal. */ tcsetpgrp (shell_terminal, shell_pgid); /*Save default terminal attributes for shell. */ tcgetattr (shell_terminal, &shell_tmodes); }}
Next:Foreground and Background, Previous:Initializing the Shell, Up:Implementing a Job Control Shell [Contents][Index]
Once the shell has taken responsibility for performing job control onits controlling terminal, it can launch jobs in response to commandstyped by the user.
To create the processes in a process group, you use the samefork
andexec
functions described inProcess Creation Concepts.Since there are multiple child processes involved, though, things are alittle more complicated and you must be careful to do things in theright order. Otherwise, nasty race conditions can result.
You have two choices for how to structure the tree of parent-childrelationships among the processes. You can either make all theprocesses in the process group be children of the shell process, or youcan make one process in group be the ancestor of all the other processesin that group. The sample shell program presented in this chapter usesthe first approach because it makes bookkeeping somewhat simpler.
As each process is forked, it should put itself in the new process groupby callingsetpgid
; seeProcess Group Functions. The firstprocess in the new group becomes itsprocess group leader, and itsprocess ID becomes theprocess group ID for the group.
The shell should also callsetpgid
to put each of its childprocesses into the new process group. This is because there is apotential timing problem: each child process must be put in the processgroup before it begins executing a new program, and the shell depends onhaving all the child processes in the group before it continuesexecuting. If both the child processes and the shell callsetpgid
, this ensures that the right things happen no matter whichprocess gets to it first.
If the job is being launched as a foreground job, the new process groupalso needs to be put into the foreground on the controlling terminalusingtcsetpgrp
. Again, this should be done by the shell as wellas by each of its child processes, to avoid race conditions.
The next thing each child process should do is to reset its signalactions.
During initialization, the shell process set itself to ignore jobcontrol signals; seeInitializing the Shell. As a result, any childprocesses it creates also ignore these signals by inheritance. This isdefinitely undesirable, so each child process should explicitly set theactions for these signals back toSIG_DFL
just after it is forked.
Since shells follow this convention, applications can assume that theyinherit the correct handling of these signals from the parent process.But every application has a responsibility not to mess up the handlingof stop signals. Applications that disable the normal interpretation ofthe SUSP character should provide some other mechanism for the user tostop the job. When the user invokes this mechanism, the program shouldsend aSIGTSTP
signal to the process group of the process, notjust to the process itself. SeeSignaling Another Process.
Finally, each child process should callexec
in the normal way.This is also the point at which redirection of the standard input andoutput channels should be handled. SeeDuplicating Descriptors,for an explanation of how to do this.
Here is the function from the sample shell program that is responsiblefor launching a program. The function is executed by each child processimmediately after it has been forked by the shell, and never returns.
voidlaunch_process (process *p, pid_t pgid, int infile, int outfile, int errfile, int foreground){ pid_t pid; if (shell_is_interactive) { /*Put the process into the process group and give the process groupthe terminal, if appropriate.This has to be done both by the shell and in the individualchild processes because of potential race conditions. */ pid = getpid (); if (pgid == 0) pgid = pid; setpgid (pid, pgid); if (foreground) tcsetpgrp (shell_terminal, pgid); /*Set the handling for job control signals back to the default. */ signal (SIGINT, SIG_DFL); signal (SIGQUIT, SIG_DFL); signal (SIGTSTP, SIG_DFL); signal (SIGTTIN, SIG_DFL); signal (SIGTTOU, SIG_DFL); signal (SIGCHLD, SIG_DFL); } /*Set the standard input/output channels of the new process. */ if (infile != STDIN_FILENO) { dup2 (infile, STDIN_FILENO); close (infile); } if (outfile != STDOUT_FILENO) { dup2 (outfile, STDOUT_FILENO); close (outfile); } if (errfile != STDERR_FILENO) { dup2 (errfile, STDERR_FILENO); close (errfile); } /*Exec the new process. Make sure we exit. */ execvp (p->argv[0], p->argv); perror ("execvp"); exit (1);}
If the shell is not running interactively, this function does not doanything with process groups or signals. Remember that a shell notperforming job control must keep all of its subprocesses in the sameprocess group as the shell itself.
Next, here is the function that actually launches a complete job.After creating the child processes, this function calls some otherfunctions to put the newly created job into the foreground or background;these are discussed inForeground and Background.
voidlaunch_job (job *j, int foreground){ process *p; pid_t pid; int mypipe[2], infile, outfile; infile = j->stdin; for (p = j->first_process; p; p = p->next) { /*Set up pipes, if necessary. */ if (p->next) { if (pipe (mypipe) < 0) { perror ("pipe"); exit (1); } outfile = mypipe[1]; } else outfile = j->stdout; /*Fork the child processes. */ pid = fork (); if (pid == 0) /*This is the child process. */ launch_process (p, j->pgid, infile, outfile, j->stderr, foreground); else if (pid < 0) { /*The fork failed. */ perror ("fork"); exit (1); } else { /*This is the parent process. */ p->pid = pid; if (shell_is_interactive) { if (!j->pgid) j->pgid = pid; setpgid (pid, j->pgid); } } /*Clean up after pipes. */ if (infile != j->stdin) close (infile); if (outfile != j->stdout) close (outfile); infile = mypipe[0]; } format_job_info (j, "launched"); if (!shell_is_interactive) wait_for_job (j); else if (foreground) put_job_in_foreground (j, 0); else put_job_in_background (j, 0);}
Next:Stopped and Terminated Jobs, Previous:Launching Jobs, Up:Implementing a Job Control Shell [Contents][Index]
Now let’s consider what actions must be taken by the shell when itlaunches a job into the foreground, and how this differs from whatmust be done when a background job is launched.
When a foreground job is launched, the shell must first give it accessto the controlling terminal by callingtcsetpgrp
. Then, theshell should wait for processes in that process group to terminate orstop. This is discussed in more detail inStopped and Terminated Jobs.
When all of the processes in the group have either completed or stopped,the shell should regain control of the terminal for its own processgroup by callingtcsetpgrp
again. Since stop signals caused byI/O from a background process or a SUSP character typed by the userare sent to the process group, normally all the processes in the jobstop together.
The foreground job may have left the terminal in a strange state, so theshell should restore its own saved terminal modes before continuing. Incase the job is merely stopped, the shell should first save the currentterminal modes so that it can restore them later if the job iscontinued. The functions for dealing with terminal modes aretcgetattr
andtcsetattr
; these are described inTerminal Modes.
Here is the sample shell’s function for doing all of this.
/*Put jobj in the foreground. Ifcont is nonzero,restore the saved terminal modes and send the process group aSIGCONT
signal to wake it up before we block. */voidput_job_in_foreground (job *j, int cont){ /*Put the job into the foreground. */ tcsetpgrp (shell_terminal, j->pgid);
/*Send the job a continue signal, if necessary. */ if (cont) { tcsetattr (shell_terminal, TCSADRAIN, &j->tmodes); if (kill (- j->pgid, SIGCONT) < 0) perror ("kill (SIGCONT)"); }
/*Wait for it to report. */ wait_for_job (j); /*Put the shell back in the foreground. */ tcsetpgrp (shell_terminal, shell_pgid);
/*Restore the shell’s terminal modes. */ tcgetattr (shell_terminal, &j->tmodes); tcsetattr (shell_terminal, TCSADRAIN, &shell_tmodes);}
If the process group is launched as a background job, the shell shouldremain in the foreground itself and continue to read commands fromthe terminal.
In the sample shell, there is not much that needs to be done to puta job into the background. Here is the function it uses:
/*Put a job in the background. If the cont argument is true, sendthe process group aSIGCONT
signal to wake it up. */voidput_job_in_background (job *j, int cont){ /*Send the job a continue signal, if necessary. */ if (cont) if (kill (-j->pgid, SIGCONT) < 0) perror ("kill (SIGCONT)");}
Next:Continuing Stopped Jobs, Previous:Foreground and Background, Up:Implementing a Job Control Shell [Contents][Index]
When a foreground process is launched, the shell must block until all ofthe processes in that job have either terminated or stopped. It can dothis by calling thewaitpid
function; seeProcess Completion. Use theWUNTRACED
option so that status is reportedfor processes that stop as well as processes that terminate.
The shell must also check on the status of background jobs so that itcan report terminated and stopped jobs to the user; this can be done bycallingwaitpid
with theWNOHANG
option. A good place toput a such a check for terminated and stopped jobs is just beforeprompting for a new command.
The shell can also receive asynchronous notification that there isstatus information available for a child process by establishing ahandler forSIGCHLD
signals. SeeSignal Handling.
In the sample shell program, theSIGCHLD
signal is normallyignored. This is to avoid reentrancy problems involving the global datastructures the shell manipulates. But at specific times when the shellis not using these data structures—such as when it is waiting forinput on the terminal—it makes sense to enable a handler forSIGCHLD
. The same function that is used to do the synchronousstatus checks (do_job_notification
, in this case) can also becalled from within this handler.
Here are the parts of the sample shell program that deal with checkingthe status of jobs and reporting the information to the user.
/*Store the status of the processpid that was returned by waitpid.Return 0 if all went well, nonzero otherwise. */intmark_process_status (pid_t pid, int status){ job *j; process *p;
if (pid > 0) { /*Update the record for the process. */ for (j = first_job; j; j = j->next) for (p = j->first_process; p; p = p->next) if (p->pid == pid) { p->status = status; if (WIFSTOPPED (status)) p->stopped = 1; else { p->completed = 1; if (WIFSIGNALED (status)) fprintf (stderr, "%d: Terminated by signal %d.\n", (int) pid, WTERMSIG (p->status)); } return 0; } fprintf (stderr, "No child process %d.\n", pid); return -1; }
else if (pid == 0 || errno == ECHILD) /*No processes ready to report. */ return -1; else { /*Other weird errors. */ perror ("waitpid"); return -1; }}
/*Check for processes that have status information available,without blocking. */voidupdate_status (void){ int status; pid_t pid; do pid = waitpid (WAIT_ANY, &status, WUNTRACED|WNOHANG); while (!mark_process_status (pid, status));}
/*Check for processes that have status information available,blocking until all processes in the given job have reported. */voidwait_for_job (job *j){ int status; pid_t pid; do pid = waitpid (WAIT_ANY, &status, WUNTRACED); while (!mark_process_status (pid, status) && !job_is_stopped (j) && !job_is_completed (j));}
/*Format information about job status for the user to look at. */voidformat_job_info (job *j, const char *status){ fprintf (stderr, "%ld (%s): %s\n", (long)j->pgid, status, j->command);}
/*Notify the user about stopped or terminated jobs.Delete terminated jobs from the active job list. */voiddo_job_notification (void){ job *j, *jlast, *jnext; /*Update status information for child processes. */ update_status (); jlast = NULL; for (j = first_job; j; j = jnext) { jnext = j->next; /*If all processes have completed, tell the user the job hascompleted and delete it from the list of active jobs. */ if (job_is_completed (j)) { format_job_info (j, "completed"); if (jlast) jlast->next = jnext; else first_job = jnext; free_job (j); } /*Notify the user about stopped jobs,marking them so that we won’t do this more than once. */ else if (job_is_stopped (j) && !j->notified) { format_job_info (j, "stopped"); j->notified = 1; jlast = j; } /*Don’t say anything about jobs that are still running. */ else jlast = j; }}
Next:The Missing Pieces, Previous:Stopped and Terminated Jobs, Up:Implementing a Job Control Shell [Contents][Index]
The shell can continue a stopped job by sending aSIGCONT
signalto its process group. If the job is being continued in the foreground,the shell should first invoketcsetpgrp
to give the job access tothe terminal, and restore the saved terminal settings. After continuinga job in the foreground, the shell should wait for the job to stop orcomplete, as if the job had just been launched in the foreground.
The sample shell program handles both newly created and continued jobswith the same pair of functions,put_job_in_foreground
andput_job_in_background
. The definitions of these functionswere given inForeground and Background. When continuing astopped job, a nonzero value is passed as thecont argument toensure that theSIGCONT
signal is sent and the terminal modesreset, as appropriate.
This leaves only a function for updating the shell’s internal bookkeepingabout the job being continued:
/*Mark a stopped job J as being running again. */voidmark_job_as_running (job *j){ Process *p; for (p = j->first_process; p; p = p->next) p->stopped = 0; j->notified = 0;}
/*Continue the job J. */voidcontinue_job (job *j, int foreground){ mark_job_as_running (j); if (foreground) put_job_in_foreground (j, 1); else put_job_in_background (j, 1);}
Previous:Continuing Stopped Jobs, Up:Implementing a Job Control Shell [Contents][Index]
The code extracts for the sample shell included in this chapter are onlya part of the entire shell program. In particular, nothing at all hasbeen said about howjob
andprogram
data structures areallocated and initialized.
Most real shells provide a complex user interface that has support fora command language; variables; abbreviations, substitutions, and patternmatching on file names; and the like. All of this is far too complicatedto explain here! Instead, we have concentrated on showing how toimplement the core process creation and job control functions that canbe called from such a shell.
Here is a table summarizing the major entry points we have presented:
void init_shell (void)
Initialize the shell’s internal state. SeeInitializing the Shell.
void launch_job (job *j, intforeground)
Launch the jobj as either a foreground or background job.SeeLaunching Jobs.
void do_job_notification (void)
Check for and report any jobs that have terminated or stopped. Can becalled synchronously or within a handler forSIGCHLD
signals.SeeStopped and Terminated Jobs.
void continue_job (job *j, intforeground)
Continue the jobj. SeeContinuing Stopped Jobs.
Of course, a real shell would also want to provide other functions formanaging jobs. For example, it would be useful to have commands to listall active jobs or to send a signal (such asSIGKILL
) to a job.
Previous:Implementing a Job Control Shell, Up:Job Control [Contents][Index]
This section contains detailed descriptions of the functions relatingto job control.
You can use thectermid
function to get a file name that you canuse to open the controlling terminal. In the GNU C Library, it returnsthe same string all the time:"/dev/tty"
. That is a special“magic” file name that refers to the controlling terminal of thecurrent process (if it has one). To find the name of the specificterminal device, usettyname
; seeIdentifying Terminals.
The functionctermid
is declared in the header filestdio.h.
char *
ctermid(char *string)
¶Preliminary:| MT-Safe !posix/!string| AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thectermid
function returns a string containing the file name ofthe controlling terminal for the current process. Ifstring isnot a null pointer, it should be an array that can hold at leastL_ctermid
characters; the string is returned in this array.Otherwise, a pointer to a string in a static area is returned, whichmight get overwritten on subsequent calls to this function.
An empty string is returned if the file name cannot be determined forany reason. Even if a file name is returned, access to the file itrepresents is not guaranteed.
int
L_ctermid ¶The value of this macro is an integer constant expression thatrepresents the size of a string large enough to hold the file namereturned byctermid
.
See also theisatty
andttyname
functions, inIdentifying Terminals.
Next:Functions for Controlling Terminal Access, Previous:Identifying the Controlling Terminal, Up:Functions for Job Control [Contents][Index]
Here are descriptions of the functions for manipulating process groups.Your program should include the header filessys/types.h andunistd.h to use these functions.
pid_t
setsid(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thesetsid
function creates a new session. The calling processbecomes the session leader, and is put in a new process group whoseprocess group ID is the same as the process ID of that process. Thereare initially no other processes in the new process group, and no otherprocess groups in the new session.
This function also makes the calling process have no controlling terminal.
Thesetsid
function returns the new process group ID of thecalling process if successful. A return value of-1
indicates anerror. The followingerrno
error conditions are defined for thisfunction:
EPERM
The calling process is already a process group leader, or there isalready another process group around that has the same process group ID.
pid_t
getsid(pid_tpid)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetsid
function returns the process group ID of the sessionleader of the specified process. If apid is0
, theprocess group ID of the session leader of the current process isreturned.
In case of error-1
is returned anderrno
is set. Thefollowingerrno
error conditions are defined for this function:
ESRCH
There is no process with the given process IDpid.
EPERM
The calling process and the process specified bypid are indifferent sessions, and the implementation doesn’t allow to access theprocess group ID of the session leader of the process with IDpidfrom the calling process.
pid_t
getpgrp(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetpgrp
function returns the process group ID ofthe calling process.
int
getpgid(pid_tpid)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetpgid
functionreturns the process group ID of the processpid. You can supply avalue of0
for thepid argument to get information aboutthe calling process.
In case of error-1
is returned anderrno
is set. Thefollowingerrno
error conditions are defined for this function:
ESRCH
There is no process with the given process IDpid.
EPERM
The calling process and the process specified bypid are indifferent sessions, and the implementation doesn’t allow to access theprocess group ID of the process with IDpid from the callingprocess.
int
setpgid(pid_tpid, pid_tpgid)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thesetpgid
function puts the processpid into the processgrouppgid. As a special case, eitherpid orpgid canbe zero to indicate the process ID of the calling process.
If the operation is successful,setpgid
returns zero. Otherwiseit returns-1
. The followingerrno
error conditions aredefined for this function:
EACCES
The child process named bypid has executed anexec
function since it was forked.
EINVAL
The value of thepgid is not valid.
ENOSYS
The system doesn’t support job control.
EPERM
The process indicated by thepid argument is a session leader,or is not in the same session as the calling process, or the value ofthepgid argument doesn’t match a process group ID in the samesession as the calling process.
ESRCH
The process indicated by thepid argument is not the callingprocess or a child of the calling process.
int
setpgrp(pid_tpid, pid_tpgid)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This is the BSD Unix name forsetpgid
. Both functions do exactlythe same thing.
Previous:Process Group Functions, Up:Functions for Job Control [Contents][Index]
These are the functions for reading or setting the foregroundprocess group of a terminal. You should include the header filessys/types.h andunistd.h in your application to usethese functions.
Although these functions take a file descriptor argument to specifythe terminal device, the foreground job is associated with the terminalfile itself and not a particular open file descriptor.
pid_t
tcgetpgrp(intfiledes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the process group ID of the foreground processgroup associated with the terminal open on descriptorfiledes.
If there is no foreground process group, the return value is a numbergreater than1
that does not match the process group ID of anyexisting process group. This can happen if all of the processes in thejob that was formerly the foreground job have terminated, and no otherjob has yet been moved into the foreground.
In case of an error, a value of-1
is returned. Thefollowingerrno
error conditions are defined for this function:
EBADF
Thefiledes argument is not a valid file descriptor.
ENOSYS
The system doesn’t support job control.
ENOTTY
The terminal file associated with thefiledes argument isn’t thecontrolling terminal of the calling process.
int
tcsetpgrp(intfiledes, pid_tpgid)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is used to set a terminal’s foreground process group ID.The argumentfiledes is a descriptor which specifies the terminal;pgid specifies the process group. The calling process must be amember of the same session aspgid and must have the samecontrolling terminal.
For terminal access purposes, this function is treated as output. If itis called from a background process on its controlling terminal,normally all processes in the process group are sent aSIGTTOU
signal. The exception is if the calling process itself is ignoring orblockingSIGTTOU
signals, in which case the operation isperformed and no signal is sent.
If successful,tcsetpgrp
returns0
. A return value of-1
indicates an error. The followingerrno
errorconditions are defined for this function:
EBADF
Thefiledes argument is not a valid file descriptor.
EINVAL
Thepgid argument is not valid.
ENOSYS
The system doesn’t support job control.
ENOTTY
Thefiledes isn’t the controlling terminal of the calling process.
EPERM
Thepgid isn’t a process group in the same session as the callingprocess.
pid_t
tcgetsid(intfildes)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function is used to obtain the process group ID of the sessionfor which the terminal specified byfildes is the controlling terminal.If the call is successful the group ID is returned. Otherwise thereturn value is(pid_t) -1
and the global variableerrno
is set to the following value:
EBADF
Thefiledes argument is not a valid file descriptor.
ENOTTY
The calling process does not have a controlling terminal, or the fileis not the controlling terminal.
Next:Users and Groups, Previous:Job Control, Up:Main Menu [Contents][Index]
Various functions in the C Library need to be configured to workcorrectly in the local environment. Traditionally, this was done byusing files (e.g.,/etc/passwd), but other nameservices (like theNetwork Information Service (NIS) and the Domain Name Service (DNS))became popular, and were hacked into the C library, usually with a fixedsearch order.
The GNU C Library contains a cleaner solution to this problem. It isdesigned after a method used by Sun Microsystems in the C library ofSolaris 2. The GNU C Library follows their name and calls thisschemeName Service Switch (NSS).
Though the interface might be similar to Sun’s version there is nocommon code. We never saw any source code of Sun’s implementation andso the internal interface is incompatible. This also manifests in thefile names we use as we will see later.
Next:The NSS Configuration File, Previous:System Databases and Name Service Switch, Up:System Databases and Name Service Switch [Contents][Index]
The basic idea is to put the implementation of the different servicesoffered to access the databases in separate modules. This has someadvantages:
To fulfill the first goal above, the ABI of the modules will be describedbelow. For getting the implementation of a new service right it isimportant to understand how the functions in the modules get called.They are in no way designed to be used by the programmer directly.Instead the programmer should only use the documented and standardizedfunctions to access the databases.
The databases available in the NSS are
aliases
Mail aliases
ethers
Ethernet numbers,
group
Groups of users, seeGroup Database.
gshadow
Group passphrase hashes and related information.
hosts
Host names and numbers, seeHost Names.
initgroups
Supplementary group access list.
netgroup
Network wide list of host and users, seeNetgroup Database.
networks
Network names and numbers, seeNetworks Database.
passwd
User identities, seeUser Database.
protocols
Network protocols, seeProtocols Database.
publickey
Public keys for Secure RPC.
rpc
Remote procedure call names and numbers.
services
Network services, seeThe Services Database.
shadow
User passphrase hashes and related information.
More databases may be added later.
Next:NSS Module Internals, Previous:NSS Basics, Up:System Databases and Name Service Switch [Contents][Index]
Somehow the NSS code must be told about the wishes of the user. Forthis reason there is the file/etc/nsswitch.conf. For eachdatabase, this file contains a specification of how the lookup process shouldwork. The file could look like this:
# /etc/nsswitch.conf## Name Service Switch configuration file.#passwd: db filesshadow: filesgroup: db fileshosts: files dnsnetworks: filesethers: db filesprotocols: db filesrpc: db filesservices: db files
The first column is the database as you can guess from the table above.The rest of the line specifies how the lookup process works. Pleasenote that you specify the way it works for each database individually.This cannot be done with the old way of a monolithic implementation.
The configuration specification for each database can contain twodifferent items:
files
,db
, ornis
.[NOTFOUND=return]
.Next:Actions in the NSS configuration, Previous:The NSS Configuration File, Up:The NSS Configuration File [Contents][Index]
The above example file mentions five different services:files
,db
,dns
,nis
, andnisplus
. This does notmean theseservices are available on all sites and neither does it mean these areall the services which will ever be available.
In fact, these names are simply strings which the NSS code uses to findthe implicitly addressed functions. The internal interface will bedescribed later. Visible to the user are the modules which implement anindividual service.
Assume the servicename shall be used for a lookup. The code forthis service is implemented in a module calledlibnss_name.On a system supporting shared libraries this is in fact a shared librarywith the name (for example)libnss_name.so.2. The numberat the end is the currently used version of the interface which will notchange frequently. Normally the user should not have to be cognizant ofthese files since they should be placed in a directory where they arefound automatically. Only the names of all available services areimportant.
Lastly, some system software may make use of the NSS configuration fileto store their own configuration for similar purposes. Examples of thisinclude theautomount
service which is used byautofs
.
Next:Notes on the NSS Configuration File, Previous:Services in the NSS configuration File, Up:The NSS Configuration File [Contents][Index]
The second item in the specification gives the user much finer controlon the lookup process. Action items are placed between two servicenames and are written within brackets. The general form is
[
(!
?status=
action )+]
where
status ⇒ success | notfound | unavail | tryagainaction ⇒ return | continue
The case of the keywords is insignificant. Thestatusvalues are the results of a call to a lookup function of a specificservice. They mean:
No error occurred and the wanted entry is returned. The default actionfor this isreturn
.
The lookup process works ok but the needed value was not found. Thedefault action iscontinue
.
The service is permanently unavailable. This can either mean the neededfile is not available, or, for DNS, the server is not available or doesnot allow queries. The default action iscontinue
.
The service is temporarily unavailable. This could mean a file islocked or a server currently cannot accept more connections. Thedefault action iscontinue
.
Theaction values mean:
If the status matches, stop the lookup process at this servicespecification. If an entry is available, provide it to the application.If an error occurred, report it to the application. In case of a prior‘merge’ action, the data is combined with previous lookup results,as explained below.
If the status matches, proceed with the lookup process at the nextentry, discarding the result of the current lookup (and any mergeddata). An exception is the ‘initgroups’ database and the‘success’ status, where ‘continue’ acts likemerge
below.
Proceed with the lookup process, retaining the current lookup result.This action is useful only with the ‘success’ status. If asubsequent service lookup succeeds and has a matching ‘return’specification, the results are merged, the lookup process ends, and themerged results are returned to the application. If the following servicehas a matching ‘merge’ action, the lookup process continues,retaining the combined data from this and any previous lookups.
After amerge
action, errors from subsequent lookups are ignored,and the data gathered so far will be returned.
The ‘merge’ only applies to the ‘success’ status. It iscurrently implemented for the ‘group’ database and its groupmembers field, ‘gr_mem’. If specified for other databases, itcauses the lookup to fail (if thestatus matches).
When processing ‘merge’ for ‘group’ membership, the group GIDand name must be identical for both entries. If only one or the other isa match, the behavior is undefined.
If we have a line like
ethers: nisplus [NOTFOUND=return] db files
this is equivalent to
ethers: nisplus [SUCCESS=return NOTFOUND=return UNAVAIL=continue TRYAGAIN=continue] db [SUCCESS=return NOTFOUND=continue UNAVAIL=continue TRYAGAIN=continue] files
(except that it would have to be written on one line). The defaultvalue for the actions are normally what you want, and only need to bechanged in exceptional cases.
If the optional!
is placed before thestatus this meansthe following action is used for all statuses butstatus itself.I.e.,!
is negation as in the C language (and others).
Before we explain the exception which makes this action item necessaryone more remark: obviously it makes no sense to add another actionitem after thefiles
service. Since there is no other servicefollowing the actionalways isreturn
.
Now, why is this[NOTFOUND=return]
action useful? To understandthis we should know that thenisplus
service is oftencomplete; i.e., if an entry is not available in the NIS+ tables it isnot available anywhere else. This is what is expressed by this actionitem: it is useless to examine further services since they will not giveus a result.
The situation would be different if the NIS+ service is not availablebecause the machine is booting. In this case the return value of thelookup function is notnotfound
but insteadunavail
. Andas you can see in the complete form above: in this situation thedb
andfiles
services are used. Neat, isn’t it? Thesystem administrator need not pay special care for the time the systemis not completely ready to work (while booting or shutdown ornetwork problems).
Previous:Actions in the NSS configuration, Up:The NSS Configuration File [Contents][Index]
Finally a few more hints. The NSS implementation is not completelyhelpless if/etc/nsswitch.conf does not exist. Forall supported databases there is a default value so it should normallybe possible to get the system running even if the file is corrupted ormissing.
For thehosts
andnetworks
databases the default value isfiles dns
. I.e., local configuration will override the contentsof the domain name system (DNS).
Thepasswd
,group
, andshadow
databases wastraditionally handled in a special way. The appropriate files in the/etc directory were read but if an entry with a name startingwith a+
character was found NIS was used. This kind of lookupwas removed and now the default value for the services isfiles
.libnss_compat no longer depends on libnsl and can be used without NIS.
For all other databases the default value isfiles
.
A second point is that the user should try to optimize the lookupprocess. The different service have different response times.A simple file look up on a local file could be fast, but if the fileis long and the needed entry is near the end of the file this may takequite some time. In this case it might be better to use thedb
service which allows fast local access to large data sets.
Often the situation is that some global information like NIS must beused. So it is unavoidable to use service entries likenis
etc.But one should avoid slow services like this if possible.
Next:Extending NSS, Previous:The NSS Configuration File, Up:System Databases and Name Service Switch [Contents][Index]
Now it is time to describe what the modules look like. The functionscontained in a module are identified by their names. I.e., there is nojump table or the like. How this is done is of no interest here; thoseinterested in this topic should read about Dynamic Linking.
Next:The Interface of the Function in NSS Modules, Previous:NSS Module Internals, Up:NSS Module Internals [Contents][Index]
The name of each function consists of various parts:
_nss_service_function
service of course corresponds to the name of the module thisfunction is found in.4 Thefunction part is derivedfrom the interface function in the C library itself. If the user callsthe functiongethostbyname
and the service used isfiles
the function
_nss_files_gethostbyname_r
in the module
libnss_files.so.2
is used. You see, what is explained above in not the whole truth. Infact the NSS modules only contain reentrant versions of the lookupfunctions. I.e., if the user would call thegethostbyname_r
function this also would end in the above function. For all userinterface functions the C library maps this call to a call to thereentrant function. For reentrant functions this is trivial since theinterface is (nearly) the same. For the non-reentrant version thelibrary keeps internal buffers which are used to replace the usersupplied buffer.
I.e., the reentrant functionscan have counterparts. No servicemodule is forced to have functions for all databases and all kinds toaccess them. If a function is not available it is simply treated as ifthe function would returnunavail
(seeActions in the NSS configuration).
The file namelibnss_files.so.2 would be on a Solaris 2systemnss_files.so.2. This is the difference mentioned above.Sun’s NSS modules are usable as modules which get indirectly loadedonly.
The NSS modules in the GNU C Library are prepared to be used as normallibraries themselves. This isnot true at the moment, though.However, the organization of the name space in the modules does not make itimpossible like it is for Solaris. Now you can see why the modules arestill libraries.5
Previous:The Naming Scheme of the NSS Modules, Up:NSS Module Internals [Contents][Index]
Now we know about the functions contained in the modules. It is nowtime to describe the types. When we mentioned the reentrant versions ofthe functions above, this means there are some additional arguments(compared with the standard, non-reentrant versions). The prototypes forthe non-reentrant and reentrant versions of our function above are:
struct hostent *gethostbyname (const char *name)int gethostbyname_r (const char *name, struct hostent *result_buf, char *buf, size_t buflen, struct hostent **result, int *h_errnop)
The actual prototype of the function in the NSS modules in this case is
enum nss_status _nss_files_gethostbyname_r (const char *name, struct hostent *result_buf, char *buf, size_t buflen, int *errnop, int *h_errnop)
I.e., the interface function is in fact the reentrant function with thechange of the return value, the omission of theresult parameter,and the addition of theerrnop parameter. While the user-levelfunction returns a pointer to the result the reentrant function returnanenum nss_status
value:
NSS_STATUS_TRYAGAIN
¶numeric value-2
NSS_STATUS_UNAVAIL
¶numeric value-1
NSS_STATUS_NOTFOUND
¶numeric value0
NSS_STATUS_SUCCESS
¶numeric value1
Now you see where the action items of the/etc/nsswitch.conf fileare used.
If you study the source code you will find there is a fifth value:NSS_STATUS_RETURN
. This is an internal use only value, used by afew functions in places where none of the above value can be used. Ifnecessary the source code should be examined to learn about the details.
In case the interface function has to return an error it is importantthat the correct error code is stored in*errnop
. Somereturn status values have only one associated error code, others havemore.
NSS_STATUS_TRYAGAIN | EAGAIN | One of the functions used ran temporarily out ofresources or a service is currently not available. |
ERANGE | The provided buffer is not large enough.The function should be called again with a larger buffer. | |
NSS_STATUS_UNAVAIL | ENOENT | A necessary input file cannot be found. |
NSS_STATUS_NOTFOUND | ENOENT | The requested entry is not available. |
NSS_STATUS_NOTFOUND | SUCCESS | There are no entries.Use this to avoid returning errors for inactive services which maybe enabled at a later time. This is not the same as the servicebeing temporarily unavailable. |
These are proposed values. There can be other error codes and thedescribed error codes can have different meaning.With oneexception: when returningNSS_STATUS_TRYAGAIN
the error codeERANGE
must mean that the user provided buffer is toosmall. Everything else is non-critical.
In statically linked programs, the main application and NSS modules donot share the same thread-local variableerrno
, which is thereason why there is an expliciterrnop function argument.
The above function has something special which is missing for almost allthe other module functions. There is an argumenth_errnop. Thispoints to a variable which will be filled with the error code in casethe execution of the function fails for some reason. (In staticallylinked programs, the thread-local variableh_errno
is not sharedwith the main application.)
ThegetXXXbyYYY
functions are the most importantfunctions in the NSS modules. But there are others which implementthe other ways to access system databases (say for theuser database, there aresetpwent
,getpwent
, andendpwent
). These will be described in more detail later.Here we give a general way to determine thesignature of the module function:
enum nss_status
;STRUCT_TYPE *result_buf
pointer to buffer where the result is stored.STRUCT_TYPE
isnormally a struct which corresponds to the database.
char *buffer
pointer to a buffer where the function can store additional data forthe result etc.
size_t buflen
length of the buffer pointed to bybuffer.
int *errnop
the low-level error code to return to the application. If the returnvalue is notNSS_STATUS_SUCCESS
,*errnop
needs to beset to a non-zero value. An NSS module should never set*errnop
to zero. The valueERANGE
is special, asdescribed above.
NSS_STATUS_SUCCESS
,*h_errnop
needs to be set to anon-zero value. A generic error code isNETDB_INTERNAL
, whichinstructs the caller to examine*errnop
for furtherdetails. (This includes theERANGE
special case.)This table is correct for all functions but theset…ent
andend…ent
functions.
Previous:NSS Module Internals, Up:System Databases and Name Service Switch [Contents][Index]
One of the advantages of NSS mentioned above is that it can be extendedquite easily. There are two ways in which the extension can happen:adding another database or adding another service. The former isnormally done only by the C library developers. It ishere only important to remember that adding another database isindependent from adding another service because a service need notsupport all databases or lookup functions.
A designer/implementer of a new service is therefore free to choose thedatabases s/he is interested in and leave the rest for later (orcompletely aside).
Next:Internals of the NSS Module Functions, Previous:Extending NSS, Up:Extending NSS [Contents][Index]
The sources for a new service need not (and should not) be part of the GNU C Libraryitself. The developer retains complete control over thesources and its development. The links between the C library and thenew service module consists solely of the interface functions.
Each module is designed following a specific interface specification.For now the version is 2 (the interface in version 1 was not adequate)and this manifests in the version number of the shared library object ofthe NSS modules: they have the extension.2
. If the interfacechanges again in an incompatible way, this number will be increased.Modules using the old interface will still be usable.
Developers of a new service will have to make sure that their module iscreated using the correct interface number. This means the file itselfmust have the correct name and on ELF systems thesoname (SharedObject Name) must also have this number. Building a module from a bunchof object files on an ELF system using GNU CC could be done like this:
gcc -shared -o libnss_NAME.so.2 -Wl,-soname,libnss_NAME.so.2 OBJECTS
Options for Linking inGNU CC, to learnmore about this command line.
To use the new module the library must be able to find it. This can beachieved by using options for the dynamic linker so that it will searchthe directory where the binary is placed. For an ELF system this could bedone by adding the wanted directory to the value ofLD_LIBRARY_PATH
.
But this is not always possible since some programs (those which rununder IDs which do not belong to the user) ignore this variable.Therefore the stable version of the module should be placed into adirectory which is searched by the dynamic linker. Normally this shouldbe the directory$prefix/lib, where$prefix corresponds tothe value given to configure using the--prefix
option. But becareful: this should only be done if it is clear the module does notcause any harm. System administrators should be careful.
Previous:Adding another Service to NSS, Up:Extending NSS [Contents][Index]
Until now we only provided the syntactic interface for the functions inthe NSS module. In fact there is not much more we can say since theimplementation obviously is different for each function. But a fewgeneral rules must be followed by all functions.
In fact there are four kinds of different functions which may appear inthe interface. All derive from the traditional ones for system databases.db in the following table is normally an abbreviation for thedatabase (e.g., it ispw
for the user database).
enum nss_status _nss_database_setdbent (void)
This function prepares the service for following operations. For asimple file based lookup this means files could be opened, for otherservices this function simply is a noop.
One special case for this function is that it takes an additionalargument for somedatabases (i.e., the interface isint setdbent (int)
).Host Names, which describes thesethostent
function.
The return value should beNSS_STATUS_SUCCESS or according to thetable above in case of an error (seeThe Interface of the Function in NSS Modules).
enum nss_status _nss_database_enddbent (void)
This function simply closes all files which are still open or removesbuffer caches. If there are no files or buffers to remove this is againa simple noop.
There normally is no return value other thanNSS_STATUS_SUCCESS.
enum nss_status _nss_database_getdbent_r (STRUCTURE *result, char *buffer, size_t buflen, int *errnop)
Since this function will be called several times in a row to retrieveone entry after the other it must keep some kind of state. But thisalso means the functions are not really reentrant. They are reentrantonly in that simultaneous calls to this function will not try towrite the retrieved data in the same place (as it would be the case forthe non-reentrant functions); instead, it writes to the structurepointed to by theresult parameter. But the calls share a commonstate and in the case of a file access this means they return neighboringentries in the file.
The buffer of lengthbuflen pointed to bybuffer can be usedfor storing some additional data for the result. It isnotguaranteed that the same buffer will be passed for the next call of thisfunction. Therefore one must not misuse this buffer to save some stateinformation from one call to another.
Before the function returns with a failure code, the implementationshould store the value of the localerrno
variable in the variablepointed to beerrnop. This is important to guarantee the moduleworking in statically linked programs. The stored value must not bezero.
As explained above this function could also have an additional lastargument. This depends on the database used; it happens only forhost
andnetworks
.
The function shall returnNSS_STATUS_SUCCESS
as long as there aremore entries. When the last entry was read it should returnNSS_STATUS_NOTFOUND
. When the buffer given as an argument is toosmall for the data to be returnedNSS_STATUS_TRYAGAIN
should bereturned. When the service was not formerly initialized by a call to_nss_DATABASE_setdbent
all return values allowed forthis function can also be returned here.
enum nss_status _nss_DATABASE_getdbbyXX_r (PARAMS,STRUCTURE *result, char *buffer, size_t buflen, int *errnop)
This function shall return the entry from the database which isaddressed by thePARAMS. The type and number of these argumentsvary. It must be individually determined by looking to the user-levelinterface functions. All arguments given to the non-reentrant versionare here described byPARAMS.
The result must be stored in the structure pointed to byresult.If there are additional data to return (say strings, where theresult structure only contains pointers) the function must use thebuffer of lengthbuflen. There must not be any referencesto non-constant global data.
The implementation of this function should honor thestayopenflag set by thesetDBent
function whenever this makes sense.
Before the function returns, the implementation should store the value ofthe localerrno
variable in the variable pointed to byerrnop. This is important to guarantee the module works instatically linked programs.
Again, this function takes an additional last argument for thehost
andnetworks
database.
The return value should as always follow the rules given above(seeThe Interface of the Function in NSS Modules).
Next:System Management, Previous:System Databases and Name Service Switch, Up:Main Menu [Contents][Index]
Every user who can log in on the system is identified by a unique numbercalled theuser ID. Each process has an effective user ID whichsays which user’s access permissions it has.
Users are classified intogroups for access control purposes. Eachprocess has one or moregroup ID values which say which groups theprocess can use for access to files.
The effective user and group IDs of a process collectively form itspersona. This determines which files the process can access.Normally, a process inherits its persona from the parent process, butunder special circumstances a process can change its persona and thuschange its access permissions.
Each file in the system also has a user ID and a group ID. Accesscontrol works by comparing the user and group IDs of the file with thoseof the running process.
The system keeps a database of all the registered users, and anotherdatabase of all the defined groups. There are library functions youcan use to examine these databases.
Next:The Persona of a Process, Up:Users and Groups [Contents][Index]
Each user account on a computer system is identified by ausername (orlogin name) anduser ID. Normally, each user namehas a unique user ID, but it is possible for several login names to havethe same user ID. The user names and corresponding user IDs are storedin a data base which you can access as described inUser Database.
Users are classified ingroups. Each user name belongs to onedefault group and may also belong to any number ofsupplementary groups. Users who are members of the same group canshare resources (such as files) that are not accessible to users who arenot a member of that group. Each group has agroup name andgroup ID. SeeGroup Database, for how to find informationabout a group ID or group name.
Next:Why Change the Persona of a Process?, Previous:User and Group IDs, Up:Users and Groups [Contents][Index]
At any time, each process has aneffective user ID, aeffectivegroup ID, and a set ofsupplementary group IDs. These IDsdetermine the privileges of the process. They are collectivelycalled thepersona of the process, because they determine “who itis” for purposes of access control.
Your login shell starts out with a persona which consists of your userID, your default group ID, and your supplementary group IDs (if you arein more than one group). In normal circumstances, all your other processesinherit these values.
A process also has areal user ID which identifies the user whocreated the process, and areal group ID which identifies thatuser’s default group. These values do not play a role in accesscontrol, so we do not consider them part of the persona. But they arealso important.
Both the real and effective user ID can be changed during the lifetimeof a process. SeeWhy Change the Persona of a Process?.
For details on how a process’s effective user ID and group IDs affectits permission to access files, seeHow Your Access to a File is Decided.
The effective user ID of a process also controls permissions for sendingsignals using thekill
function. SeeSignaling Another Process.
Finally, there are many operations which can only be performed by aprocess whose effective user ID is zero. A process with this user ID isaprivileged process. Commonly the user nameroot
isassociated with user ID 0, but there may be other user names with thisID.
Next:How an Application Can Change Persona, Previous:The Persona of a Process, Up:Users and Groups [Contents][Index]
The most obvious situation where it is necessary for a process to changeits user and/or group IDs is thelogin
program. Whenlogin
starts running, its user ID isroot
. Its job is tostart a shell whose user and group IDs are those of the user who islogging in. (To accomplish this fully,login
must set the realuser and group IDs as well as its persona. But this is a special case.)
The more common case of changing persona is when an ordinary userprogram needs access to a resource that wouldn’t ordinarily beaccessible to the user actually running it.
For example, you may have a file that is controlled by your program butthat shouldn’t be read or modified directly by other users, eitherbecause it implements some kind of locking protocol, or because you wantto preserve the integrity or privacy of the information it contains.This kind of restricted access can be implemented by having the programchange its effective user or group ID to match that of the resource.
Thus, imagine a game program that saves scores in a file. The gameprogram itself needs to be able to update this file no matter who isrunning it, but if users can write the file without going through thegame, they can give themselves any scores they like. Some peopleconsider this undesirable, or even reprehensible. It can be preventedby creating a new user ID and login name (say,games
) to own thescores file, and make the file writable only by this user. Then, whenthe game program wants to update this file, it can change its effectiveuser ID to be that forgames
. In effect, the program mustadopt the persona ofgames
so it can write to the scores file.
Next:Reading the Persona of a Process, Previous:Why Change the Persona of a Process?, Up:Users and Groups [Contents][Index]
The ability to change the persona of a process can be a source ofunintentional privacy violations, or even intentional abuse. Because ofthe potential for problems, changing persona is restricted to specialcircumstances.
You can’t arbitrarily set your user ID or group ID to anything you want;only privileged processes can do that. Instead, the normal way for aprogram to change its persona is that it has been set up in advance tochange to a particular user or group. This is the function of the setuidand setgid bits of a file’s access mode. SeeThe Mode Bits for Access Permission.
When the setuid bit of an executable file is on, executing that filegives the process a third user ID: thefile user ID. This ID isset to the owner ID of the file. The system then changes the effectiveuser ID to the file user ID. The real user ID remains as it was.Likewise, if the setgid bit is on, the process is given afilegroup ID equal to the group ID of the file, and its effective group IDis changed to the file group ID.
If a process has a file ID (user or group), then it can at any timechange its effective ID to its real ID and back to its file ID.Programs use this feature to relinquish their special privileges exceptwhen they actually need them. This makes it less likely that they canbe tricked into doing something inappropriate with their privileges.
Portability Note: Older systems do not have file IDs.To determine if a system has this feature, you can test the compilerdefine_POSIX_SAVED_IDS
. (In the POSIX standard, file IDs areknown as saved IDs.)
SeeFile Attributes, for a more general discussion of file modes andaccessibility.
Next:Setting the User ID, Previous:How an Application Can Change Persona, Up:Users and Groups [Contents][Index]
Here are detailed descriptions of the functions for reading the user andgroup IDs of a process, both real and effective. To use thesefacilities, you must include the header filessys/types.h andunistd.h.
This is an integer data type used to represent user IDs. Inthe GNU C Library, this is an alias forunsigned int
.
This is an integer data type used to represent group IDs. Inthe GNU C Library, this is an alias forunsigned int
.
uid_t
getuid(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetuid
function returns the real user ID of the process.
gid_t
getgid(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetgid
function returns the real group ID of the process.
uid_t
geteuid(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegeteuid
function returns the effective user ID of the process.
gid_t
getegid(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetegid
function returns the effective group ID of the process.
int
getgroups(intcount, gid_t *groups)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thegetgroups
function is used to inquire about the supplementarygroup IDs of the process. Up tocount of these group IDs arestored in the arraygroups; the return value from the function isthe number of group IDs actually stored. Ifcount is smaller thanthe total number of supplementary group IDs, thengetgroups
returns a value of-1
anderrno
is set toEINVAL
.
Ifcount is zero, thengetgroups
just returns the totalnumber of supplementary group IDs. On systems that do not supportsupplementary groups, this will always be zero.
Here’s how to usegetgroups
to read all the supplementary groupIDs:
gid_t *read_all_groups (void){ int ngroups = getgroups (0, NULL); gid_t *groups = (gid_t *) xmalloc (ngroups * sizeof (gid_t)); int val = getgroups (ngroups, groups); if (val < 0) { free (groups); return NULL; } return groups;}
Next:Setting the Group IDs, Previous:Reading the Persona of a Process, Up:Users and Groups [Contents][Index]
This section describes the functions for altering the user ID (realand/or effective) of a process. To use these facilities, you mustinclude the header filessys/types.h andunistd.h.
int
seteuid(uid_tneweuid)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function sets the effective user ID of a process toneweuid,provided that the process is allowed to change its effective user ID. Aprivileged process (effective user ID zero) can change its effectiveuser ID to any legal value. An unprivileged process with a file user IDcan change its effective user ID to its real user ID or to its file userID. Otherwise, a process may not change its effective user ID at all.
Theseteuid
function returns a value of0
to indicatesuccessful completion, and a value of-1
to indicate an error.The followingerrno
error conditions are defined for thisfunction:
EINVAL
The value of theneweuid argument is invalid.
EPERM
The process may not change to the specified ID.
Older systems (those without the_POSIX_SAVED_IDS
feature) do nothave this function.
int
setuid(uid_tnewuid)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
If the calling process is privileged, this function sets both the realand effective user IDs of the process tonewuid. It also deletesthe file user ID of the process, if any.newuid may be anylegal value. (Once this has been done, there is no way to recover theold effective user ID.)
If the process is not privileged, and the system supports the_POSIX_SAVED_IDS
feature, then this function behaves likeseteuid
.
The return values and error conditions are the same as forseteuid
.
int
setreuid(uid_truid, uid_teuid)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function sets the real user ID of the process toruid and theeffective user ID toeuid. Ifruid is-1
, it meansnot to change the real user ID; likewise ifeuid is-1
, itmeans not to change the effective user ID.
Thesetreuid
function exists for compatibility with 4.3 BSD Unix,which does not support file IDs. You can use this function to swap theeffective and real user IDs of the process. (Privileged processes arenot limited to this particular usage.) If file IDs are supported, youshould use that feature instead of this function. SeeEnabling and Disabling Setuid Access.
The return value is0
on success and-1
on failure.The followingerrno
error conditions are defined for thisfunction:
EPERM
The process does not have the appropriate privileges; you do nothave permission to change to the specified ID.
Next:Enabling and Disabling Setuid Access, Previous:Setting the User ID, Up:Users and Groups [Contents][Index]
This section describes the functions for altering the group IDs (realand effective) of a process. To use these facilities, you must includethe header filessys/types.h andunistd.h.
int
setegid(gid_tnewgid)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function sets the effective group ID of the process tonewgid, provided that the process is allowed to change its groupID. Just as withseteuid
, if the process is privileged it maychange its effective group ID to any value; if it isn’t, but it has afile group ID, then it may change to its real group ID or file group ID;otherwise it may not change its effective group ID.
Note that a process is only privileged if its effectiveuser IDis zero. The effective group ID only affects access permissions.
The return values and error conditions forsetegid
are the sameas those forseteuid
.
This function is only present if_POSIX_SAVED_IDS
is defined.
int
setgid(gid_tnewgid)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function sets both the real and effective group ID of the processtonewgid, provided that the process is privileged. It alsodeletes the file group ID, if any.
If the process is not privileged, thensetgid
behaves likesetegid
.
The return values and error conditions forsetgid
are the sameas those forseteuid
.
int
setregid(gid_trgid, gid_tegid)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function sets the real group ID of the process torgid andthe effective group ID toegid. Ifrgid is-1
, itmeans not to change the real group ID; likewise ifegid is-1
, it means not to change the effective group ID.
Thesetregid
function is provided for compatibility with 4.3 BSDUnix, which does not support file IDs. You can use this function toswap the effective and real group IDs of the process. (Privilegedprocesses are not limited to this usage.) If file IDs are supported,you should use that feature instead of using this function.SeeEnabling and Disabling Setuid Access.
The return values and error conditions forsetregid
are the sameas those forsetreuid
.
setuid
andsetgid
behave differently depending on whetherthe effective user ID at the time is zero. If it is not zero, theybehave likeseteuid
andsetegid
. If it is, they changeboth effective and real IDs and delete the file ID. To avoid confusion,we recommend you always useseteuid
andsetegid
exceptwhen you know the effective user ID is zero and your intent is to changethe persona permanently. This case is rare—most of the programs thatneed it, such aslogin
andsu
, have already been written.
Note that if your program is setuid to some user other thanroot
,there is no way to drop privileges permanently.
The system also lets privileged processes change their supplementarygroup IDs. To usesetgroups
orinitgroups
, your programsshould include the header filegrp.h.
int
setgroups(size_tcount, const gid_t *groups)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function sets the process’s supplementary group IDs. It can onlybe called from privileged processes. Thecount argument specifiesthe number of group IDs in the arraygroups.
This function returns0
if successful and-1
on error.The followingerrno
error conditions are defined for thisfunction:
EPERM
The calling process is not privileged.
int
initgroups(const char *user, gid_tgroup)
¶Preliminary:| MT-Safe locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt mem fd lock| SeePOSIX Safety Concepts.
Theinitgroups
function sets the process’s supplementary groupIDs to be the normal default for the user nameuser. The groupgroup is automatically included.
This function works by scanning the group database for all the groupsuser belongs to. It then callssetgroups
with the list ithas constructed.
The return values and error conditions are the same as forsetgroups
.
If you are interested in the groups a particular user belongs to, but donot want to change the process’s supplementary group IDs, you can usegetgrouplist
. To usegetgrouplist
, your programs shouldinclude the header filegrp.h.
int
getgrouplist(const char *user, gid_tgroup, gid_t *groups, int *ngroups)
¶Preliminary:| MT-Safe locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt mem fd lock| SeePOSIX Safety Concepts.
Thegetgrouplist
function scans the group database for all thegroupsuser belongs to. Up to *ngroups group IDscorresponding to these groups are stored in the arraygroups; thereturn value from the function is the number of group IDs actuallystored. If *ngroups is smaller than the total number of groupsfound, thengetgrouplist
returns a value of-1
and storesthe actual number of groups in *ngroups. The groupgroup isautomatically included in the list of groups returned bygetgrouplist
.
Here’s how to usegetgrouplist
to read all supplementary groupsforuser:
gid_t *supplementary_groups (char *user){ int ngroups = 16; gid_t *groups = (gid_t *) xmalloc (ngroups * sizeof (gid_t)); struct passwd *pw = getpwnam (user); if (pw == NULL) return NULL; if (getgrouplist (pw->pw_name, pw->pw_gid, groups, &ngroups) < 0) { groups = xreallocarray (ngroups, sizeof *groups); getgrouplist (pw->pw_name, pw->pw_gid, groups, &ngroups); } return groups;}
Next:Setuid Program Example, Previous:Setting the Group IDs, Up:Users and Groups [Contents][Index]
A typical setuid program does not need its special access all of thetime. It’s a good idea to turn off this access when it isn’t needed,so it can’t possibly give unintended access.
If the system supports the_POSIX_SAVED_IDS
feature, you canaccomplish this withseteuid
. When the game program starts, itsreal user ID isjdoe
, its effective user ID isgames
, andits saved user ID is alsogames
. The program should record bothuser ID values once at the beginning, like this:
user_user_id = getuid ();game_user_id = geteuid ();
Then it can turn off game file access with
seteuid (user_user_id);
and turn it on with
seteuid (game_user_id);
Throughout this process, the real user ID remainsjdoe
and thefile user ID remainsgames
, so the program can always set itseffective user ID to either one.
On other systems that don’t support file user IDs, you canturn setuid access on and off by usingsetreuid
to swap the realand effective user IDs of the process, as follows:
setreuid (geteuid (), getuid ());
This special case is always allowed—it cannot fail.
Why does this have the effect of toggling the setuid access? Suppose agame program has just started, and its real user ID isjdoe
whileits effective user ID isgames
. In this state, the game canwrite the scores file. If it swaps the two uids, the real becomesgames
and the effective becomesjdoe
; now the program hasonlyjdoe
access. Another swap bringsgames
back tothe effective user ID and restores access to the scores file.
In order to handle both kinds of systems, test for the saved user IDfeature with a preprocessor conditional, like this:
#ifdef _POSIX_SAVED_IDS seteuid (user_user_id);#else setreuid (geteuid (), getuid ());#endif
Next:Tips for Writing Setuid Programs, Previous:Enabling and Disabling Setuid Access, Up:Users and Groups [Contents][Index]
Here’s an example showing how to set up a program that changes itseffective user ID.
This is part of a game program calledcaber-toss
that manipulatesa filescores that should be writable only by the game programitself. The program assumes that its executable file will be installedwith the setuid bit set and owned by the same user as thescoresfile. Typically, a system administrator will set up an account likegames
for this purpose.
The executable file is given mode4755
, so that doing an‘ls -l’ on it produces output like:
-rwsr-xr-x 1 games 184422 Jul 30 15:17 caber-toss
The setuid bit shows up in the file modes as the ‘s’.
The scores file is given mode644
, and doing an ‘ls -l’ onit shows:
-rw-r--r-- 1 games 0 Jul 31 15:33 scores
Here are the parts of the program that show how to set up the changeduser ID. This program is conditionalized so that it makes use of thefile IDs feature if it is supported, and otherwise usessetreuid
to swap the effective and real user IDs.
#include <stdio.h>#include <sys/types.h>#include <unistd.h>#include <stdlib.h>/*Remember the effective and real UIDs. */static uid_t euid, ruid;/*Restore the effective UID to its original value. */voiddo_setuid (void){ int status;#ifdef _POSIX_SAVED_IDS status = seteuid (euid);#else status = setreuid (ruid, euid);#endif if (status < 0) { fprintf (stderr, "Couldn't set uid.\n"); exit (status); }}
/*Set the effective UID to the real UID. */voidundo_setuid (void){ int status;#ifdef _POSIX_SAVED_IDS status = seteuid (ruid);#else status = setreuid (euid, ruid);#endif if (status < 0) { fprintf (stderr, "Couldn't set uid.\n"); exit (status); }}
/*Main program. */intmain (void){ /*Remember the real and effective user IDs. */ ruid = getuid (); euid = geteuid (); undo_setuid (); /*Do the game and record the score. */ ...}
Notice how the first thing themain
function does is to set theeffective user ID back to the real user ID. This is so that any otherfile accesses that are performed while the user is playing the game usethe real user ID for determining permissions. Only when the programneeds to open the scores file does it switch back to the file user ID,like this:
/*Record the score. */intrecord_score (int score){ FILE *stream; char *myname; /*Open the scores file. */ do_setuid (); stream = fopen (SCORES_FILE, "a"); undo_setuid ();
/*Write the score to the file. */ if (stream) { myname = cuserid (NULL); if (score < 0) fprintf (stream, "%10s: Couldn't lift the caber.\n", myname); else fprintf (stream, "%10s: %d feet.\n", myname, score); fclose (stream); return 0; } else return -1;}
Next:Identifying Who Logged In, Previous:Setuid Program Example, Up:Users and Groups [Contents][Index]
It is easy for setuid programs to give the user access that isn’tintended—in fact, if you want to avoid this, you need to be careful.Here are some guidelines for preventing unintended access andminimizing its consequences when it does occur:
setuid
programs with privileged user IDs such asroot
unless it is absolutely necessary. If the resource isspecific to your particular program, it’s better to define a new,nonprivileged user ID or group ID just to manage that resource.It’s better if you can write your program to use a special group than aspecial user.exec
functions in combination withchanging the effective user ID. Don’t let users of your program executearbitrary programs under a changed user ID. Executing a shell isespecially bad news. Less obviously, theexeclp
andexecvp
functions are a potential risk (since the program they execute dependson the user’sPATH
environment variable).If you mustexec
another program under a changed ID, specify anabsolute file name (seeFile Name Resolution) for the executable,and make sure that the protections on that executable andallcontaining directories are such that ordinary users cannot replace itwith some other program.
You should also check the arguments passed to the program to make surethey do not have unexpected effects. Likewise, you should examine theenvironment variables. Decide which arguments and variables are safe,and reject all others.
You should never usesystem
in a privileged program, because itinvokes a shell.
setuid
part of your program needs to access other filesbesides the controlled resource, it should verify that the real userwould ordinarily have permission to access those files. You can use theaccess
function (seeHow Your Access to a File is Decided) to check this; ituses the real user and group IDs, rather than the effective IDs.Next:The User Accounting Database, Previous:Tips for Writing Setuid Programs, Up:Users and Groups [Contents][Index]
You can use the functions listed in this section to determine the loginname of the user who is running a process, and the name of the user whologged in the current session. See also the functiongetuid
andfriends (seeReading the Persona of a Process). How this information is collected bythe system and how to control/add/remove information from the backgroundstorage is described inThe User Accounting Database.
Thegetlogin
function is declared inunistd.h, whilecuserid
andL_cuserid
are declared instdio.h.
char *
getlogin(void)
¶Preliminary:| MT-Unsafe race:getlogin race:utent sig:ALRM timer locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegetlogin
function returns a pointer to a string containing thename of the user logged in on the controlling terminal of the process,or a null pointer if this information cannot be determined. The stringis statically allocated and might be overwritten on subsequent calls tothis function or tocuserid
.
char *
cuserid(char *string)
¶Preliminary:| MT-Unsafe race:cuserid/!string locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thecuserid
function returns a pointer to a string containing auser name associated with the effective ID of the process. Ifstring is not a null pointer, it should be an array that can holdat leastL_cuserid
characters; the string is returned in thisarray. Otherwise, a pointer to a string in a static area is returned.This string is statically allocated and might be overwritten onsubsequent calls to this function or togetlogin
.
The use of this function is deprecated since it is marked to bewithdrawn in XPG4.2 and has already been removed from newer revisions ofPOSIX.1.
int
L_cuserid ¶An integer constant that indicates how long an array you might need tostore a user name.
These functions let your program identify positively the user who isrunning or the user who logged in this session. (These can differ whensetuid programs are involved; seeThe Persona of a Process.) The user cannotdo anything to fool these functions.
For most purposes, it is more useful to use the environment variableLOGNAME
to find out who the user is. This is more flexibleprecisely because the user can setLOGNAME
arbitrarily.SeeStandard Environment Variables.
Next:User Database, Previous:Identifying Who Logged In, Up:Users and Groups [Contents][Index]
Most Unix-like operating systems keep track of logged in users bymaintaining a user accounting database. This user accounting databasestores for each terminal, who has logged on, at what time, the processID of the user’s login shell, etc., etc., but also stores informationabout the run level of the system, the time of the last system reboot,and possibly more.
The user accounting database typically lives in/etc/utmp,/var/adm/utmp or/var/run/utmp. However, these filesshouldnever be accessed directly. For reading informationfrom and writing information to the user accounting database, thefunctions described in this section should be used.
These functions and the corresponding data structures are declared inthe header fileutmp.h.
Theexit_status
data structure is used to hold information aboutthe exit status of processes marked asDEAD_PROCESS
in the useraccounting database.
short int e_termination
The exit status of the process.
short int e_exit
The exit status of the process.
Theutmp
data structure is used to hold information about entriesin the user accounting database. On GNU systems it has the followingmembers:
short int ut_type
Specifies the type of login; one ofEMPTY
,RUN_LVL
,BOOT_TIME
,OLD_TIME
,NEW_TIME
,INIT_PROCESS
,LOGIN_PROCESS
,USER_PROCESS
,DEAD_PROCESS
orACCOUNTING
.
pid_t ut_pid
The process ID number of the login process.
char ut_line[]
The device name of the tty (without/dev/).
char ut_id[]
The inittab ID of the process.
char ut_user[]
The user’s login name.
char ut_host[]
The name of the host from which the user logged in.
struct exit_status ut_exit
The exit status of a process marked asDEAD_PROCESS
.
long ut_session
The Session ID, used for windowing.
struct timeval ut_tv
Time the entry was made. For entries of typeOLD_TIME
this isthe time when the system clock changed, and for entries of typeNEW_TIME
this is the time the system clock was set to.
int32_t ut_addr_v6[4]
The Internet address of a remote host.
Theut_type
,ut_pid
,ut_id
,ut_tv
, andut_host
fields are not available on all systems. Portableapplications therefore should be prepared for these situations. To helpdo this theutmp.h header provides macros_HAVE_UT_TYPE
,_HAVE_UT_PID
,_HAVE_UT_ID
,_HAVE_UT_TV
, and_HAVE_UT_HOST
if the respective field isavailable. The programmer can handle the situations by using#ifdef
in the program code.
The following macros are defined for use as values for theut_type
member of theutmp
structure. The values areinteger constants.
EMPTY
¶This macro is used to indicate that the entry contains no valid useraccounting information.
RUN_LVL
¶This macro is used to identify the system’s runlevel.
BOOT_TIME
¶This macro is used to identify the time of system boot.
OLD_TIME
¶This macro is used to identify the time when the system clock changed.
NEW_TIME
¶This macro is used to identify the time after the system clock changed.
INIT_PROCESS
¶This macro is used to identify a process spawned by the init process.
LOGIN_PROCESS
¶This macro is used to identify the session leader of a logged in user.
USER_PROCESS
¶This macro is used to identify a user process.
DEAD_PROCESS
¶This macro is used to identify a terminated process.
ACCOUNTING
¶???
The size of theut_line
,ut_id
,ut_user
andut_host
arrays can be found using thesizeof
operator.
Many older systems have, instead of anut_tv
member, anut_time
member, usually of typetime_t
, for representingthe time associated with the entry. Therefore, for backwardscompatibility only,utmp.h definesut_time
as an alias forut_tv.tv_sec
.
void
setutent(void)
¶Preliminary:| MT-Unsafe race:utent| AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
This function opens the user accounting database to begin scanning it.You can then callgetutent
,getutid
orgetutline
toread entries andpututline
to write entries.
If the database is already open, it resets the input to the beginning ofthe database.
struct utmp *
getutent(void)
¶Preliminary:| MT-Unsafe init race:utent race:utentbuf sig:ALRM timer| AS-Unsafe heap lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Thegetutent
function reads the next entry from the useraccounting database. It returns a pointer to the entry, which isstatically allocated and may be overwritten by subsequent calls togetutent
. You must copy the contents of the structure if youwish to save the information or you can use thegetutent_r
function which stores the data in a user-provided buffer.
A null pointer is returned in case no further entry is available.
void
endutent(void)
¶Preliminary:| MT-Unsafe race:utent| AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
This function closes the user accounting database.
struct utmp *
getutid(const struct utmp *id)
¶Preliminary:| MT-Unsafe init race:utent sig:ALRM timer| AS-Unsafe lock heap| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
This function searches forward from the current point in the databasefor an entry that matchesid. If theut_type
member of theid structure is one ofRUN_LVL
,BOOT_TIME
,OLD_TIME
orNEW_TIME
the entries match if theut_type
members are identical. If theut_type
member oftheid structure isINIT_PROCESS
,LOGIN_PROCESS
,USER_PROCESS
orDEAD_PROCESS
, the entries match if theut_type
member of the entry read from the database is one ofthese four, and theut_id
members match. However if theut_id
member of either theid structure or the entry readfrom the database is empty it checks if theut_line
members matchinstead. If a matching entry is found,getutid
returns a pointerto the entry, which is statically allocated, and may be overwritten by asubsequent call togetutent
,getutid
orgetutline
.You must copy the contents of the structure if you wish to save theinformation.
A null pointer is returned in case the end of the database is reachedwithout a match.
Thegetutid
function may cache the last read entry. Therefore,if you are usinggetutid
to search for multiple occurrences, itis necessary to zero out the static data after each call. Otherwisegetutid
could just return a pointer to the same entry over andover again.
struct utmp *
getutline(const struct utmp *line)
¶Preliminary:| MT-Unsafe init race:utent sig:ALRM timer| AS-Unsafe heap lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
This function searches forward from the current point in the databaseuntil it finds an entry whoseut_type
value isLOGIN_PROCESS
orUSER_PROCESS
, and whoseut_line
member matches theut_line
member of theline structure.If it finds such an entry, it returns a pointer to the entry which isstatically allocated, and may be overwritten by a subsequent call togetutent
,getutid
orgetutline
. You must copy thecontents of the structure if you wish to save the information.
A null pointer is returned in case the end of the database is reachedwithout a match.
Thegetutline
function may cache the last read entry. Thereforeif you are usinggetutline
to search for multiple occurrences, itis necessary to zero out the static data after each call. Otherwisegetutline
could just return a pointer to the same entry over andover again.
struct utmp *
pututline(const struct utmp *utmp)
¶Preliminary:| MT-Unsafe race:utent sig:ALRM timer| AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
Thepututline
function inserts the entry*utmp
atthe appropriate place in the user accounting database. If it finds thatit is not already at the correct place in the database, it usesgetutid
to search for the position to insert the entry, howeverthis will not modify the static structure returned bygetutent
,getutid
andgetutline
. If this search fails, the entryis appended to the database.
Thepututline
function returns a pointer to a copy of the entryinserted in the user accounting database, or a null pointer if the entrycould not be added. The followingerrno
error conditions aredefined for this function:
EPERM
The process does not have the appropriate privileges; you cannot modifythe user accounting database.
All theget*
functions mentioned before store the informationthey return in a static buffer. This can be a problem in multi-threadedprograms since the data returned for the request is overwritten by thereturn value data in another thread. Therefore the GNU C Libraryprovides as extensions three more functions which return the data in auser-provided buffer.
int
getutent_r(struct utmp *buffer, struct utmp **result)
¶Preliminary:| MT-Unsafe race:utent sig:ALRM timer| AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
Thegetutent_r
is equivalent to thegetutent
function. Itreturns the next entry from the database. But instead of storing theinformation in a static buffer it stores it in the buffer pointed to bythe parameterbuffer.
If the call was successful, the function returns0
and thepointer variable pointed to by the parameterresult contains apointer to the buffer which contains the result (this is most probablythe same value asbuffer). If something went wrong during theexecution ofgetutent_r
the function returns-1
.
This function is a GNU extension.
int
getutid_r(const struct utmp *id, struct utmp *buffer, struct utmp **result)
¶Preliminary:| MT-Unsafe race:utent sig:ALRM timer| AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
This function retrieves just likegetutid
the next entry matchingthe information stored inid. But the result is stored in thebuffer pointed to by the parameterbuffer.
If successful the function returns0
and the pointer variablepointed to by the parameterresult contains a pointer to thebuffer with the result (probably the same asresult. If notsuccessful the function return-1
.
This function is a GNU extension.
int
getutline_r(const struct utmp *line, struct utmp *buffer, struct utmp **result)
¶Preliminary:| MT-Unsafe race:utent sig:ALRM timer| AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
This function retrieves just likegetutline
the next entrymatching the information stored inline. But the result is storedin the buffer pointed to by the parameterbuffer.
If successful the function returns0
and the pointer variablepointed to by the parameterresult contains a pointer to thebuffer with the result (probably the same asresult. If notsuccessful the function return-1
.
This function is a GNU extension.
In addition to the user accounting database, most systems keep a numberof similar databases. For example most systems keep a log file with allprevious logins (usually in/etc/wtmp or/var/log/wtmp).
For specifying which database to examine, the following function shouldbe used.
int
utmpname(const char *file)
¶Preliminary:| MT-Unsafe race:utent| AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
Theutmpname
function changes the name of the database to beexamined tofile, and closes any previously opened database. Bydefaultgetutent
,getutid
,getutline
andpututline
read from and write to the user accounting database.
The following macros are defined for use as thefile argument:
char *
_PATH_UTMP ¶This macro is used to specify the user accounting database.
char *
_PATH_WTMP ¶This macro is used to specify the user accounting log file.
Theutmpname
function returns a value of0
if the new namewas successfully stored, and a value of-1
to indicate an error.Note thatutmpname
does not try to open the database, and thattherefore the return value does not say anything about whether thedatabase can be successfully opened.
Specially for maintaining log-like databases the GNU C Library providesthe following function:
void
updwtmp(const char *wtmp_file, const struct utmp *utmp)
¶Preliminary:| MT-Unsafe sig:ALRM timer| AS-Unsafe | AC-Unsafe fd| SeePOSIX Safety Concepts.
Theupdwtmp
function appends the entry *utmp to thedatabase specified bywtmp_file. For possible values for thewtmp_file argument see theutmpname
function.
Portability Note: Although many operating systems provide asubset of these functions, they are not standardized. There are oftensubtle differences in the return types, and there are considerabledifferences between the various definitions ofstruct utmp
. Whenprogramming for the GNU C Library, it is probably best to stickwith the functions described in this section. If however, you want yourprogram to be portable, consider using the XPG functions described inXPG User Accounting Database Functions, or take a look at the BSD compatible functions inLogging In and Out.
Next:Logging In and Out, Previous:Manipulating the User Accounting Database, Up:The User Accounting Database [Contents][Index]
These functions, described in the X/Open Portability Guide, are declaredin the header fileutmpx.h.
Theutmpx
data structure contains at least the following members:
short int ut_type
Specifies the type of login; one ofEMPTY
,RUN_LVL
,BOOT_TIME
,OLD_TIME
,NEW_TIME
,INIT_PROCESS
,LOGIN_PROCESS
,USER_PROCESS
orDEAD_PROCESS
.
pid_t ut_pid
The process ID number of the login process.
char ut_line[]
The device name of the tty (without/dev/).
char ut_id[]
The inittab ID of the process.
char ut_user[]
The user’s login name.
struct timeval ut_tv
Time the entry was made. For entries of typeOLD_TIME
this isthe time when the system clock changed, and for entries of typeNEW_TIME
this is the time the system clock was set to.
In the GNU C Library,struct utmpx
is identical tostructutmp
except for the fact that includingutmpx.h does not makevisible the declaration ofstruct exit_status
.
The following macros are defined for use as values for theut_type
member of theutmpx
structure. The values areinteger constants and are, in the GNU C Library, identical to thedefinitions inutmp.h.
EMPTY
¶This macro is used to indicate that the entry contains no valid useraccounting information.
RUN_LVL
¶This macro is used to identify the system’s runlevel.
BOOT_TIME
¶This macro is used to identify the time of system boot.
OLD_TIME
¶This macro is used to identify the time when the system clock changed.
NEW_TIME
¶This macro is used to identify the time after the system clock changed.
INIT_PROCESS
¶This macro is used to identify a process spawned by the init process.
LOGIN_PROCESS
¶This macro is used to identify the session leader of a logged in user.
USER_PROCESS
¶This macro is used to identify a user process.
DEAD_PROCESS
¶This macro is used to identify a terminated process.
The size of theut_line
,ut_id
andut_user
arrayscan be found using thesizeof
operator.
void
setutxent(void)
¶Preliminary:| MT-Unsafe race:utent| AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
This function is similar tosetutent
. In the GNU C Library it issimply an alias forsetutent
.
struct utmpx *
getutxent(void)
¶Preliminary:| MT-Unsafe init race:utent sig:ALRM timer| AS-Unsafe heap lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
Thegetutxent
function is similar togetutent
, but returnsa pointer to astruct utmpx
instead ofstruct utmp
. Inthe GNU C Library it simply is an alias forgetutent
.
void
endutxent(void)
¶Preliminary:| MT-Unsafe race:utent| AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This function is similar toendutent
. In the GNU C Library it issimply an alias forendutent
.
struct utmpx *
getutxid(const struct utmpx *id)
¶Preliminary:| MT-Unsafe init race:utent sig:ALRM timer| AS-Unsafe lock heap| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
This function is similar togetutid
, but usesstruct utmpx
instead ofstruct utmp
. In the GNU C Library it is simply an aliasforgetutid
.
struct utmpx *
getutxline(const struct utmpx *line)
¶Preliminary:| MT-Unsafe init race:utent sig:ALRM timer| AS-Unsafe heap lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
This function is similar togetutid
, but usesstruct utmpx
instead ofstruct utmp
. In the GNU C Library it is simply an aliasforgetutline
.
struct utmpx *
pututxline(const struct utmpx *utmp)
¶Preliminary:| MT-Unsafe race:utent sig:ALRM timer| AS-Unsafe lock| AC-Unsafe lock fd| SeePOSIX Safety Concepts.
Thepututxline
function is functionally identical topututline
, but usesstruct utmpx
instead ofstructutmp
. In the GNU C Library,pututxline
is simply an alias forpututline
.
int
utmpxname(const char *file)
¶Preliminary:| MT-Unsafe race:utent| AS-Unsafe lock heap| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
Theutmpxname
function is functionally identical toutmpname
. In the GNU C Library,utmpxname
is simply analias forutmpname
.
You can translate between a traditionalstruct utmp
and an XPGstruct utmpx
with the following functions. In the GNU C Library,these functions are merely copies, since the two structures areidentical.
int
getutmp(const struct utmpx *utmpx, struct utmp *utmp)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
getutmp
copies the information, insofar as the structures arecompatible, fromutmpx toutmp.
int
getutmpx(const struct utmp *utmp, struct utmpx *utmpx)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
getutmpx
copies the information, insofar as the structures arecompatible, fromutmp toutmpx.
These functions, derived from BSD, are available in the separatelibutil library, and declared inutmp.h.
Note that theut_user
member ofstruct utmp
is calledut_name
in BSD. Therefore,ut_name
is defined as an aliasforut_user
inutmp.h.
int
login_tty(intfiledes)
¶Preliminary:| MT-Unsafe race:ttyname| AS-Unsafe heap lock| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
This function makesfiledes the controlling terminal of thecurrent process, redirects standard input, standard output andstandard error output to this terminal, and closesfiledes.
This function returns0
on successful completion, and-1
on error.
void
login(const struct utmp *entry)
¶Preliminary:| MT-Unsafe race:utent sig:ALRM timer| AS-Unsafe lock heap| AC-Unsafe lock corrupt fd mem| SeePOSIX Safety Concepts.
Thelogin
functions inserts an entry into the user accountingdatabase. Theut_line
member is set to the name of the terminalon standard input. If standard input is not a terminallogin
uses standard output or standard error output to determine the name ofthe terminal. Ifstruct utmp
has aut_type
member,login
sets it toUSER_PROCESS
, and if there is anut_pid
member, it will be set to the process ID of the currentprocess. The remaining entries are copied fromentry.
A copy of the entry is written to the user accounting log file.
int
logout(const char *ut_line)
¶Preliminary:| MT-Unsafe race:utent sig:ALRM timer| AS-Unsafe lock heap| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
This function modifies the user accounting database to indicate that theuser onut_line has logged out.
Thelogout
function returns1
if the entry was successfullywritten to the database, or0
on error.
void
logwtmp(const char *ut_line, const char *ut_name, const char *ut_host)
¶Preliminary:| MT-Unsafe sig:ALRM timer| AS-Unsafe | AC-Unsafe fd| SeePOSIX Safety Concepts.
Thelogwtmp
function appends an entry to the user accounting logfile, for the current time and the information provided in theut_line,ut_name andut_host arguments.
Portability Note: The BSDstruct utmp
only has theut_line
,ut_name
,ut_host
andut_time
members. Older systems do not even have theut_host
member.
Next:Group Database, Previous:The User Accounting Database, Up:Users and Groups [Contents][Index]
This section describes how to search and scan the database of registeredusers. The database itself is kept in the file/etc/passwd onmost systems, but on some systems a special network server gives accessto it.
Historically, this database included one-way hashes of userpassphrases, as well as public information about each user(such as their user ID and full name). Many of the names offunctions and data structures associated with this database, and thefilename/etc/passwd itself, reflect this history. However,the information in this database is available to all users, and it isno longer considered safe to make passphrase hashes available to allusers, so they have been moved to a “shadow” database that can onlybe accessed with special privileges.
Next:Looking Up One User, Up:User Database [Contents][Index]
The functions and data structures for accessing the system user databaseare declared in the header filepwd.h.
Thepasswd
data structure is used to hold information aboutentries in the system user data base. It has at least the following members:
char *pw_name
The user’s login name.
char *pw_passwd
Historically, this field would hold the one-way hash of the user’spassphrase. Nowadays, it will almost always be the single character‘x’, indicating that the hash is in the shadow database.
uid_t pw_uid
The user ID number.
gid_t pw_gid
The user’s default group ID number.
char *pw_gecos
A string typically containing the user’s real name, and possibly otherinformation such as a phone number.
char *pw_dir
The user’s home directory, or initial working directory. This might bea null pointer, in which case the interpretation is system-dependent.
char *pw_shell
The user’s default shell, or the initial program run when the user logs in.This might be a null pointer, indicating that the system default shouldbe used.
Next:Scanning the List of All Users, Previous:The Data Structure that Describes a User, Up:User Database [Contents][Index]
You can search the system user database for information about aspecific user usinggetpwuid
orgetpwnam
. Thesefunctions are declared inpwd.h.
struct passwd *
getpwuid(uid_tuid)
¶Preliminary:| MT-Unsafe race:pwuid locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function returns a pointer to a statically-allocated structurecontaining information about the user whose user ID isuid. Thisstructure may be overwritten on subsequent calls togetpwuid
.
A null pointer value indicates there is no user in the data base withuser IDuid.
int
getpwuid_r(uid_tuid, struct passwd *result_buf, char *buffer, size_tbuflen, struct passwd **result)
¶Preliminary:| MT-Safe locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function is similar togetpwuid
in that it returnsinformation about the user whose user ID isuid. However, itfills the user supplied structure pointed to byresult_buf withthe information instead of using a static buffer. The firstbuflen bytes of the additional buffer pointed to bybufferare used to contain additional information, normally strings which arepointed to by the elements of the result structure.
If a user with IDuid is found, the pointer returned inresult points to the record which contains the wanted data (i.e.,result contains the valueresult_buf). If no user is foundor if an error occurred, the pointer returned inresult is a nullpointer. The function returns zero or an error code. If the bufferbuffer is too small to contain all the needed information, theerror codeERANGE
is returned anderrno
is set toERANGE
.
struct passwd *
getpwnam(const char *name)
¶Preliminary:| MT-Unsafe race:pwnam locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function returns a pointer to a statically-allocated structurecontaining information about the user whose user name isname.This structure may be overwritten on subsequent calls togetpwnam
.
A null pointer return indicates there is no user namedname.
int
getpwnam_r(const char *name, struct passwd *result_buf, char *buffer, size_tbuflen, struct passwd **result)
¶Preliminary:| MT-Safe locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function is similar togetpwnam
in that it returnsinformation about the user whose user name isname. However, likegetpwuid_r
, it fills the user supplied buffers inresult_buf andbuffer with the information instead of usinga static buffer.
The return values are the same as forgetpwuid_r
.
Next:Writing a User Entry, Previous:Looking Up One User, Up:User Database [Contents][Index]
This section explains how a program can read the list of all users inthe system, one user at a time. The functions described here aredeclared inpwd.h.
You can use thefgetpwent
function to read user entries from aparticular file.
struct passwd *
fgetpwent(FILE *stream)
¶Preliminary:| MT-Unsafe race:fpwent| AS-Unsafe corrupt lock| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
This function reads the next user entry fromstream and returns apointer to the entry. The structure is statically allocated and isrewritten on subsequent calls tofgetpwent
. You must copy thecontents of the structure if you wish to save the information.
The stream must correspond to a file in the same format as the standarduser database file.
int
fgetpwent_r(FILE *stream, struct passwd *result_buf, char *buffer, size_tbuflen, struct passwd **result)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
This function is similar tofgetpwent
in that it reads the nextuser entry fromstream. But the result is returned in thestructure pointed to byresult_buf. Thefirstbuflen bytes of the additional buffer pointed to bybuffer are used to contain additional information, normallystrings which are pointed to by the elements of the result structure.
The stream must correspond to a file in the same format as the standarduser database file.
If the function returns zeroresult points to the structure withthe wanted data (normally this is inresult_buf). If errorsoccurred the return value is nonzero andresult contains a nullpointer.
The way to scan all the entries in the user database is withsetpwent
,getpwent
, andendpwent
.
void
setpwent(void)
¶Preliminary:| MT-Unsafe race:pwent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function initializes a stream whichgetpwent
andgetpwent_r
use to read the user database.
struct passwd *
getpwent(void)
¶Preliminary:| MT-Unsafe race:pwent race:pwentbuf locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegetpwent
function reads the next entry from the streaminitialized bysetpwent
. It returns a pointer to the entry. Thestructure is statically allocated and is rewritten on subsequent callstogetpwent
. You must copy the contents of the structure if youwish to save the information.
A null pointer is returned when no more entries are available.
int
getpwent_r(struct passwd *result_buf, char *buffer, size_tbuflen, struct passwd **result)
¶Preliminary:| MT-Unsafe race:pwent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function is similar togetpwent
in that it returns the nextentry from the stream initialized bysetpwent
. Likefgetpwent_r
, it uses the user-supplied buffers inresult_buf andbuffer to return the information requested.
The return values are the same as forfgetpwent_r
.
void
endpwent(void)
¶Preliminary:| MT-Unsafe race:pwent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function closes the internal stream used bygetpwent
orgetpwent_r
.
Previous:Scanning the List of All Users, Up:User Database [Contents][Index]
int
putpwent(const struct passwd *p, FILE *stream)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt| AC-Unsafe lock corrupt| SeePOSIX Safety Concepts.
This function writes the user entry*p
to the streamstream, in the format used for the standard user databasefile. The return value is zero on success and nonzero on failure.
This function exists for compatibility with SVID. We recommend that youavoid using it, because it makes sense only on the assumption that thestruct passwd
structure has no members except the standard ones;on a system which merges the traditional Unix data base with otherextended information about users, adding an entry using this functionwould inevitably leave out much of the important information.
The group and user ID fields are left empty if the group or user namestarts with a - or +.
The functionputpwent
is declared inpwd.h.
Next:User and Group Database Example, Previous:User Database, Up:Users and Groups [Contents][Index]
This section describes how to search and scan the database ofregistered groups. The database itself is kept in the file/etc/group on most systems, but on some systems a special networkservice provides access to it.
Next:Looking Up One Group, Up:Group Database [Contents][Index]
The functions and data structures for accessing the system groupdatabase are declared in the header filegrp.h.
Thegroup
structure is used to hold information about an entry inthe system group database. It has at least the following members:
char *gr_name
The name of the group.
gid_t gr_gid
The group ID of the group.
char **gr_mem
A vector of pointers to the names of users in the group. Each user nameis a null-terminated string, and the vector itself is terminated by anull pointer.
Next:Scanning the List of All Groups, Previous:The Data Structure for a Group, Up:Group Database [Contents][Index]
You can search the group database for information about a specificgroup usinggetgrgid
orgetgrnam
. These functions aredeclared ingrp.h.
struct group *
getgrgid(gid_tgid)
¶Preliminary:| MT-Unsafe race:grgid locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function returns a pointer to a statically-allocated structurecontaining information about the group whose group ID isgid.This structure may be overwritten by subsequent calls togetgrgid
.
A null pointer indicates there is no group with IDgid.
int
getgrgid_r(gid_tgid, struct group *result_buf, char *buffer, size_tbuflen, struct group **result)
¶Preliminary:| MT-Safe locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function is similar togetgrgid
in that it returnsinformation about the group whose group ID isgid. However, itfills the user supplied structure pointed to byresult_buf withthe information instead of using a static buffer. The firstbuflen bytes of the additional buffer pointed to bybufferare used to contain additional information, normally strings which arepointed to by the elements of the result structure.
If a group with IDgid is found, the pointer returned inresult points to the record which contains the wanted data (i.e.,result contains the valueresult_buf). If no group is foundor if an error occurred, the pointer returned inresult is a nullpointer. The function returns zero or an error code. If the bufferbuffer is too small to contain all the needed information, theerror codeERANGE
is returned anderrno
is set toERANGE
.
struct group *
getgrnam(const char *name)
¶Preliminary:| MT-Unsafe race:grnam locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function returns a pointer to a statically-allocated structurecontaining information about the group whose group name isname.This structure may be overwritten by subsequent calls togetgrnam
.
A null pointer indicates there is no group namedname.
int
getgrnam_r(const char *name, struct group *result_buf, char *buffer, size_tbuflen, struct group **result)
¶Preliminary:| MT-Safe locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function is similar togetgrnam
in that it returnsinformation about the group whose group name isname. Likegetgrgid_r
, it uses the user supplied buffers inresult_buf andbuffer, not a static buffer.
The return values are the same as forgetgrgid_r
.
Previous:Looking Up One Group, Up:Group Database [Contents][Index]
This section explains how a program can read the list of all groups inthe system, one group at a time. The functions described here aredeclared ingrp.h.
You can use thefgetgrent
function to read group entries from aparticular file.
struct group *
fgetgrent(FILE *stream)
¶Preliminary:| MT-Unsafe race:fgrent| AS-Unsafe corrupt lock| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
Thefgetgrent
function reads the next entry fromstream.It returns a pointer to the entry. The structure is staticallyallocated and is overwritten on subsequent calls tofgetgrent
. Youmust copy the contents of the structure if you wish to save theinformation.
The stream must correspond to a file in the same format as the standardgroup database file.
int
fgetgrent_r(FILE *stream, struct group *result_buf, char *buffer, size_tbuflen, struct group **result)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt lock| SeePOSIX Safety Concepts.
This function is similar tofgetgrent
in that it reads the nextuser entry fromstream. But the result is returned in thestructure pointed to byresult_buf. The firstbuflen bytesof the additional buffer pointed to bybuffer are used to containadditional information, normally strings which are pointed to by theelements of the result structure.
This stream must correspond to a file in the same format as the standardgroup database file.
If the function returns zeroresult points to the structure withthe wanted data (normally this is inresult_buf). If errorsoccurred the return value is non-zero andresult contains a nullpointer.
The way to scan all the entries in the group database is withsetgrent
,getgrent
, andendgrent
.
void
setgrent(void)
¶Preliminary:| MT-Unsafe race:grent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function initializes a stream for reading from the group data base.You use this stream by callinggetgrent
orgetgrent_r
.
struct group *
getgrent(void)
¶Preliminary:| MT-Unsafe race:grent race:grentbuf locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
Thegetgrent
function reads the next entry from the streaminitialized bysetgrent
. It returns a pointer to the entry. Thestructure is statically allocated and is overwritten on subsequent callstogetgrent
. You must copy the contents of the structure if youwish to save the information.
int
getgrent_r(struct group *result_buf, char *buffer, size_tbuflen, struct group **result)
¶Preliminary:| MT-Unsafe race:grent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function is similar togetgrent
in that it returns the nextentry from the stream initialized bysetgrent
. Likefgetgrent_r
, it places the result in user-supplied bufferspointed to byresult_buf andbuffer.
If the function returns zeroresult contains a pointer to the data(normally equal toresult_buf). If errors occurred the returnvalue is non-zero andresult contains a null pointer.
void
endgrent(void)
¶Preliminary:| MT-Unsafe race:grent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function closes the internal stream used bygetgrent
orgetgrent_r
.
Next:Netgroup Database, Previous:Group Database, Up:Users and Groups [Contents][Index]
Here is an example program showing the use of the system database inquiryfunctions. The program prints some information about the user runningthe program.
#include <grp.h>#include <pwd.h>#include <sys/types.h>#include <unistd.h>#include <stdlib.h>intmain (void){ uid_t me; struct passwd *my_passwd; struct group *my_group; char **members; /*Get information about the user ID. */ me = getuid (); my_passwd = getpwuid (me); if (!my_passwd) { printf ("Couldn't find out about user %d.\n", (int) me); exit (EXIT_FAILURE); } /*Print the information. */ printf ("I am %s.\n", my_passwd->pw_gecos); printf ("My login name is %s.\n", my_passwd->pw_name); printf ("My uid is %d.\n", (int) (my_passwd->pw_uid)); printf ("My home directory is %s.\n", my_passwd->pw_dir); printf ("My default shell is %s.\n", my_passwd->pw_shell); /*Get information about the default group ID. */ my_group = getgrgid (my_passwd->pw_gid); if (!my_group) { printf ("Couldn't find out about group %d.\n", (int) my_passwd->pw_gid); exit (EXIT_FAILURE); } /*Print the information. */ printf ("My default group is %s (%d).\n", my_group->gr_name, (int) (my_passwd->pw_gid)); printf ("The members of this group are:\n"); members = my_group->gr_mem; while (*members) { printf (" %s\n", *(members)); members++; } return EXIT_SUCCESS;}
Here is some output from this program:
I am Throckmorton Snurd.My login name is snurd.My uid is 31093.My home directory is /home/fsg/snurd.My default shell is /bin/sh.My default group is guest (12).The members of this group are: friedman tami
Previous:User and Group Database Example, Up:Users and Groups [Contents][Index]
Next:Looking up one Netgroup, Up:Netgroup Database [Contents][Index]
Sometimes it is useful to group users according to other criteria(seeGroup Database). E.g., it is useful to associate a certaingroup of users with a certain machine. On the other hand grouping ofhost names is not supported so far.
In Sun Microsystems’ SunOS appeared a new kind of database, the netgroupdatabase. It allows grouping hosts, users, and domains freely, givingthem individual names. To be more concrete, a netgroup is a list of triplesconsisting of a host name, a user name, and a domain name where any ofthe entries can be a wildcard entry matching all inputs. A lastpossibility is that names of other netgroups can also be given in thelist specifying a netgroup. So one can construct arbitrary hierarchieswithout loops.
Sun’s implementation allows netgroups only for thenis
ornisplus
service, seeServices in the NSS configuration File. Theimplementation in the GNU C Library has no such restriction. An entryin either of the input services must have the following form:
groupname (groupname |(
hostname,
username,
domainname
)
)+
Any of the fields in the triple can be empty which means anythingmatches. While describing the functions we will see that the oppositecase is useful as well. I.e., there may be entries which will notmatch any input. For entries like this, a name consisting of the singlecharacter-
shall be used.
Next:Testing for Netgroup Membership, Previous:Netgroup Data, Up:Netgroup Database [Contents][Index]
The lookup functions for netgroups are a bit different than all othersystem database handling functions. Since a single netgroup can containmany entries a two-step process is needed. First a single netgroup isselected and then one can iterate over all entries in this netgroup.These functions are declared innetdb.h.
int
setnetgrent(const char *netgroup)
¶Preliminary:| MT-Unsafe race:netgrent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
A call to this function initializes the internal state of the library toallow following calls ofgetnetgrent
to iterate over all entriesin the netgroup with namenetgroup.
When the call is successful (i.e., when a netgroup with this name exists)the return value is1
. When the return value is0
nonetgroup of this name is known or some other error occurred.
It is important to remember that there is only one single state foriterating the netgroups. Even if the programmer uses thegetnetgrent_r
function the result is not really reentrant sincealways only one single netgroup at a time can be processed. If theprogram needs to process more than one netgroup simultaneously shemust protect this by using external locking. This problem wasintroduced in the original netgroups implementation in SunOS and sincewe must stay compatible it is not possible to change this.
Some other functions also use the netgroups state. Currently these aretheinnetgr
function and parts of the implementation of thecompat
service part of the NSS implementation.
int
getnetgrent(char **hostp, char **userp, char **domainp)
¶Preliminary:| MT-Unsafe race:netgrent race:netgrentbuf locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function returns the next unprocessed entry of the currentlyselected netgroup. The string pointers, in which addresses are passed inthe argumentshostp,userp, anddomainp, will containafter a successful call pointers to appropriate strings. If the stringin the next entry is empty the pointer has the valueNULL
.The returned string pointers are only valid if none of the netgrouprelated functions are called.
The return value is1
if the next entry was successfully read. Avalue of0
means no further entries exist or internal errors occurred.
int
getnetgrent_r(char **hostp, char **userp, char **domainp, char *buffer, size_tbuflen)
¶Preliminary:| MT-Unsafe race:netgrent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function is similar togetnetgrent
with only one exception:the strings the three string pointershostp,userp, anddomainp point to, are placed in the buffer ofbuflen bytesstarting atbuffer. This means the returned values are valideven after other netgroup related functions are called.
The return value is1
if the next entry was successfully read andthe buffer contains enough room to place the strings in it.0
isreturned in case no more entries are found, the buffer is too small, orinternal errors occurred.
This function is a GNU extension. The original implementation in theSunOS libc does not provide this function.
void
endnetgrent(void)
¶Preliminary:| MT-Unsafe race:netgrent| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function frees all buffers which were allocated to process the lastselected netgroup. As a result all string pointers returned by callstogetnetgrent
are invalid afterwards.
Previous:Looking up one Netgroup, Up:Netgroup Database [Contents][Index]
It is often not necessary to scan the whole netgroup since often theonly interesting question is whether a given entry is part of theselected netgroup.
int
innetgr(const char *netgroup, const char *host, const char *user, const char *domain)
¶Preliminary:| MT-Unsafe race:netgrent locale| AS-Unsafe dlopen plugin heap lock| AC-Unsafe corrupt lock fd mem| SeePOSIX Safety Concepts.
This function tests whether the triple specified by the parametershost,user, anddomain is part of the netgroupnetgroup. Using this function has the advantage that
set
/get
/endnetgrent
functions.Any of the pointershost,user, ordomain can beNULL
which means any value is accepted in this position. This isalso true for the name-
which should not match any other stringotherwise.
The return value is1
if an entry matching the given triple isfound in the netgroup. The return value is0
if the netgroupitself is not found, the netgroup does not contain the triple orinternal errors occurred.
Next:System Configuration Parameters, Previous:Users and Groups, Up:Main Menu [Contents][Index]
This chapter describes facilities for controlling the system thatunderlies a process (including the operating system and hardware) andfor getting information about it. Anyone can generally use theinformational facilities, but usually only a properly privileged processcan make changes.
To get information on parameters of the system that are built into thesystem, such as the maximum length of a filename,System Configuration Parameters.
Next:Platform Type Identification, Up:System Management [Contents][Index]
This section explains how to identify the particular system on which yourprogram is running. First, let’s review the various ways computer systemsare named, which is a little complicated because of the history of thedevelopment of the Internet.
Every Unix system (also known as a host) has a host name, whether it’sconnected to a network or not. In its simplest form, as used beforecomputer networks were an issue, it’s just a word like ‘chicken’.
But any system attached to the Internet or any network like it conformsto a more rigorous naming convention as part of the Domain Name System(DNS). In the DNS, every host name is composed of two parts:
You will note that “hostname” looks a lot like “host name”, but isnot the same thing, and that people often incorrectly refer to entirehost names as “domain names.”
In the DNS, the full host name is properly called the FQDN (Fully QualifiedDomain Name) and consists of the hostname, then a period, then thedomain name. The domain name itself usually has multiple componentsseparated by periods. So for example, a system’s hostname may be‘chicken’ and its domain name might be ‘ai.mit.edu’, soits FQDN (which is its host name) is ‘chicken.ai.mit.edu’.
Adding to the confusion, though, is that the DNS is not the only name spacein which a computer needs to be known. Another name space is theNIS (aka YP) name space. For NIS purposes, there is another domainname, which is called the NIS domain name or the YP domain name. Itneed not have anything to do with the DNS domain name.
Confusing things even more is the fact that in the DNS, it is possible formultiple FQDNs to refer to the same system. However, there is alwaysexactly one of them that is the true host name, and it is called thecanonical FQDN.
In some contexts, the host name is called a “node name.”
For more information on DNS host naming, seeHost Names.
Prototypes for these functions appear inunistd.h.
The programshostname
,hostid
, anddomainname
workby calling these functions.
int
gethostname(char *name, size_tsize)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the host name of the system on which it is called,in the arrayname. Thesize argument specifies the size ofthis array, in bytes. Note that this isnot the DNS hostname.If the system participates in the DNS, this is the FQDN (see above).
The return value is0
on success and-1
on failure. Inthe GNU C Library,gethostname
fails ifsize is not largeenough; then you can try again with a larger array. The followingerrno
error condition is defined for this function:
ENAMETOOLONG
Thesize argument is less than the size of the host name plus one.
On some systems, there is a symbol for the maximum possible host namelength:MAXHOSTNAMELEN
. It is defined insys/param.h.But you can’t count on this to exist, so it is cleaner to handlefailure and try again.
gethostname
stores the beginning of the host name innameeven if the host name won’t entirely fit. For some purposes, atruncated host name is good enough. If it is, you can ignore theerror code.
int
sethostname(const char *name, size_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Thesethostname
function sets the host name of the system thatcalls it toname, a string with lengthlength. Onlyprivileged processes are permitted to do this.
Usuallysethostname
gets called just once, at system boot time.Often, the program that calls it sets it to the value it finds in thefile/etc/hostname
.
Be sure to set the host name to the full host name, not just the DNShostname (see above).
The return value is0
on success and-1
on failure.The followingerrno
error condition is defined for this function:
EPERM
This process cannot set the host name because it is not privileged.
int
getdomainnname(char *name, size_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
getdomainname
returns the NIS (aka YP) domain name of the systemon which it is called. Note that this is not the more popular DNSdomain name. Get that withgethostname
.
The specifics of this function are analogous togethostname
, above.
int
setdomainname(const char *name, size_tlength)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
setdomainname
sets the NIS (aka YP) domain name of the systemon which it is called. Note that this is not the more popular DNSdomain name. Set that withsethostname
.
The specifics of this function are analogous tosethostname
, above.
long int
gethostid(void)
¶Preliminary:| MT-Safe hostid env locale| AS-Unsafe dlopen plugin corrupt heap lock| AC-Unsafe lock corrupt mem fd| SeePOSIX Safety Concepts.
This function returns the “host ID” of the machine the program isrunning on. By convention, this is usually the primary Internet IP addressof that machine, converted to along int
. However, on somesystems it is a meaningless but unique number which is hard-coded foreach machine.
This is not widely used. It arose in BSD 4.2, but was dropped in BSD 4.4.It is not required by POSIX.
The proper way to query the IP address is to usegethostbyname
on the results ofgethostname
. For more information on IP addresses,SeeHost Addresses.
int
sethostid(long intid)
¶Preliminary:| MT-Unsafe const:hostid| AS-Unsafe | AC-Unsafe corrupt fd| SeePOSIX Safety Concepts.
Thesethostid
function sets the “host ID” of the host machinetoid. Only privileged processes are permitted to do this. Usuallyit happens just once, at system boot time.
The proper way to establish the primary IP address of a systemis to configure the IP address resolver to associate that IP address withthe system’s host name as returned bygethostname
. For example,put a record for the system in/etc/hosts.
Seegethostid
above for more information on host ids.
The return value is0
on success and-1
on failure.The followingerrno
error conditions are defined for this function:
EPERM
This process cannot set the host name because it is not privileged.
ENOSYS
The operating system does not support setting the host ID. On somesystems, the host ID is a meaningless but unique number hard-coded foreach machine.
Next:Controlling and Querying Mounts, Previous:Host Identification, Up:System Management [Contents][Index]
You can use theuname
function to find out some information aboutthe type of computer your program is running on. This function and theassociated data type are declared in the header filesys/utsname.h.
As a bonus,uname
also gives some information identifying theparticular system your program is running on. This is the same informationwhich you can get with functions targeted to this purpose described inHost Identification.
Theutsname
structure is used to hold information returnedby theuname
function. It has the following members:
char sysname[]
This is the name of the operating system in use.
char release[]
This is the current release level of the operating system implementation.
char version[]
This is the current version level within the release of the operatingsystem.
char machine[]
This is a description of the type of hardware that is in use.
Some systems provide a mechanism to interrogate the kernel directly forthis information. On systems without such a mechanism, the GNU C Libraryfills in this field based on the configuration name that wasspecified when building and installing the library.
GNU uses a three-part name to describe a system configuration; the threeparts arecpu,manufacturer andsystem-type, and theyare separated with dashes. Any possible combination of three names ispotentially meaningful, but most such combinations are meaningless inpractice and even the meaningful ones are not necessarily supported byany particular GNU program.
Since the value inmachine
is supposed to describe just thehardware, it consists of the first two parts of the configuration name:‘cpu-manufacturer’. For example, it might be one of these:
"sparc-sun"
,"i386-anything"
,"m68k-hp"
,"m68k-sony"
,"m68k-sun"
,"mips-dec"
char nodename[]
This is the host name of this particular computer. In the GNU C Library,the value is the same as that returned bygethostname
;seeHost Identification.
gethostname
is implemented with a call touname
.
char domainname[]
This is the NIS or YP domain name. It is the same value returned bygetdomainname
; seeHost Identification. This elementis a relatively recent invention and use of it is not as portable asuse of the rest of the structure.
int
uname(struct utsname *info)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theuname
function fills in the structure pointed to byinfo with information about the operating system and host machine.A non-negative return value indicates that the data was successfully stored.
-1
as the return value indicates an error. The only error possible isEFAULT
, which we normally don’t mention as it is always apossibility.
Previous:Platform Type Identification, Up:System Management [Contents][Index]
All files are in filesystems, and before you can access any file, itsfilesystem must be mounted. Because of Unix’s concept ofEverything is a file, mounting of filesystems is central to doingalmost anything. This section explains how to find out what filesystemsare currently mounted and what filesystems are available for mounting,and how to change what is mounted.
The classic filesystem is the contents of a disk drive. The concept isconsiderably more abstract, though, and lots of things other than diskdrives can be mounted.
Some block devices don’t correspond to traditional devices like diskdrives. For example, a loop device is a block device whose driver usesa regular file in another filesystem as its medium. So if that regularfile contains appropriate data for a filesystem, you can by mounting theloop device essentially mount a regular file.
Some filesystems aren’t based on a device of any kind. The “proc”filesystem, for example, contains files whose data is made up by thefilesystem driver on the fly whenever you ask for it. And when youwrite to it, the data you write causes changes in the system. No datagets stored.
For some programs it is desirable and necessary to access informationabout whether a certain filesystem is mounted and, if it is, where, orsimply to get lists of all the available filesystems. The GNU C Libraryprovides some functions to retrieve this information portably.
Traditionally Unix systems have a file named/etc/fstab whichdescribes all possibly mounted filesystems. Themount
programuses this file to mount at startup time of the system all thenecessary filesystems. The information about all the filesystemsactually mounted is normally kept in a file named either/var/run/mtab or/etc/mtab. Both files share the samesyntax and it is crucial that this syntax is followed all the time.Therefore it is best to never directly write to the files. The functionsdescribed in this section can do this and they also provide thefunctionality to convert the external textual representation to theinternal representation.
Note that thefstab andmtab files are maintained on asystem byconvention. It is possible for the files not to existor not to be consistent with what is really mounted or available tomount, if the system’s administration policy allows it. But programsthat mount and unmount filesystems typically maintain and use thesefiles as described herein.
The filenames given above should never be used directly. The portableway to handle these files is to use the macros_PATH_FSTAB
,defined infstab.h, or_PATH_MNTTAB
, defined inmntent.h andpaths.h, forfstab; and the macro_PATH_MOUNTED
, also defined inmntent.h andpaths.h, formtab. There are also two alternate macronamesFSTAB
,MNTTAB
, andMOUNTED
defined butthese names are deprecated and kept only for backward compatibility.The names_PATH_MNTTAB
and_PATH_MOUNTED
should always be used.
Next:Themtab file, Up:Mount Information [Contents][Index]
The internal representation for entries of the file isstruct fstab
, defined infstab.h.
This structure is used with thegetfsent
,getfsspec
, andgetfsfile
functions.
char *fs_spec
This element describes the device from which the filesystem is mounted.Normally this is the name of a special device, such as a hard diskpartition, but it could also be a more or less generic string. ForNFS it would be a hostname and directory name combination.
Even though the element is not declaredconst
it shouldn’t bemodified. The missingconst
has historic reasons, since thisfunction predates ISO C. The same is true for the other stringelements of this structure.
char *fs_file
This describes the mount point on the local system. I.e., accessing anyfile in this filesystem has implicitly or explicitly this string as aprefix.
char *fs_vfstype
This is the type of the filesystem. Depending on what the underlyingkernel understands it can be any string.
char *fs_mntops
This is a string containing options passed to the kernel with themount
call. Again, this can be almost anything. There can bemore than one option, separated from the others by a comma. Each optionconsists of a name and an optional value part, introduced by an=
character.
If the value of this element must be processed it should ideally be doneusing thegetsubopt
function; seeParsing of Suboptions.
const char *fs_type
This name is poorly chosen. This element points to a string (possiblyin thefs_mntops
string) which describes the modes with which thefilesystem is mounted.fstab defines five macros to describe thepossible values:
FSTAB_RW
¶The filesystem gets mounted with read and write enabled.
FSTAB_RQ
¶The filesystem gets mounted with read and write enabled. Write accessis restricted by quotas.
FSTAB_RO
¶The filesystem gets mounted read-only.
FSTAB_SW
¶This is not a real filesystem, it is a swap device.
FSTAB_XX
¶This entry from thefstab file is totally ignored.
Testing for equality with these values must happen usingstrcmp
since these are all strings. Comparing the pointer will probably alwaysfail.
int fs_freq
This element describes the dump frequency in days.
int fs_passno
This element describes the pass number on parallel dumps. It is closelyrelated to thedump
utility used on Unix systems.
To read the entire content of the of thefstab file the GNU C Librarycontains a set of three functions which are designed in the usual way.
int
setfsent(void)
¶Preliminary:| MT-Unsafe race:fsent| AS-Unsafe heap corrupt lock| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
This function makes sure that the internal read pointer for thefstab file is at the beginning of the file. This is done byeither opening the file or resetting the read pointer.
Since the file handle is internal to the libc this function is notthread-safe.
This function returns a non-zero value if the operation was successfuland thegetfs*
functions can be used to read the entries of thefile.
void
endfsent(void)
¶Preliminary:| MT-Unsafe race:fsent| AS-Unsafe heap corrupt lock| AC-Unsafe corrupt lock mem fd| SeePOSIX Safety Concepts.
This function makes sure that all resources acquired by a prior call tosetfsent
(explicitly or implicitly by callinggetfsent
) arefreed.
struct fstab *
getfsent(void)
¶Preliminary:| MT-Unsafe race:fsent locale| AS-Unsafe corrupt heap lock| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
This function returns the next entry of thefstab file. If thisis the first call to any of the functions handlingfstab sinceprogram start or the last call ofendfsent
, the file will beopened.
The function returns a pointer to a variable of typestructfstab
. This variable is shared by all threads and therefore thisfunction is not thread-safe. If an error occurredgetfsent
returns aNULL
pointer.
struct fstab *
getfsspec(const char *name)
¶Preliminary:| MT-Unsafe race:fsent locale| AS-Unsafe corrupt heap lock| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
This function returns the next entry of thefstab file which hasa string equal toname pointed to by thefs_spec
element.Since there is normally exactly one entry for each special device itmakes no sense to call this function more than once for the sameargument. If this is the first call to any of the functions handlingfstab since program start or the last call ofendfsent
,the file will be opened.
The function returns a pointer to a variable of typestructfstab
. This variable is shared by all threads and therefore thisfunction is not thread-safe. If an error occurredgetfsent
returns aNULL
pointer.
struct fstab *
getfsfile(const char *name)
¶Preliminary:| MT-Unsafe race:fsent locale| AS-Unsafe corrupt heap lock| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
This function returns the next entry of thefstab file which hasa string equal toname pointed to by thefs_file
element.Since there is normally exactly one entry for each mount point itmakes no sense to call this function more than once for the sameargument. If this is the first call to any of the functions handlingfstab since program start or the last call ofendfsent
,the file will be opened.
The function returns a pointer to a variable of typestructfstab
. This variable is shared by all threads and therefore thisfunction is not thread-safe. If an error occurredgetfsent
returns aNULL
pointer.
Next:Other (Non-libc) Sources of Mount Information, Previous:Thefstab file, Up:Mount Information [Contents][Index]
The following functions and data structure access themtab file.
This structure is used with thegetmntent
,getmntent_r
,addmntent
, andhasmntopt
functions.
char *mnt_fsname
This element contains a pointer to a string describing the name of thespecial device from which the filesystem is mounted. It corresponds tothefs_spec
element instruct fstab
.
char *mnt_dir
This element points to a string describing the mount point of thefilesystem. It corresponds to thefs_file
element instruct fstab
.
char *mnt_type
mnt_type
describes the filesystem type and is thereforeequivalent tofs_vfstype
instruct fstab
.mntent.hdefines a few symbolic names for some of the values this string can have.But since the kernel can support arbitrary filesystems it does notmake much sense to give them symbolic names. If one knows the symbolname one also knows the filesystem name. Nevertheless here follows thelist of the symbols provided inmntent.h.
MNTTYPE_IGNORE
¶This symbol expands to"ignore"
. The value is sometimes used infstab files to make sure entries are not used without removing them.
MNTTYPE_NFS
¶Expands to"nfs"
. Using this macro sometimes could make sensesince it names the default NFS implementation, in case both version 2and 3 are supported.
MNTTYPE_SWAP
¶This symbol expands to"swap"
. It names the specialfstabentry which names one of the possibly multiple swap partitions.
char *mnt_opts
The element contains a string describing the options used while mountingthe filesystem. As for the equivalent elementfs_mntops
ofstruct fstab
it is best to use the functiongetsubopt
(seeParsing of Suboptions) to access the parts of this string.
Themntent.h file defines a number of macros with string valueswhich correspond to some of the options understood by the kernel. Theremight be many more options which are possible so it doesn’t make much senseto rely on these macros but to be consistent here is the list:
MNTOPT_DEFAULTS
¶Expands to"defaults"
. This option should be used alone since itindicates all values for the customizable values are chosen to be thedefault.
MNTOPT_RO
¶Expands to"ro"
. See theFSTAB_RO
value, it means thefilesystem is mounted read-only.
MNTOPT_RW
¶Expands to"rw"
. See theFSTAB_RW
value, it means thefilesystem is mounted with read and write permissions.
MNTOPT_SUID
¶Expands to"suid"
. This means that the SUID bit (seeHow an Application Can Change Persona) is respected when a program from the filesystem isstarted.
MNTOPT_NOSUID
¶Expands to"nosuid"
. This is the opposite ofMNTOPT_SUID
,the SUID bit for all files from the filesystem is ignored.
MNTOPT_NOAUTO
¶Expands to"noauto"
. At startup time themount
programwill ignore this entry if it is started with the-a
option tomount all filesystems mentioned in thefstab file.
As for theFSTAB_*
entries introduced above it is important tousestrcmp
to check for equality.
mnt_freq
This elements corresponds tofs_freq
and also specifies thefrequency in days in which dumps are made.
mnt_passno
This element is equivalent tofs_passno
with the same meaningwhich is uninteresting for all programs besidedump
.
For accessing themtab file there is again a set of threefunctions to access all entries in a row. Unlike the functions tohandlefstab these functions do not access a fixed file and thereis even a thread safe variant of the get function. Besides this the GNU C Librarycontains functions to alter the file and test for specific options.
FILE *
setmntent(const char *file, const char *mode)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe mem fd lock| SeePOSIX Safety Concepts.
Thesetmntent
function prepares the file namedFILE whichmust be in the format of afstab andmtab file for theupcoming processing through the other functions of the family. Themode parameter can be chosen in the way theopentypeparameter forfopen
(seeOpening Streams) can be chosen. Ifthe file is opened for writing the file is also allowed to be empty.
If the file was successfully openedsetmntent
returns a filehandle for future use. Otherwise the return value isNULL
anderrno
is set accordingly.
int
endmntent(FILE *stream)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
This function takes for thestream parameter a file handle whichpreviously was returned from thesetmntent
call.endmntent
closes the stream and frees all resources.
The return value is1 unless an error occurred in which case itis0.
struct mntent *
getmntent(FILE *stream)
¶Preliminary:| MT-Unsafe race:mntentbuf locale| AS-Unsafe corrupt heap init| AC-Unsafe init corrupt lock mem| SeePOSIX Safety Concepts.
Thegetmntent
function takes as the parameter a file handlepreviously returned by a successful call tosetmntent
. It returnsa pointer to a static variable of typestruct mntent
which isfilled with the information from the next entry from the file currentlyread.
The file format used prescribes the use of spaces or tab characters toseparate the fields. This makes it harder to use names containing oneof these characters (e.g., mount points using spaces). Thereforethese characters are encoded in the files and thegetmntent
function takes care of the decoding while reading the entries back in.'\040'
is used to encode a space character,'\011'
toencode a tab character,'\012'
to encode a newline character,and'\\'
to encode a backslash.
If there was an error or the end of the file is reached the return valueisNULL
.
This function is not thread-safe since all calls to this function returna pointer to the same static variable.getmntent_r
should beused in situations where multiple threads access the file.
struct mntent *
getmntent_r(FILE *stream, struct mntent *result, char *buffer, intbufsize)
¶Preliminary:| MT-Safe locale| AS-Unsafe corrupt heap| AC-Unsafe corrupt lock mem| SeePOSIX Safety Concepts.
Thegetmntent_r
function is the reentrant variant ofgetmntent
. It also returns the next entry from the file andreturns a pointer. The actual variable the values are stored in is notstatic, though. Instead the function stores the values in the variablepointed to by theresult parameter. Additional information (e.g.,the strings pointed to by the elements of the result) are kept in thebuffer of sizebufsize pointed to bybuffer.
Escaped characters (space, tab, backslash) are converted back in thesame way as it happens forgetmentent
.
The function returns aNULL
pointer in error cases. Errors could be:
int
addmntent(FILE *stream, const struct mntent *mnt)
¶Preliminary:| MT-Safe race:stream locale| AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theaddmntent
function allows adding a new entry to the filepreviously opened withsetmntent
. The new entries are alwaysappended. I.e., even if the position of the file descriptor is not atthe end of the file this function does not overwrite an existing entryfollowing the current position.
The implication of this is that to remove an entry from a file one hasto create a new file while leaving out the entry to be removed and afterclosing the file remove the old one and rename the new file to thechosen name.
This function takes care of spaces and tab characters in the names to bewritten to the file. It converts them and the backslash character intothe format described in thegetmntent
description above.
This function returns0 in case the operation was successful.Otherwise the return value is1 anderrno
is setappropriately.
char *
hasmntopt(const struct mntent *mnt, const char *opt)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function can be used to check whether the string pointed to by themnt_opts
element of the variable pointed to bymnt containsthe optionopt. If this is true a pointer to the beginning of theoption in themnt_opts
element is returned. If no such optionexists the function returnsNULL
.
This function is useful to test whether a specific option is present butwhen all options have to be processed one is better off with using thegetsubopt
function to iterate over all options in the string.
Previous:Themtab file, Up:Mount Information [Contents][Index]
On a system with a Linux kernel and theproc
filesystem, you canget information on currently mounted filesystems from the filemounts in theproc
filesystem. Its format is similar tothat of themtab file, but represents what is truly mountedwithout relying on facilities outside the kernel to keepmtab upto date.
Previous:Mount Information, Up:Controlling and Querying Mounts [Contents][Index]
This section describes the functions for mounting, unmounting, andremounting filesystems.
Only the superuser can mount, unmount, or remount a filesystem.
These functions do not access thefstab andmtab files. Youshould maintain and use these separately. SeeMount Information.
The symbols in this section are declared insys/mount.h.
int
mount(const char *special_file, const char *dir, const char *fstype, unsigned long intoptions, const void *data)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
mount
mounts or remounts a filesystem. The two operations arequite different and are merged rather unnaturally into this one function.TheMS_REMOUNT
option, explained below, determines whethermount
mounts or remounts.
For a mount, the filesystem on the block device represented by thedevice special file namedspecial_file gets mounted over the mountpointdir. This means that the directorydir (along with anyfiles in it) is no longer visible; in its place (and still with the namedir) is the root directory of the filesystem on the device.
As an exception, if the filesystem type (see below) is one which is notbased on a device (e.g. “proc”),mount
instantiates afilesystem and mounts it overdir and ignoresspecial_file.
For a remount,dir specifies the mount point where the filesystemto be remounted is (and remains) mounted andspecial_file isignored. Remounting a filesystem means changing the options that controloperations on the filesystem while it is mounted. It does not meanunmounting and mounting again.
For a mount, you must identify the type of the filesystem withfstype. This type tells the kernel how to access the filesystemand can be thought of as the name of a filesystem driver. Theacceptable values are system dependent. On a system with a Linux kerneland theproc
filesystem, the list of possible values is in thefilefilesystems in theproc
filesystem (e.g. typecat /proc/filesystems to see the list). With a Linux kernel, thetypes of filesystems thatmount
can mount, and their type names,depends on what filesystem drivers are configured into the kernel orloaded as loadable kernel modules. An example of a common value forfstype isext2
.
For a remount,mount
ignoresfstype.
options specifies a variety of options that apply until thefilesystem is unmounted or remounted. The precise meaning of an optiondepends on the filesystem and with some filesystems, an option may haveno effect at all. Furthermore, for some filesystems, some of theseoptions (but neverMS_RDONLY
) can be overridden for individualfile accesses viaioctl
.
options is a bit string with bit fields defined using thefollowing mask and masked value macros:
MS_MGC_MASK
¶This multibit field contains a magic number. If it does not have the valueMS_MGC_VAL
,mount
assumes all the following bits are zero andthedata argument is a null string, regardless of their actual values.
MS_REMOUNT
¶This bit on means to remount the filesystem. Off means to mount it.
MS_RDONLY
¶This bit on specifies that no writing to the filesystem shall be allowedwhile it is mounted. This cannot be overridden byioctl
. Thisoption is available on nearly all filesystems.
MS_NOSUID
¶This bit on specifies that Setuid and Setgid permissions on files in thefilesystem shall be ignored while it is mounted.
MS_NOEXEC
¶This bit on specifies that no files in the filesystem shall be executedwhile the filesystem is mounted.
MS_NODEV
¶This bit on specifies that no device special files in the filesystemshall be accessible while the filesystem is mounted.
MS_SYNCHRONOUS
¶This bit on specifies that all writes to the filesystem while it ismounted shall be synchronous; i.e., data shall be synced before eachwrite completes rather than held in the buffer cache.
MS_MANDLOCK
¶This bit on specifies that mandatory locks on files shall be permitted whilethe filesystem is mounted.
MS_NOATIME
¶This bit on specifies that access times of files shall not be updated whenthe files are accessed while the filesystem is mounted.
MS_NODIRATIME
¶This bit on specifies that access times of directories shall not be updatedwhen the directories are accessed while the filesystem in mounted.
Any bits not covered by the above masks should be set off; otherwise,results are undefined.
The meaning ofdata depends on the filesystem type and is controlledentirely by the filesystem driver in the kernel.
Example:
#include <sys/mount.h>mount("/dev/hdb", "/cdrom", "iso9660", MS_MGC_VAL | MS_RDONLY | MS_NOSUID, "");mount("/dev/hda2", "/mnt", "", MS_MGC_VAL | MS_REMOUNT, "");
Appropriate arguments formount
are conventionally recorded inthefstab table. SeeMount Information.
The return value is zero if the mount or remount is successful. Otherwise,it is-1
anderrno
is set appropriately. The values oferrno
are filesystem dependent, but here is a general list:
EPERM
The process is not superuser.
ENODEV
The file system typefstype is not known to the kernel.
ENOTBLK
The filedev is not a block device special file.
EBUSY
EINVAL
EACCES
MS_RDONLY
bit off).MS_NODEV
option.EM_FILE
The table of dummy devices is full.mount
needs to create adummy device (aka “unnamed” device) if the filesystem being mounted isnot one that uses a device.
int
umount2(const char *file, intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
umount2
unmounts a filesystem.
You can identify the filesystem to unmount either by the device specialfile that contains the filesystem or by the mount point. The effect isthe same. Specify either as the stringfile.
flags contains the one-bit field identified by the followingmask macro:
MNT_FORCE
¶This bit on means to force the unmounting even if the filesystem isbusy, by making it unbusy first. If the bit is off and the filesystem isbusy,umount2
fails witherrno
=EBUSY
. Dependingon the filesystem, this may override all, some, or no busy conditions.
All other bits inflags should be set to zero; otherwise, the resultis undefined.
Example:
#include <sys/mount.h>umount2("/mnt", MNT_FORCE);umount2("/dev/hdd1", 0);
After the filesystem is unmounted, the directory that was the mount pointis visible, as are any files in it.
As part of unmounting,umount2
syncs the filesystem.
If the unmounting is successful, the return value is zero. Otherwise, itis-1
anderrno
is set accordingly:
EPERM
The process is not superuser.
EBUSY
The filesystem cannot be unmounted because it is busy. E.g. it containsa directory that is some process’s working directory or a file that someprocess has open. With some filesystems in some cases, you can avoidthis failure with theMNT_FORCE
option.
EINVAL
file validly refers to a file, but that file is neither a mountpoint nor a device special file of a currently mounted filesystem.
This function is not available on all systems.
int
umount(const char *file)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
umount
does the same thing asumount2
withflags setto zeroes. It is more widely available thanumount2
but since itlacks the possibility to forcefully unmount a filesystem is deprecatedwhenumount2
is also available.
Next:Cryptographic Functions, Previous:System Management, Up:Main Menu [Contents][Index]
The functions and macros listed in this chapter give information aboutconfiguration parameters of the operating system—for example, capacitylimits, presence of optional POSIX features, and the default path forexecutable files (seeString-Valued Parameters).
sysconf
pathconf
The POSIX.1 and POSIX.2 standards specify a number of parameters thatdescribe capacity limitations of the system. These limits can be fixedconstants for a given operating system, or they can vary from machine tomachine. For example, some limit values may be configurable by thesystem administrator, either at run time or by rebuilding the kernel,and this should not require recompiling application programs.
Each of the following limit parameters has a macro that is defined inlimits.h only if the system has a fixed, uniform limit for theparameter in question. If the system allows different file systems orfiles to have different limits, then the macro is undefined; usesysconf
to find out the limit that applies at a particular timeon a particular machine. SeeUsingsysconf
.
Each of these parameters also has another macro, with a name startingwith ‘_POSIX’, which gives the lowest value that the limit isallowed to have onany POSIX system. SeeMinimum Values for General Capacity Limits.
int
ARG_MAX ¶If defined, the unvarying maximum combined length of theargv andenviron arguments that can be passed to theexec
functions.
int
CHILD_MAX ¶If defined, the unvarying maximum number of processes that can existwith the same real user ID at any one time. In BSD and GNU, this iscontrolled by theRLIMIT_NPROC
resource limit; seeLimiting Resource Usage.
int
OPEN_MAX ¶If defined, the unvarying maximum number of files that a single processcan have open simultaneously. In BSD and GNU, this is controlledby theRLIMIT_NOFILE
resource limit; seeLimiting Resource Usage.
int
STREAM_MAX ¶If defined, the unvarying maximum number of streams that a singleprocess can have open simultaneously. SeeOpening Streams.
int
TZNAME_MAX ¶If defined, the unvarying maximum length of a time zone abbreviation.SeeSpecifying the Time Zone withTZ
.
These limit macros are always defined inlimits.h.
int
NGROUPS_MAX ¶The maximum number of supplementary group IDs that one process can have.
The value of this macro is actually a lower bound for the maximum. Thatis, you can count on being able to have that many supplementary groupIDs, but a particular machine might let you have even more. You can usesysconf
to see whether a particular machine will let you havemore (seeUsingsysconf
).
ssize_t
SSIZE_MAX ¶The largest value that can fit in an object of typessize_t
.Effectively, this is the limit on the number of bytes that can be reador written in a single operation.
This macro is defined in all POSIX systems because this limit is neverconfigurable.
int
RE_DUP_MAX ¶The largest number of repetitions you are guaranteed is allowed in theconstruct ‘\{min,max\}’ in a regular expression.
The value of this macro is actually a lower bound for the maximum. Thatis, you can count on being able to have that many repetitions, but aparticular machine might let you have even more. You can usesysconf
to see whether a particular machine will let you havemore (seeUsingsysconf
). And even the value thatsysconf
tellsyou is just a lower bound—larger values might work.
This macro is defined in all POSIX.2 systems, because POSIX.2 says itshould always be defined even if there is no specific imposed limit.
Next:Which Version of POSIX is Supported, Previous:General Capacity Limits, Up:System Configuration Parameters [Contents][Index]
POSIX defines certain system-specific options that not all POSIX systemssupport. Since these options are provided in the kernel, not in thelibrary, simply using the GNU C Library does not guarantee any of thesefeatures are supported; it depends on the system you are using.
You can test for the availability of a given option using the macros inthis section, together with the functionsysconf
. The macros aredefined only if you includeunistd.h.
For the following macros, if the macro is defined inunistd.h,then the option is supported. Otherwise, the option may or may not besupported; usesysconf
to find out. SeeUsingsysconf
.
int
_POSIX_JOB_CONTROL ¶If this symbol is defined, it indicates that the system supports jobcontrol. Otherwise, the implementation behaves as if all processeswithin a session belong to a single process group. SeeJob Control.Systems conforming to the 2001 revision of POSIX, or newer, willalways define this symbol.
int
_POSIX_SAVED_IDS ¶If this symbol is defined, it indicates that the system remembers theeffective user and group IDs of a process before it executes anexecutable file with the set-user-ID or set-group-ID bits set, and thatexplicitly changing the effective user or group IDs back to these valuesis permitted. If this option is not defined, then if a nonprivilegedprocess changes its effective user or group ID to the real user or groupID of the process, it can’t change it back again. SeeEnabling and Disabling Setuid Access.
For the following macros, if the macro is defined inunistd.h,then its value indicates whether the option is supported. A value of-1
means no, and any other value means yes. If the macro is notdefined, then the option may or may not be supported; usesysconf
to find out. SeeUsingsysconf
.
int
_POSIX2_C_DEV ¶If this symbol is defined, it indicates that the system has the POSIX.2C compiler command,c89
. The GNU C Library always defines thisas1
, on the assumption that you would not have installed it ifyou didn’t have a C compiler.
int
_POSIX2_FORT_DEV ¶If this symbol is defined, it indicates that the system has the POSIX.2Fortran compiler command,fort77
. The GNU C Library neverdefines this, because we don’t know what the system has.
int
_POSIX2_FORT_RUN ¶If this symbol is defined, it indicates that the system has the POSIX.2asa
command to interpret Fortran carriage control. The GNU C Librarynever defines this, because we don’t know what the system has.
int
_POSIX2_LOCALEDEF ¶If this symbol is defined, it indicates that the system has the POSIX.2localedef
command. The GNU C Library never defines this, becausewe don’t know what the system has.
int
_POSIX2_SW_DEV ¶If this symbol is defined, it indicates that the system has the POSIX.2commandsar
,make
, andstrip
. The GNU C Libraryalways defines this as1
, on the assumption that you had to havear
andmake
to install the library, and it’s unlikely thatstrip
would be absent when those are present.
Next:Usingsysconf
, Previous:Overall System Options, Up:System Configuration Parameters [Contents][Index]
long int
_POSIX_VERSION ¶This constant represents the version of the POSIX.1 standard to whichthe implementation conforms. For an implementation conforming to the1995 POSIX.1 standard, the value is the integer199506L
.
_POSIX_VERSION
is always defined (inunistd.h) in anyPOSIX system.
Usage Note: Don’t try to test whether the system supports POSIXby includingunistd.h and then checking whether_POSIX_VERSION
is defined. On a non-POSIX system, this willprobably fail because there is nounistd.h. We do not know ofany way you can reliably test at compilation time whether yourtarget system supports POSIX or whetherunistd.h exists.
long int
_POSIX2_C_VERSION ¶This constant represents the version of the POSIX.2 standard which thelibrary and system kernel support. We don’t know what value this willbe for the first version of the POSIX.2 standard, because the value isbased on the year and month in which the standard is officially adopted.
The value of this symbol says nothing about the utilities installed onthe system.
Usage Note: You can use this macro to tell whether a POSIX.1system library supports POSIX.2 as well. Any POSIX.1 system containsunistd.h, so include that file and then testdefined(_POSIX2_C_VERSION)
.
Next:Minimum Values for General Capacity Limits, Previous:Which Version of POSIX is Supported, Up:System Configuration Parameters [Contents][Index]
sysconf
¶When your system has configurable system limits, you can use thesysconf
function to find out the value that applies to anyparticular machine. The function and the associatedparameterconstants are declared in the header fileunistd.h.
Next:Constants forsysconf
Parameters, Up:Usingsysconf
[Contents][Index]
sysconf
¶long int
sysconf(intparameter)
¶Preliminary:| MT-Safe env| AS-Unsafe lock heap| AC-Unsafe lock mem fd| SeePOSIX Safety Concepts.
This function is used to inquire about runtime system parameters. Theparameter argument should be one of the ‘_SC_’ symbols listedbelow.
The normal return value fromsysconf
is the value you requested.A value of-1
is returned both if the implementation does notimpose a limit, and in case of an error.
The followingerrno
error conditions are defined for this function:
EINVAL
The value of theparameter is invalid.
Next:Examples ofsysconf
, Previous:Definition ofsysconf
, Up:Usingsysconf
[Contents][Index]
sysconf
Parameters ¶Here are the symbolic constants for use as theparameter argumenttosysconf
. The values are all integer constants (morespecifically, enumeration type values).
_SC_ARG_MAX
¶Inquire about the parameter corresponding toARG_MAX
.
_SC_CHILD_MAX
¶Inquire about the parameter corresponding toCHILD_MAX
.
_SC_OPEN_MAX
¶Inquire about the parameter corresponding toOPEN_MAX
.
_SC_STREAM_MAX
¶Inquire about the parameter corresponding toSTREAM_MAX
.
_SC_TZNAME_MAX
¶Inquire about the parameter corresponding toTZNAME_MAX
.
_SC_NGROUPS_MAX
¶Inquire about the parameter corresponding toNGROUPS_MAX
.
_SC_JOB_CONTROL
¶Inquire about the parameter corresponding to_POSIX_JOB_CONTROL
.
_SC_SAVED_IDS
¶Inquire about the parameter corresponding to_POSIX_SAVED_IDS
.
_SC_VERSION
¶Inquire about the parameter corresponding to_POSIX_VERSION
.
_SC_CLK_TCK
¶Inquire about the number of clock ticks per second; seeCPU Time Inquiry.The corresponding parameterCLK_TCK
is obsolete.
_SC_CHARCLASS_NAME_MAX
¶Inquire about the parameter corresponding to maximal length allowed fora character class name in an extended locale specification. Theseextensions are not yet standardized and so this option is not standardizedas well.
_SC_REALTIME_SIGNALS
¶Inquire about the parameter corresponding to_POSIX_REALTIME_SIGNALS
.
_SC_PRIORITY_SCHEDULING
¶Inquire about the parameter corresponding to_POSIX_PRIORITY_SCHEDULING
.
_SC_TIMERS
¶Inquire about the parameter corresponding to_POSIX_TIMERS
.
_SC_ASYNCHRONOUS_IO
¶Inquire about the parameter corresponding to_POSIX_ASYNCHRONOUS_IO
.
_SC_PRIORITIZED_IO
¶Inquire about the parameter corresponding to_POSIX_PRIORITIZED_IO
.
_SC_SYNCHRONIZED_IO
¶Inquire about the parameter corresponding to_POSIX_SYNCHRONIZED_IO
.
_SC_FSYNC
¶Inquire about the parameter corresponding to_POSIX_FSYNC
.
_SC_MAPPED_FILES
¶Inquire about the parameter corresponding to_POSIX_MAPPED_FILES
.
_SC_MEMLOCK
¶Inquire about the parameter corresponding to_POSIX_MEMLOCK
.
_SC_MEMLOCK_RANGE
¶Inquire about the parameter corresponding to_POSIX_MEMLOCK_RANGE
.
_SC_MEMORY_PROTECTION
¶Inquire about the parameter corresponding to_POSIX_MEMORY_PROTECTION
.
_SC_MESSAGE_PASSING
¶Inquire about the parameter corresponding to_POSIX_MESSAGE_PASSING
.
_SC_SEMAPHORES
¶Inquire about the parameter corresponding to_POSIX_SEMAPHORES
.
_SC_SHARED_MEMORY_OBJECTS
¶Inquire about the parameter corresponding to_POSIX_SHARED_MEMORY_OBJECTS
.
_SC_AIO_LISTIO_MAX
¶Inquire about the parameter corresponding to_POSIX_AIO_LISTIO_MAX
.
_SC_AIO_MAX
¶Inquire about the parameter corresponding to_POSIX_AIO_MAX
.
_SC_AIO_PRIO_DELTA_MAX
¶Inquire about the value by which a process can decrease its asynchronous I/Opriority level from its own scheduling priority. This corresponds to therun-time invariant valueAIO_PRIO_DELTA_MAX
.
_SC_DELAYTIMER_MAX
¶Inquire about the parameter corresponding to_POSIX_DELAYTIMER_MAX
.
_SC_MQ_OPEN_MAX
¶Inquire about the parameter corresponding to_POSIX_MQ_OPEN_MAX
.
_SC_MQ_PRIO_MAX
¶Inquire about the parameter corresponding to_POSIX_MQ_PRIO_MAX
.
_SC_RTSIG_MAX
¶Inquire about the parameter corresponding to_POSIX_RTSIG_MAX
.
_SC_SEM_NSEMS_MAX
¶Inquire about the parameter corresponding to_POSIX_SEM_NSEMS_MAX
.
_SC_SEM_VALUE_MAX
¶Inquire about the parameter corresponding to_POSIX_SEM_VALUE_MAX
.
_SC_SIGQUEUE_MAX
¶Inquire about the parameter corresponding to_POSIX_SIGQUEUE_MAX
.
_SC_TIMER_MAX
¶Inquire about the parameter corresponding to_POSIX_TIMER_MAX
.
_SC_PII
¶Inquire about the parameter corresponding to_POSIX_PII
.
_SC_PII_XTI
¶Inquire about the parameter corresponding to_POSIX_PII_XTI
.
_SC_PII_SOCKET
¶Inquire about the parameter corresponding to_POSIX_PII_SOCKET
.
_SC_PII_INTERNET
¶Inquire about the parameter corresponding to_POSIX_PII_INTERNET
.
_SC_PII_OSI
¶Inquire about the parameter corresponding to_POSIX_PII_OSI
.
_SC_SELECT
¶Inquire about the parameter corresponding to_POSIX_SELECT
.
_SC_UIO_MAXIOV
¶Inquire about the parameter corresponding to_POSIX_UIO_MAXIOV
.
_SC_PII_INTERNET_STREAM
¶Inquire about the parameter corresponding to_POSIX_PII_INTERNET_STREAM
.
_SC_PII_INTERNET_DGRAM
¶Inquire about the parameter corresponding to_POSIX_PII_INTERNET_DGRAM
.
_SC_PII_OSI_COTS
¶Inquire about the parameter corresponding to_POSIX_PII_OSI_COTS
.
_SC_PII_OSI_CLTS
¶Inquire about the parameter corresponding to_POSIX_PII_OSI_CLTS
.
_SC_PII_OSI_M
¶Inquire about the parameter corresponding to_POSIX_PII_OSI_M
.
_SC_T_IOV_MAX
¶Inquire about the value associated with theT_IOV_MAX
variable.
_SC_THREADS
¶Inquire about the parameter corresponding to_POSIX_THREADS
.
_SC_THREAD_SAFE_FUNCTIONS
¶Inquire about the parameter corresponding to_POSIX_THREAD_SAFE_FUNCTIONS
.
_SC_GETGR_R_SIZE_MAX
¶Inquire about the parameter corresponding to_POSIX_GETGR_R_SIZE_MAX
.
_SC_GETPW_R_SIZE_MAX
¶Inquire about the parameter corresponding to_POSIX_GETPW_R_SIZE_MAX
.
_SC_LOGIN_NAME_MAX
¶Inquire about the parameter corresponding to_POSIX_LOGIN_NAME_MAX
.
_SC_TTY_NAME_MAX
¶Inquire about the parameter corresponding to_POSIX_TTY_NAME_MAX
.
_SC_THREAD_DESTRUCTOR_ITERATIONS
¶Inquire about the parameter corresponding to_POSIX_THREAD_DESTRUCTOR_ITERATIONS
.
_SC_THREAD_KEYS_MAX
¶Inquire about the parameter corresponding to_POSIX_THREAD_KEYS_MAX
.
_SC_THREAD_STACK_MIN
¶Inquire about the parameter corresponding to_POSIX_THREAD_STACK_MIN
.
_SC_THREAD_THREADS_MAX
¶Inquire about the parameter corresponding to_POSIX_THREAD_THREADS_MAX
.
_SC_THREAD_ATTR_STACKADDR
¶Inquire about the parameter corresponding to
a_POSIX_THREAD_ATTR_STACKADDR
.
_SC_THREAD_ATTR_STACKSIZE
¶Inquire about the parameter corresponding to_POSIX_THREAD_ATTR_STACKSIZE
.
_SC_THREAD_PRIORITY_SCHEDULING
¶Inquire about the parameter corresponding to_POSIX_THREAD_PRIORITY_SCHEDULING
.
_SC_THREAD_PRIO_INHERIT
¶Inquire about the parameter corresponding to_POSIX_THREAD_PRIO_INHERIT
.
_SC_THREAD_PRIO_PROTECT
¶Inquire about the parameter corresponding to_POSIX_THREAD_PRIO_PROTECT
.
_SC_THREAD_PROCESS_SHARED
¶Inquire about the parameter corresponding to_POSIX_THREAD_PROCESS_SHARED
.
_SC_2_C_DEV
¶Inquire about whether the system has the POSIX.2 C compiler command,c89
.
_SC_2_FORT_DEV
¶Inquire about whether the system has the POSIX.2 Fortran compilercommand,fort77
.
_SC_2_FORT_RUN
¶Inquire about whether the system has the POSIX.2asa
command tointerpret Fortran carriage control.
_SC_2_LOCALEDEF
¶Inquire about whether the system has the POSIX.2localedef
command.
_SC_2_SW_DEV
¶Inquire about whether the system has the POSIX.2 commandsar
,make
, andstrip
.
_SC_BC_BASE_MAX
¶Inquire about the maximum value ofobase
in thebc
utility.
_SC_BC_DIM_MAX
¶Inquire about the maximum size of an array in thebc
utility.
_SC_BC_SCALE_MAX
¶Inquire about the maximum value ofscale
in thebc
utility.
_SC_BC_STRING_MAX
¶Inquire about the maximum size of a string constant in thebc
utility.
_SC_COLL_WEIGHTS_MAX
¶Inquire about the maximum number of weights that can necessarilybe used in defining the collating sequence for a locale.
_SC_EXPR_NEST_MAX
¶Inquire about the maximum number of expressions nested withinparentheses when using theexpr
utility.
_SC_LINE_MAX
¶Inquire about the maximum size of a text line that the POSIX.2 textutilities can handle.
_SC_EQUIV_CLASS_MAX
¶Inquire about the maximum number of weights that can be assigned to anentry of theLC_COLLATE
category ‘order’ keyword in a localedefinition. The GNU C Library does not presently support localedefinitions.
_SC_VERSION
¶Inquire about the version number of POSIX.1 that the library and kernelsupport.
_SC_2_VERSION
¶Inquire about the version number of POSIX.2 that the system utilitiessupport.
_SC_PAGESIZE
¶Inquire about the virtual memory page size of the machine.getpagesize
returns the same value (seeHow to get information about the memory subsystem?).
_SC_NPROCESSORS_CONF
¶Inquire about the number of configured processors.
_SC_NPROCESSORS_ONLN
¶Inquire about the number of processors online.
_SC_PHYS_PAGES
¶Inquire about the number of physical pages in the system.
_SC_AVPHYS_PAGES
¶Inquire about the number of available physical pages in the system.
_SC_ATEXIT_MAX
¶Inquire about the number of functions which can be registered as terminationfunctions foratexit
; seeCleanups on Exit.
_SC_LEVEL1_ICACHE_SIZE
¶Inquire about the size of the Level 1 instruction cache.
_SC_LEVEL1_ICACHE_ASSOC
¶Inquire about the associativity of the Level 1 instruction cache.
_SC_LEVEL1_ICACHE_LINESIZE
¶Inquire about the line length of the Level 1 instruction cache.
On aarch64, the cache line size returned is the minimum instruction cache linesize observable by userspace. This is typically the same as the L1 icachesize but on some cores it may not be so. However, it is specified in thearchitecture that operations such as cache line invalidation are consistentwith the size reported with this variable.
_SC_LEVEL1_DCACHE_SIZE
¶Inquire about the size of the Level 1 data cache.
_SC_LEVEL1_DCACHE_ASSOC
¶Inquire about the associativity of the Level 1 data cache.
_SC_LEVEL1_DCACHE_LINESIZE
¶Inquire about the line length of the Level 1 data cache.
On aarch64, the cache line size returned is the minimum data cache line sizeobservable by userspace. This is typically the same as the L1 dcache size buton some cores it may not be so. However, it is specified in the architecturethat operations such as cache line invalidation are consistent with the sizereported with this variable.
_SC_LEVEL2_CACHE_SIZE
¶Inquire about the size of the Level 2 cache.
_SC_LEVEL2_CACHE_ASSOC
¶Inquire about the associativity of the Level 2 cache.
_SC_LEVEL2_CACHE_LINESIZE
¶Inquire about the line length of the Level 2 cache.
_SC_LEVEL3_CACHE_SIZE
¶Inquire about the size of the Level 3 cache.
_SC_LEVEL3_CACHE_ASSOC
¶Inquire about the associativity of the Level 3 cache.
_SC_LEVEL3_CACHE_LINESIZE
¶Inquire about the line length of the Level 3 cache.
_SC_LEVEL4_CACHE_SIZE
¶Inquire about the size of the Level 4 cache.
_SC_LEVEL4_CACHE_ASSOC
¶Inquire about the associativity of the Level 4 cache.
_SC_LEVEL4_CACHE_LINESIZE
¶Inquire about the line length of the Level 4 cache.
_SC_XOPEN_VERSION
¶Inquire about the parameter corresponding to_XOPEN_VERSION
.
_SC_XOPEN_XCU_VERSION
¶Inquire about the parameter corresponding to_XOPEN_XCU_VERSION
.
_SC_XOPEN_UNIX
¶Inquire about the parameter corresponding to_XOPEN_UNIX
.
_SC_XOPEN_REALTIME
¶Inquire about the parameter corresponding to_XOPEN_REALTIME
.
_SC_XOPEN_REALTIME_THREADS
¶Inquire about the parameter corresponding to_XOPEN_REALTIME_THREADS
.
_SC_XOPEN_LEGACY
¶Inquire about the parameter corresponding to_XOPEN_LEGACY
.
_SC_XOPEN_CRYPT
¶Inquire about the parameter corresponding to_XOPEN_CRYPT
.The GNU C Library no longer implements the_XOPEN_CRYPT
extensions,so ‘sysconf (_SC_XOPEN_CRYPT)’ always returns-1
.
_SC_XOPEN_ENH_I18N
¶Inquire about the parameter corresponding to_XOPEN_ENH_I18N
.
_SC_XOPEN_SHM
¶Inquire about the parameter corresponding to_XOPEN_SHM
.
_SC_XOPEN_XPG2
¶Inquire about the parameter corresponding to_XOPEN_XPG2
.
_SC_XOPEN_XPG3
¶Inquire about the parameter corresponding to_XOPEN_XPG3
.
_SC_XOPEN_XPG4
¶Inquire about the parameter corresponding to_XOPEN_XPG4
.
_SC_CHAR_BIT
¶Inquire about the number of bits in a variable of typechar
.
_SC_CHAR_MAX
¶Inquire about the maximum value which can be stored in a variable of typechar
.
_SC_CHAR_MIN
¶Inquire about the minimum value which can be stored in a variable of typechar
.
_SC_INT_MAX
¶Inquire about the maximum value which can be stored in a variable of typeint
.
_SC_INT_MIN
¶Inquire about the minimum value which can be stored in a variable of typeint
.
_SC_LONG_BIT
¶Inquire about the number of bits in a variable of typelong int
.
_SC_WORD_BIT
¶Inquire about the number of bits in a variable of a register word.
_SC_MB_LEN_MAX
¶Inquire about the maximum length of a multi-byte representation of a widecharacter value.
_SC_NZERO
¶Inquire about the value used to internally represent the zero priority level forthe process execution.
_SC_SSIZE_MAX
¶Inquire about the maximum value which can be stored in a variable of typessize_t
.
_SC_SCHAR_MAX
¶Inquire about the maximum value which can be stored in a variable of typesigned char
.
_SC_SCHAR_MIN
¶Inquire about the minimum value which can be stored in a variable of typesigned char
.
_SC_SHRT_MAX
¶Inquire about the maximum value which can be stored in a variable of typeshort int
.
_SC_SHRT_MIN
¶Inquire about the minimum value which can be stored in a variable of typeshort int
.
_SC_UCHAR_MAX
¶Inquire about the maximum value which can be stored in a variable of typeunsigned char
.
_SC_UINT_MAX
¶Inquire about the maximum value which can be stored in a variable of typeunsigned int
.
_SC_ULONG_MAX
¶Inquire about the maximum value which can be stored in a variable of typeunsigned long int
.
_SC_USHRT_MAX
¶Inquire about the maximum value which can be stored in a variable of typeunsigned short int
.
_SC_NL_ARGMAX
¶Inquire about the parameter corresponding toNL_ARGMAX
.
_SC_NL_LANGMAX
¶Inquire about the parameter corresponding toNL_LANGMAX
.
_SC_NL_MSGMAX
¶Inquire about the parameter corresponding toNL_MSGMAX
.
_SC_NL_NMAX
¶Inquire about the parameter corresponding toNL_NMAX
.
_SC_NL_SETMAX
¶Inquire about the parameter corresponding toNL_SETMAX
.
_SC_NL_TEXTMAX
¶Inquire about the parameter corresponding toNL_TEXTMAX
.
_SC_MINSIGSTKSZ
¶Inquire about the minimum number of bytes of free stack space requiredin order to guarantee successful, non-nested handling of a single signalwhose handler is an empty function.
_SC_SIGSTKSZ
¶Inquire about the suggested minimum number of bytes of stack spacerequired for a signal stack.
This is not guaranteed to be enough for any specific purpose other thanthe invocation of a single, non-nested, empty handler, but nonethelessshould be enough for basic scenarios involving simple signal handlersand very low levels of signal nesting (say, 2 or 3 levels at the verymost).
This value is provided for developer convenience and to ease migrationfrom the legacySIGSTKSZ
constant. Programs requiring strongerguarantees should avoid using it if at all possible.
Previous:Constants forsysconf
Parameters, Up:Usingsysconf
[Contents][Index]
sysconf
¶We recommend that you first test for a macro definition for theparameter you are interested in, and callsysconf
only if themacro is not defined. For example, here is how to test whether jobcontrol is supported:
inthave_job_control (void){#ifdef _POSIX_JOB_CONTROL return 1;#else int value = sysconf (_SC_JOB_CONTROL); if (value < 0) /*If the system is that badly wedged,there’s no use trying to go on. */ fatal (strerror (errno)); return value;#endif}
Here is how to get the value of a numeric limit:
intget_child_max (){#ifdef CHILD_MAX return CHILD_MAX;#else int value = sysconf (_SC_CHILD_MAX); if (value < 0) fatal (strerror (errno)); return value;#endif}
Next:Limits on File System Capacity, Previous:Usingsysconf
, Up:System Configuration Parameters [Contents][Index]
Here are the names for the POSIX minimum upper bounds for the systemlimit parameters. The significance of these values is that you cansafely push to these limits without checking whether the particularsystem you are using can go that far.
_POSIX_AIO_LISTIO_MAX
¶The most restrictive limit permitted by POSIX for the maximum number ofI/O operations that can be specified in a list I/O call. The value ofthis constant is2
; thus you can add up to two new entriesof the list of outstanding operations.
_POSIX_AIO_MAX
¶The most restrictive limit permitted by POSIX for the maximum number ofoutstanding asynchronous I/O operations. The value of this constant is1
. So you cannot expect that you can issue more than oneoperation and immediately continue with the normal work, receiving thenotifications asynchronously.
_POSIX_ARG_MAX
¶The value of this macro is the most restrictive limit permitted by POSIXfor the maximum combined length of theargv andenvironarguments that can be passed to theexec
functions.Its value is4096
.
_POSIX_CHILD_MAX
¶The value of this macro is the most restrictive limit permitted by POSIXfor the maximum number of simultaneous processes per real user ID. Itsvalue is6
.
_POSIX_NGROUPS_MAX
¶The value of this macro is the most restrictive limit permitted by POSIXfor the maximum number of supplementary group IDs per process. Itsvalue is0
.
_POSIX_OPEN_MAX
¶The value of this macro is the most restrictive limit permitted by POSIXfor the maximum number of files that a single process can have opensimultaneously. Its value is16
.
_POSIX_SSIZE_MAX
¶The value of this macro is the most restrictive limit permitted by POSIXfor the maximum value that can be stored in an object of typessize_t
. Its value is32767
.
_POSIX_STREAM_MAX
¶The value of this macro is the most restrictive limit permitted by POSIXfor the maximum number of streams that a single process can have opensimultaneously. Its value is8
.
_POSIX_TZNAME_MAX
¶The value of this macro is the most restrictive limit permitted by POSIXfor the maximum length of a time zone abbreviation. Its value is3
.
_POSIX2_RE_DUP_MAX
¶The value of this macro is the most restrictive limit permitted by POSIXfor the numbers used in the ‘\{min,max\}’ constructin a regular expression. Its value is255
.
Next:Optional Features in File Support, Previous:Minimum Values for General Capacity Limits, Up:System Configuration Parameters [Contents][Index]
The POSIX.1 standard specifies a number of parameters that describe thelimitations of the file system. It’s possible for the system to have afixed, uniform limit for a parameter, but this isn’t the usual case. Onmost systems, it’s possible for different file systems (and, for someparameters, even different files) to have different maximum limits. Forexample, this is very likely if you use NFS to mount some of the filesystems from other machines.
Each of the following macros is defined inlimits.h only if thesystem has a fixed, uniform limit for the parameter in question. If thesystem allows different file systems or files to have different limits,then the macro is undefined; usepathconf
orfpathconf
tofind out the limit that applies to a particular file. SeeUsingpathconf
.
Each parameter also has another macro, with a name starting with‘_POSIX’, which gives the lowest value that the limit is allowed tohave onany POSIX system. SeeMinimum Values for File System Limits.
int
LINK_MAX ¶The uniform system limit (if any) for the number of names for a givenfile. SeeHard Links.
int
MAX_CANON ¶The uniform system limit (if any) for the amount of text in a line ofinput when input editing is enabled. SeeTwo Styles of Input: Canonical or Not.
int
MAX_INPUT ¶The uniform system limit (if any) for the total number of characterstyped ahead as input. SeeI/O Queues.
int
NAME_MAX ¶The uniform system limit (if any) for the length of a file name component, notincluding the terminating null character.
Portability Note: On some systems, the GNU C Library definesNAME_MAX
, but does not actually enforce this limit.
int
PATH_MAX ¶The uniform system limit (if any) for the length of an entire file name (thatis, the argument given to system calls such asopen
), including theterminating null character.
Portability Note: The GNU C Library does not enforce this limiteven ifPATH_MAX
is defined.
int
PIPE_BUF ¶The uniform system limit (if any) for the number of bytes that can bewritten atomically to a pipe. If multiple processes are writing to thesame pipe simultaneously, output from different processes might beinterleaved in chunks of this size. SeePipes and FIFOs.
These are alternative macro names for some of the same information.
int
MAXNAMLEN ¶This is the BSD name forNAME_MAX
. It is defined indirent.h.
int
FILENAME_MAX ¶The value of this macro is an integer constant expression thatrepresents the maximum length of a file name string. It is defined instdio.h.
UnlikePATH_MAX
, this macro is defined even if there is no actuallimit imposed. In such a case, its value is typically a very largenumber.This is always the case on GNU/Hurd systems.
Usage Note: Don’t useFILENAME_MAX
as the size of anarray in which to store a file name! You can’t possibly make an arraythat big! Use dynamic allocation (seeAllocating Storage For Program Data) instead.
Next:Minimum Values for File System Limits, Previous:Limits on File System Capacity, Up:System Configuration Parameters [Contents][Index]
POSIX defines certain system-specific options in the system calls foroperating on files. Some systems support these options and others donot. Since these options are provided in the kernel, not in thelibrary, simply using the GNU C Library does not guarantee that any of thesefeatures is supported; it depends on the system you are using. They canalso vary between file systems on a single machine.
This section describes the macros you can test to determine whether aparticular option is supported on your machine. If a given macro isdefined inunistd.h, then its value says whether thecorresponding feature is supported. (A value of-1
indicates no;any other value indicates yes.) If the macro is undefined, it meansparticular files may or may not support the feature.
Since all the machines that support the GNU C Library also support NFS,one can never make a general statement about whether all file systemssupport the_POSIX_CHOWN_RESTRICTED
and_POSIX_NO_TRUNC
features. So these names are never defined as macros in the GNU C Library.
int
_POSIX_CHOWN_RESTRICTED ¶If this option is in effect, thechown
function is restricted sothat the only changes permitted to nonprivileged processes is to changethe group owner of a file to either be the effective group ID of theprocess, or one of its supplementary group IDs. SeeFile Owner.
int
_POSIX_NO_TRUNC ¶If this option is in effect, file name components longer thanNAME_MAX
generate anENAMETOOLONG
error. Otherwise, filename components that are too long are silently truncated.
unsigned char
_POSIX_VDISABLE ¶This option is only meaningful for files that are terminal devices.If it is enabled, then handling for special control characters canbe disabled individually. SeeSpecial Characters.
If one of these macros is undefined, that means that the option might bein effect for some files and not for others. To inquire about aparticular file, callpathconf
orfpathconf
.SeeUsingpathconf
.
Next:Usingpathconf
, Previous:Optional Features in File Support, Up:System Configuration Parameters [Contents][Index]
Here are the names for the POSIX minimum upper bounds for some of theabove parameters. The significance of these values is that you cansafely push to these limits without checking whether the particularsystem you are using can go that far. In most cases GNU systems do nothave these strict limitations. The actual limit should be requested ifnecessary.
_POSIX_LINK_MAX
¶The most restrictive limit permitted by POSIX for the maximum value of afile’s link count. The value of this constant is8
; thus, youcan always make up to eight names for a file without running into asystem limit.
_POSIX_MAX_CANON
¶The most restrictive limit permitted by POSIX for the maximum number ofbytes in a canonical input line from a terminal device. The value ofthis constant is255
.
_POSIX_MAX_INPUT
¶The most restrictive limit permitted by POSIX for the maximum number ofbytes in a terminal device input queue (or typeahead buffer).SeeInput Modes. The value of this constant is255
.
_POSIX_NAME_MAX
¶The most restrictive limit permitted by POSIX for the maximum number ofbytes in a file name component. The value of this constant is14
.
_POSIX_PATH_MAX
¶The most restrictive limit permitted by POSIX for the maximum number ofbytes in a file name. The value of this constant is256
.
_POSIX_PIPE_BUF
¶The most restrictive limit permitted by POSIX for the maximum number ofbytes that can be written atomically to a pipe. The value of thisconstant is512
.
SYMLINK_MAX
¶Maximum number of bytes in a symbolic link.
POSIX_REC_INCR_XFER_SIZE
¶Recommended increment for file transfer sizes between thePOSIX_REC_MIN_XFER_SIZE
andPOSIX_REC_MAX_XFER_SIZE
values.
POSIX_REC_MAX_XFER_SIZE
¶Maximum recommended file transfer size.
POSIX_REC_MIN_XFER_SIZE
¶Minimum recommended file transfer size.
POSIX_REC_XFER_ALIGN
¶Recommended file transfer buffer alignment.
Next:Utility Program Capacity Limits, Previous:Minimum Values for File System Limits, Up:System Configuration Parameters [Contents][Index]
pathconf
¶When your machine allows different files to have different values for afile system parameter, you can use the functions in this section to findout the value that applies to any particular file.
These functions and the associated constants for theparameterargument are declared in the header fileunistd.h.
long int
pathconf(const char *filename, intparameter)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
This function is used to inquire about the limits that apply tothe file namedfilename.
Theparameter argument should be one of the ‘_PC_’ constantslisted below.
The normal return value frompathconf
is the value you requested.A value of-1
is returned both if the implementation does notimpose a limit, and in case of an error. In the former case,errno
is not set, while in the latter case,errno
is setto indicate the cause of the problem. So the only way to use thisfunction robustly is to store0
intoerrno
just beforecalling it.
Besides the usual file name errors (seeFile Name Errors),the following error condition is defined for this function:
EINVAL
The value ofparameter is invalid, or the implementation doesn’tsupport theparameter for the specific file.
long int
fpathconf(intfiledes, intparameter)
¶Preliminary:| MT-Safe | AS-Unsafe lock heap| AC-Unsafe lock fd mem| SeePOSIX Safety Concepts.
This is just likepathconf
except that an open file descriptoris used to specify the file for which information is requested, insteadof a file name.
The followingerrno
error conditions are defined for this function:
EBADF
Thefiledes argument is not a valid file descriptor.
EINVAL
The value ofparameter is invalid, or the implementation doesn’tsupport theparameter for the specific file.
Here are the symbolic constants that you can use as theparameterargument topathconf
andfpathconf
. The values are allinteger constants.
_PC_LINK_MAX
¶Inquire about the value ofLINK_MAX
.
_PC_MAX_CANON
¶Inquire about the value ofMAX_CANON
.
_PC_MAX_INPUT
¶Inquire about the value ofMAX_INPUT
.
_PC_NAME_MAX
¶Inquire about the value ofNAME_MAX
.
_PC_PATH_MAX
¶Inquire about the value ofPATH_MAX
.
_PC_PIPE_BUF
¶Inquire about the value ofPIPE_BUF
.
_PC_CHOWN_RESTRICTED
¶Inquire about the value of_POSIX_CHOWN_RESTRICTED
.
_PC_NO_TRUNC
¶Inquire about the value of_POSIX_NO_TRUNC
.
_PC_VDISABLE
¶Inquire about the value of_POSIX_VDISABLE
.
_PC_SYNC_IO
¶Inquire about the value of_POSIX_SYNC_IO
.
_PC_ASYNC_IO
¶Inquire about the value of_POSIX_ASYNC_IO
.
_PC_PRIO_IO
¶Inquire about the value of_POSIX_PRIO_IO
.
_PC_FILESIZEBITS
¶Inquire about the availability of large files on the filesystem.
_PC_REC_INCR_XFER_SIZE
¶Inquire about the value ofPOSIX_REC_INCR_XFER_SIZE
.
_PC_REC_MAX_XFER_SIZE
¶Inquire about the value ofPOSIX_REC_MAX_XFER_SIZE
.
_PC_REC_MIN_XFER_SIZE
¶Inquire about the value ofPOSIX_REC_MIN_XFER_SIZE
.
_PC_REC_XFER_ALIGN
¶Inquire about the value ofPOSIX_REC_XFER_ALIGN
.
Portability Note: On some systems, the GNU C Library does notenforce_PC_NAME_MAX
or_PC_PATH_MAX
limits.
Next:Minimum Values for Utility Limits, Previous:Usingpathconf
, Up:System Configuration Parameters [Contents][Index]
The POSIX.2 standard specifies certain system limits that you can accessthroughsysconf
that apply to utility behavior rather than thebehavior of the library or the operating system.
The GNU C Library defines macros for these limits, andsysconf
returns values for them if you ask; but these values convey nomeaningful information. They are simply the smallest values thatPOSIX.2 permits.
int
BC_BASE_MAX ¶The largest value ofobase
that thebc
utility isguaranteed to support.
int
BC_DIM_MAX ¶The largest number of elements in one array that thebc
utilityis guaranteed to support.
int
BC_SCALE_MAX ¶The largest value ofscale
that thebc
utility isguaranteed to support.
int
BC_STRING_MAX ¶The largest number of characters in one string constant that thebc
utility is guaranteed to support.
int
COLL_WEIGHTS_MAX ¶The largest number of weights that can necessarily be used in definingthe collating sequence for a locale.
int
EXPR_NEST_MAX ¶The maximum number of expressions that can be nested within parenthesesby theexpr
utility.
int
LINE_MAX ¶The largest text line that the text-oriented POSIX.2 utilities cansupport. (If you are using the GNU versions of these utilities, thenthere is no actual limit except that imposed by the available virtualmemory, but there is no way that the library can tell you this.)
int
EQUIV_CLASS_MAX ¶The maximum number of weights that can be assigned to an entry of theLC_COLLATE
category ‘order’ keyword in a locale definition.The GNU C Library does not presently support locale definitions.
Next:String-Valued Parameters, Previous:Utility Program Capacity Limits, Up:System Configuration Parameters [Contents][Index]
_POSIX2_BC_BASE_MAX
¶The most restrictive limit permitted by POSIX.2 for the maximum value ofobase
in thebc
utility. Its value is99
.
_POSIX2_BC_DIM_MAX
¶The most restrictive limit permitted by POSIX.2 for the maximum size ofan array in thebc
utility. Its value is2048
.
_POSIX2_BC_SCALE_MAX
¶The most restrictive limit permitted by POSIX.2 for the maximum value ofscale
in thebc
utility. Its value is99
.
_POSIX2_BC_STRING_MAX
¶The most restrictive limit permitted by POSIX.2 for the maximum size ofa string constant in thebc
utility. Its value is1000
.
_POSIX2_COLL_WEIGHTS_MAX
¶The most restrictive limit permitted by POSIX.2 for the maximum numberof weights that can necessarily be used in defining the collatingsequence for a locale. Its value is2
.
_POSIX2_EXPR_NEST_MAX
¶The most restrictive limit permitted by POSIX.2 for the maximum numberof expressions nested within parenthesis when using theexpr
utility.Its value is32
.
_POSIX2_LINE_MAX
¶The most restrictive limit permitted by POSIX.2 for the maximum size ofa text line that the text utilities can handle. Its value is2048
.
_POSIX2_EQUIV_CLASS_MAX
¶The most restrictive limit permitted by POSIX.2 for the maximum numberof weights that can be assigned to an entry of theLC_COLLATE
category ‘order’ keyword in a locale definition. Its value is2
. The GNU C Library does not presently support localedefinitions.
POSIX.2 defines a way to get string-valued parameters from the operatingsystem with the functionconfstr
:
size_t
confstr(intparameter, char *buf, size_tlen)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function reads the value of a string-valued system parameter,storing the string intolen bytes of memory space starting atbuf. Theparameter argument should be one of the‘_CS_’ symbols listed below.
The normal return value fromconfstr
is the length of the stringvalue that you asked for. If you supply a null pointer forbuf,thenconfstr
does not try to store the string; it just returnsits length. A value of0
indicates an error.
If the string you asked for is too long for the buffer (that is, longerthanlen - 1
), thenconfstr
stores just that much(leaving room for the terminating null character). You can tell thatthis has happened becauseconfstr
returns a value greater than orequal tolen.
The followingerrno
error conditions are defined for this function:
EINVAL
The value of theparameter is invalid.
Currently there is just one parameter you can read withconfstr
:
_CS_PATH
¶This parameter’s value is the recommended default path for searching forexecutable files. This is the path that a user has by default justafter logging in.
_CS_LFS_CFLAGS
¶The returned string specifies which additional flags must be given tothe C compiler if a source is compiled using the_LARGEFILE_SOURCE
feature select macro; seeFeature Test Macros.
_CS_LFS_LDFLAGS
¶The returned string specifies which additional flags must be given tothe linker if a source is compiled using the_LARGEFILE_SOURCE
feature select macro; seeFeature Test Macros.
_CS_LFS_LIBS
¶The returned string specifies which additional libraries must be linkedto the application if a source is compiled using the_LARGEFILE_SOURCE
feature select macro; seeFeature Test Macros.
_CS_LFS_LINTFLAGS
¶The returned string specifies which additional flags must be given tothe lint tool if a source is compiled using the_LARGEFILE_SOURCE
feature select macro; seeFeature Test Macros.
_CS_LFS64_CFLAGS
¶The returned string specifies which additional flags must be given tothe C compiler if a source is compiled using the_LARGEFILE64_SOURCE
feature select macro; seeFeature Test Macros.
_CS_LFS64_LDFLAGS
¶The returned string specifies which additional flags must be given tothe linker if a source is compiled using the_LARGEFILE64_SOURCE
feature select macro; seeFeature Test Macros.
_CS_LFS64_LIBS
¶The returned string specifies which additional libraries must be linkedto the application if a source is compiled using the_LARGEFILE64_SOURCE
feature select macro; seeFeature Test Macros.
_CS_LFS64_LINTFLAGS
¶The returned string specifies which additional flags must be given tothe lint tool if a source is compiled using the_LARGEFILE64_SOURCE
feature select macro; seeFeature Test Macros.
The way to useconfstr
without any arbitrary limit on string sizeis to call it twice: first call it to get the length, allocate thebuffer accordingly, and then callconfstr
again to fill thebuffer, like this:
char *get_default_path (void){ size_t len = confstr (_CS_PATH, NULL, 0); char *buffer = (char *) xmalloc (len); if (confstr (_CS_PATH, buf, len + 1) == 0) { free (buffer); return NULL; } return buffer;}
Next:Debugging support, Previous:System Configuration Parameters, Up:Main Menu [Contents][Index]
The GNU C Library includes only one type of special-purpose cryptographicfunctions; these allow use of a source of cryptographically strongpseudorandom numbers, if such a source is provided by the operatingsystem. Programs that need general-purpose cryptography should usea dedicated cryptography library, such aslibgcrypt.
Cryptographic applications often need random data that will be asdifficult as possible for a hostile eavesdropper to guess.The pseudo-random number generators provided by the GNU C Library(seePseudo-Random Numbers) are not suitable for this purpose.They produce output that isstatistically random, but fails tobeunpredictable. Cryptographic applications require acryptographic random number generator (CRNG), also known as acryptographically strong pseudo-random number generator (CSPRNG)or adeterministic random bit generator (DRBG).
Currently, the GNU C Library does not provide a cryptographic random numbergenerator, but it does provide functions that read cryptographicallystrong random data from arandomness source supplied by theoperating system. This randomness source is a CRNG at heart, but italso continually “re-seeds” itself from physical sources ofrandomness, such as electronic noise and clock jitter. This meansapplications do not need to do anything to ensure that the randomnumbers it produces are different on each run.
The catch, however, is that these functions will only producerelatively short random strings in any one call. Often this is not aproblem, but applications that need more than a few kilobytes ofcryptographically strong random data should call these functions onceand use their output to seed a CRNG.
Most applications should usegetentropy
. Thegetrandom
function is intended for low-level applications which need additionalcontrol over blocking behavior.
int
getentropy(void *buffer, size_tlength)
¶| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function writes exactlylength bytes of random data to thearray starting atbuffer.length can be no more than 256.On success, it returns zero. On failure, it returns-1, anderrno
is set to indicate the problem. Some of the possibleerrors are listed below.
ENOSYS
The operating system does not implement a randomness source, or doesnot support this way of accessing it. (For instance, the system callused by this function was added to the Linux kernel in version 3.17.)
EFAULT
The combination ofbuffer andlength arguments specifiesan invalid memory range.
EIO
length is larger than 256, or the kernel entropy pool hassuffered a catastrophic failure.
A call togetentropy
can only block when the system has justbooted and the randomness source has not yet been initialized.However, if it does block, it cannot be interrupted by signals orthread cancellation. Programs intended to run in very early stages ofthe boot process may need to usegetrandom
in non-blocking modeinstead, and be prepared to cope with random data not being availableat all.
Thegetentropy
function is declared in the header filesys/random.h. It is derived from OpenBSD.
ssize_t
getrandom(void *buffer, size_tlength, unsigned intflags)
¶| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function writes up tolength bytes of random data to thearray starting atbuffer. Theflags argument should beeither zero, or the bitwise OR of some of the following flags:
GRND_RANDOM
Use the/dev/random (blocking) source instead of the/dev/urandom (non-blocking) source to obtain randomness.
If this flag is specified, the call may block, potentially for quitesome time, even after the randomness source has been initialized. If itis not specified, the call can only block when the system has justbooted and the randomness source has not yet been initialized.
GRND_NONBLOCK
Instead of blocking, return to the caller immediately if no data isavailable.
GRND_INSECURE
Write random data that may not be cryptographically secure.
Unlikegetentropy
, thegetrandom
function is acancellation point, and if it blocks, it can be interrupted bysignals.
On success,getrandom
returns the number of bytes which havebeen written to the buffer, which may be less thanlength. Onerror, it returns-1, anderrno
is set to indicate theproblem. Some of the possible errors are:
ENOSYS
The operating system does not implement a randomness source, or doesnot support this way of accessing it. (For instance, the system callused by this function was added to the Linux kernel in version 3.17.)
EAGAIN
No random data was available andGRND_NONBLOCK
was specified inflags.
EFAULT
The combination ofbuffer andlength arguments specifiesan invalid memory range.
EINTR
The system call was interrupted. During the system boot process, beforethe kernel randomness pool is initialized, this can happen even ifflags is zero.
EINVAL
Theflags argument contains an invalid combination of flags.
Thegetrandom
function is declared in the header filesys/random.h. It is a GNU extension.
Next:Threads, Previous:Cryptographic Functions, Up:Main Menu [Contents][Index]
Applications are usually debugged using dedicated debugger programs.But sometimes this is not possible and, in any case, it is useful toprovide the developer with as much information as possible at the timethe problems are experienced. For this reason a few functions areprovided which a program can use to help the developer more easilylocate the problem.
Up:Debugging support [Contents][Index]
Abacktrace is a list of the function calls that are currentlyactive in a thread. The usual way to inspect a backtrace of a programis to use an external debugger such as gdb. However, sometimes it isuseful to obtain a backtrace programmatically from within a program,e.g., for the purposes of logging or diagnostics.
The header fileexecinfo.h declares three functions that obtainand manipulate backtraces of the current thread.
int
backtrace(void **buffer, intsize)
¶Preliminary:| MT-Safe | AS-Unsafe init heap dlopen plugin lock| AC-Unsafe init mem lock fd| SeePOSIX Safety Concepts.
Thebacktrace
function obtains a backtrace for the currentthread, as a list of pointers, and places the information intobuffer. The argumentsize should be the number ofvoid *
elements that will fit intobuffer. The returnvalue is the actual number of entries ofbuffer that are obtained,and is at mostsize.
The pointers placed inbuffer are actually return addressesobtained by inspecting the stack, one return address per stack frame.
Note that certain compiler optimizations may interfere with obtaining avalid backtrace. Function inlining causes the inlined function to nothave a stack frame; tail call optimization replaces one stack frame withanother; frame pointer elimination will stopbacktrace
frominterpreting the stack contents correctly.
char **
backtrace_symbols(void *const *buffer, intsize)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem lock| SeePOSIX Safety Concepts.
Thebacktrace_symbols
function translates the informationobtained from thebacktrace
function into an array of strings.The argumentbuffer should be a pointer to an array of addressesobtained via thebacktrace
function, andsize is the numberof entries in that array (the return value ofbacktrace
).
The return value is a pointer to an array of strings, which hassize entries just like the arraybuffer. Each stringcontains a printable representation of the corresponding element ofbuffer. It includes the function name (if this can bedetermined), an offset into the function, and the actual return address(in hexadecimal).
Currently, the function name and offset can only be obtained on systems thatuse the ELF binary format for programs and libraries. On other systems,only the hexadecimal return address will be present. Also, you may needto pass additional flags to the linker to make the function namesavailable to the program. (For example, on systems using GNU ld, youmust pass-rdynamic
.)
The return value ofbacktrace_symbols
is a pointer obtained viathemalloc
function, and it is the responsibility of the callertofree
that pointer. Note that only the return value need befreed, not the individual strings.
The return value isNULL
if sufficient memory for the stringscannot be obtained.
void
backtrace_symbols_fd(void *const *buffer, intsize, intfd)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe lock| SeePOSIX Safety Concepts.
Thebacktrace_symbols_fd
function performs the same translationas the functionbacktrace_symbols
function. Instead of returningthe strings to the caller, it writes the strings to the file descriptorfd, one per line. It does not use themalloc
function, andcan therefore be used in situations where that function might fail.
The following program illustrates the use of these functions. Note thatthe array to contain the return addresses returned bybacktrace
is allocated on the stack. Therefore code like this can be used insituations where the memory handling viamalloc
does not workanymore (in which case thebacktrace_symbols
has to be replacedby abacktrace_symbols_fd
call as well). The number of returnaddresses is normally not very large. Even complicated programs ratherseldom have a nesting level of more than, say, 50 and with 200 possibleentries probably all programs should be covered.
#include <execinfo.h>#include <stdio.h>#include <stdlib.h>/*Obtain a backtrace and print it tostdout
. */voidprint_trace (void){ void *array[10]; char **strings; int size, i; size = backtrace (array, 10); strings = backtrace_symbols (array, size); if (strings != NULL) { printf ("Obtained %d stack frames.\n", size); for (i = 0; i < size; i++) printf ("%s\n", strings[i]); } free (strings);}/*A dummy function to make the backtrace more interesting. */voiddummy_function (void){ print_trace ();}intmain (void){ dummy_function (); return 0;}
Next:Dynamic Linker, Previous:Debugging support, Up:Main Menu [Contents][Index]
This chapter describes functions used for managing threads.The GNU C Library provides two threading implementations: ISO C threads andPOSIX threads.
Next:POSIX Threads, Up:Threads [Contents][Index]
This section describes the GNU C Library ISO C threads implementation.To have a deeper understanding of this API, it is strongly recommendedto read ISO/IEC 9899:2011, section 7.26, in which ISO C threads wereoriginally specified. All types and function prototypes are declaredin the header filethreads.h.
Next:Creation and Control, Up:ISO C Threads [Contents][Index]
The ISO C thread specification provides the following enumerationconstants for return values from functions in the API:
thrd_timedout
¶A specified time was reached without acquiring the requested resource,usually a mutex or condition variable.
thrd_success
¶The requested operation succeeded.
thrd_busy
¶The requested operation failed because a requested resource is alreadyin use.
thrd_error
¶The requested operation failed.
thrd_nomem
¶The requested operation failed because it was unable to allocateenough memory.
Next:Call Once, Previous:Return Values, Up:ISO C Threads [Contents][Index]
The GNU C Library implements a set of functions that allow the user to easilycreate and use threads. Additional functionality is provided to controlthe behavior of threads.
The following data types are defined for managing threads:
A unique object that identifies a thread.
This data type is anint (*) (void *)
typedef that is passed tothrd_create
when creating a new thread. It should point to thefirst function that thread will run.
The following functions are used for working with threads:
int
thrd_create(thrd_t *thr, thrd_start_tfunc, void *arg)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
thrd_create
creates a new thread that will execute the functionfunc. The object pointed to byarg will be used as theargument tofunc. If successful,thr is set to the newthread identifier.
This function may returnthrd_success
,thrd_nomem
, orthrd_error
.
thrd_t
thrd_current(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function returns the identifier of the calling thread.
int
thrd_equal(thrd_tlhs, thrd_trhs)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
thrd_equal
checks whetherlhs andrhs refer to thesame thread. Iflhs andrhs are different threads, thisfunction returns0; otherwise, the return value is non-zero.
int
thrd_sleep(const struct timespec *time_point, struct timespec *remaining)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
thrd_sleep
blocks the execution of the current thread for atleast until the elapsed time pointed to bytime_point has beenreached. This function does not take an absolute time, but a durationthat the thread is required to be blocked. SeeTime Basics, andTime Types.
The thread may wake early if a signal that is not ignored is received.In such a case, ifremaining
is not NULL, the remaining timeduration is stored in the object pointed to byremaining.
thrd_sleep
returns0 if it blocked for at least theamount of time intime_point
,-1 if it was interruptedby a signal, or a negative number on failure.
void
thrd_yield(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
thrd_yield
provides a hint to the implementation to reschedulethe execution of the current thread, allowing other threads to run.
_Noreturn void
thrd_exit(intres)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
thrd_exit
terminates execution of the calling thread and setsits result code tores.
If this function is called from a single-threaded process, the call isequivalent to callingexit
withEXIT_SUCCESS
(seeNormal Termination). Also note that returning from afunction that started a thread is equivalent to callingthrd_exit
.
int
thrd_detach(thrd_tthr)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
thrd_detach
detaches the thread identified bythr
fromthe current control thread. The resources held by the detached threadwill be freed automatically once the thread exits. The parent threadwill never be notified by anythr signal.
Callingthrd_detach
on a thread that was previously detached orjoined by another thread results in undefined behavior.
This function returns eitherthrd_success
orthrd_error
.
int
thrd_join(thrd_tthr, int *res)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
thrd_join
blocks the current thread until the thread identifiedbythr
finishes execution. Ifres
is not NULL, theresult code of the thread is put into the location pointed to byres. The termination of the threadsynchronizes-with thecompletion of this function, meaning both threads have arrived at acommon point in their execution.
Callingthrd_join
on a thread that was previously detached orjoined by another thread results in undefined behavior.
This function returns eitherthrd_success
orthrd_error
.
Next:Mutexes, Previous:Creation and Control, Up:ISO C Threads [Contents][Index]
In order to guarantee single access to a function, the GNU C Libraryimplements acall once function to ensure a function is onlycalled once in the presence of multiple, potentially calling threads.
A complete object type capable of holding a flag used bycall_once
.
This value is used to initialize an object of typeonce_flag
.
void
call_once(once_flag *flag, void (*func) (void))
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
call_once
calls functionfunc exactly once, even ifinvoked from several threads. The completion of the functionfunc synchronizes-with all previous or subsequent calls tocall_once
with the sameflag
variable.
Next:Condition Variables, Previous:Call Once, Up:ISO C Threads [Contents][Index]
To have better control of resources and how threads access them,the GNU C Library implements amutex object, which can help avoid raceconditions and other concurrency issues. The term “mutex” refers tomutual exclusion.
The fundamental data type for a mutex is themtx_t
:
Themtx_t
data type uniquely identifies a mutex object.
The ISO C standard defines several types of mutexes. They arerepresented by the following symbolic constants:
mtx_plain
¶A mutex that does not support timeout, or test and return.
mtx_recursive
¶A mutex that supports recursive locking, which means that the owningthread can lock it more than once without causing deadlock.
mtx_timed
¶A mutex that supports timeout.
The following functions are used for working with mutexes:
int
mtx_init(mtx_t *mutex, inttype)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
mtx_init
creates a new mutex object with typetype. Theobject pointed to bymutex is set to the identifier of the newlycreated mutex.
Not all combinations of mutex types are valid for thetype
argument. Valid uses of mutex types for thetype
argument are:
mtx_plain
A non-recursive mutex that does not support timeout.
mtx_timed
A non-recursive mutex that does support timeout.
mtx_plain | mtx_recursive
A recursive mutex that does not support timeout.
mtx_timed | mtx_recursive
A recursive mutex that does support timeout.
This function returns eitherthrd_success
orthrd_error
.
int
mtx_lock(mtx_t *mutex)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
mtx_lock
blocks the current thread until the mutex pointed tobymutex is locked. The behavior is undefined if the currentthread has already locked the mutex and the mutex is not recursive.
Prior calls tomtx_unlock
on the same mutex synchronize-withthis operation (if this operation succeeds), and all lock/unlockoperations on any given mutex form a single total order (similar tothe modification order of an atomic).
This function returns eitherthrd_success
orthrd_error
.
int
mtx_timedlock(mtx_t *restrictmutex, const struct timespec *restricttime_point)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
mtx_timedlock
blocks the current thread until the mutex pointedto bymutex is locked or until the calendar time pointed to bytime_point has been reached. Since this function takes anabsolute time, if a duration is required, the calendar time must becalculated manually. SeeTime Basics, andCalendar Time.
If the current thread has already locked the mutex and the mutex isnot recursive, or if the mutex does not support timeout, the behaviorof this function is undefined.
Prior calls tomtx_unlock
on the same mutex synchronize-withthis operation (if this operation succeeds), and all lock/unlockoperations on any given mutex form a single total order (similar tothe modification order of an atomic).
This function returns eitherthrd_success
orthrd_error
.
int
mtx_trylock(mtx_t *mutex)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
mtx_trylock
tries to lock the mutex pointed to bymutexwithout blocking. It returns immediately if the mutex is alreadylocked.
Prior calls tomtx_unlock
on the same mutex synchronize-withthis operation (if this operation succeeds), and all lock/unlockoperations on any given mutex form a single total order (similar tothe modification order of an atomic).
This function returnsthrd_success
if the lock was obtained,thrd_busy
if the mutex is already locked, andthrd_error
on failure.
int
mtx_unlock(mtx_t *mutex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
mtx_unlock
unlocks the mutex pointed to bymutex. Thebehavior is undefined if the mutex is not locked by the callingthread.
This function synchronizes-with subsequentmtx_lock
,mtx_trylock
, andmtx_timedlock
calls on the same mutex.All lock/unlock operations on any given mutex form a single totalorder (similar to the modification order of an atomic).
This function returns eitherthrd_success
orthrd_error
.
void
mtx_destroy(mtx_t *mutex)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
mtx_destroy
destroys the mutex pointed to bymutex. Ifthere are any threads waiting on the mutex, the behavior isundefined.
Next:Thread-local Storage, Previous:Mutexes, Up:ISO C Threads [Contents][Index]
Mutexes are not the only synchronization mechanisms available. Forsome more complex tasks, the GNU C Library also implementsconditionvariables, which allow the programmer to think at a higher level whensolving complex synchronization problems. They are used tosynchronize threads waiting on a certain condition to happen.
The fundamental data type for condition variables is thecnd_t
:
Thecnd_t
uniquely identifies a condition variable object.
The following functions are used for working with condition variables:
int
cnd_init(cnd_t *cond)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
cnd_init
initializes a new condition variable, identified bycond.
This function may returnthrd_success
,thrd_nomem
, orthrd_error
.
int
cnd_signal(cnd_t *cond)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
cnd_signal
unblocks one thread that is currently waiting on thecondition variable pointed to bycond. If a thread issuccessfully unblocked, this function returnsthrd_success
. Ifno threads are blocked, this function does nothing and returnsthrd_success
. Otherwise, this function returnsthrd_error
.
int
cnd_broadcast(cnd_t *cond)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
cnd_broadcast
unblocks all the threads that are currentlywaiting on the condition variable pointed to bycond. Thisfunction returnsthrd_success
on success. If no threads areblocked, this function does nothing and returnsthrd_success
. Otherwise, this function returnsthrd_error
.
int
cnd_wait(cnd_t *cond, mtx_t *mutex)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
cnd_wait
atomically unlocks the mutex pointed to bymutexand blocks on the condition variable pointed to bycond untilthe thread is signaled bycnd_signal
orcnd_broadcast
.The mutex is locked again before the function returns.
This function returns eitherthrd_success
orthrd_error
.
int
cnd_timedwait(cnd_t *restrictcond, mtx_t *restrictmutex, const struct timespec *restricttime_point)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
cnd_timedwait
atomically unlocks the mutex pointed to bymutex and blocks on the condition variable pointed to bycond until the thread is signaled bycnd_signal
orcnd_broadcast
, or until the calendar time pointed to bytime_point has been reached. The mutex is locked again beforethe function returns.
As formtx_timedlock
, since this function takes an absolutetime, if a duration is required, the calendar time must be calculatedmanually. SeeTime Basics, andCalendar Time.
This function may returnthrd_success
,thrd_nomem
, orthrd_error
.
void
cnd_destroy(cnd_t *cond)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
cnd_destroy
destroys the condition variable pointed to bycond. If there are threads waiting oncond, the behavioris undefined.
Previous:Condition Variables, Up:ISO C Threads [Contents][Index]
The GNU C Library implements functions to providethread-localstorage, a mechanism by which variables can be defined to have uniqueper-thread storage, lifetimes that match the thread lifetime, anddestructors that cleanup the unique per-thread storage.
Several data types and macros exist for working with thread-localstorage:
Thetss_t
data type identifies a thread-specific storageobject. Even if shared, every thread will have its own instance ofthe variable, with different values.
Thetss_dtor_t
is a function pointer of typevoid (*)(void *)
, to be used as a thread-specific storage destructor. Thefunction will be called when the current thread callsthrd_exit
(but never when callingtss_delete
orexit
).
thread_local
is used to mark a variable with thread storageduration, which means it is created when the thread starts and cleanedup when the thread ends.
Note: For C++, C++11 or later is required to use thethread_local
keyword.
TSS_DTOR_ITERATIONS
is an integer constant expressionrepresenting the maximum number of iterations over all thread-localdestructors at the time of thread termination. This value provides abounded limit to the destruction of thread-local storage; e.g.,consider a destructor that creates more thread-local storage.
The following functions are used to manage thread-local storage:
int
tss_create(tss_t *tss_key, tss_dtor_tdestructor)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
tss_create
creates a new thread-specific storage key and storesit in the object pointed to bytss_key. Although the same keyvalue may be used by different threads, the values bound to the key bytss_set
are maintained on a per-thread basis and persist forthe life of the calling thread.
Ifdestructor
is not NULL, a destructor function will be set,and called when the thread finishes its execution by callingthrd_exit
.
This function returnsthrd_success
iftss_key
issuccessfully set to a unique value for the thread; otherwise,thrd_error
is returned and the value oftss_key
isundefined.
int
tss_set(tss_ttss_key, void *val)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
tss_set
sets the value of the thread-specific storageidentified bytss_key for the current thread toval.Different threads may set different values to the same key.
This function returns eitherthrd_success
orthrd_error
.
void *
tss_get(tss_ttss_key)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
tss_get
returns the value identified bytss_key held inthread-specific storage for the current thread. Different threads mayget different values identified by the same key. On failure,tss_get
returns zero.
void
tss_delete(tss_ttss_key)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
tss_delete
destroys the thread-specific storage identified bytss_key.
Previous:ISO C Threads, Up:Threads [Contents][Index]
This section describes the GNU C Library POSIX Threads implementation.
Next:Thread-specific Data, Up:POSIX Threads [Contents][Index]
int
pthread_create(pthread_t *newthread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)
¶This function creates a new thread with attributesattr. Thisthread will callstart_routine and pass itarg. Ifstart_routine returns, the thread will exit and the return valuewill become the thread’s exit value. The new thread’s ID is stored innewthread. Returns 0 on success.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_create(3)SeeLinux (The Linux Kernel).
int
pthread_detach(pthread_tth)
¶Indicates that threadth must clean up after itselfautomatically when it exits, as the parent thread will not callpthread_join
on it.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_detach(3)SeeLinux (The Linux Kernel).
int
pthread_join(pthread_tth, void **thread_return)
¶Waits for threadth to exit, and stores its return value inthread_return.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_join(3)SeeLinux (The Linux Kernel).
int
pthread_kill(pthread_tth, intsignal)
¶Sends signalsignal to threadth.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_kill(3)SeeLinux (The Linux Kernel).
pthread_t
pthread_self(void)
¶Returns the ID of the thread which performed the call.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_self(3)SeeLinux (The Linux Kernel).
Each thread has a set of attributes which are passed topthread_create
via thepthread_attr_t
type, which shouldbe considered an opaque type.
int
pthread_attr_init(pthread_attr_t *attr)
¶Initializesattr to its default values and allocates anyresources required. Once initialized,attr can be modified byotherpthread_attr_*
functions, or used bypthread_create
.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_attr_init(3)SeeLinux (The Linux Kernel).
int
pthread_attr_destroy(pthread_attr_t *attr)
¶When no longer needed,attr should be destroyed with thisfunction, which releases any resources allocated. Note thatattr is only needed for thepthread_create
call, not forthe running thread itself.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_attr_destroy(3)SeeLinux (The Linux Kernel).
int
pthread_attr_setdetachstate(pthread_attr_t *attr, intdetachstate)
¶Sets the detach state attribute forattr. This attribute may be one of the following:
PTHREAD_CREATE_DETACHED
Causes the created thread to be detached, that is, as ifpthread_detach
had been called on it.
PTHREAD_CREATE_JOINABLE
Causes the created thread to be joinable, that is,pthread_join
must be called on it.
This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_attr_setdetachstate(3)SeeLinux (The Linux Kernel).
int
pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate)
¶Gets the detach state attribute fromattr.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_attr_getdetachstate(3)SeeLinux (The Linux Kernel).
Next:Functions for Waiting According to a Specific Clock, Previous:Creating and Destroying Threads, Up:POSIX Threads [Contents][Index]
The GNU C Library implements functions to allow users to create and managedata specific to a thread. Such data may be destroyed at thread exit,if a destructor is provided. The following functions are defined:
int
pthread_key_create(pthread_key_t *key, void (*destructor)(void*))
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Create a thread-specific data key for the calling thread, referenced bykey.
Objects declared with the C++11thread_local
keyword are destroyedbefore thread-specific data, so they should not be used in thread-specificdata destructors or even as members of the thread-specific data, since thelatter is passed as an argument to the destructor function.
int
pthread_key_delete(pthread_key_tkey)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Destroy the thread-specific datakey in the calling thread. Thedestructor for the thread-specific data is not called during destruction, noris it called during thread exit.
void *
pthread_getspecific(pthread_key_tkey)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Return the thread-specific data associated withkey in the callingthread.
int
pthread_setspecific(pthread_key_tkey, const void *value)
¶Preliminary:| MT-Safe | AS-Unsafe corrupt heap| AC-Unsafe corrupt mem| SeePOSIX Safety Concepts.
Associate the thread-specificvalue withkey in the calling thread.
Next:POSIX Semaphores, Previous:Thread-specific Data, Up:POSIX Threads [Contents][Index]
The GNU C Library provides several waiting functions that expect an explicitclockid_t
argument. These functions were all adopted byPOSIX.1-2024.
int
pthread_cond_clockwait(pthread_cond_t *cond, pthread_mutex_t *mutex, clockid_tclockid, const struct timespec *abstime)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Behaves likepthread_cond_timedwait
except the timeabstime ismeasured against the clock specified byclockid rather than the clockspecified or defaulted whenpthread_cond_init
was called. Currently,clockid must be eitherCLOCK_MONOTONIC
orCLOCK_REALTIME
.
int
pthread_rwlock_clockrdlock(pthread_rwlock_t *rwlock, clockid_tclockid, const struct timespec *abstime)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Behaves likepthread_rwlock_timedrdlock
except the timeabstime is measured against the clock specified byclockidrather thanCLOCK_REALTIME
. Currently,clockid must be eitherCLOCK_MONOTONIC
orCLOCK_REALTIME
, otherwiseEINVAL
isreturned.
int
pthread_rwlock_clockwrlock(pthread_rwlock_t *rwlock, clockid_tclockid, const struct timespec *abstime)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Behaves likepthread_rwlock_timedwrlock
except the timeabstime is measured against the clock specified byclockidrather thanCLOCK_REALTIME
. Currently,clockid must be eitherCLOCK_MONOTONIC
orCLOCK_REALTIME
, otherwiseEINVAL
isreturned.
Next:POSIX Barriers, Previous:Functions for Waiting According to a Specific Clock, Up:POSIX Threads [Contents][Index]
int
sem_init(sem_t *sem, intpshared, unsigned intvalue)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This documentation is a stub. For additional information on thisfunction, consult the manual pagesem_init(3)SeeLinux (The Linux Kernel).
int
sem_destroy(sem_t *sem)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This documentation is a stub. For additional information on thisfunction, consult the manual pagesem_destroy(3)SeeLinux (The Linux Kernel).
sem_t *
sem_open(const char *name, intoflag, ...)
¶Preliminary:| MT-Safe | AS-Unsafe init| AC-Unsafe init| SeePOSIX Safety Concepts.
This documentation is a stub. For additional information on thisfunction, consult the manual pagesem_open(3)SeeLinux (The Linux Kernel).
int
sem_close(sem_t *sem)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
This documentation is a stub. For additional information on thisfunction, consult the manual pagesem_close(3)SeeLinux (The Linux Kernel).
int
sem_unlink(const char *name)
¶Preliminary:| MT-Safe | AS-Unsafe init| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This documentation is a stub. For additional information on thisfunction, consult the manual pagesem_unlink(3)SeeLinux (The Linux Kernel).
int
sem_wait(sem_t *sem)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This documentation is a stub. For additional information on thisfunction, consult the manual pagesem_wait(3)SeeLinux (The Linux Kernel).
int
sem_timedwait(sem_t *sem, const struct timespec *abstime)
¶Preliminary:| MT-Safe | AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This documentation is a stub. For additional information on thisfunction, consult the manual pagesem_timedwait(3)SeeLinux (The Linux Kernel).
int
sem_clockwait(sem_t *sem, clockid_tclockid, const struct timespec *abstime)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Behaves likesem_timedwait
except the timeabstime is measuredagainst the clock specified byclockid rather thanCLOCK_REALTIME
. Currently,clockid must be eitherCLOCK_MONOTONIC
orCLOCK_REALTIME
.
int
sem_trywait(sem_t *sem)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This documentation is a stub. For additional information on thisfunction, consult the manual pagesem_trywait(3)SeeLinux (The Linux Kernel).
int
sem_post(sem_t *sem)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This documentation is a stub. For additional information on thisfunction, consult the manual pagesem_post(3)SeeLinux (The Linux Kernel).
int
sem_getvalue(sem_t *sem, int *sval)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This documentation is a stub. For additional information on thisfunction, consult the manual pagesem_getvalue(3)SeeLinux (The Linux Kernel).
Next:POSIX Spin Locks, Previous:POSIX Semaphores, Up:POSIX Threads [Contents][Index]
A POSIX barrier works as follows: a file-local or globalpthread_barrier_t
object is initialized viapthread_barrier_init
to requirecount threads to wait onit. After that, up tocount-1 threads will wait on the barrierviapthread_barrier_wait
. None of these calls will returnuntilcount threads are waiting via the next call topthread_barrier_wait
, at which point, all of these calls willreturn. The net result is thatcount threads will besynchronized at that point. At some point after this, the barrier isdestroyed viapthread_barrier_destroy
. Note that a barriermust be destroyed before being re-initialized, to ensure that allthreads are properly synchronized, but need not be destroyed andre-initialized before being reused.
int
pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned intcount)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function initializes a barrier to synchronizecountthreads. The barrier must be uninitialized or destroyed before it isinitialized; attempting to initialize an in-use barrier results inundefined behavior.
Theattr argument topthread_barrier_init
is typicallyNULL for a process-private barrier, but may be used to share a barrieracross processes (documentation TBD).
On success, 0 is returned. On error, one of the following is returned:
EINVAL
Eithercount is zero, or is large enough to cause an internaloverflow.
int
pthread_barrier_wait(pthread_barrier_t *barrier)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This function synchronizes threads. The firstcount-1 threadsthat wait onbarrier will just wait. The next thread that waitsonbarrier will cause allcount threads’ calls to return.Thebarrier must be initialized withpthread_barrier_init
and not yet destroyed withpthread_barrier_destroy
.
The return value of this function isPTHREAD_BARRIER_SERIAL_THREAD
for one thread (it is unspecifiedwhich thread) and 0 for the remainder, for each batch ofcountthreads synchronized. After such a batch is synchronized, thebarrier will begin synchronizing the nextcount threads.
int
pthread_barrier_destroy(pthread_barrier_t *barrier)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Destroysbarrier and releases any resources it may haveallocated. A barrier must not be destroyed if any thread is waitingon it, or if it was not initialized. This call always succeeds andreturns 0.
Next:POSIX Mutexes, Previous:POSIX Barriers, Up:POSIX Threads [Contents][Index]
A spinlock is a low overhead lock suitable for use in a realtimethread where it’s known that the thread won’t be paused by thescheduler. Non-realtime threads should use mutexes instead.
int
pthread_spin_init(pthread_spinlock_t *lock, intpshared)
¶Initializes a spinlock.pshared is one of:
PTHREAD_PROCESS_PRIVATE
This spinlock is private to the process which created it.
PTHREAD_PROCESS_SHARED
This spinlock is shared across any process that can access it, forexample through shared memory.
This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_spin_init(3)SeeLinux (The Linux Kernel).
int
pthread_spin_destroy(pthread_spinlock_t *lock)
¶Destroys a spinlock and releases any resources it held.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_spin_destroy(3)SeeLinux (The Linux Kernel).
int
pthread_spin_lock(pthread_spinlock_t *lock)
¶Locks a spinlock. Only one thread at a time can lock a spinlock. Ifanother thread has locked this spinlock, the calling thread waitsuntil it is unlocked, then attempts to lock it.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_spin_lock(3)SeeLinux (The Linux Kernel).
int
pthread_spin_unlock(pthread_spinlock_t *lock)
¶Unlocks a spinlock. If one or more threads are waiting for the lockto be unlocked, one of them (unspecified which) will succeed inlocking it, and will return frompthread_spin_lock
).This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_spin_unlock(3)SeeLinux (The Linux Kernel).
int
pthread_spin_trylock(pthread_spinlock_t *lock)
¶Likepthread_spin_unlock
but returns 0 if the lock wasunlocked, or EBUSY if it was locked.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_spin_trylock(3)SeeLinux (The Linux Kernel).
Next:POSIX Threads Other APIs, Previous:POSIX Spin Locks, Up:POSIX Threads [Contents][Index]
Amutex, or “mutual exclusion”, is a way of guaranteeing thatonly one thread at a time is able to execute a protected bit of code(or access any other resource). Two or more threads trying to executethe same code at the same time, will instead take turns, according tothe mutex.
A mutex is much like a spinlock, but implemented in a way that is moreappropriate for use in non-realtime threads, and is moreresource-conserving.
int
pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr)
¶Initiailizes a mutex.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_mutex_init(3)SeeLinux (The Linux Kernel).
int
pthread_mutex_destroy(pthread_mutex_t *mutex)
¶Destroys a no-longer-needed mutex.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_mutex_destroy(3)SeeLinux (The Linux Kernel).
int
pthread_mutex_lock(pthread_mutex_t *mutex)
¶Only one thread at a time may lockmutex, and must unlock itwhen appropriate. If a thread callspthread_mutex_lock
whilemutex is locked by another thread, the calling thread will waituntilmutex is unlocked, then attempt to lock it. Since theremay be many threads waiting at the same time, the calling thread mayneed to repeat this wait-and-try many times before it successfullylocksmutex, at which point the call topthread_mutex_locks
returns succesfully.
This function may fail with the following:
EAGAIN
Too many locks were attempted.
EDEADLK
The calling thread already holds a lock onmutex.
EINVAL
mutex has an invalid kind, or an invalid priority was requested.
ENOTRECOVERABLE
The thread holding the lock died in a way that the system cannot recover from.
EOWNERDEAD
The thread holding the lock died in a way that the system can recover from.
This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_mutex_lock(3)SeeLinux (The Linux Kernel).
int
pthread_mutex_trylock(pthread_mutex_t *mutex)
¶Likepthread_mutex_lock
but if the lock cannot be immediatelyobtained, returns EBUSY.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_mutex_trylock(3)SeeLinux (The Linux Kernel).
int
pthread_mutex_unlock(pthread_mutex_t *mutex)
¶Unlocksmutex. Returns EPERM if the calling thread doesn’t holdthe lock onmutex.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_mutex_unlock(3)SeeLinux (The Linux Kernel).
int
pthread_mutex_clocklock(pthread_mutex_t *mutex, clockid_tclockid, const struct timespec *abstime)
¶int
pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *abstime)
¶These two functions act likepthread_mutex_lock
with theexception that the call will not wait past timeabstime, asreported byclockid or (forpthread_mutex_timedlock
)CLOCK_REALTIME
. Ifabstime is reached and the mutexstill cannot be locked, anETIMEDOUT
error is returned.If the time had already passed when these functionsare called, and the mutex cannot be immediately locked, the functiontimes out immediately.
int
pthread_mutexattr_init(const pthread_mutexattr_t *attr)
¶Initializesattr with default values.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_mutexattr_init(3)SeeLinux (The Linux Kernel).
int
pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
¶Destroysattr and releases any resources it may have allocated.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_mutexattr_destroy(3)SeeLinux (The Linux Kernel).
int
pthread_mutexattr_settype(pthread_mutexattr_t *attr, intkind)
¶This functions allow you to change what kind of mutex a mutex is, bychanging the attributes used to initialize it. The values forkind are:
PTHREAD_MUTEX_NORMAL
No attempt to detect deadlock is performed; a thread will deadlock ifit tries to lock this mutex yet already holds a lock to it.Attempting to unlock a mutex not locked by the calling thread resultsin undefined behavior.
PTHREAD_MUTEX_ERRORCHECK
Attemps to relock a mutex, or unlock a mutex not held, will result in an error.
PTHREAD_MUTEX_RECURSIVE
Attempts to relock a mutex already held succeed, but require amatching number of unlocks to release it. Attempts to unlock a mutexnot held will result in an error.
PTHREAD_MUTEX_DEFAULT
Attemps to relock a mutex, or unlock a mutex not held, will result inundefined behavior. This is the default.
int
pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *kind)
¶This function gets the kind of mutexmutex is.
Next:Non-POSIX Extensions, Previous:POSIX Mutexes, Up:POSIX Threads [Contents][Index]
int
pthread_equal(pthread_tthread1, pthread_tthread2)
¶Compares two thread IDs. If they are the same, returns nonzero, else returns zero.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_equal(3)SeeLinux (The Linux Kernel).
int
pthread_getcpuclockid(pthread_tth, __clockid_t *clock_id)
¶Get the clock associated withth.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_getcpuclockid(3)SeeLinux (The Linux Kernel).
int
pthread_once(pthread_once_t *once_control, void (*init_routine) (void))
¶Callsinit_routine once for eachonce_control, which mustbe statically initalized toPTHREAD_ONCE_INIT
. Subsequentcalls topthread_once
with the sameonce_control do notcallinit_routine, even in multi-threaded environments.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_once(3)SeeLinux (The Linux Kernel).
int
pthread_sigmask(inthow, const __sigset_t *newmask, __sigset_t *oldmask)
¶This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_sigmask(3)SeeLinux (The Linux Kernel).
Previous:POSIX Threads Other APIs, Up:POSIX Threads [Contents][Index]
In addition to implementing the POSIX API for threads, the GNU C Library providesadditional functions and interfaces to provide functionality not specified inthe standard.
The GNU C Library provides non-standard API functions to set and get the defaultattributes used in the creation of threads in a process.
int
pthread_getattr_default_np(pthread_attr_t *attr)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Get the default attribute values and setattr to match. Thisfunction returns0 on success and a non-zero error code onfailure.
int
pthread_setattr_default_np(pthread_attr_t *attr)
¶Preliminary:| MT-Safe | AS-Unsafe heap lock| AC-Unsafe lock mem| SeePOSIX Safety Concepts.
Set the default attribute values to match the values inattr. Thefunction returns0 on success and a non-zero error code on failure.The following error codes are defined for this function:
EINVAL
At least one of the values inattr does not qualify as valid for theattributes or the stack address is set in the attribute.
ENOMEM
The system does not have sufficient memory.
Next:Thread CPU Affinity, Previous:Setting Process-wide defaults for thread attributes, Up:Non-POSIX Extensions [Contents][Index]
The GNU C Library provides a way to specify the initial signal mask of athread created usingpthread_create
, passing a thread attributeobject configured for this purpose.
int
pthread_attr_setsigmask_np(pthread_attr_t *attr, const sigset_t *sigmask)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Change the initial signal mask specified byattr. Ifsigmask is notNULL
, the initial signal mask for newthreads created withattr is set to*sigmask
. Ifsigmask isNULL
,attr will no longer specify anexplicit signal mask, so that the initial signal mask of the newthread is inherited from the thread that callspthread_create
.
This function returns zero on success, andENOMEM
on memoryallocation failure.
int
pthread_attr_getsigmask_np(const pthread_attr_t *attr, sigset_t *sigmask)
¶Preliminary:| MT-Safe | AS-Unsafe heap| AC-Unsafe mem| SeePOSIX Safety Concepts.
Retrieve the signal mask stored inattr and copy it to*sigmask
. If the signal mask has not been set, returnthe special constantPTHREAD_ATTR_NO_SIGMASK_NP
, otherwisereturn zero.
Obtaining the signal mask only works if it has been previously storedbypthread_attr_setsigmask_np
. For example, thepthread_getattr_np
function does not obtain the current signalmask of the specified thread, andpthread_attr_getsigmask_np
will subsequently report the signal mask as unset.
int
PTHREAD_ATTR_NO_SIGMASK_NP ¶The special value returned bypthread_attr_setsigmask_np
toindicate that no signal mask has been set for the attribute.
It is possible to create a new thread with a specific signal maskwithout using these functions. On the thread that callspthread_create
, the required steps for the general case are:
pthread_sigmask
. This ensures that the new thread will becreated with all signals masked, so that no signals can be deliveredto the thread until the desired signal mask is set.pthread_create
to create the new thread, passing thedesired signal mask to the thread start routine (which could be awrapper function for the actual thread start routine). It may benecessary to make a copy of the desired signal mask on the heap, sothat the life-time of the copy extends to the point when the startroutine needs to access the signal mask.The start routine for the created thread needs to locate the desiredsignal mask and usepthread_sigmask
to apply it to the thread.If the signal mask was copied to a heap allocation, the copy should befreed.
Next:Wait for a thread to terminate, Previous:Controlling the Initial Signal Mask of a New Thread, Up:Non-POSIX Extensions [Contents][Index]
Processes and threads normally run on any available CPU. However,they can be given anaffinity to one or more CPUs, which limitsthem to the CPU set specified.
int
pthread_attr_setaffinity_np(pthread_attr_t *attr, size_tcpusetsize, const cpu_set_t *cpuset)
¶Sets the CPU affinity inattr. The CPU affinitycontrols which CPUs a thread may execute on. SeeLimiting execution to certain CPUs.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_attr_setaffinity_np(3)SeeLinux (The Linux Kernel).
int
pthread_attr_getaffinity_np(const pthread_attr_t *attr, size_tcpusetsize, cpu_set_t *cpuset)
¶Gets the CPU affinity settings fromattr.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_attr_getaffinity_np(3)SeeLinux (The Linux Kernel).
int
pthread_setaffinity_np(pthread_t *th, size_tcpusetsize, const cpu_set_t *cpuset)
¶Sets the CPU affinity for threadth. The CPU affinity controlswhich CPUs a thread may execute on. SeeLimiting execution to certain CPUs.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_setaffinity_np(3)SeeLinux (The Linux Kernel).
int
pthread_getaffinity_np(const pthread_t *th, size_tcpusetsize, cpu_set_t *cpuset)
¶Gets the CPU affinity for threadth. The CPU affinity controlswhich CPUs a thread may execute on. SeeLimiting execution to certain CPUs.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_getaffinity_np(3)SeeLinux (The Linux Kernel).
Next:Thread Names, Previous:Thread CPU Affinity, Up:Non-POSIX Extensions [Contents][Index]
The GNU C Library provides several extensions to thepthread_join
function.
int
pthread_tryjoin_np(pthread_t *thread, void **thread_return)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Behaves likepthread_join
except that it will returnEBUSY
immediately if the thread specified bythread has not yet terminated.
int
pthread_timedjoin_np(pthread_t *thread, void **thread_return, const struct timespec *abstime)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Behaves likepthread_tryjoin_np
except that it will block until theabsolute timeabstime measured againstCLOCK_REALTIME
isreached if the thread has not terminated by that time and returnEBUSY
. Ifabstime is equal toNULL
then the functionwill wait forever in the same way aspthread_join
.
int
pthread_clockjoin_np(pthread_t *thread, void **thread_return, clockid_tclockid, const struct timespec *abstime)
¶Preliminary:| MT-Safe | AS-Unsafe lock| AC-Unsafe lock| SeePOSIX Safety Concepts.
Behaves likepthread_timedjoin_np
except that the absolute time inabstime is measured against the clock specified byclockid.Currently,clockid must be eitherCLOCK_MONOTONIC
orCLOCK_REALTIME
.
Thesem_clockwait
function also works using aclockid_t
argument. SeePOSIX Semaphores.
Next:Detecting Single-Threaded Execution, Previous:Wait for a thread to terminate, Up:Non-POSIX Extensions [Contents][Index]
int
pthread_setname_np(pthread_tth, const char *name)
¶Gives threadth the namename. This name shows up inps
when it’s listing individual threads.name is aNUL-terminated string of no more than 15 non-NUL characters.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_setname_np(3)SeeLinux (The Linux Kernel).
int
pthread_getname_np(pthread_tth, char *buf, size_tbuflen)
¶Retrieves the name of threadth.This documentation is a stub. For additional information on thisfunction, consult the manual pagepthread_getname_np(3)SeeLinux (The Linux Kernel).
Next:Restartable Sequences, Previous:Thread Names, Up:Non-POSIX Extensions [Contents][Index]
Multi-threaded programs require synchronization among threads. Thissynchronization can be costly even if there is just a single threadand no data is shared between multiple processors. The GNU C Library offersan interface to detect whether the process is in single-threaded mode.Applications can use this information to avoid synchronization, forexample by using regular instructions to load and store memory insteadof atomic instructions, or using relaxed memory ordering instead ofstronger memory ordering.
char
__libc_single_threaded ¶This variable is non-zero if the current process is definitelysingle-threaded. If it is zero, the process may be multi-threaded,or the GNU C Library cannot determine at this point of the program executionwhether the process is single-threaded or not.
Applications must never write to this variable.
Most applications should perform the same actions whether or not__libc_single_threaded
is true, except with lesssynchronization. If this rule is followed, a process thatsubsequently becomes multi-threaded is already in a consistent state.For example, in order to increment a reference count, the followingcode can be used:
if (__libc_single_threaded) atomic_fetch_add (&reference_count, 1, memory_order_relaxed);else atomic_fetch_add (&reference_count, 1, memory_order_acq_rel);
This still requires some form of synchronization on thesingle-threaded branch, so it can be beneficial not to declare thereference count as_Atomic
, and use the GCC__atomic
built-ins. SeeBuilt-in Functions for MemoryModel Aware Atomic Operations inUsing the GNU Compiler Collection(GCC). Then the code to increment a reference count looks like this:
if (__libc_single_threaded) ++reference_count;else __atomic_fetch_add (&reference_count, 1, __ATOMIC_ACQ_REL);
(Depending on the data associated with the reference count, it may bepossible to use the weaker__ATOMIC_RELAXED
memory ordering onthe multi-threaded branch.)
Several functions in the GNU C Library can change the value of the__libc_single_threaded
variable. For example, creating newthreads using thepthread_create
orthrd_create
functionsets the variable to false. This can also happen indirectly, say viaa call todlopen
. Therefore, applications need to make a copyof the value of__libc_single_threaded
if after such a functioncall, behavior must match the value as it was before the call, likethis:
bool single_threaded = __libc_single_threaded;if (single_threaded) prepare_single_threaded ();else prepare_multi_thread ();void *handle = dlopen (shared_library_name, RTLD_NOW);lookup_symbols (handle);if (single_threaded) cleanup_single_threaded ();else cleanup_multi_thread ();
Since the value of__libc_single_threaded
can change from trueto false during the execution of the program, it is not useful forselecting optimized function implementations in IFUNC resolvers.
Atomic operations can also be used on mappings shared amongsingle-threaded processes. This means that a compiler must not use__libc_single_threaded
to optimize atomic operations, unless itis able to prove that the memory is not shared.
Implementation Note: The__libc_single_threaded
variable is not declared asvolatile
because it is expectedthat compilers optimize a sequence of single-threaded checks into onecheck, for example if several reference counts are updated. Thecurrent implementation in the GNU C Library does not set the__libc_single_threaded
variable to a true value if a processturns single-threaded again. Future versions of the GNU C Library may dothis, but only as the result of function calls which imply an acquire(compiler) barrier. (Some compilers assume that well-known functionssuch asmalloc
do not write to global variables, and setting__libc_single_threaded
would introduce a data race andundefined behavior.) In any case, an application must not write to__libc_single_threaded
even if it has joined the lastapplication-created thread because future versions of the GNU C Library maycreate background threads after the first thread has been created, andthe application has no way of knowing that these threads are present.
Previous:Detecting Single-Threaded Execution, Up:Non-POSIX Extensions [Contents][Index]
This section describes restartable sequences integration forthe GNU C Library. This functionality is only available on Linux.
The type of the restartable sequences area. Future versionsof Linux may add additional fields to the end of this structure.
Users need to obtain the address of the restartable sequences area usingthe thread pointer and the__rseq_offset
variable, describedbelow.
One use of the restartable sequences area is to read the current CPUnumber from itscpu_id
field, as an inline version ofsched_getcpu
. The GNU C Library sets thecpu_id
field toRSEQ_CPU_ID_REGISTRATION_FAILED
if registration failed or wasexplicitly disabled.
Furthermore, users can store the address of astruct rseq_cs
object into therseq_cs
field ofstruct rseq
, thusinforming the kernel that the thread enters a restartable sequencecritical section. This pointer and the code areas it itself points tomust not be left pointing to memory areas which are freed or re-used.Several approaches can guarantee this. If the application or librarycan guarantee that the memory used to hold thestruct rseq_cs
andthe code areas it refers to are never freed or re-used, no specialaction must be taken. Else, before that memory is re-used of freed, theapplication is responsible for setting therseq_cs
field toNULL
in each thread’s restartable sequence area to guarantee thatit does not leak dangling references. Because the application does nottypically have knowledge of libraries’ use of restartable sequences, itis recommended that libraries using restartable sequences which may endup freeing or re-using their memory set therseq_cs
field toNULL
before returning from library functions which userestartable sequences.
The manual for therseq
system call can be foundathttps://git.kernel.org/pub/scm/libs/librseq/librseq.git/tree/doc/man/rseq.2.
ptrdiff_t
__rseq_offset ¶This variable contains the offset between the thread pointer (as definedby__builtin_thread_pointer
or the thread pointer register forthe architecture) and the restartable sequences area. This value is thesame for all threads in the process. If the restartable sequences areais located at a lower address than the location to which the threadpointer points, the value is negative.
unsigned int
__rseq_size ¶This variable is either zero (if restartable sequence registrationfailed or has been disabled) or the size of the restartable sequenceregistration. This can be different from the size ofstruct rseq
if the kernel has extended the size of the registration. Ifregistration is successful,__rseq_size
is at least 20 (theinitially active size ofstruct rseq
).
Previous versions of the GNU C Library set this to 32 even if the kernel onlysupported the initial area of 20 bytes because the value included unusedpadding at the end of the restartable sequence area.
unsigned int
__rseq_flags ¶The flags used during restartable sequence registration with the kernel.Currently zero.
int
RSEQ_SIG ¶Each supported architecture provides aRSEQ_SIG
macro insys/rseq.h which contains a signature. That signature isexpected to be present in the code before each restartable sequencesabort handler. Failure to provide the expected signature may terminatethe process with a segmentation fault.
Next:Internal probes, Previous:Threads, Up:Main Menu [Contents][Index]
Thedynamic linker is responsible for loading dynamically linkedprograms and their dependencies (in the form of shared objects). Thedynamic linker in the GNU C Library also supports loading shared objects (suchas plugins) later at run time.
Dynamic linkers are sometimes calleddynamic loaders.
Next:Dynamic Linker Introspection, Up:Dynamic Linker [Contents][Index]
When a dynamically linked program starts, the operating systemautomatically loads the dynamic linker along with the program.The GNU C Library also supports invoking the dynamic linker explicitly tolaunch a program. This command uses the implied dynamic linker(also sometimes called theprogram interpreter):
sh -c 'echo "Hello, world!"'
This command specifies the dynamic linker explicitly:
ld.so /bin/sh -c 'echo "Hello, world!"'
Note thatld.so
does not search thePATH
environmentvariable, so the full file name of the executable needs to be specified.
Theld.so
program supports various options. Options start‘--’ and need to come before the program that is being launched.Some of the supported options are listed below.
--list-diagnostics
Print system diagnostic information in a machine-readable format.SeeDynamic Linker Diagnostics.
The ‘ld.so --list-diagnostics’ produces machine-readablediagnostics output. This output contains system data that affects thebehavior of the GNU C Library, and potentially application behavior as well.
The exact set of diagnostic items can change between releases ofthe GNU C Library. The output format itself is not expected to changeradically.
The following table shows some example lines that can be written by thediagnostics command.
dl_pagesize=0x1000
The system page size is 4096 bytes.
env[0x14]="LANG=en_US.UTF-8"
This item indicates that the 21st environment variable at processstartup contains a setting forLANG
.
env_filtered[0x22]="DISPLAY"
The 35th environment variable isDISPLAY
. Its value is notincluded in the output for privacy reasons because it is not recognizedas harmless by the diagnostics code.
path.prefix="/usr"
This means that the GNU C Library was configured with--prefix=/usr
.
path.system_dirs[0x0]="/lib64/"
path.system_dirs[0x1]="/usr/lib64/"
The built-in dynamic linker search path contains two directories,/lib64
and/usr/lib64
.
As seen above, diagnostic lines assign values (integers or strings) to asequence of labeled subscripts, separated by ‘.’. Some subscriptshave integer indices associated with them. The subscript indices arenot necessarily contiguous or small, so an associative array should beused to store them. Currently, all integers fit into the 64-bitunsigned integer range. Every access path to a value has a fixed type(string or integer) independent of subscript index values. Likewise,whether a subscript is indexed does not depend on previous indices (butmay depend on previous subscript labels).
A syntax description in ABNF (RFC 5234) follows. Note that%x30-39
denotes the range of decimal digits. Diagnostic outputlines are expected to match theline
production.
HEXDIG = %x30-39 / %x61-6f ; lowercase a-f onlyALPHA = %x41-5a / %x61-7a / %x7f ; letters and underscoreALPHA-NUMERIC = ALPHA / %x30-39 / "_"DQUOTE = %x22 ; "; Numbers are always hexadecimal and use a 0x prefix.hex-value-prefix = %x30 %x78hex-value = hex-value-prefix 1*HEXDIG; Strings use octal escape sequences and \\, \".string-char = %x20-21 / %x23-5c / %x5d-7e ; printable but not "\string-quoted-octal = %x30-33 2*2%x30-37string-quoted = "\" ("\" / DQUOTE / string-quoted-octal)string-value = DQUOTE *(string-char / string-quoted) DQUOTEvalue = hex-value / string-valuelabel = ALPHA *ALPHA-NUMERICindex = "[" hex-value "]"subscript = label [index]line = subscript *("." subscript) "=" value
Previous:Dynamic Linker Diagnostics Format, Up:Dynamic Linker Diagnostics [Contents][Index]
As mentioned above, the set of diagnostics may change betweenthe GNU C Library releases. Nevertheless, the following table documents a fewcommon diagnostic items. All numbers are in hexadecimal, with a‘0x’ prefix.
dl_dst_lib=string
The$LIB
dynamic string token expands tostring.
dl_hwcap=integer
¶dl_hwcap2=integer
The HWCAP and HWCAP2 values, as returned forgetauxval
, and asused in other places depending on the architecture.
dl_pagesize=integer
¶The system page size isinteger bytes.
dl_platform=string
The$PLATFORM
dynamic string token expands tostring.
dso.libc=string
This is the soname of the sharedlibc
object that is part ofthe GNU C Library. On most architectures, this islibc.so.6
.
env[index]=string
env_filtered[index]=string
An environment variable from the process environment. The integerindex is the array index in the environment array. Variablesunderenv
include the variable value after the ‘=’ (assumingthat it was present), variables underenv_filtered
do not.
path.prefix=string
This indicates that the GNU C Library was configured using‘--prefix=string’.
path.sysconfdir=string
The GNU C Library was configured (perhaps implicitly) with‘--sysconfdir=string’ (typically/etc
).
path.system_dirs[index]=string
These items list the elements of the built-in array that describes thedefault library search path. The valuestring is a directory filename with a trailing ‘/’.
path.rtld=string
This string indicates the application binary interface (ABI) file nameof the run-time dynamic linker.
version.release="stable"
version.release="development"
The value"stable"
indicates that this build of the GNU C Library isfrom a release branch. Releases labeled as"development"
areunreleased development versions.
version.version="major.minor"
¶version.version="major.minor.9000"
The GNU C Library version. Development releases end in ‘.9000’.
auxv[index].a_type=type
¶auxv[index].a_val=integer
auxv[index].a_val_string=string
An entry in the auxiliary vector (specific to Linux). The valuestype (an integer) andinteger correspond to the members ofstruct auxv
. If the value is a string,a_val_string
isused instead ofa_val
, so that values have consistent types.
TheAT_HWCAP
andAT_HWCAP2
values in this output do notreflect adjustment by the GNU C Library.
uname.sysname=string
uname.nodename=string
uname.release=string
uname.version=string
uname.machine=string
uname.domain=string
These Linux-specific items show the values ofstruct utsname
, asreported by theuname
function. SeePlatform Type Identification.
aarch64.cpu_features.…
These items are specific to the AArch64 architectures. They report datathe GNU C Library uses to activate conditionally supported features such asBTI and MTE, and to select alternative function implementations.
aarch64.processor[index].…
These are additional items for the AArch64 architecture and aredescribed below.
aarch64.processor[index].requested=kernel-cpu
The kernel is told to run the subsequent probing on the CPU numberedkernel-cpu. The valueskernel-cpu andindex can bedistinct if there are gaps in the process CPU affinity mask. This lineis not included if CPU affinity mask information is not available.
aarch64.processor[index].observed=kernel-cpu
This line reports the kernel CPU numberkernel-cpu on which theprobing code initially ran. If the CPU number cannot be obtained,this line is not printed.
aarch64.processor[index].observed_node=node
This reports the observed NUMA node number, as reported by thegetcpu
system call. If this information cannot be obtained, thisline is not printed.
aarch64.processor[index].midr_el1=value
The value of themidr_el1
system register on the processorindex. This line is only printed if the kernel indicates thatthis system register is supported.
aarch64.processor[index].dczid_el0=value
The value of thedczid_el0
system register on the processorindex.
x86.cpu_features.…
¶These items are specific to the i386 and x86-64 architectures. Theyreflect supported CPU features and information on cache geometry, mostlycollected using the CPUID instruction.
x86.processor[index].…
These are additional items for the i386 and x86-64 architectures, asdescribed below. They mostly contain raw data from the CPUIDinstruction. The probes are performed for each active CPU for theld.so
process, and data for different probed CPUs receives auniqeindex value. Some CPUID data is expected to differ from CPUcore to CPU core. In some cases, CPUs are not correctly initialized andindicate the presence of different feature sets.
x86.processor[index].requested=kernel-cpu
The kernel is told to run the subsequent probing on the CPU numberedkernel-cpu. The valueskernel-cpu andindex can bedistinct if there are gaps in the process CPU affinity mask. This lineis not included if CPU affinity mask information is not available.
x86.processor[index].observed=kernel-cpu
This line reports the kernel CPU numberkernel-cpu on which theprobing code initially ran. If the CPU number cannot be obtained,this line is not printed.
x86.processor[index].observed_node=node
This reports the observed NUMA node number, as reported by thegetcpu
system call. If this information cannot be obtained, thisline is not printed.
x86.processor[index].cpuid_leaves=count
This line indicates thatcount distinct CPUID leaves wereencountered. (This reflects internalld.so
storage space, itdoes not directly correspond toCPUID
enumeration ranges.)
x86.processor[index].ecx_limit=value
The CPUID data extraction code uses a brute-force approach to enumeratesubleaves (see the ‘.subleaf_eax’ lines below). The last%rcx
value used in a CPUID query on this probed CPU wasvalue.
x86.processor[index].cpuid.eax[query_eax].eax=eax
x86.processor[index].cpuid.eax[query_eax].ebx=ebx
x86.processor[index].cpuid.eax[query_eax].ecx=ecx
x86.processor[index].cpuid.eax[query_eax].edx=edx
These lines report the register contents after executing the CPUIDinstruction with ‘%rax ==query_eax’ and ‘%rcx == 0’ (aleaf). For the first probed CPU (with a zeroindex), onlyleaves with non-zero register contents are reported. For subsequentCPUs, only leaves whose register contents differs from the previouslyprobed CPUs (withindex one less) are reported.
Basic and extended leaves are reported using the same syntax. Thismeans there is a large jump inquery_eax for the first reportedextended leaf.
x86.processor[index].cpuid.subleaf_eax[query_eax].ecx[query_ecx].eax=eax
x86.processor[index].cpuid.subleaf_eax[query_eax].ecx[query_ecx].ebx=ebx
x86.processor[index].cpuid.subleaf_eax[query_eax].ecx[query_ecx].ecx=ecx
x86.processor[index].cpuid.subleaf_eax[query_eax].ecx[query_ecx].edx=edx
This is similar to the leaves above, but for asubleaf. Forsubleaves, the CPUID instruction is executed with ‘%rax ==query_eax’ and ‘%rcx ==query_ecx’, so the resultdepends on both register values. The same rules about filtering zeroand identical results apply.
x86.processor[index].cpuid.subleaf_eax[query_eax].ecx[query_ecx].until_ecx=ecx_limit
Some CPUID results are the same regardless thequery_ecx value.If this situation is detected, a line with the ‘.until_ecx’selector ins included, and this indicates that the CPUID registercontents is the same for%rcx
values betweenquery_ecxandecx_limit (inclusive).
x86.processor[index].cpuid.subleaf_eax[query_eax].ecx[query_ecx].ecx_query_mask=0xff
This line indicates that in an ‘.until_ecx’ range, the CPUIDinstruction preserved the lowested 8 bits of the input%rcx
inthe output%rcx
registers. Otherwise, the subleaves in the rangehave identical values. This special treatment is necessary to reportcompact range information in case such copying occurs (because thesubleaves would otherwise be all different).
x86.processor[index].xgetbv.ecx[query_ecx]=result
This line shows the 64-bitresult value in the%rdx:%rax
register pair after executing the XGETBV instruction with%rcx
set toquery_ecx. Zero values and values matching the previouslyprobed CPU are omitted. Nothing is printed if the system does notsupport the XGETBV instruction.
Next:Avoiding Unexpected Issues With Dynamic Linking, Previous:Dynamic Linker Invocation, Up:Dynamic Linker [Contents][Index]
The GNU C Library provides various facilities for querying information from thedynamic linker.
Alink map is associated with the main executable and each sharedobject. Some fields of the link map are accessible to applications andexposed through thestruct link_map
. Applications must not modifythe link map directly.
Pointers to link maps can be obtained from the_r_debug
variable,from theRTLD_DI_LINKMAP
request fordlinfo
, and from the_dl_find_object
function. See below for details.
l_addr
¶This field contains theload address of the object. This is theoffset that needs to be applied to unrelocated addresses in the objectimage (as stored on disk) to form an address that can be used at runtime for accessing data or running code. For position-dependentexecutables, the load address is typically zero, and no adjustment isrequired. For position-independent objects, thel_addr
fieldusually contains the address of the object’s ELF header in the processimage. However, this correspondence is not guaranteed because the ELFheader might not be mapped at all, and the ELF file as stored on diskmight use zero as the lowest virtual address. Due to the secondvariable, values of thel_addr
field do not necessarily uniquelyidentify a shared object.
On Linux, to obtain the lowest loaded address of the main program, usegetauxval
to obtain theAT_PHDR
andAT_PHNUM
valuesfor the current process. Alternatively, call‘dlinfo (_r_debug.r_map, &phdr)’to obtain the number of program headers, and the address of the programheader array will be stored inphdr(of typeconst ElfW(Phdr) *
, as explained below).These values allow processing the array of program headers and theaddress information in thePT_LOAD
entries among them.This works even when the program was started with an explicit loaderinvocation.
l_name
For a shared object, this field contains the file name that thethe GNU C Library dynamic loader used when opening the object. This can bea relative path (relative to the current directory at process start,or if the object was loaded later, viadlopen
ordlmopen
). Symbolic links are not necessarily resolved.
For the main executable,l_name
is ‘""’ (the empty string).(The main executable is not loaded by the GNU C Library, so its file name isnot available.) On Linux, the main executable is available as/proc/self/exe (unless an explicit loader invocation was used tostart the program). The file name/proc/self/exe continues toresolve to the same file even if it is moved within or deleted from thefile system. Its current location can be read usingreadlink
.SeeSymbolic Links. (Although/proc/self/exe is not actuallya symbol link, it is only presented as one.) Note that/proc maynot be mounted, in which case/proc/self/exe is not available.
If an explicit loader invocation is used (such as ‘ld.so/usr/bin/emacs’), the/proc/self/exe approach does not workbecause the file name refers to the dynamic linkerld.so
, and notthe/usr/bin/emacs
program. An approximation to the executablepath is still available in theinfo.dli_fname
member aftercalling ‘dladdr (_r_debug.r_map->l_ld, &info)’. Note thatthis could be a relative path, and it is supplied by the process thatcreated the current process, not the kernel, so it could be inaccurate.
l_ld
This is a pointer to the ELF dynamic segment, an array of tag/valuepairs that provide various pieces of information that the dynamiclinking process uses. On most architectures, addresses in the dynamicsegment are relocated at run time, but on some architectures and in somerun-time configurations, it is necessary to add thel_addr
fieldvalue to obtain a proper address.
l_prev
l_next
These fields are used to maintain a double-linked linked list of alllink maps within onedlmopen
namespace. Note that there iscurrently no thread-safe way to iterate over this list. Thecallback-baseddl_iterate_phdr
interface can be used instead.
Portability note: It is not possible to create astructlink_map
object and pass a pointer to a function that expects astruct link_map *
argument. Only link map pointers initiallysupplied by the GNU C Library are permitted as arguments. In current versionsof the GNU C Library, handles returned bydlopen
anddlmopen
arepointers to link maps. However, this is not a portable assumption, andmay even change in future versions of the GNU C Library. To obtain the linkmap associated with a handle, seedlinfo
andRTLD_DI_LINKMAP
below. If a function accepts bothdlopen
/dlmopen
handles andstruct link_map
pointersin itsvoid *
argument, that is documented explicitly.
Thedlinfo
function provides access to internal informationassociated withdlopen
/dlmopen
handles and link maps.
int
dlinfo(void *handle, intrequest, void *arg)
¶| MT-Safe | AS-Unsafe corrupt| AC-Unsafe corrupt| SeePOSIX Safety Concepts.
This function returns information abouthandle in the memorylocationarg, based onrequest. Thehandle argumentmust be a pointer returned bydlopen
ordlmopen
; it mustnot have been closed bydlclose
. Alternatively,handlecan be astruct link_map *
value for a link map of an objectthat has not been closed.
On success,dlinfo
returns 0 for most request types; exceptionsare noted below. If there is an error, the function returns-1,anddlerror
can be used to obtain a corresponding error message.
The following operations are defined for use withrequest:
RTLD_DI_LINKMAP
¶The correspondingstruct link_map
pointer forhandle iswritten to*arg
. Thearg argument must be theaddress of an object of typestruct link_map *
.
RTLD_DI_LMID
¶The namespace identifier ofhandle is written to*arg
. Thearg argument must be the address of anobject of typeLmid_t
.
RTLD_DI_ORIGIN
¶The value of the$ORIGIN
dynamic string token forhandle iswritten to the character array starting atarg as anull-terminated string.
This request type should not be used because it is prone to bufferoverflows.
RTLD_DI_SERINFO
¶RTLD_DI_SERINFOSIZE
¶These requests can be used to obtain search path information forhandle. For both requests,arg must point to aDl_serinfo
object. TheRTLD_DI_SERINFOSIZE
request mustbe made first; it updates thedls_size
anddls_cnt
membersof theDl_serinfo
object. The caller should then allocate memoryto store at leastdls_size
bytes and pass that buffer to aRTLD_DI_SERINFO
request. This second request fills thedls_serpath
array. The number of array elements was returned inthedls_cnt
member in the initialRTLD_DI_SERINFOSIZE
request. The caller is responsible for freeing the allocated buffer.
This interface is prone to buffer overflows in multi-threaded processesbecause the required size can change between theRTLD_DI_SERINFOSIZE
andRTLD_DI_SERINFO
requests.
RTLD_DI_TLS_DATA
¶This request writes the address of the TLS block (in the current thread)for the shared object identified byhandle to*arg
.The argumentarg must be the address of an object of typevoid *
. A null pointer is written if the object does not haveany associated TLS block.
RTLD_DI_TLS_MODID
¶This request writes the TLS module ID for the shared objecthandleto*arg
. The argumentarg must be the address of anobject of typesize_t
. The module ID is zero if the objectdoes not have an associated TLS block.
RTLD_DI_PHDR
¶This request writes the address of the program header array to*arg
. The argumentarg must be the address of anobject of typeconst ElfW(Phdr) *
(that is,const Elf32_Phdr *
orconst Elf64_Phdr *
, as appropriatefor the current architecture). For this request, the value returned bydlinfo
is the number of program headers in the program headerarray.
Thedlinfo
function is a GNU extension.
The remainder of this section documents the_dl_find_object
function and supporting types and constants.
This structure contains information about a main program or loadedobject. The_dl_find_object
function uses it to returnresult data to the caller.
unsigned long long int dlfo_flags
Bit zero signals if SFrame stack data is valid. SeeDLFO_FLAG_SFRAME
below.
void *dlfo_map_start
The start address of the inspected mapping. This information comes fromthe program header, so it follows its convention, and the address is notnecessarily page-aligned.
void *dlfo_map_end
The end address of the mapping.
struct link_map *dlfo_link_map
This member contains a pointer to the link map of the object.
void *dlfo_eh_frame
This member contains a pointer to the exception handling data of theobject. SeeDLFO_EH_SEGMENT_TYPE
below.
void *dlfo_sframe
This member points to the SFrame stack trace data associated with theobject. It is valid only whenDLFO_FLAG_SFRAME
is set indlfo_flags
; otherwise, it may be null or undefined.
This structure is a GNU extension.
int
DLFO_STRUCT_HAS_EH_DBASE ¶On most targets, this macro is defined as0
. If it is defined to1
,struct dl_find_object
contains an additional memberdlfo_eh_dbase
of typevoid *
. It is the base address forDW_EH_PE_datarel
DWARF encodings to this location.
This macro is a GNU extension.
int
DLFO_STRUCT_HAS_EH_COUNT ¶On most targets, this macro is defined as0
. If it is defined to1
,struct dl_find_object
contains an additional memberdlfo_eh_count
of typeint
. It is the number of exceptionhandling entries in the EH frame segment identified by thedlfo_eh_frame
member.
This macro is a GNU extension.
int
DLFO_EH_SEGMENT_TYPE ¶On targets using DWARF-based exception unwinding, this macro expands toPT_GNU_EH_FRAME
. This indicates thatdlfo_eh_frame
instruct dl_find_object
points to thePT_GNU_EH_FRAME
segment of the object. On targets that use other unwinding formats, themacro expands to the program header type for the unwinding data.
This macro is a GNU extension.
int
_dl_find_object(void *address, struct dl_find_object *result)
¶| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
On success, this function returns 0 and writes about the objectsurrounding the address to*result
. On failure, -1 isreturned.
Theaddress can be a code address or data address. Onarchitectures using function descriptors, no attempt is made to decodethe function descriptor. Depending on how these descriptors areimplemented,_dl_find_object
may return the object that definesthe function descriptor (and not the object that contains the codeimplementing the function), or fail to find any object at all.
On successaddress is greater than or equal toresult->dlfo_map_start
and less thanresult->dlfo_map_end
, that is, the supplied code address islocated within the reported mapping.
This function returns a pointer to the unwinding information for theobject that contains the program codeaddress inresult->dlfo_eh_frame
. If the platform uses DWARFunwinding information, this is the in-memory address of thePT_GNU_EH_FRAME
segment. SeeDLFO_EH_SEGMENT_TYPE
above.In caseaddress resides in an object that lacks unwinding information,the function still returns 0, but setsresult->dlfo_eh_frame
to a null pointer.
_dl_find_object
itself is thread-safe. However, if theapplication invokesdlclose
for the object that containsaddress concurrently with_dl_find_object
or after the callreturns, accessing the unwinding data for that object or the link map(throughresult->dlfo_link_map
) is not safe. Therefore, theapplication needs to ensure by other means (e.g., by convention) thataddress remains a valid code address while the unwindinginformation is processed.
This function is a GNU extension.
The following flag masks are defined for use withdlfo_flags
:
DLFO_FLAG_SFRAME
A bit mask used to signal that the object contains SFrame data. Seedlfo_sframe
above.
Previous:Dynamic Linker Introspection, Up:Dynamic Linker [Contents][Index]
This section details recommendations for increasing applicationrobustness, by avoiding potential issues related to dynamic linking.The recommendations have two main aims: reduce the involvement of thedynamic linker in application execution after process startup, andrestrict the application to a dynamic linker feature set whose behavioris more easily understood.
Key aspects of limiting dynamic linker usage after startup are: no useof thedlopen
function, disabling lazy binding, and using thestatic TLS model. More easily understood dynamic linker behaviorrequires avoiding name conflicts (symbols and sonames) and highlycustomizable features like the audit subsystem.
Note that while these steps can be considered a form of applicationhardening, they do not guard against potential harm from accidental ordeliberate loading of untrusted or malicious code. There is onlylimited overlap with traditional security hardening for applicationsrunning on GNU systems.
Avoiding certain dynamic linker features can increase predictability ofapplications and reduce the risk of running into dynamic linker defects.
dlopen
,dlmopen
, ordlclose
. Dynamic loading and unloading of shared objectsintroduces substantial complications related to symbol and thread-localstorage (TLS) management.dlopen
function,dlsym
anddlvsym
cannot be used with shared object handles. Minimizing the use of bothfunctions is recommended. If they have to be used, only theRTLD_DEFAULT
pseudo-handle should be used.dlopen
is notused, there are no compatibility concerns for initial-exec TLS. ThisTLS model avoids most of the complexity around TLS access. Inparticular, there are no TLS-related run-time memory allocations afterprocess or thread start.If shared objects are expected to be used more generally, outside thehardened, feature-restricted context, lack of compatibility betweendlopen
and initial-exec TLS could be a concern. In that case,the second-best alternative is to use global-dynamic TLS with GNU2 TLSdescriptors, for targets that fully implement them, including the fastpath for access to TLS variables defined in the initially loaded set ofobjects. Like initial-exec TLS, this avoids memory allocations afterthread creation, but only if thedlopen
function is not used.
libc.so.6
) are always loaded.Specifically, if a main program or shared object references a symbol,create an ELFDT_NEEDED
dependency on that shared object, or onanother shared object that is documented (or otherwise guaranteed) tohave the required explicit dependency. Referencing a symbol without amatching link dependency results in underlinking, and underlinkedobjects cannot always be loaded correctly: Initialization of objects maynot happen in the required order.libA.so.1
depending onlibB.so.1
depending onlibC.so.1
depending onlibA.so.1
). The GNU C Library has to initialize one of the objects inthe cycle first, and the choice of that object is arbitrary and canchange over time. The object which is initialized first (and otherobjects involved in the cycle) may not run correctly because not all ofits dependencies have been initialized.Underlinking (see above) can hide the presence of cycles.
LD_AUDIT
,DT_AUDIT
,DT_DEPAUDIT
). Its callback and hooking capabilities introduce alot of complexity and subtly alter dynamic linker behavior in cornercases even if the audit module is inactive.Exceptions to this rule are copy relocations (see the next item), andvague linkage, as used by the C++ implementation (see below).
A different approach to this situation uses hidden visibility forsymbols in the static library, but this can cause problems if thelibrary does not expect that multiple copies of its code coexist withinthe same process, with no or partial sharing of state.
.text
).DT_PREINIT_ARRAY
dynamic tag, and do not flagobjects asDF_1_INITFIRST
. Do not change the default linkerscript of BFD ld. Do not override ABI defaults, such as the dynamiclinker path (with--dynamic-linker).dlopen
. Useiconv_open
with built-in converters only(such asUTF-8
). Do not use NSS functionality such asgetaddrinfo
orgetpwuid_r
unless the system is configuredfor built-in NSS service modules only (see below).Several considerations apply to ELF constructors and destructors.
DT_NEEDED
dependency on the object that needs to be initializedearlier.dlsym
anddlvsym
, it is still possible to access uninitialized facilitieseven with these restrictions in place. (Of course, access touninitialized functionality is also possible within a single sharedobject or the main executable, without resorting to explicit symbollookup.) Consider using dynamic, on-demand initialization instead. Todeal with access after de-initialization, it may be necessary toimplement special cases for that scenario, potentially with degradedfunctionality.dlsym
anddlvsym
function calls, forexample if client code using a shared object has registered callbacks orobjects with another shared object. The ELF destructor for the clientcode is executed before the ELF destructor for the shared objects thatit uses, based on the expected dependency order.dlopen
anddlmopen
are not used,DT_NEEDED
dependency information is complete, and lazy binding is disabled, theexecution order of ELF destructors is expected to be the reverse of theELF constructor order. However, two separate dependency sort operationsstill occur. Even though the listed preconditions should ensure thatboth sorts produce the same ordering, it is recommended not to depend onthe destructor order being the reverse of the constructor order.The following items provide C++-specific guidance for preparingapplications. If another programming language is used and it uses thesetoolchain features targeted at C++ to implement some languageconstructs, these restrictions and recommendations still apply inanalogous ways.
By default, variables of block scope of static storage have consistentaddresses across different translation units, even if defined infunctions that use vague linkage.
Due to the complex interaction between ELF symbol management and C++symbol generation, it is recommended to use C++ language features forsymbol management, in particular inline namespaces.
This does not matter if the original (language-independent) adviceregarding symbol interposition is followed. However, as the advice maybe difficult to implement for C++ applications, it is recommended toavoid ODR violations across the entire process image. Inline namespacescan be helpful in this context because they can be used to createdistinct ELF symbols while maintaining source code compatibility at theC++ level.
STB_GNU_UNIQUE
binding type do not follow the usual ELF symbolnamespace isolation rules: such symbols bind acrossRTLD_LOCAL
boundaries. Furthermore, symbol versioning is ignored for such symbols;they are bound by symbol name only. All their definitions and uses musttherefore be compatible. Hidden visibility still prevents the creationofSTB_GNU_UNIQUE
symbols and can achieve isolation ofincompatible definitions.RTLD_LOCAL
ordlmopen
.This can cause issues in applications that contain multiple incompatibledefinitions of the same type. Inline namespaces can be used to createdistinct symbols at the ELF layer, avoiding this type of issue.
dlmopen
namespaces maynot work, particular with the unwinder in GCC versions before 12.Current toolchain versions are able to process unwinding tables acrossdlmopen
boundaries. However, note that type comparison isname-based, not address-based (see the previous item), so exceptiontypes may still be matched in unexpected ways. An important specialcase of exception handling, invoking destructors for variables of blockscope, is not impacted by this RTTI type-sharing. Likewise, regularvirtual member function dispatch for objects is unaffected (but stillrequires that the type definitions match in all directly involvedtranslation units).Once more, inline namespaces can be used to create distinct ELF symbolsfor different types.
dlclose
.thread_local
variables with threadstorage duration of types that have non-trivial destructors. However,in this case, memory allocation failure during registration leads toprocess termination. If process termination is not acceptable, usethread_local
variables with trivial destructors only.Functions for per-thread cleanup can be registered usingpthread_key_create
(globally for all threads) and activatedusingpthread_setspecific
(on each thread). Note that apthread_key_create
call may still fail (andpthread_create
keys are a limited resource in the GNU C Library), butthis failure can be handled without terminating the process.This subsection recommends tools and build flags for producingapplications that meet the recommendations of the previous subsection.
bfd.ld
) from GNU binutils to produce binaries,invoked through a compiler driver such asgcc
. The versionshould be not too far ahead of what was current when the version ofthe GNU C Library was first released..so
files (which can be linkerscripts) and searching with the-l option. Do not specify thefile names of shared objects on the linker command line.LOAD
segment in the ELF program header, fileoffsets, memory sizes, and load addresses are multiples of the largestpage size supported at run time. Similarly, the start address and sizeof theGNU_RELRO
range should be multiples of the page size.Avoid creating gaps betweenLOAD
segments. The differencebetween the load addresses of two subsequentLOAD
segments shouldbe the size of the firstLOAD
segment. (This may require linkingwith-Wl,-z,noseparate-code.)
This may not be possible to achieve with the currently available linkeditors.
GNU_RELRO
regioncannot be achieved, ensure that the process memory image right beforethe start of the region does not contain executable or writable memory.In some cases, if the previous recommendations are not followed, thiscan be determined from the produced binaries. This section containssuggestions for verifying aspects of these binaries.
NEEDED
entries are present. (It is not necessary tolist indirect dependencies if these dependencies are guaranteed toremain during the evolution of the explicitly listed directdependencies.)NEEDED
entries should not contain full path names includingslashes, onlysonames
.NEEDED
entries in dynamic segments, transitively, starting atthe main program. Then determine their dynamic symbol tables (using‘readelf -sDW’, for example). Ideally, every symbol should bedefined at most once, so that symbol interposition does not happen.If there are interposed data symbols, check if the single interposingdefinition is in the main program. In this case, there must be a copyrelocation for it. (This only applies to targets with copy relocations.)
Function symbols should only be interposed in C++ applications, toimplement vague linkage. (See the discussion in the C++ recommendationsabove.)
NEEDED
entries, check that thedependency graph does not contain any cycles.BIND_NOW
on theFLAGS
line orNOW
on theFLAGS_1
line (one isenough).R_AARCH64_TLS_TPREL
andX86_64_TPOFF64
. As the second-best option, and only ifcompatibility with non-hardened applications usingdlopen
isneeded, GNU2 TLS descriptor relocations can be used (for example,R_AARCH64_TLSDESC
orR_X86_64_TLSDESC
).__tls_get_addr
,__tls_get_offset
,__tls_get_addr_opt
in the dynamic symbol table (in the‘readelf -sDW’ output). Supporting global dynamic TLS relocations(such asR_AARCH64_TLS_DTPMOD
,R_AARCH64_TLS_DTPREL
,R_X86_64_DTPMOD64
,R_X86_64_DTPOFF64
) should not be used,either.dlopen
,dlmopen
,dlclose
should not be referenced from the dynamic symbol table.SONAME
entry that matchesthe file name (the base name, i.e., the part after the slash). TheSONAME
string must not contain a slash ‘/’.RPATH
orRUNPATH
entries.AUDIT
,DEPAUDIT
,AUXILIARY
,FILTER
, orPREINIT_ARRAY
tags.HASH
tag, itmust also contain aGNU_HASH
tag.INITFIRST
flag (undeerFLAGS_1
) should not be used.LOAD
segments that are writableand executable at the same time.GNU_STACK
program header thatis not marked as executable. (However, on some newer targets, anon-executable stack is the default, so theGNU_STACK
programheader is not required.)In addition to preparing program binaries in a recommended fashion, therun-time environment should be set up in such a way that problematicdynamic linker features are not used.
LD_…
variables such asLD_PRELOAD
orLD_LIBRARY_PATH
, orGLIBC_TUNABLES
)to change default dynamic linker behavior.ldconfig
,usually/etc/ld.so.conf, or in files included from there.)glibc-hwcaps
subdirectories.dlopen
facility. Thefiles
anddns
modules are built in and do not rely ondlopen
.rename
to replace thealready-installed version.Next:Tunables, Previous:Dynamic Linker, Up:Main Menu [Contents][Index]
In order to aid in debugging and monitoring internal behavior,the GNU C Library exposes nearly-zero-overhead SystemTap probes marked withthelibc
provider.
These probes are not part of the GNU C Library stable ABI, and they aresubject to change or removal across releases. Our only promise withregard to them is that, if we find a need to remove or modify thearguments of a probe, the modified probe will have a different name, sothat program monitors relying on the old probe will not get unexpectedarguments.
Next:Non-local Goto Probes, Up:Internal probes [Contents][Index]
These probes are designed to signal relatively unusual situations withinthe virtual memory subsystem of the GNU C Library.
This probe is triggered after the main arena is extended by callingsbrk
. Argument$arg1 is the additional size requested tosbrk
, and$arg2 is the pointer that marks the end of thesbrk
area, returned in response to the request.
This probe is triggered after the size of the main arena is decreased bycallingsbrk
. Argument$arg1 is the size released bysbrk
(the positive value, rather than the negative value passedtosbrk
), and$arg2 is the pointer that marks the end ofthesbrk
area, returned in response to the request.
This probe is triggered after a new heap ismmap
ed. Argument$arg1 is a pointer to the base of the memory area, where theheap_info
data structure is held, and$arg2 is the size ofthe heap.
This probe is triggeredbefore (unlike the other sbrk and heapprobes) a heap is completely removed viamunmap
. Argument$arg1 is a pointer to the heap, and$arg2 is the size of theheap.
This probe is triggered after a trailing portion of anmmap
edheap is extended. Argument$arg1 is a pointer to the heap, and$arg2 is the new size of the heap.
This probe is triggered after a trailing portion of anmmap
edheap is released. Argument$arg1 is a pointer to the heap, and$arg2 is the new size of the heap.
These probes are triggered when the corresponding functions fail toobtain the requested amount of memory from the arena in use, before theycallarena_get_retry
to select an alternate arena in which toretry the allocation. Argument$arg1 is the amount of memoryrequested by the user; in thecalloc
case, that is the total sizecomputed from both function arguments. In therealloc
case,$arg2 is the pointer to the memory area being resized. In thememalign
case,$arg2 is the alignment to be used for therequest, which may be stricter than the value passed to thememalign
function. Amemalign
probe is also used by functionsposix_memalign, valloc
andpvalloc
.
Note that the argument order doesnot match that of thecorresponding two-argument functions, so that in all of these probes theuser-requested allocation size is in$arg1.
This probe is triggered withinarena_get_retry
(the functioncalled to select the alternate arena in which to retry an allocationthat failed on the first attempt), before the selection of an alternatearena. This probe is redundant, but much easier to use when it’s notimportant to determine which of the various memory allocation functionsis failing to allocate on the first try. Argument$arg1 is thesame as in the function-specific probes, except for extra room forpadding introduced by functions that have to ensure stricter alignment.Argument$arg2 is the arena in which allocation failed.
This probe is triggered whenmalloc
allocates and initializes anadditional arena (not the main arena), but before the arena is assignedto the running thread or inserted into the internal linked list ofarenas. The arena’smalloc_state
internal data structure islocated at$arg1, within a newly-allocated heap big enough to holdat least$arg2 bytes.
This probe is triggered whenmalloc
has just selected an existingarena to reuse, and (temporarily) reserved it for exclusive use.Argument$arg1 is a pointer to the newly-selected arena, and$arg2 is a pointer to the arena previously used by that thread.
This occurs withinreused_arena
, right after the mutex mentioned in probememory_arena_reuse_wait
is acquired; argument$arg1 willpoint to the same arena. In this configuration, this will usually onlyoccur once per thread. The exception is when a thread first selectedthe main arena, but a subsequent allocation from it fails: then, andonly then, may we switch to another arena to retry that allocation, andfor further allocations within that thread.
This probe is triggered whenmalloc
is about to wait for an arenato become available for reuse. Argument$arg1 holds a pointer tothe mutex the thread is going to wait on,$arg2 is a pointer to anewly-chosen arena to be reused, and$arg3 is a pointer to thearena previously used by that thread.
This occurs withinreused_arena
, when a thread first tries to allocate memory orneeds a retry after a failure to allocate from the main arena, thereisn’t any free arena, the maximum number of arenas has been reached, andan existing arena was chosen for reuse, but its mutex could not beimmediately acquired. The mutex in$arg1 is the mutex of theselected arena.
This probe is triggered whenmalloc
has chosen an arena that isin the free list for use by a thread, within theget_free_list
function. The argument$arg1 holds a pointer to the selected arena.
This probe is triggered when functionmallopt
is called to changemalloc
internal configuration parameters, before any change tothe parameters is made. The arguments$arg1 and$arg2 arethe ones passed to themallopt
function.
This probe is triggered shortly after thememory_mallopt
probe,when the parameter to be changed isM_MXFAST
, and the requestedvalue is in an acceptable range. Argument$arg1 is the requestedvalue, and$arg2 is the previous value of thismalloc
parameter.
This probe is triggered shortly after thememory_mallopt
probe,when the parameter to be changed isM_TRIM_THRESHOLD
. Argument$arg1 is the requested value,$arg2 is the previous value ofthismalloc
parameter, and$arg3 is nonzero if dynamicthreshold adjustment was already disabled.
This probe is triggered shortly after thememory_mallopt
probe,when the parameter to be changed isM_TOP_PAD
. Argument$arg1 is the requested value,$arg2 is the previous value ofthismalloc
parameter, and$arg3 is nonzero if dynamicthreshold adjustment was already disabled.
This probe is triggered shortly after thememory_mallopt
probe,when the parameter to be changed isM_MMAP_THRESHOLD
, and therequested value is in an acceptable range. Argument$arg1 is therequested value,$arg2 is the previous value of thismalloc
parameter, and$arg3 is nonzero if dynamic threshold adjustmentwas already disabled.
This probe is triggered shortly after thememory_mallopt
probe,when the parameter to be changed isM_MMAP_MAX
. Argument$arg1 is the requested value,$arg2 is the previous value ofthismalloc
parameter, and$arg3 is nonzero if dynamicthreshold adjustment was already disabled.
This probe is triggered shortly after thememory_mallopt
probe,when the parameter to be changed isM_PERTURB
. Argument$arg1 is the requested value, and$arg2 is the previousvalue of thismalloc
parameter.
This probe is triggered shortly after thememory_mallopt
probe,when the parameter to be changed isM_ARENA_TEST
, and therequested value is in an acceptable range. Argument$arg1 is therequested value, and$arg2 is the previous value of thismalloc
parameter.
This probe is triggered shortly after thememory_mallopt
probe,when the parameter to be changed isM_ARENA_MAX
, and therequested value is in an acceptable range. Argument$arg1 is therequested value, and$arg2 is the previous value of thismalloc
parameter.
This probe is triggered when functionfree
decides to adjust thedynamic brk/mmap thresholds. Argument$arg1 and$arg2 arethe adjusted mmap and trim thresholds, respectively.
This probe is triggered when theglibc.malloc.tcache_max
tunable is set. Argument$arg1 is the requested value, and$arg2 is the previous value of this tunable.
This probe is triggered when theglibc.malloc.tcache_count
tunable is set. Argument$arg1 is the requested value, and$arg2 is the previous value of this tunable.
This probe is triggered when theglibc.malloc.tcache_unsorted_limit
tunable is set. Argument$arg1 is the requested value, and$arg2 is the previousvalue of this tunable.
This probe is triggered whenfree
determines that the memorybeing freed has probably already been freed, and resides in theper-thread cache. Note that there is an extremely unlikely chancethat this probe will trigger due to random payload data remaining inthe allocated memory matching the key used to detect double frees.This probe actually indicates that an expensive linear search of thetcache, looking for a double free, has happened. Argument$arg1is the memory location as passed tofree
, Argument$arg2is the tcache bin it resides in.
Previous:Memory Allocation Probes, Up:Internal probes [Contents][Index]
These probes are used to signal calls tosetjmp
,sigsetjmp
,longjmp
orsiglongjmp
.
This probe is triggered wheneversetjmp
orsigsetjmp
iscalled. Argument$arg1 is a pointer to thejmp_buf
passed as the first argument ofsetjmp
orsigsetjmp
,$arg2 is the second argument ofsigsetjmp
or zero if thisis a call tosetjmp
and$arg3 is a pointer to the returnaddress that will be stored in thejmp_buf
.
This probe is triggered wheneverlongjmp
orsiglongjmp
is called. Argument$arg1 is a pointer to thejmp_buf
passed as the first argument oflongjmp
orsiglongjmp
,$arg2 is the return value passed as the second argument oflongjmp
orsiglongjmp
and$arg3 is a pointer tothe return addresslongjmp
orsiglongjmp
will return to.
Thelongjmp
probe is triggered at a point where the registershave not yet been restored to the values in thejmp_buf
andunwinding will show a call stack including the caller oflongjmp
orsiglongjmp
.
This probe is triggered under the same conditions and with the samearguments as thelongjmp
probe.
Thelongjmp_target
probe is triggered at a point where theregisters have been restored to the values in thejmp_buf
andunwinding will show a call stack including the caller ofsetjmp
orsigsetjmp
.
Next:C Language Facilities in the Library, Previous:Internal probes, Up:Main Menu [Contents][Index]
Tunables are a feature in the GNU C Library that allows application authors anddistribution maintainers to alter the runtime library behavior to matchtheir workload. These are implemented as a set of switches that may bemodified in different ways. The current default method to do this is viatheGLIBC_TUNABLES
environment variable by setting it to a stringof colon-separatedname=value pairs. For example, the followingexample enablesmalloc
checking and sets themalloc
trim threshold to 128bytes:
GLIBC_TUNABLES=glibc.malloc.trim_threshold=128:glibc.malloc.check=3export GLIBC_TUNABLES
Tunables are not part of the GNU C Library stable ABI, and they aresubject to change or removal across releases. Additionally, the method tomodify tunable values may change between releases and across distributions.It is possible to implement multiple ‘frontends’ for the tunables allowingdistributions to choose their preferred method at build time.
Finally, the set of tunables available may vary between distributions asthe tunables feature allows distributions to add their own tunables undertheir own namespace.
Passing--list-tunables to the dynamic loader to print alltunables with minimum and maximum values:
$ /lib64/ld-linux-x86-64.so.2 --list-tunablesglibc.rtld.nns: 0x4 (min: 0x1, max: 0x10)glibc.elision.skip_lock_after_retries: 3 (min: 0, max: 2147483647)glibc.malloc.trim_threshold: 0x0 (min: 0x0, max: 0xffffffffffffffff)glibc.malloc.perturb: 0 (min: 0, max: 255)glibc.cpu.x86_shared_cache_size: 0x100000 (min: 0x0, max: 0xffffffffffffffff)glibc.pthread.rseq: 1 (min: 0, max: 1)glibc.cpu.prefer_map_32bit_exec: 0 (min: 0, max: 1)glibc.mem.tagging: 0 (min: 0, max: 255)glibc.elision.tries: 3 (min: 0, max: 2147483647)glibc.elision.enable: 0 (min: 0, max: 1)glibc.malloc.hugetlb: 0x0 (min: 0x0, max: 0xffffffffffffffff)glibc.cpu.x86_rep_movsb_threshold: 0x2000 (min: 0x100, max: 0xffffffffffffffff)glibc.malloc.mxfast: 0x0 (min: 0x0, max: 0xffffffffffffffff)glibc.rtld.dynamic_sort: 2 (min: 1, max: 2)glibc.elision.skip_lock_busy: 3 (min: 0, max: 2147483647)glibc.malloc.top_pad: 0x20000 (min: 0x0, max: 0xffffffffffffffff)glibc.cpu.x86_rep_stosb_threshold: 0x800 (min: 0x1, max: 0xffffffffffffffff)glibc.cpu.x86_non_temporal_threshold: 0xc0000 (min: 0x4040, max: 0xfffffffffffffff)glibc.cpu.x86_memset_non_temporal_threshold: 0xc0000 (min: 0x4040, max: 0xfffffffffffffff)glibc.cpu.x86_shstk:glibc.pthread.stack_cache_size: 0x2800000 (min: 0x0, max: 0xffffffffffffffff)glibc.malloc.mmap_max: 0 (min: 0, max: 2147483647)glibc.elision.skip_trylock_internal_abort: 3 (min: 0, max: 2147483647)glibc.cpu.plt_rewrite: 0 (min: 0, max: 2)glibc.malloc.tcache_unsorted_limit: 0x0 (min: 0x0, max: 0xffffffffffffffff)glibc.cpu.x86_ibt:glibc.cpu.hwcaps:glibc.elision.skip_lock_internal_abort: 3 (min: 0, max: 2147483647)glibc.malloc.arena_max: 0x0 (min: 0x1, max: 0xffffffffffffffff)glibc.malloc.mmap_threshold: 0x0 (min: 0x0, max: 0xffffffffffffffff)glibc.cpu.x86_data_cache_size: 0x8000 (min: 0x0, max: 0xffffffffffffffff)glibc.malloc.tcache_count: 0x0 (min: 0x0, max: 0xffffffffffffffff)glibc.malloc.arena_test: 0x0 (min: 0x1, max: 0xffffffffffffffff)glibc.pthread.mutex_spin_count: 100 (min: 0, max: 32767)glibc.rtld.optional_static_tls: 0x200 (min: 0x0, max: 0xffffffffffffffff)glibc.malloc.tcache_max: 0x0 (min: 0x0, max: 0xffffffffffffffff)glibc.malloc.check: 0 (min: 0, max: 3)
Next:Memory Allocation Tunables, Up:Tunables [Contents][Index]
A tunable name is split into three components, a top namespace, a tunablenamespace and the tunable name. The top namespace for tunables implemented inthe GNU C Library isglibc
. Distributions that choose to add custom tunablesin their maintained versions of the GNU C Library may choose to do so under their owntop namespace.
The tunable namespace is a logical grouping of tunables in a singlemodule. This currently holds no special significance, although that maychange in the future.
The tunable name is the actual name of the tunable. It is possible thatdifferent tunable namespaces may have tunables within them that have thesame name, likewise for top namespaces. Hence, we only supportidentification of tunables by their full name, i.e. with the topnamespace, tunable namespace and tunable name, separated by periods.
Next:Dynamic Linking Tunables, Previous:Tunable names, Up:Tunables [Contents][Index]
Memory allocation behavior can be modified by setting any of thefollowing tunables in themalloc
namespace:
This tunable supersedes theMALLOC_CHECK_
environment variable and isidentical in features. This tunable has no effect by default and needs thedebug librarylibc_malloc_debug to be preloaded using theLD_PRELOAD
environment variable.
Setting this tunable to a non-zero value less than 4 enables a special (lessefficient) memory allocator for themalloc
family of functions that isdesigned to be tolerant against simple errors such as double calls offree with the same argument, or overruns of a single byte (off-by-onebugs). Not all such errors can be protected against, however, and memoryleaks can result. Any detected heap corruption results in immediatetermination of the process.
LikeMALLOC_CHECK_
,glibc.malloc.check
has a problem in that itdiverges from normal program behavior by writing tostderr
, which couldby exploited in SUID and SGID binaries. Therefore,glibc.malloc.check
is disabled by default for SUID and SGID binaries.
This tunable supersedes theMALLOC_TOP_PAD_
environment variable and isidentical in features.
This tunable determines the amount of extra memory in bytes to obtain from thesystem when any of the arenas need to be extended. It also specifies thenumber of bytes to retain when shrinking any of the arenas. This provides thenecessary hysteresis in heap size such that excessive amounts of system callscan be avoided.
The default value of this tunable is ‘131072’ (128 KB).
This tunable supersedes theMALLOC_PERTURB_
environment variable and isidentical in features.
If set to a non-zero value, memory blocks are initialized with values dependingon some low order bits of this tunable when they are allocated (except whenallocated bycalloc
) and freed. This can be used to debug the use ofuninitialized or freed heap memory. Note that this option does not guaranteethat the freed block will have any specific values. It only guarantees that thecontent the block had before it was freed will be overwritten.
The default value of this tunable is ‘0’.
This tunable supersedes theMALLOC_MMAP_THRESHOLD_
environment variableand is identical in features.
When this tunable is set, all chunks larger than this value in bytes areallocated outside the normal heap, using themmap
system call. This wayit is guaranteed that the memory for these chunks can be returned to the systemonfree
. Note that requests smaller than this threshold might still beallocated viammap
.
If this tunable is not set, the default value is set to ‘131072’ bytes andthe threshold is adjusted dynamically to suit the allocation patterns of theprogram. If the tunable is set, the dynamic adjustment is disabled and thevalue is set as static.
This tunable supersedes theMALLOC_TRIM_THRESHOLD_
environment variableand is identical in features.
The value of this tunable is the minimum size (in bytes) of the top-most,releasable chunk in an arena that will trigger a system call in order to returnmemory to the system from that arena.
If this tunable is not set, the default value is set as 128 KB and thethreshold is adjusted dynamically to suit the allocation patterns of theprogram. If the tunable is set, the dynamic adjustment is disabled and thevalue is set as static.
This tunable supersedes theMALLOC_MMAP_MAX_
environment variable and isidentical in features.
The value of this tunable is maximum number of chunks to allocate withmmap
. Setting this to zero disables all use ofmmap
.
The default value of this tunable is ‘65536’.
This tunable supersedes theMALLOC_ARENA_TEST
environment variable and isidentical in features.
Theglibc.malloc.arena_test
tunable specifies the number of arenas thatcan be created before the test on the limit to the number of arenas isconducted. The value is ignored ifglibc.malloc.arena_max
is set.
The default value of this tunable is 2 for 32-bit systems and 8 for 64-bitsystems.
This tunable supersedes theMALLOC_ARENA_MAX
environment variable and isidentical in features.
This tunable sets the number of arenas to use in a process regardless of thenumber of cores in the system.
The default value of this tunable is0
, meaning that the limit on thenumber of arenas is determined by the number of CPU cores online. For 32-bitsystems the limit is twice the number of cores online and on 64-bit systems, itis 8 times the number of cores online.
The maximum size of a request (in bytes) which may be met via theper-thread cache. The default (and maximum) value is 1032 bytes on64-bit systems and 516 bytes on 32-bit systems.
The maximum number of chunks of each size to cache. The default is 7.The upper limit is 65535. If set to zero, the per-thread cache is effectivelydisabled.
The approximate maximum overhead of the per-thread cache is thus equalto the number of bins times the chunk count in each bin times the sizeof each chunk. With defaults, the approximate maximum overhead of theper-thread cache is approximately 236 KB on 64-bit systems and 118 KBon 32-bit systems.
When the user requests memory and the request cannot be met via theper-thread cache, the arenas are used to meet the request. At thistime, additional chunks will be moved from existing arena lists topre-fill the corresponding cache. While copies from the fastbins,smallbins, and regular bins are bounded and predictable due to the binsizes, copies from the unsorted bin are not bounded, and incuradditional time penalties as they need to be sorted as they’rescanned. To make scanning the unsorted list more predictable andbounded, the user may set this tunable to limit the number of chunksthat are scanned from the unsorted list while searching for chunks topre-fill the per-thread cache with. The default, or when set to zero,is no limit.
One of the optimizationsmalloc
uses is to maintain a series of “fastbins” that hold chunks up to a specific size. The default andmaximum size which may be held this way is 80 bytes on 32-bit systemsor 160 bytes on 64-bit systems. Applications which value size overspeed may choose to reduce the size of requests which are servicedfrom fast bins with this tunable. Note that the value specifiedincludesmalloc
’s internal overhead, which is normally the size of onepointer, so add 4 on 32-bit systems or 8 on 64-bit systems to the sizepassed tomalloc
for the largest bin size to enable.
This tunable controls the usage of Huge Pages onmalloc
calls. Thedefault value is0
, which disables any additional support onmalloc
.
Setting its value to1
enables the use ofmadvise
withMADV_HUGEPAGE
after memory allocation withmmap
. It is enabledonly if the system supports Transparent Huge Page (currently only on Linux).
Setting its value to2
enables the use of Huge Page directly withmmap
with the use ofMAP_HUGETLB
flag. The huge page sizeto use will be the default one provided by the system. A value larger than2
specifies huge page size, which will be matched against the systemsupported ones. If provided value is invalid,MAP_HUGETLB
will notbe used.
Next:Elision Tunables, Previous:Memory Allocation Tunables, Up:Tunables [Contents][Index]
Dynamic linker behavior can be modified by setting thefollowing tunables in thertld
namespace:
Sets the number of supported dynamic link namespaces (seedlmopen
).Currently this limit can be set between 1 and 16 inclusive, the default is 4.Each link namespace consumes some memory in all thread, and thus raising thelimit will increase the amount of memory each thread uses. Raising the limitis useful when your application uses more than 4 dynamic link namespaces ascreated bydlmopen
with an lmid argument ofLM_ID_NEWLM
.Dynamic linker audit modules are loaded in their own dynamic link namespaces,but they are not accounted for inglibc.rtld.nns
. They implicitlyincrease the per-thread memory usage as necessary, so this tunable doesnot need to be changed to allow many audit modules e.g. viaLD_AUDIT
.
Sets the amount of surplus static TLS in bytes to allocate at programstartup. Every thread created allocates this amount of specified surplusstatic TLS. This is a minimum value and additional space may be allocatedfor internal purposes including alignment. Optional static TLS is used foroptimizing dynamic TLS access for platforms that support such optimizationse.g. TLS descriptors or optimized TLS access for POWER (DT_PPC64_OPT
andDT_PPC_OPT
). In order to make the best use of such optimizationsthe value should be as many bytes as would be required to hold all TLSvariables in all dynamic loaded shared libraries. The value cannot be knownby the dynamic loader because it doesn’t know the expected set of sharedlibraries which will be loaded. The existing static TLS space cannot bechanged once allocated at process startup. The default allocation ofoptional static TLS is 512 bytes and is allocated in every thread.
Sets the algorithm to use for DSO sorting, valid values are ‘1’ and‘2’. For value of ‘1’, an older O(n^3) algorithm is used, which islong time tested, but may have performance issues when dependencies betweenshared objects contain cycles due to circular dependencies. When set to thevalue of ‘2’, a different algorithm is used, which implements atopological sort through depth-first search, and does not exhibit theperformance issues of ‘1’.
The default value of this tunable is ‘2’.
Used to run a program as if it were a setuid process. The only valid valueis ‘1’ as this tunable can only be used to set and not unsetenable_secure
. Setting this tunable to ‘1’ also disables all othertunables. This tunable is intended to facilitate more extensive verificationtests forAT_SECURE
programs and not meant to be a security feature.
The default value of this tunable is ‘0’.
The GNU C Library will use either the default architecture ABI flags (that mightcontain the executable bit) or the value ofPT_GNU_STACK
(if present)to define whether to mark the stack non-executable and if the program orany shared library dependency requires an executable stack the loader willchange the main stack permission if kernel starts with a non-executable stack.
Theglibc.rtld.execstack
can be used to control whether an executablestack is allowed from the main program. Setting the value to0
disablesthe ABI auto-negotiation (meaning no executable stacks even if the ABI or ELFheader requires it),1
enables auto-negotiation (although the programmight not need an executable stack), while2
forces an executablestack at process start. This is provided for compatibility reasons, whenthe program dynamically loads modules withdlopen
which requirean executable stack.
When executable stacks are not allowed, and if the main program requires it,the loader will fail with an error message.
Some systems do not have separate page protection flags at the hardwarelevel for read access and execute access (sometimes called read-implies-exec).This mode can also be enabled on certain systems where the hardware supportsseparate protection flags. The the GNU C Library tunable configuration is independentof hardware capabilities and kernel configuration.
NB: Trying to load a dynamic shared library withdlopen
ordlmopen
that requires an executable stack will always fail if themain program does not require an executable stack at loading time. Thiscan be worked around by setting the tunable to2
, where the stack isalways executable.
Next:POSIX Thread Tunables, Previous:Dynamic Linking Tunables, Up:Tunables [Contents][Index]
Contended locks are usually slow and can lead to performance and scalabilityissues in multithread code. Lock elision will use memory transactions to undercertain conditions, to elide locks and improve performance.Elision behavior can be modified by setting the following tunables intheelision
namespace:
Theglibc.elision.enable
tunable enables lock elision if the feature issupported by the hardware. If elision is not supported by the hardware thistunable has no effect.
Elision tunables are supported for 64-bit Intel, IBM POWER, and z Systemarchitectures.
Theglibc.elision.skip_lock_busy
tunable sets how many times to use anon-transactional lock after a transactional failure has occurred because thelock is already acquired. Expressed in number of lock acquisition attempts.
The default value of this tunable is ‘3’.
Theglibc.elision.skip_lock_internal_abort
tunable sets how many timesthe thread should avoid using elision if a transaction aborted for any reasonother than a different thread’s memory accesses. Expressed in number of lockacquisition attempts.
The default value of this tunable is ‘3’.
Theglibc.elision.skip_lock_after_retries
tunable sets how many timesto try to elide a lock with transactions, that only failed due to a differentthread’s memory accesses, before falling back to regular lock.Expressed in number of lock elision attempts.
This tunable is supported only on IBM POWER, and z System architectures.
The default value of this tunable is ‘3’.
Theglibc.elision.tries
sets how many times to retry elision if there ischance for the transaction to finish execution e.g., it wasn’taborted due to the lock being already acquired. If elision is not supportedby the hardware this tunable is set to ‘0’ to avoid retries.
The default value of this tunable is ‘3’.
Theglibc.elision.skip_trylock_internal_abort
tunable sets how manytimes the thread should avoid trying the lock if a transaction aborted due toreasons other than a different thread’s memory accesses. Expressed in numberof try lock attempts.
The default value of this tunable is ‘3’.
Next:Hardware Capability Tunables, Previous:Elision Tunables, Up:Tunables [Contents][Index]
The behavior of POSIX threads can be tuned to gain performance improvementsaccording to specific hardware capabilities and workload characteristics bysetting the following tunables in thepthread
namespace:
Theglibc.pthread.mutex_spin_count
tunable sets the maximum number of timesa thread should spin on the lock before calling into the kernel to block.Adaptive spin is used for mutexes initialized with thePTHREAD_MUTEX_ADAPTIVE_NP
GNU extension. It affects bothpthread_mutex_lock
andpthread_mutex_timedlock
.
The thread spins until either the maximum spin count is reached or the lockis acquired.
The default value of this tunable is ‘100’.
This tunable configures the maximum size of the stack cache. Once thestack cache exceeds this size, unused thread stacks are returned tothe kernel, to bring the cache size below this limit.
The value is measured in bytes. The default is ‘41943040’(forty mibibytes).
Theglibc.pthread.rseq
tunable can be set to ‘0’, to disablerestartable sequences support in the GNU C Library. This enables applicationsto perform direct restartable sequence registration with the kernel.The default is ‘1’, which means that the GNU C Library performsregistration on behalf of the application.
Restartable sequences are a Linux-specific extension.
This tunable controls whether to use Huge Pages in the stacks created bypthread_create
. This tunable only affects the stacks created bythe GNU C Library, it has no effect on stack assigned withpthread_attr_setstack
.
The default is ‘1’ where the system default value is used. Settingits value to0
enables the use ofmadvise
withMADV_NOHUGEPAGE
after stack creation withmmap
.
This is a memory utilization optimization, since internal glibc setup of eitherthe thread descriptor and the guard page might force the kernel to move thethread stack originally backup by Huge Pages to default pages.
Next:Memory Related Tunables, Previous:POSIX Thread Tunables, Up:Tunables [Contents][Index]
Behavior of the GNU C Library can be tuned to assume specific hardware capabilitiesby setting the following tunables in thecpu
namespace:
Theglibc.cpu.hwcaps=-xxx,yyy,-zzz...
tunable allows the user toenable CPU/ARCH featureyyy
, disable CPU/ARCH featurexxx
andzzz
where the feature name is case-sensitive and has to matchthe ones insysdeps/x86/include/cpu-features.h
.
On s390x, the supported HWCAP and STFLE features can be found insysdeps/s390/cpu-features.c
. In addition the user can also seta CPU arch-level likez13
instead of single HWCAP and STFLE features.
On powerpc, the supported HWCAP and HWCAP2 features can be found insysdeps/powerpc/dl-procinfo.c
.
On loongarch, the supported HWCAP features can be found insysdeps/loongarch/cpu-tunables.c
.
This tunable is specific to i386, x86-64, s390x, powerpc and loongarch.
Theglibc.cpu.cached_memopt=[0|1]
tunable allows the user toenable optimizations recommended for cacheable memory. If set to1
, the GNU C Library assumes that the process memory image consistsof cacheable (non-device) memory only. The default,0
,indicates that the process may use device memory.
This tunable is specific to powerpc, powerpc64 and powerpc64le.
Theglibc.cpu.name=xxx
tunable allows the user to tell the GNU C Library toassume that the CPU isxxx
where xxx may have one of these values:generic
,thunderxt88
,thunderx2t99
,thunderx2t99p1
,ares
,emag
,kunpeng
,a64fx
.
This tunable is specific to aarch64.
Theglibc.cpu.x86_data_cache_size
tunable allows the user to setdata cache size in bytes for use in memory and string routines.
This tunable is specific to i386 and x86-64.
Theglibc.cpu.x86_shared_cache_size
tunable allows the user toset shared cache size in bytes for use in memory and string routines.
Theglibc.cpu.x86_non_temporal_threshold
tunable allows the userto set threshold in bytes for non temporal store. Non temporal storesgive a hint to the hardware to move data directly to memory withoutdisplacing other data from the cache. This tunable is used by someplatforms to determine when to use non temporal stores in operationslike memmove and memcpy.
This tunable is specific to i386 and x86-64.
Theglibc.cpu.x86_memset_non_temporal_threshold
tunable allowsthe user to set threshold in bytes for non temporal store inmemset. Non temporal stores give a hint to the hardware to move datadirectly to memory without displacing other data from the cache. Thistunable is used by some platforms to determine when to use nontemporal stores memset.
This tunable is specific to i386 and x86-64.
Theglibc.cpu.x86_rep_movsb_threshold
tunable allows the user toset threshold in bytes to start using "rep movsb". The value must begreater than zero, and currently defaults to 2048 bytes.
This tunable is specific to i386 and x86-64.
Theglibc.cpu.x86_rep_stosb_threshold
tunable allows the user toset threshold in bytes to start using "rep stosb". The value must begreater than zero, and currently defaults to 2048 bytes.
This tunable is specific to i386 and x86-64.
Theglibc.cpu.x86_ibt
tunable allows the user to control howindirect branch tracking (IBT) should be enabled. Accepted values areon
,off
, andpermissive
.on
always turnson IBT regardless of whether IBT is enabled in the executable and itsdependent shared libraries.off
always turns off IBT regardlessof whether IBT is enabled in the executable and its dependent sharedlibraries.permissive
is the same as the default which disablesIBT on non-CET executables and shared libraries.
This tunable is specific to i386 and x86-64.
Theglibc.cpu.x86_shstk
tunable allows the user to control howthe shadow stack (SHSTK) should be enabled. Accepted values areon
,off
, andpermissive
.on
always turns onSHSTK regardless of whether SHSTK is enabled in the executable and itsdependent shared libraries.off
always turns off SHSTK regardlessof whether SHSTK is enabled in the executable and its dependent sharedlibraries.permissive
changes how dlopen works on non-CET sharedlibraries. By default, when SHSTK is enabled, dlopening a non-CET sharedlibrary returns an error. Withpermissive
, it turns off SHSTKinstead.
This tunable is specific to i386 and x86-64.
When this tunable is set to1
, shared libraries of non-setuidprograms will be loaded below 2GB with MAP_32BIT.
Note that theLD_PREFER_MAP_32BIT_EXEC
environment is an alias ofthis tunable.
This tunable is specific to 64-bit x86-64.
When this tunable is set to1
, the dynamic linker will rewritethe PLT section with 32-bit direct jump. When it is set to2
,the dynamic linker will rewrite the PLT section with 32-bit directjump and on APX processors with 64-bit absolute jump.
This tunable is specific to x86-64 and effective only when the lazybinding is disabled.
This tunable controls Guarded Control Stack (GCS) for the process.
Accepted values are:
0 = disabled: do not enable GCS.
1 = enforced: check markings and fail if any binary is not marked.
2 = optional: check markings but keep GCS off if any binary is unmarked.
3 = override: enable GCS, markings are ignored.
If unmarked binary is loaded viadlopen
when GCS is enabled andmarkings are not ignored (aarch64_gcs == 1
or2
), thenthe process will be aborted.
Default is0
, so GCS is disabled by default.
This tunable is specific to AArch64. On systems that do not supportGuarded Control Stack this tunable has no effect.
Before enabling GCS for the process the value of this tunable is checkedand depending on it the following outcomes are possible.
aarch64_gcs == 0
: GCS will not be enabled and GCS markings will not bechecked for any binaries.
aarch64_gcs == 1
: GCS markings will be checked for all binaries loadedat startup and, only if all binaries are GCS-marked, GCS will be enabled. Ifany of the binaries are not GCS-marked, the process will abort. Subsequent calltodlopen
for an unmarked binary will also result in abort.
aarch64_gcs == 2
: GCS markings will be checked for all binaries loadedat startup and, if any of such binaries are not GCS-marked, GCS will not beenabled and there will be no more checks for GCS marking. If all binariesloaded at startup are GCS-marked, then GCS will be enabled, in which case acall todlopen
for an unmarked binary will also result in abort.
aarch64_gcs == 3
: GCS will be enabled and GCS markings will not bechecked for any binaries.
Next:gmon Tunables, Previous:Hardware Capability Tunables, Up:Tunables [Contents][Index]
This tunable namespace supports operations that affect the way the GNU C Libraryand the process manage memory.
If the hardware supports memory tagging, this tunable can be used tocontrol the way the GNU C Library uses this feature. At present this is onlysupported on AArch64 systems with the MTE extension; it is ignored forall other systems.
This tunable takes a value between 0 and 255 and acts as a bitmaskthat enables various capabilities.
Bit 0 (the least significant bit) causes themalloc
subsystem to allocatetagged memory, with each allocation being assigned a random tag.
Bit 1 enables precise faulting mode for tag violations on systems thatsupport deferred tag violation reporting. This may cause programsto run more slowly.
Bit 2 enables either precise or deferred faulting mode for tag violationswhichever is preferred by the system.
Other bits are currently reserved.
The GNU C Library startup code will automatically enable memory taggingsupport in the kernel if this tunable has any non-zero value.
The default value is ‘0’, which disables all memory tagging.
If the kernel supports naming anonymous virtual memory areas (sinceLinux version 5.17, although not always enabled by some kernelconfigurations), this tunable can be used to control whetherthe GNU C Library decorates the underlying memory obtained from operatingsystem with a string describing its usage (for instance, on the threadstack created byptthread_create
or memory allocated bymalloc
).
The process mappings can be obtained by reading the/proc/<pid>maps
(withpid
being either theprocess ID orself
for theprocess own mapping).
This tunable takes a value of 0 and 1, where 1 enables the feature.The default value is ‘0’, which disables the decoration.
Previous:Memory Related Tunables, Up:Tunables [Contents][Index]
This tunable namespace affects the behaviour of the gmon profiler.gmon is a component of the GNU C Library which is normally used inconjunction with gprof.
When GCC compiles a program with the-pg
option, it instrumentsthe program with calls to themcount
function, to record theprogram’s call graph. At program startup, a memory buffer is allocatedto store this call graph; the size of the buffer is calculated using aheuristic based on code size. If during execution, the buffer is foundto be too small, profiling will be aborted and nogmon.out filewill be produced. In that case, you will see the following messageprinted to standard error:
mcount: call graph buffer size limit exceeded, gmon.out will not be generated
Most of the symbols discussed in this section are defined in the headersys/gmon.h
. However, some symbols (for examplemcount
)are not defined in any header file, since they are only intended to becalled from code generated by the compiler.
The heuristic for sizing the call graph buffer is known to beinsufficient for small programs; hence, the calculated value is clampedto be at least a minimum size. The default minimum (in units ofcall graph entries,struct tostruct
), is given by the macroMINARCS
. If you have some program with an unusually complexcall graph, for which the heuristic fails to allocate enough space,you can use this tunable to increase the minimum to a larger value.
To prevent excessive memory consumption when profiling very largeprograms, the call graph buffer is allowed to have a maximum ofMAXARCS
entries. For some very large programs, the defaultvalue ofMAXARCS
defined insys/gmon.h is too small; inthat case, you can use this tunable to increase it.
Note the value of themaxarcs
tunable must be greater or equalto that of theminarcs
tunable; if this constraint is violated,a warning will printed to standard error at program startup, andtheminarcs
value will be used as the maximum as well.
Setting either tunable too high may result in a call graph bufferwhose size exceeds the available memory; in that case, an out of memoryerror will be printed at program startup, the profiler will bedisabled, and nogmon.out file will be generated.
Next:Summary of Library Facilities, Previous:Tunables, Up:Main Menu [Contents][Index]
Some of the facilities implemented by the C library really should bethought of as parts of the C language itself. These facilities ought tobe documented in the C Language Manual, not in the library manual; butsince we don’t have the language manual yet, and documentation for thesefeatures has been written, we are publishing it here.
When you’re writing a program, it’s often a good idea to put in checksat strategic places for “impossible” errors or violations of basicassumptions. These kinds of checks are helpful in debugging problemswith the interfaces between different parts of the program, for example.
Theassert
macro, defined in the header fileassert.h,provides a convenient way to abort the program while printing a messageabout where in the program the error was detected.
Once you think your program is debugged, you can disable the errorchecks performed by theassert
macro by recompiling with themacroNDEBUG
defined. This means you don’t actually have tochange the program source code to disable these checks.
But disabling these consistency checks is undesirable unless they makethe program significantly slower. All else being equal, more errorchecking is good no matter who is running the program. A wise userwould rather have a program crash, visibly, than have it return nonsensewithout indicating anything might be wrong.
void
assert(intexpression)
¶Preliminary:| MT-Safe | AS-Unsafe heap corrupt| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
Verify the programmer’s belief thatexpression is nonzero atthis point in the program.
IfNDEBUG
is not defined,assert
tests the value ofexpression. If it is false (zero),assert
aborts theprogram (seeAborting a Program) after printing a message of theform:
file:linenum:function: Assertion `expression' failed.
on the standard error streamstderr
(seeStandard Streams).The filename and line number are taken from the C preprocessor macros__FILE__
and__LINE__
and specify where the call toassert
was made. When using the GNU C compiler, the name ofthe function which callsassert
is taken from the built-invariable__PRETTY_FUNCTION__
; with older compilers, the functionname and following colon are omitted.
If the preprocessor macroNDEBUG
is defined beforeassert.h is included, theassert
macro is defined to doabsolutely nothing.
Warning: Even the argument expressionexpression is notevaluated ifNDEBUG
is in effect. So never useassert
with arguments that involve side effects. For example,assert(++i > 0);
is a bad idea, becausei
will not be incremented ifNDEBUG
is defined.
Sometimes the “impossible” condition you want to check for is an errorreturn from an operating system function. Then it is useful to displaynot only where the program crashes, but also what error was returned.Theassert_perror
macro makes this easy.
void
assert_perror(interrnum)
¶Preliminary:| MT-Safe | AS-Unsafe heap corrupt| AC-Unsafe mem lock corrupt| SeePOSIX Safety Concepts.
Similar toassert
, but verifies thaterrnum is zero.
IfNDEBUG
is not defined,assert_perror
tests the value oferrnum. If it is nonzero,assert_perror
aborts the programafter printing a message of the form:
file:linenum:function:error text
on the standard error stream. The file name, line number, and functionname are as forassert
. The error text is the result ofstrerror (errnum)
. SeeError Messages.
Likeassert
, ifNDEBUG
is defined beforeassert.his included, theassert_perror
macro does absolutely nothing. Itdoes not evaluate the argument, soerrnum should not have any sideeffects. It is best forerrnum to be just a simple variablereference; often it will beerrno
.
This macro is a GNU extension.
Usage note: Theassert
facility is designed fordetectinginternal inconsistency; it is not suitable forreporting invalid input or improper usage by theuser of theprogram.
The information in the diagnostic messages printed by theassert
andassert_perror
macro is intended to help you, the programmer,track down the cause of a bug, but is not really useful for telling a userof your program why his or her input was invalid or why a command could notbe carried out. What’s more, your program should not abort when giveninvalid input, asassert
would do—it should exit with nonzerostatus (seeExit Status) after printing its error messages, or perhapsread another command or move on to the next input file.
SeeError Messages, for information on printing error messages forproblems thatdo not represent bugs in the program.
Next:Null Pointer Constant, Previous:Explicitly Checking Internal Consistency, Up:C Language Facilities in the Library [Contents][Index]
ISO C defines a syntax for declaring a function to take a variablenumber or type of arguments. (Such functions are referred to asvarargs functions orvariadic functions.) However, thelanguage itself provides no mechanism for such functions to access theirnon-required arguments; instead, you use the variable arguments macrosdefined instdarg.h.
This section describes how to declare variadic functions, how to writethem, and how to call them properly.
Compatibility Note: Many older C dialects provide a similar,but incompatible, mechanism for defining functions with variable numbersof arguments, usingvarargs.h.
Ordinary C functions take a fixed number of arguments. When you definea function, you specify the data type for each argument. Every call tothe function should supply the expected number of arguments, with typesthat can be converted to the specified ones. Thus, if the function‘foo’ is declared withint foo (int, char *);
then you mustcall it with two arguments, a number (any kind will do) and a stringpointer.
But some functions perform operations that can meaningfully accept anunlimited number of arguments.
In some cases a function can handle any number of values by operating onall of them as a block. For example, consider a function that allocatesa one-dimensional array withmalloc
to hold a specified set ofvalues. This operation makes sense for any number of values, as long asthe length of the array corresponds to that number. Without facilitiesfor variable arguments, you would have to define a separate function foreach possible array size.
The library functionprintf
(seeFormatted Output) is anexample of another class of function where variable arguments areuseful. This function prints its arguments (which can vary in type aswell as number) under the control of a format template string.
These are good reasons to define avariadic function which canhandle as many arguments as the caller chooses to pass.
Some functions such asopen
take a fixed set of arguments, butoccasionally ignore the last few. Strict adherence to ISO C requiresthese functions to be defined as variadic; in practice, however, the GNUC compiler and most other C compilers let you define such a function totake a fixed set of arguments—the most it can ever use—and then onlydeclare the function as variadic (or not declare its argumentsat all!).
Next:Example of a Variadic Function, Previous:Why Variadic Functions are Used, Up:Variadic Functions [Contents][Index]
Defining and using a variadic function involves three steps:
Next:Receiving the Argument Values, Up:How Variadic Functions are Defined and Used [Contents][Index]
A function that accepts a variable number of arguments must be declaredwith a prototype that says so. You write the fixed arguments as usual,and then tack on ‘…’ to indicate the possibility ofadditional arguments. The syntax of ISO C requires at least one fixedargument before the ‘…’. For example,
intfunc (const char *a, int b, ...){ ...}
defines a functionfunc
which returns anint
and takes tworequired arguments, aconst char *
and anint
. These arefollowed by any number of anonymous arguments.
Portability note: For some C compilers, the last requiredargument must not be declaredregister
in the functiondefinition. Furthermore, this argument’s type must beself-promoting: that is, the default promotions must not changeits type. This rules out array and function types, as well asfloat
,char
(whether signed or not) andshort int
(whether signed or not). This is actually an ISO C requirement.
Next:How Many Arguments Were Supplied, Previous:Syntax for Variable Arguments, Up:How Variadic Functions are Defined and Used [Contents][Index]
Ordinary fixed arguments have individual names, and you can use thesenames to access their values. But optional arguments have nonames—nothing but ‘…’. How can you access them?
The only way to access them is sequentially, in the order they werewritten, and you must use special macros fromstdarg.h in thefollowing three step process:
va_list
usingva_start
. The argument pointer when initialized points to thefirst optional argument.va_arg
.The first call tova_arg
gives you the first optional argument,the next call gives you the second, and so on.You can stop at any time if you wish to ignore any remaining optionalarguments. It is perfectly all right for a function to access fewerarguments than were supplied in the call, but you will get garbagevalues if you try to access too many arguments.
va_end
.(In practice, with most C compilers, callingva_end
does nothing.This is always true in the GNU C compiler. But you might as well callva_end
just in case your program is someday compiled with a peculiarcompiler.)
SeeArgument Access Macros, for the full definitions ofva_start
,va_arg
andva_end
.
Steps 1 and 3 must be performed in the function that accepts theoptional arguments. However, you can pass theva_list
variableas an argument to another function and perform all or part of step 2there.
You can perform the entire sequence of three steps multiple timeswithin a single function invocation. If you want to ignore the optionalarguments, you can do these steps zero times.
You can have more than one argument pointer variable if you like. Youcan initialize each variable withva_start
when you wish, andthen you can fetch arguments with each argument pointer as you wish.Each argument pointer variable will sequence through the same set ofargument values, but at its own pace.
Portability note: With some compilers, once you pass anargument pointer value to a subroutine, you must not keep using the sameargument pointer value after that subroutine returns. For fullportability, you should just pass it tova_end
. This is actuallyan ISO C requirement, but most ANSI C compilers work happilyregardless.
Next:Calling Variadic Functions, Previous:Receiving the Argument Values, Up:How Variadic Functions are Defined and Used [Contents][Index]
There is no general way for a function to determine the number and typeof the optional arguments it was called with. So whoever designs thefunction typically designs a convention for the caller to specify the numberand type of arguments. It is up to you to define an appropriate callingconvention for each variadic function, and write all calls accordingly.
One kind of calling convention is to pass the number of optionalarguments as one of the fixed arguments. This convention works providedall of the optional arguments are of the same type.
A similar alternative is to have one of the required arguments be a bitmask, with a bit for each possible purpose for which an optionalargument might be supplied. You would test the bits in a predefinedsequence; if the bit is set, fetch the value of the next argument,otherwise use a default value.
A required argument can be used as a pattern to specify both the numberand types of the optional arguments. The format string argument toprintf
is one example of this (seeFormatted Output Functions).
Another possibility is to pass an “end marker” value as the lastoptional argument. For example, for a function that manipulates anarbitrary number of pointer arguments, a null pointer might indicate theend of the argument list. (This assumes that a null pointer isn’totherwise meaningful to the function.) Theexecl
function worksin just this way; seeExecuting a File.
Next:Argument Access Macros, Previous:How Many Arguments Were Supplied, Up:How Variadic Functions are Defined and Used [Contents][Index]
You don’t have to do anything special to call a variadic function.Just put the arguments (required arguments, followed by optional ones)inside parentheses, separated by commas, as usual. But you must declarethe function with a prototype and know how the argument values are converted.
In principle, functions that aredefined to be variadic must alsobedeclared to be variadic using a function prototype wheneveryou call them. (SeeSyntax for Variable Arguments, for how.) This is becausesome C compilers use a different calling convention to pass the same setof argument values to a function depending on whether that functiontakes variable arguments or fixed arguments.
In practice, the GNU C compiler always passes a given set of argumenttypes in the same way regardless of whether they are optional orrequired. So, as long as the argument types are self-promoting, you cansafely omit declaring them. Usually it is a good idea to declare theargument types for variadic functions, and indeed for all functions.But there are a few functions which it is extremely convenient not tohave to declare as variadic—for example,open
andprintf
.
Since the prototype doesn’t specify types for optional arguments, in acall to a variadic function thedefault argument promotions areperformed on the optional argument values. This means the objects oftypechar
orshort int
(whether signed or not) arepromoted to eitherint
orunsigned int
, asappropriate; and that objects of typefloat
are promoted to typedouble
. So, if the caller passes achar
as an optionalargument, it is promoted to anint
, and the function can accessit withva_arg (ap, int)
.
Conversion of the required arguments is controlled by the functionprototype in the usual way: the argument expression is converted to thedeclared argument type as if it were being assigned to a variable ofthat type.
Previous:Calling Variadic Functions, Up:How Variadic Functions are Defined and Used [Contents][Index]
Here are descriptions of the macros used to retrieve variable arguments.These macros are defined in the header filestdarg.h.
The typeva_list
is used for argument pointer variables.
void
va_start(va_listap,last-required)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This macro initializes the argument pointer variableap to pointto the first of the optional arguments of the current function;last-required must be the last required argument to the function.
type
va_arg(va_listap,type)
¶Preliminary:| MT-Safe race:ap| AS-Safe | AC-Unsafe corrupt| SeePOSIX Safety Concepts.
Theva_arg
macro returns the value of the next optional argument,and modifies the value ofap to point to the subsequent argument.Thus, successive uses ofva_arg
return successive optionalarguments.
The type of the value returned byva_arg
istype asspecified in the call.type must be a self-promoting type (notchar
orshort int
orfloat
) that matches the typeof the actual argument.
void
va_end(va_listap)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This ends the use ofap. After ava_end
call, furtherva_arg
calls with the sameap may not work. You should invokeva_end
before returning from the function in whichva_start
was invoked with the sameap argument.
In the GNU C Library,va_end
does nothing, and you need not everuse it except for reasons of portability.
Sometimes it is necessary to parse the list of parameters more than onceor one wants to remember a certain position in the parameter list. Todo this, one will have to make a copy of the current value of theargument. Butva_list
is an opaque type and one cannot necessarilyassign the value of one variable of typeva_list
to another variableof the same type.
void
va_copy(va_listdest, va_listsrc)
¶void
__va_copy(va_listdest, va_listsrc)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Theva_copy
macro allows copying of objects of typeva_list
even if this is not an integral type. The argument pointerindest is initialized to point to the same argument as thepointer insrc.
va_copy
was added in ISO C99. When building for strictconformance to ISO C90 (‘gcc -std=c90’), it is not available.GCC provides__va_copy
, as an extension, in any standards mode;before GCC 3.0, it was the only macro for this functionality.
These macros are no longer provided by the GNU C Library, but rather by thecompiler.
If you want to useva_copy
and be portable to pre-C99 systems,you should always be prepared for thepossibility that this macro will not be available. On architectures where asimple assignment is invalid, hopefullyva_copy
will be available,so one should always write something like this if concerned aboutpre-C99 portability:
{ va_list ap, save; ...#ifdef va_copy va_copy (save, ap);#else save = ap;#endif ...}
Previous:How Variadic Functions are Defined and Used, Up:Variadic Functions [Contents][Index]
Here is a complete sample function that accepts a variable number ofarguments. The first argument to the function is the count of remainingarguments, which are added up and the result returned. While trivial,this function is sufficient to illustrate how to use the variablearguments facility.
#include <stdarg.h>#include <stdio.h>intadd_em_up (int count,...){ va_list ap; int i, sum; va_start (ap, count); /*Initialize the argument list. */ sum = 0; for (i = 0; i < count; i++) sum += va_arg (ap, int); /*Get the next argument value. */ va_end (ap); /*Clean up. */ return sum;}intmain (void){ /*This call prints 16. */ printf ("%d\n", add_em_up (3, 5, 5, 6)); /*This call prints 55. */ printf ("%d\n", add_em_up (10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); return 0;}
Next:Important Data Types, Previous:Variadic Functions, Up:C Language Facilities in the Library [Contents][Index]
The null pointer constant is guaranteed not to point to any real object.You can assign it to any pointer variable since it has typevoid*
. The preferred way to write a null pointer constant is withNULL
.
void *
NULL ¶This is a null pointer constant.
You can also use0
or(void *)0
as a null pointerconstant, but usingNULL
is cleaner because it makes the purposeof the constant more evident.
If you use the null pointer constant as a function argument, then forcomplete portability you should make sure that the function has aprototype declaration. Otherwise, if the target machine has twodifferent pointer representations, the compiler won’t know whichrepresentation to use for that argument. You can avoid the problem byexplicitly casting the constant to the proper pointer type, but werecommend instead adding a prototype for the function you are calling.
Next:Data Type Measurements, Previous:Null Pointer Constant, Up:C Language Facilities in the Library [Contents][Index]
The result of subtracting two pointers in C is always an integer, but theprecise data type varies from C compiler to C compiler. Likewise, thedata type of the result ofsizeof
also varies between compilers.ISO C defines standard aliases for these two types, so you can refer tothem in a portable fashion. They are defined in the header filestddef.h.
This is the signed integer type of the result of subtracting twopointers. For example, with the declarationchar *p1, *p2;
, theexpressionp2 - p1
is of typeptrdiff_t
. This willprobably be one of the standard signed integer types (short int
,int
orlong int
), but might be a nonstandardtype that exists only for this purpose.
This is an unsigned integer type used to represent the sizes of objects.The result of thesizeof
operator is of this type, and functionssuch asmalloc
(seeUnconstrained Allocation) andmemcpy
(seeCopying Strings and Arrays) accept arguments ofthis type to specify object sizes. On systems using the GNU C Library, thiswill beunsigned int
orunsigned long int
.
Usage Note:size_t
is the preferred way to declare anyarguments or variables that hold the size of an object.
Compatibility Note: Implementations of C before the advent ofISO C generally usedunsigned int
for representing object sizesandint
for pointer subtraction results. They did notnecessarily define eithersize_t
orptrdiff_t
. Unixsystems did definesize_t
, insys/types.h, but thedefinition was usually a signed type.
Previous:Important Data Types, Up:C Language Facilities in the Library [Contents][Index]
Most of the time, if you choose the proper C data type for each objectin your program, you need not be concerned with just how it isrepresented or how many bits it uses. When you do need suchinformation, the C language itself does not provide a way to get it.The header fileslimits.h andfloat.h contain macroswhich give you this information in full detail.
Next:Range of an Integer Type, Up:Data Type Measurements [Contents][Index]
TS 18661-1:2014 defines macros for the width of integer types (thenumber of value and sign bits). One benefit of these macros is theycan be used in#if
preprocessor directives, whereassizeof
cannot. The following macros are defined inlimits.h.
CHAR_WIDTH
¶SCHAR_WIDTH
¶UCHAR_WIDTH
¶SHRT_WIDTH
¶USHRT_WIDTH
¶INT_WIDTH
¶UINT_WIDTH
¶LONG_WIDTH
¶ULONG_WIDTH
¶LLONG_WIDTH
¶ULLONG_WIDTH
¶These are the widths of the typeschar
,signed char
,unsigned char
,short int
,unsigned short int
,int
,unsigned int
,long int
,unsigned longint
,long long int
andunsigned long long int
,respectively.
Further such macros are defined instdint.h. Apart from thosefor types specified by width (seeIntegers), the following aredefined:
INTPTR_WIDTH
¶UINTPTR_WIDTH
¶PTRDIFF_WIDTH
¶SIG_ATOMIC_WIDTH
¶SIZE_WIDTH
¶WCHAR_WIDTH
¶WINT_WIDTH
¶These are the widths of the typesintptr_t
,uintptr_t
,ptrdiff_t
,sig_atomic_t
,size_t
,wchar_t
andwint_t
, respectively.
A common reason that a program needs to know how many bits are in aninteger type is for using an array ofunsigned long int
as abit vector. You can access the bit at indexn with:
vector[n / ULONG_WIDTH] & (1UL << (n % ULONG_WIDTH))
BeforeULONG_WIDTH
was a part of the C language,CHAR_BIT
was used to compute the number of bits in an integerdata type.
int
CHAR_BIT ¶This is the number of bits in achar
. POSIX.1-2001 requiresthis to be 8.
The number of bits in any data typetype can be computed likethis:
sizeof (type) * CHAR_BIT
That expression includes padding bits as well as value and sign bits.On all systems supported by the GNU C Library, standard integer types otherthan_Bool
do not have any padding bits.
Portability Note: One cannot actually easily compute thenumber of usable bits in a portable manner.
Next:Floating Type Macros, Previous:Width of an Integer Type, Up:Data Type Measurements [Contents][Index]
Suppose you need to store an integer value which can range from zero toone million. Which is the smallest type you can use? There is nogeneral rule; it depends on the C compiler and target machine. You canuse the ‘MIN’ and ‘MAX’ macros inlimits.h to determinewhich type will work.
Each signed integer type has a pair of macros which give the smallestand largest values that it can hold. Each unsigned integer type has onesuch macro, for the maximum value; the minimum value is, of course,zero.
The values of these macros are all integer constant expressions. The‘MAX’ and ‘MIN’ macros forchar
andshort int
types have values of typeint
. The ‘MAX’ and‘MIN’ macros for the other types have values of the same typedescribed by the macro—thus,ULONG_MAX
has typeunsigned long int
.
SCHAR_MIN
¶This is the minimum value that can be represented by asigned char
.
SCHAR_MAX
¶UCHAR_MAX
¶These are the maximum values that can be represented by asigned char
andunsigned char
, respectively.
CHAR_MIN
¶This is the minimum value that can be represented by achar
.It’s equal toSCHAR_MIN
ifchar
is signed, or zerootherwise.
CHAR_MAX
¶This is the maximum value that can be represented by achar
.It’s equal toSCHAR_MAX
ifchar
is signed, orUCHAR_MAX
otherwise.
SHRT_MIN
¶This is the minimum value that can be represented by asigned short int
. On most machines that the GNU C Library runs on,short
integers are 16-bit quantities.
SHRT_MAX
¶USHRT_MAX
¶These are the maximum values that can be represented by asigned short int
andunsigned short int
,respectively.
INT_MIN
¶This is the minimum value that can be represented by asigned int
. On most machines that the GNU C Library runs on, anint
isa 32-bit quantity.
INT_MAX
¶UINT_MAX
¶These are the maximum values that can be represented by, respectively,the typesigned int
and the typeunsigned int
.
LONG_MIN
¶This is the minimum value that can be represented by asigned long int
. On most machines that the GNU C Library runs on,long
integers are 32-bit quantities, the same size asint
.
LONG_MAX
¶ULONG_MAX
¶These are the maximum values that can be represented by asigned long int
andunsigned long int
, respectively.
LLONG_MIN
¶This is the minimum value that can be represented by asigned long long int
. On most machines that the GNU C Library runs on,long long
integers are 64-bit quantities.
LLONG_MAX
¶ULLONG_MAX
¶These are the maximum values that can be represented by asignedlong long int
andunsigned long long int
, respectively.
LONG_LONG_MIN
¶LONG_LONG_MAX
¶ULONG_LONG_MAX
¶These are obsolete names forLLONG_MIN
,LLONG_MAX
, andULLONG_MAX
. They are only available if_GNU_SOURCE
isdefined (seeFeature Test Macros). In GCC versions prior to 3.0,these were the only names available.
WCHAR_MAX
¶This is the maximum value that can be represented by awchar_t
.SeeIntroduction to Extended Characters.
The header filelimits.h also defines some additional constantsthat parameterize various operating system and file system limits. Theseconstants are described inSystem Configuration Parameters.
Next:Structure Field Offset Measurement, Previous:Range of an Integer Type, Up:Data Type Measurements [Contents][Index]
The specific representation of floating point numbers varies frommachine to machine. Because floating point numbers are representedinternally as approximate quantities, algorithms for manipulatingfloating point data often need to take account of the precise details ofthe machine’s floating point representation.
Some of the functions in the C library itself need this information; forexample, the algorithms for printing and reading floating point numbers(seeInput/Output on Streams) and for calculating trigonometric andirrational functions (seeMathematics) use it to avoid round-offerror and loss of accuracy. User programs that implement numericalanalysis techniques also often need this information in order tominimize or compute error bounds.
The header filefloat.h describes the format used by yourmachine.
Next:Floating Point Parameters, Up:Floating Type Macros [Contents][Index]
This section introduces the terminology for describing floating pointrepresentations.
You are probably already familiar with most of these concepts in termsof scientific or exponential notation for floating point numbers. Forexample, the number123456.0
could be expressed in exponentialnotation as1.23456e+05
, a shorthand notation indicating that themantissa1.23456
is multiplied by the base10
raised topower5
.
More formally, the internal representation of a floating point numbercan be characterized in terms of the following parameters:
-1
or1
.1
. This is a constant for a particular representation.Sometimes, in the actual bits representing the floating point number,the exponent isbiased by adding a constant to it, to make italways be represented as an unsigned quantity. This is only importantif you have some reason to pick apart the bit fields making up thefloating point number by hand, which is something for which the GNU C Libraryprovides no support. So this is ignored in the discussion thatfollows.
Many floating point representations have an implicithidden bit inthe mantissa. This is a bit which is present virtually in the mantissa,but not stored in memory because its value is always 1 in a normalizednumber. The precision figure (see above) includes any hidden bits.
Again, the GNU C Library provides no facilities for dealing with suchlow-level aspects of the representation.
The mantissa of a floating point number represents an implicit fractionwhose denominator is the base raised to the power of the precision. Sincethe largest representable mantissa is one less than this denominator, thevalue of the fraction is always strictly less than1
. Themathematical value of a floating point number is then the product of thisfraction, the sign, and the base raised to the exponent.
We say that the floating point number isnormalized if thefraction is at least1/b
, whereb is the base. Inother words, the mantissa would be too large to fit if it weremultiplied by the base. Non-normalized numbers are sometimes calleddenormal; they contain less precision than the representationnormally can hold.
If the number is not normalized, then you can subtract1
from theexponent while multiplying the mantissa by the base, and get anotherfloating point number with the same value.Normalization consistsof doing this repeatedly until the number is normalized. Two distinctnormalized floating point numbers cannot be equal in value.
(There is an exception to this rule: if the mantissa is zero, it isconsidered normalized. Another exception happens on certain machineswhere the exponent is as small as the representation can hold. Thenit is impossible to subtract1
from the exponent, so a numbermay be normalized even if its fraction is less than1/b
.)
Next:IEEE Floating Point, Previous:Floating Point Representation Concepts, Up:Floating Type Macros [Contents][Index]
These macro definitions can be accessed by including the header filefloat.h in your program.
Macro names starting with ‘FLT_’ refer to thefloat
type,while names beginning with ‘DBL_’ refer to thedouble
typeand names beginning with ‘LDBL_’ refer to thelong double
type. (If GCC does not supportlong double
as a distinct datatype on a target machine then the values for the ‘LDBL_’ constantsare equal to the corresponding constants for thedouble
type.)
Of these macros, onlyFLT_RADIX
is guaranteed to be a constantexpression. The other macros listed here cannot be reliably used inplaces that require constant expressions, such as ‘#if’preprocessing directives or in the dimensions of static arrays.
Although the ISO C standard specifies minimum and maximum values formost of these parameters, the GNU C implementation uses whatever valuesdescribe the floating point representation of the target machine. So inprinciple GNU C actually satisfies the ISO C requirements only if thetarget machine is suitable. In practice, all the machines currentlysupported are suitable.
FLT_ROUNDS
¶This value characterizes the rounding mode for floating point addition.The following values indicate standard rounding modes:
-1
The mode is indeterminable.
0
Rounding is towards zero.
1
Rounding is to the nearest number.
2
Rounding is towards positive infinity.
3
Rounding is towards negative infinity.
Any other value represents a machine-dependent nonstandard roundingmode.
On most machines, the value is1
, in accordance with the IEEEstandard for floating point.
Here is a table showing how certain values round for each possible valueofFLT_ROUNDS
, if the other aspects of the representation matchthe IEEE single-precision standard.
0 1 2 3 1.00000003 1.0 1.0 1.00000012 1.0 1.00000007 1.0 1.00000012 1.00000012 1.0-1.00000003 -1.0 -1.0 -1.0 -1.00000012-1.00000007 -1.0 -1.00000012 -1.0 -1.00000012
FLT_RADIX
¶This is the value of the base, or radix, of the exponent representation.This is guaranteed to be a constant expression, unlike the other macrosdescribed in this section. The value is 2 on all machines we know ofexcept the IBM 360 and derivatives.
FLT_MANT_DIG
¶This is the number of base-FLT_RADIX
digits in the floating pointmantissa for thefloat
data type. The following expressionyields1.0
(even though mathematically it should not) due to thelimited number of mantissa digits:
float radix = FLT_RADIX;1.0f + 1.0f / radix / radix / ... / radix
whereradix
appearsFLT_MANT_DIG
times.
DBL_MANT_DIG
¶LDBL_MANT_DIG
¶This is the number of base-FLT_RADIX
digits in the floating pointmantissa for the data typesdouble
andlong double
,respectively.
FLT_DIG
¶This is the number of decimal digits of precision for thefloat
data type. Technically, ifp andb are the precision andbase (respectively) for the representation, then the decimal precisionq is the maximum number of decimal digits such that any floatingpoint number withq base 10 digits can be rounded to a floatingpoint number withp baseb digits and back again, withoutchange to theq decimal digits.
The value of this macro is supposed to be at least6
, to satisfyISO C.
DBL_DIG
¶LDBL_DIG
¶These are similar toFLT_DIG
, but for the data typesdouble
andlong double
, respectively. The values of thesemacros are supposed to be at least10
.
FLT_MIN_EXP
¶This is the smallest possible exponent value for typefloat
.More precisely, it is the minimum negative integer such that the valueFLT_RADIX
raised to one less than this power can be represented as anormalized floating point number of typefloat
.
DBL_MIN_EXP
¶LDBL_MIN_EXP
¶These are similar toFLT_MIN_EXP
, but for the data typesdouble
andlong double
, respectively.
FLT_MIN_10_EXP
¶This is the minimum negative integer such that10
raised to thispower can be represented as a normalized floating point numberof typefloat
. This is supposed to be-37
or even less.
DBL_MIN_10_EXP
¶LDBL_MIN_10_EXP
¶These are similar toFLT_MIN_10_EXP
, but for the data typesdouble
andlong double
, respectively.
FLT_MAX_EXP
¶This is the largest possible exponent value for typefloat
. Moreprecisely, this is the maximum positive integer such that valueFLT_RADIX
raised to one less than this power can be represented as afinite floating point number of typefloat
.
DBL_MAX_EXP
¶LDBL_MAX_EXP
¶These are similar toFLT_MAX_EXP
, but for the data typesdouble
andlong double
, respectively.
FLT_MAX_10_EXP
¶This is the maximum positive integer such that10
raised to thispower can be represented as a finite floating point numberof typefloat
. This is supposed to be at least37
.
DBL_MAX_10_EXP
¶LDBL_MAX_10_EXP
¶These are similar toFLT_MAX_10_EXP
, but for the data typesdouble
andlong double
, respectively.
FLT_MAX
¶The value of this macro is the maximum number representable in typefloat
. It is supposed to be at least1E+37
. The valuehas typefloat
.
The smallest representable number is- FLT_MAX
.
DBL_MAX
¶LDBL_MAX
¶These are similar toFLT_MAX
, but for the data typesdouble
andlong double
, respectively. The type of themacro’s value is the same as the type it describes.
FLT_MIN
¶The value of this macro is the minimum normalized positive floatingpoint number that is representable in typefloat
. It is supposedto be no more than1E-37
.
DBL_MIN
¶LDBL_MIN
¶These are similar toFLT_MIN
, but for the data typesdouble
andlong double
, respectively. The type of themacro’s value is the same as the type it describes.
FLT_EPSILON
¶This is the difference between 1 and the smallest floating pointnumber of typefloat
that is greater than 1. It’s supposed tobe no greater than1E-5
.
DBL_EPSILON
¶LDBL_EPSILON
¶These are similar toFLT_EPSILON
, but for the data typesdouble
andlong double
, respectively. The type of themacro’s value is the same as the type it describes. The values are notsupposed to be greater than1E-9
.
Previous:Floating Point Parameters, Up:Floating Type Macros [Contents][Index]
Here is an example showing how the floating type measurements come outfor the most common floating point representation, specified by theIEEE Standard for Binary Floating Point Arithmetic (ANSI/IEEE Std754-1985). Nearly all computers designed since the 1980s use thisformat.
The IEEE single-precision float representation uses a base of 2. Thereis a sign bit, a mantissa with 23 bits plus one hidden bit (so the totalprecision is 24 base-2 digits), and an 8-bit exponent that can representvalues in the range -125 to 128, inclusive.
So, for an implementation that uses this representation for thefloat
data type, appropriate values for the correspondingparameters are:
FLT_RADIX 2FLT_MANT_DIG 24FLT_DIG 6FLT_MIN_EXP -125FLT_MIN_10_EXP -37FLT_MAX_EXP 128FLT_MAX_10_EXP +38FLT_MIN 1.17549435E-38FFLT_MAX 3.40282347E+38FFLT_EPSILON 1.19209290E-07F
Here are the values for thedouble
data type:
DBL_MANT_DIG 53DBL_DIG 15DBL_MIN_EXP -1021DBL_MIN_10_EXP -307DBL_MAX_EXP 1024DBL_MAX_10_EXP 308DBL_MAX 1.7976931348623157E+308DBL_MIN 2.2250738585072014E-308DBL_EPSILON 2.2204460492503131E-016
Previous:Floating Type Macros, Up:Data Type Measurements [Contents][Index]
You can useoffsetof
to measure the location within a structuretype of a particular structure member.
size_t
offsetof(type,member)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
This expands to an integer constant expression that is the offset of thestructure member namedmember in the structure typetype.For example,offsetof (struct s, elem)
is the offset, in bytes,of the memberelem
in astruct s
.
This macro won’t work ifmember is a bit field; you get an errorfrom the C compiler in that case.
Next:Installing the GNU C Library, Previous:C Language Facilities in the Library, Up:Main Menu [Contents][Index]
This appendix is a complete list of the facilities declared within theheader files supplied with the GNU C Library. Each entry also lists thestandard or other source from which each facility is derived, and tellsyou where in the manual you can find more information about how to useit.
ACCOUNTING
utmp.h (SVID):Manipulating the User Accounting Database.
AF_FILE
sys/socket.h (GNU):Address Formats.
AF_INET
sys/socket.h (BSD):Address Formats.
AF_INET6
sys/socket.h (IPv6 Basic API):Address Formats.
AF_LOCAL
sys/socket.h (POSIX):Address Formats.
AF_UNIX
sys/socket.h (BSD):Address Formats.
sys/socket.h (Unix98):Address Formats.
AF_UNSPEC
sys/socket.h (BSD):Address Formats.
tcflag_t ALTWERASE
termios.h (BSD):Local Modes.
int ARGP_ERR_UNKNOWN
argp.h (GNU):Argp Parser Functions.
ARGP_HELP_BUG_ADDR
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_DOC
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_EXIT_ERR
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_EXIT_OK
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_LONG
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_LONG_ONLY
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_POST_DOC
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_PRE_DOC
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_SEE
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_SHORT_USAGE
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_STD_ERR
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_STD_HELP
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_STD_USAGE
argp.h (GNU):Flags for theargp_help
Function.
ARGP_HELP_USAGE
argp.h (GNU):Flags for theargp_help
Function.
ARGP_IN_ORDER
argp.h (GNU):Flags forargp_parse
.
ARGP_KEY_ARG
argp.h (GNU):Special Keys for Argp Parser Functions.
ARGP_KEY_ARGS
argp.h (GNU):Special Keys for Argp Parser Functions.
ARGP_KEY_END
argp.h (GNU):Special Keys for Argp Parser Functions.
ARGP_KEY_ERROR
argp.h (GNU):Special Keys for Argp Parser Functions.
ARGP_KEY_FINI
argp.h (GNU):Special Keys for Argp Parser Functions.
ARGP_KEY_HELP_ARGS_DOC
argp.h (GNU):Special Keys for Argp Help Filter Functions.
ARGP_KEY_HELP_DUP_ARGS_NOTE
argp.h (GNU):Special Keys for Argp Help Filter Functions.
ARGP_KEY_HELP_EXTRA
argp.h (GNU):Special Keys for Argp Help Filter Functions.
ARGP_KEY_HELP_HEADER
argp.h (GNU):Special Keys for Argp Help Filter Functions.
ARGP_KEY_HELP_POST_DOC
argp.h (GNU):Special Keys for Argp Help Filter Functions.
ARGP_KEY_HELP_PRE_DOC
argp.h (GNU):Special Keys for Argp Help Filter Functions.
ARGP_KEY_INIT
argp.h (GNU):Special Keys for Argp Parser Functions.
ARGP_KEY_NO_ARGS
argp.h (GNU):Special Keys for Argp Parser Functions.
ARGP_KEY_SUCCESS
argp.h (GNU):Special Keys for Argp Parser Functions.
ARGP_LONG_ONLY
argp.h (GNU):Flags forargp_parse
.
ARGP_NO_ARGS
argp.h (GNU):Flags forargp_parse
.
ARGP_NO_ERRS
argp.h (GNU):Flags forargp_parse
.
ARGP_NO_EXIT
argp.h (GNU):Flags forargp_parse
.
ARGP_NO_HELP
argp.h (GNU):Flags forargp_parse
.
ARGP_PARSE_ARGV0
argp.h (GNU):Flags forargp_parse
.
ARGP_SILENT
argp.h (GNU):Flags forargp_parse
.
int ARG_MAX
limits.h (POSIX.1):General Capacity Limits.
baud_t BAUD_MAX
termios.h (GNU):Line Speed.
int BC_BASE_MAX
limits.h (POSIX.2):Utility Program Capacity Limits.
int BC_DIM_MAX
limits.h (POSIX.2):Utility Program Capacity Limits.
int BC_SCALE_MAX
limits.h (POSIX.2):Utility Program Capacity Limits.
int BC_STRING_MAX
limits.h (POSIX.2):Utility Program Capacity Limits.
BOOT_TIME
utmp.h (SVID):Manipulating the User Accounting Database.
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
tcflag_t BRKINT
termios.h (POSIX.1):Input Modes.
int BUFSIZ
stdio.h (ISO):Controlling Which Kind of Buffering.
tcflag_t CCTS_OFLOW
termios.h (BSD):Control Modes.
int CHAR_BIT
limits.h (C90):Width of an Integer Type.
CHAR_MAX
limits.h (ISO):Range of an Integer Type.
CHAR_MIN
limits.h (ISO):Range of an Integer Type.
CHAR_WIDTH
limits.h (ISO):Width of an Integer Type.
int CHILD_MAX
limits.h (POSIX.1):General Capacity Limits.
tcflag_t CIGNORE
termios.h (BSD):Control Modes.
int CLK_TCK
time.h (POSIX.1):Processor Time Inquiry.
tcflag_t CLOCAL
termios.h (POSIX.1):Control Modes.
CLOCKS_PER_SEC
time.h (ISO):Processor And CPU Time.
int CLOCKS_PER_SEC
time.h (ISO):CPU Time Inquiry.
clockid_t CLOCK_BOOTTIME
time.h (Linux):Getting the Time.
clockid_t CLOCK_BOOTTIME_ALARM
time.h (Linux):Getting the Time.
clockid_t CLOCK_MONOTONIC
time.h (POSIX.1):Getting the Time.
clockid_t CLOCK_MONOTONIC_COARSE
time.h (Linux):Getting the Time.
clockid_t CLOCK_MONOTONIC_RAW
time.h (Linux):Getting the Time.
clockid_t CLOCK_PROCESS_CPUTIME_ID
time.h (POSIX.1):Getting the Time.
clockid_t CLOCK_REALTIME
time.h (POSIX.1):Getting the Time.
clockid_t CLOCK_REALTIME_ALARM
time.h (Linux):Getting the Time.
clockid_t CLOCK_REALTIME_COARSE
time.h (Linux):Getting the Time.
clockid_t CLOCK_TAI
time.h (Linux):Getting the Time.
clockid_t CLOCK_THREAD_CPUTIME_ID
time.h (POSIX.1):Getting the Time.
int COLL_WEIGHTS_MAX
limits.h (POSIX.2):Utility Program Capacity Limits.
cpu_set_t * CPU_ALLOC (size_tcount)
sched.h (GNU):Limiting execution to certain CPUs.
size_t CPU_ALLOC_SIZE (size_tcount)
sched.h (GNU):Limiting execution to certain CPUs.
cpu_set_t * CPU_AND (cpu_set_t *dest, cpu_set_t *src1, cpu_set_t *src2)
sched.h (GNU):Limiting execution to certain CPUs.
void CPU_CLR (intcpu, cpu_set_t *set)
sched.h (GNU):Limiting execution to certain CPUs.
int CPU_COUNT (const cpu_set_t *set)
sched.h (GNU):Limiting execution to certain CPUs.
int CPU_EQUAL (cpu_set_t *src1, cpu_set_t *src2)
sched.h (GNU):Limiting execution to certain CPUs.
void CPU_FREE (cpu_set_t *set)
sched.h (GNU):Limiting execution to certain CPUs.
int CPU_ISSET (intcpu, const cpu_set_t *set)
sched.h (GNU):Limiting execution to certain CPUs.
cpu_set_t * CPU_OR (cpu_set_t *dest, cpu_set_t *src1, cpu_set_t *src2)
sched.h (GNU):Limiting execution to certain CPUs.
void CPU_SET (intcpu, cpu_set_t *set)
sched.h (GNU):Limiting execution to certain CPUs.
int CPU_SETSIZE
sched.h (GNU):Limiting execution to certain CPUs.
cpu_set_t * CPU_XOR (cpu_set_t *dest, cpu_set_t *src1, cpu_set_t *src2)
sched.h (GNU):Limiting execution to certain CPUs.
void CPU_ZERO (cpu_set_t *set)
sched.h (GNU):Limiting execution to certain CPUs.
tcflag_t CREAD
termios.h (POSIX.1):Control Modes.
tcflag_t CRTS_IFLOW
termios.h (BSD):Control Modes.
tcflag_t CS5
termios.h (POSIX.1):Control Modes.
tcflag_t CS6
termios.h (POSIX.1):Control Modes.
tcflag_t CS7
termios.h (POSIX.1):Control Modes.
tcflag_t CS8
termios.h (POSIX.1):Control Modes.
tcflag_t CSIZE
termios.h (POSIX.1):Control Modes.
tcflag_t CSTOPB
termios.h (POSIX.1):Control Modes.
DBL_DIG
float.h (C90):Floating Point Parameters.
DBL_EPSILON
float.h (C90):Floating Point Parameters.
DBL_MANT_DIG
float.h (C90):Floating Point Parameters.
DBL_MAX
float.h (C90):Floating Point Parameters.
DBL_MAX_10_EXP
float.h (C90):Floating Point Parameters.
DBL_MAX_EXP
float.h (C90):Floating Point Parameters.
DBL_MIN
float.h (C90):Floating Point Parameters.
DBL_MIN_10_EXP
float.h (C90):Floating Point Parameters.
DBL_MIN_EXP
float.h (C90):Floating Point Parameters.
DEAD_PROCESS
utmp.h (SVID):Manipulating the User Accounting Database.
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
DIR
dirent.h (POSIX.1):Opening a Directory Stream.
int DLFO_EH_SEGMENT_TYPE
dlfcn.h (GNU):Dynamic Linker Introspection.
int DLFO_STRUCT_HAS_EH_COUNT
dlfcn.h (GNU):Dynamic Linker Introspection.
int DLFO_STRUCT_HAS_EH_DBASE
dlfcn.h (GNU):Dynamic Linker Introspection.
mode_t DTTOIF (intdtype)
dirent.h (BSD):Format of a Directory Entry.
int E2BIG
errno.h (POSIX.1):Error Codes.
int EACCES
errno.h (POSIX.1):Error Codes.
int EADDRINUSE
errno.h (BSD):Error Codes.
int EADDRNOTAVAIL
errno.h (BSD):Error Codes.
int EADV
errno.h (Linux???):Error Codes.
int EAFNOSUPPORT
errno.h (BSD):Error Codes.
int EAGAIN
errno.h (POSIX.1):Error Codes.
int EALREADY
errno.h (BSD):Error Codes.
int EAUTH
errno.h (BSD):Error Codes.
int EBACKGROUND
errno.h (GNU):Error Codes.
int EBADE
errno.h (Linux???):Error Codes.
int EBADF
errno.h (POSIX.1):Error Codes.
int EBADFD
errno.h (Linux???):Error Codes.
int EBADMSG
errno.h (XOPEN):Error Codes.
int EBADR
errno.h (Linux???):Error Codes.
int EBADRPC
errno.h (BSD):Error Codes.
int EBADRQC
errno.h (Linux???):Error Codes.
int EBADSLT
errno.h (Linux???):Error Codes.
int EBFONT
errno.h (Linux???):Error Codes.
int EBUSY
errno.h (POSIX.1):Error Codes.
int ECANCELED
errno.h (POSIX.1):Error Codes.
int ECHILD
errno.h (POSIX.1):Error Codes.
tcflag_t ECHO
termios.h (POSIX.1):Local Modes.
tcflag_t ECHOCTL
termios.h (BSD):Local Modes.
tcflag_t ECHOE
termios.h (POSIX.1):Local Modes.
tcflag_t ECHOK
termios.h (POSIX.1):Local Modes.
tcflag_t ECHOKE
termios.h (BSD):Local Modes.
tcflag_t ECHONL
termios.h (POSIX.1):Local Modes.
tcflag_t ECHOPRT
termios.h (BSD):Local Modes.
int ECHRNG
errno.h (Linux???):Error Codes.
int ECOMM
errno.h (Linux???):Error Codes.
int ECONNABORTED
errno.h (BSD):Error Codes.
int ECONNREFUSED
errno.h (BSD):Error Codes.
int ECONNRESET
errno.h (BSD):Error Codes.
int ED
errno.h (GNU):Error Codes.
int EDEADLK
errno.h (POSIX.1):Error Codes.
int EDEADLOCK
errno.h (Linux???):Error Codes.
int EDESTADDRREQ
errno.h (BSD):Error Codes.
int EDIED
errno.h (GNU):Error Codes.
int EDOM
errno.h (ISO):Error Codes.
int EDOTDOT
errno.h (Linux???):Error Codes.
int EDQUOT
errno.h (BSD):Error Codes.
int EEXIST
errno.h (POSIX.1):Error Codes.
int EFAULT
errno.h (POSIX.1):Error Codes.
int EFBIG
errno.h (POSIX.1):Error Codes.
int EFTYPE
errno.h (BSD):Error Codes.
int EGRATUITOUS
errno.h (GNU):Error Codes.
int EGREGIOUS
errno.h (GNU):Error Codes.
int EHOSTDOWN
errno.h (BSD):Error Codes.
int EHOSTUNREACH
errno.h (BSD):Error Codes.
int EHWPOISON
errno.h (Linux):Error Codes.
int EIDRM
errno.h (XOPEN):Error Codes.
int EIEIO
errno.h (GNU):Error Codes.
int EILSEQ
errno.h (ISO):Error Codes.
int EINPROGRESS
errno.h (BSD):Error Codes.
int EINTR
errno.h (POSIX.1):Error Codes.
int EINVAL
errno.h (POSIX.1):Error Codes.
int EIO
errno.h (POSIX.1):Error Codes.
int EISCONN
errno.h (BSD):Error Codes.
int EISDIR
errno.h (POSIX.1):Error Codes.
int EISNAM
errno.h (Linux???):Error Codes.
int EKEYEXPIRED
errno.h (Linux):Error Codes.
int EKEYREJECTED
errno.h (Linux):Error Codes.
int EKEYREVOKED
errno.h (Linux):Error Codes.
int EL2HLT
errno.h (Obsolete):Error Codes.
int EL2NSYNC
errno.h (Obsolete):Error Codes.
int EL3HLT
errno.h (Obsolete):Error Codes.
int EL3RST
errno.h (Obsolete):Error Codes.
int ELIBACC
errno.h (Linux???):Error Codes.
int ELIBBAD
errno.h (Linux???):Error Codes.
int ELIBEXEC
errno.h (GNU):Error Codes.
int ELIBMAX
errno.h (Linux???):Error Codes.
int ELIBSCN
errno.h (Linux???):Error Codes.
int ELNRNG
errno.h (Linux???):Error Codes.
int ELOOP
errno.h (BSD):Error Codes.
int EMEDIUMTYPE
errno.h (Linux???):Error Codes.
int EMFILE
errno.h (POSIX.1):Error Codes.
int EMLINK
errno.h (POSIX.1):Error Codes.
EMPTY
utmp.h (SVID):Manipulating the User Accounting Database.
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
int EMSGSIZE
errno.h (BSD):Error Codes.
int EMULTIHOP
errno.h (XOPEN):Error Codes.
int ENAMETOOLONG
errno.h (POSIX.1):Error Codes.
int ENAVAIL
errno.h (Linux???):Error Codes.
int ENEEDAUTH
errno.h (BSD):Error Codes.
int ENETDOWN
errno.h (BSD):Error Codes.
int ENETRESET
errno.h (BSD):Error Codes.
int ENETUNREACH
errno.h (BSD):Error Codes.
int ENFILE
errno.h (POSIX.1):Error Codes.
int ENOANO
errno.h (Linux???):Error Codes.
int ENOBUFS
errno.h (BSD):Error Codes.
int ENOCSI
errno.h (Linux???):Error Codes.
int ENODATA
errno.h (XOPEN):Error Codes.
int ENODEV
errno.h (POSIX.1):Error Codes.
int ENOENT
errno.h (POSIX.1):Error Codes.
int ENOEXEC
errno.h (POSIX.1):Error Codes.
int ENOKEY
errno.h (Linux):Error Codes.
int ENOLCK
errno.h (POSIX.1):Error Codes.
int ENOLINK
errno.h (XOPEN):Error Codes.
int ENOMEDIUM
errno.h (Linux???):Error Codes.
int ENOMEM
errno.h (POSIX.1):Error Codes.
int ENOMSG
errno.h (XOPEN):Error Codes.
int ENONET
errno.h (Linux???):Error Codes.
int ENOPKG
errno.h (Linux???):Error Codes.
int ENOPROTOOPT
errno.h (BSD):Error Codes.
int ENOSPC
errno.h (POSIX.1):Error Codes.
int ENOSR
errno.h (XOPEN):Error Codes.
int ENOSTR
errno.h (XOPEN):Error Codes.
int ENOSYS
errno.h (POSIX.1):Error Codes.
int ENOTBLK
errno.h (BSD):Error Codes.
int ENOTCONN
errno.h (BSD):Error Codes.
int ENOTDIR
errno.h (POSIX.1):Error Codes.
int ENOTEMPTY
errno.h (POSIX.1):Error Codes.
int ENOTNAM
errno.h (Linux???):Error Codes.
int ENOTRECOVERABLE
errno.h (GNU):Error Codes.
int ENOTSOCK
errno.h (BSD):Error Codes.
int ENOTSUP
errno.h (POSIX.1):Error Codes.
int ENOTTY
errno.h (POSIX.1):Error Codes.
int ENOTUNIQ
errno.h (Linux???):Error Codes.
int ENXIO
errno.h (POSIX.1):Error Codes.
int EOF
stdio.h (ISO):End-Of-File and Errors.
int EOPNOTSUPP
errno.h (BSD):Error Codes.
int EOVERFLOW
errno.h (XOPEN):Error Codes.
int EOWNERDEAD
errno.h (GNU):Error Codes.
int EPERM
errno.h (POSIX.1):Error Codes.
int EPFNOSUPPORT
errno.h (BSD):Error Codes.
int EPIPE
errno.h (POSIX.1):Error Codes.
int EPROCLIM
errno.h (BSD):Error Codes.
int EPROCUNAVAIL
errno.h (BSD):Error Codes.
int EPROGMISMATCH
errno.h (BSD):Error Codes.
int EPROGUNAVAIL
errno.h (BSD):Error Codes.
int EPROTO
errno.h (XOPEN):Error Codes.
int EPROTONOSUPPORT
errno.h (BSD):Error Codes.
int EPROTOTYPE
errno.h (BSD):Error Codes.
int EQUIV_CLASS_MAX
limits.h (POSIX.2):Utility Program Capacity Limits.
int ERANGE
errno.h (ISO):Error Codes.
int EREMCHG
errno.h (Linux???):Error Codes.
int EREMOTE
errno.h (BSD):Error Codes.
int EREMOTEIO
errno.h (Linux???):Error Codes.
int ERESTART
errno.h (Linux???):Error Codes.
int ERFKILL
errno.h (Linux):Error Codes.
int EROFS
errno.h (POSIX.1):Error Codes.
int ERPCMISMATCH
errno.h (BSD):Error Codes.
int ESHUTDOWN
errno.h (BSD):Error Codes.
int ESOCKTNOSUPPORT
errno.h (BSD):Error Codes.
int ESPIPE
errno.h (POSIX.1):Error Codes.
int ESRCH
errno.h (POSIX.1):Error Codes.
int ESRMNT
errno.h (Linux???):Error Codes.
int ESTALE
errno.h (BSD):Error Codes.
int ESTRPIPE
errno.h (Linux???):Error Codes.
int ETIME
errno.h (XOPEN):Error Codes.
int ETIMEDOUT
errno.h (BSD):Error Codes.
int ETOOMANYREFS
errno.h (BSD):Error Codes.
int ETXTBSY
errno.h (BSD):Error Codes.
int EUCLEAN
errno.h (Linux???):Error Codes.
int EUNATCH
errno.h (Linux???):Error Codes.
int EUSERS
errno.h (BSD):Error Codes.
int EWOULDBLOCK
errno.h (BSD):Error Codes.
int EXDEV
errno.h (POSIX.1):Error Codes.
int EXFULL
errno.h (Linux???):Error Codes.
int EXIT_FAILURE
stdlib.h (ISO):Exit Status.
int EXIT_SUCCESS
stdlib.h (ISO):Exit Status.
int EXPR_NEST_MAX
limits.h (POSIX.2):Utility Program Capacity Limits.
int FD_CLOEXEC
fcntl.h (POSIX.1):File Descriptor Flags.
void FD_CLR (intfiledes, fd_set *set)
sys/types.h (BSD):Waiting for Input or Output.
int FD_ISSET (intfiledes, const fd_set *set)
sys/types.h (BSD):Waiting for Input or Output.
void FD_SET (intfiledes, fd_set *set)
sys/types.h (BSD):Waiting for Input or Output.
int FD_SETSIZE
sys/types.h (BSD):Waiting for Input or Output.
void FD_ZERO (fd_set *set)
sys/types.h (BSD):Waiting for Input or Output.
FE_DIVBYZERO
fenv.h (ISO):Examining the FPU status word.
FE_DOWNWARD
fenv.h (ISO):Rounding Modes.
FE_INEXACT
fenv.h (ISO):Examining the FPU status word.
FE_INVALID
fenv.h (ISO):Examining the FPU status word.
FE_OVERFLOW
fenv.h (ISO):Examining the FPU status word.
int FE_SNANS_ALWAYS_SIGNAL
fenv.h (ISO):Infinity and NaN.
FE_TONEAREST
fenv.h (ISO):Rounding Modes.
FE_TOWARDZERO
fenv.h (ISO):Rounding Modes.
FE_UNDERFLOW
fenv.h (ISO):Examining the FPU status word.
FE_UPWARD
fenv.h (ISO):Rounding Modes.
FILE
stdio.h (ISO):Streams.
int FILENAME_MAX
stdio.h (ISO):Limits on File System Capacity.
FLT_DIG
float.h (C90):Floating Point Parameters.
FLT_EPSILON
float.h (C90):Floating Point Parameters.
FLT_MANT_DIG
float.h (C90):Floating Point Parameters.
FLT_MAX
float.h (C90):Floating Point Parameters.
FLT_MAX_10_EXP
float.h (C90):Floating Point Parameters.
FLT_MAX_EXP
float.h (C90):Floating Point Parameters.
FLT_MIN
float.h (C90):Floating Point Parameters.
FLT_MIN_10_EXP
float.h (C90):Floating Point Parameters.
FLT_MIN_EXP
float.h (C90):Floating Point Parameters.
FLT_RADIX
float.h (C90):Floating Point Parameters.
FLT_ROUNDS
float.h (C90):Floating Point Parameters.
tcflag_t FLUSHO
termios.h (BSD):Local Modes.
FNM_CASEFOLD
fnmatch.h (POSIX.1-2024):Wildcard Matching.
FNM_EXTMATCH
fnmatch.h (GNU):Wildcard Matching.
FNM_FILE_NAME
fnmatch.h (GNU):Wildcard Matching.
FNM_LEADING_DIR
fnmatch.h (GNU):Wildcard Matching.
FNM_NOESCAPE
fnmatch.h (POSIX.2):Wildcard Matching.
FNM_PATHNAME
fnmatch.h (POSIX.2):Wildcard Matching.
FNM_PERIOD
fnmatch.h (POSIX.2):Wildcard Matching.
int FOPEN_MAX
stdio.h (ISO):Opening Streams.
FPE_DECOVF_TRAP
signal.h (BSD):Program Error Signals.
FPE_FLTDIV_FAULT
signal.h (BSD):Program Error Signals.
FPE_FLTDIV_TRAP
signal.h (BSD):Program Error Signals.
FPE_FLTOVF_FAULT
signal.h (BSD):Program Error Signals.
FPE_FLTOVF_TRAP
signal.h (BSD):Program Error Signals.
FPE_FLTUND_FAULT
signal.h (BSD):Program Error Signals.
FPE_FLTUND_TRAP
signal.h (BSD):Program Error Signals.
FPE_INTDIV_TRAP
signal.h (BSD):Program Error Signals.
FPE_INTOVF_TRAP
signal.h (BSD):Program Error Signals.
FPE_SUBRNG_TRAP
signal.h (BSD):Program Error Signals.
int FP_ILOGB0
math.h (ISO):Exponentiation and Logarithms.
int FP_ILOGBNAN
math.h (ISO):Exponentiation and Logarithms.
FP_INFINITE
math.h (C99):Floating-Point Number Classification Functions.
FP_INT_DOWNWARD
math.h (ISO):Rounding Functions.
FP_INT_TONEAREST
math.h (ISO):Rounding Functions.
FP_INT_TONEARESTFROMZERO
math.h (ISO):Rounding Functions.
FP_INT_TOWARDZERO
math.h (ISO):Rounding Functions.
FP_INT_UPWARD
math.h (ISO):Rounding Functions.
long int FP_LLOGB0
math.h (ISO):Exponentiation and Logarithms.
long int FP_LLOGBNAN
math.h (ISO):Exponentiation and Logarithms.
FP_NAN
math.h (C99):Floating-Point Number Classification Functions.
FP_NORMAL
math.h (C99):Floating-Point Number Classification Functions.
FP_SUBNORMAL
math.h (C99):Floating-Point Number Classification Functions.
FP_ZERO
math.h (C99):Floating-Point Number Classification Functions.
struct FTW
ftw.h (XPG4.2):Working with Directory Trees.
int F_DUPFD
fcntl.h (POSIX.1):Duplicating Descriptors.
int F_GETFD
fcntl.h (POSIX.1):File Descriptor Flags.
int F_GETFL
fcntl.h (POSIX.1):Getting and Setting File Status Flags.
int F_GETLK
fcntl.h (POSIX.1):File Locks.
int F_GETOWN
fcntl.h (BSD):Interrupt-Driven Input.
int F_OFD_SETLK
fcntl.h (POSIX.1):Open File Description Locks.
int F_OFD_SETLKW
fcntl.h (POSIX.1):Open File Description Locks.
int F_OK
unistd.h (POSIX.1):Testing Permission to Access a File.
F_RDLCK
fcntl.h (POSIX.1):File Locks.
int F_SETFD
fcntl.h (POSIX.1):File Descriptor Flags.
int F_SETFL
fcntl.h (POSIX.1):Getting and Setting File Status Flags.
int F_SETLK
fcntl.h (POSIX.1):File Locks.
int F_SETLKW
fcntl.h (POSIX.1):File Locks.
int F_SETOWN
fcntl.h (BSD):Interrupt-Driven Input.
F_UNLCK
fcntl.h (POSIX.1):File Locks.
F_WRLCK
fcntl.h (POSIX.1):File Locks.
GLOB_ABORTED
glob.h (POSIX.2):Callingglob
.
GLOB_ALTDIRFUNC
glob.h (GNU):More Flags for Globbing.
GLOB_APPEND
glob.h (POSIX.2):Flags for Globbing.
GLOB_BRACE
glob.h (GNU):More Flags for Globbing.
GLOB_DOOFFS
glob.h (POSIX.2):Flags for Globbing.
GLOB_ERR
glob.h (POSIX.2):Flags for Globbing.
GLOB_MAGCHAR
glob.h (GNU):More Flags for Globbing.
GLOB_MARK
glob.h (POSIX.2):Flags for Globbing.
GLOB_NOCHECK
glob.h (POSIX.2):Flags for Globbing.
GLOB_NOESCAPE
glob.h (POSIX.2):Flags for Globbing.
GLOB_NOMAGIC
glob.h (GNU):More Flags for Globbing.
GLOB_NOMATCH
glob.h (POSIX.2):Callingglob
.
GLOB_NOSORT
glob.h (POSIX.2):Flags for Globbing.
GLOB_NOSPACE
glob.h (POSIX.2):Callingglob
.
GLOB_ONLYDIR
glob.h (GNU):More Flags for Globbing.
GLOB_PERIOD
glob.h (GNU):More Flags for Globbing.
GLOB_TILDE
glob.h (GNU):More Flags for Globbing.
GLOB_TILDE_CHECK
glob.h (GNU):More Flags for Globbing.
HOST_NOT_FOUND
netdb.h (BSD):Host Names.
double HUGE_VAL
math.h (ISO):Error Reporting by Mathematical Functions.
float HUGE_VALF
math.h (ISO):Error Reporting by Mathematical Functions.
long double HUGE_VALL
math.h (ISO):Error Reporting by Mathematical Functions.
_FloatN HUGE_VAL_FN
math.h (TS 18661-3:2015):Error Reporting by Mathematical Functions.
_FloatNx HUGE_VAL_FNx
math.h (TS 18661-3:2015):Error Reporting by Mathematical Functions.
tcflag_t HUPCL
termios.h (POSIX.1):Control Modes.
const float complex I
complex.h (C99):Complex Numbers.
tcflag_t ICANON
termios.h (POSIX.1):Local Modes.
tcflag_t ICRNL
termios.h (POSIX.1):Input Modes.
tcflag_t IEXTEN
termios.h (POSIX.1):Local Modes.
size_t IFNAMSIZ
net/if.h (???):Interface Naming.
int IFTODT (mode_tmode)
dirent.h (BSD):Format of a Directory Entry.
tcflag_t IGNBRK
termios.h (POSIX.1):Input Modes.
tcflag_t IGNCR
termios.h (POSIX.1):Input Modes.
tcflag_t IGNPAR
termios.h (POSIX.1):Input Modes.
tcflag_t IMAXBEL
termios.h (BSD):Input Modes.
uint32_t INADDR_ANY
netinet/in.h (BSD):Host Address Data Type.
uint32_t INADDR_BROADCAST
netinet/in.h (BSD):Host Address Data Type.
uint32_t INADDR_LOOPBACK
netinet/in.h (BSD):Host Address Data Type.
uint32_t INADDR_NONE
netinet/in.h (BSD):Host Address Data Type.
float INFINITY
math.h (ISO):Infinity and NaN.
INIT_PROCESS
utmp.h (SVID):Manipulating the User Accounting Database.
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
tcflag_t INLCR
termios.h (POSIX.1):Input Modes.
tcflag_t INPCK
termios.h (POSIX.1):Input Modes.
INTPTR_WIDTH
stdint.h (ISO):Width of an Integer Type.
INT_MAX
limits.h (ISO):Range of an Integer Type.
INT_MIN
limits.h (ISO):Range of an Integer Type.
INT_WIDTH
limits.h (ISO):Width of an Integer Type.
int IPPORT_RESERVED
netinet/in.h (BSD):Internet Ports.
int IPPORT_USERRESERVED
netinet/in.h (BSD):Internet Ports.
tcflag_t ISIG
termios.h (POSIX.1):Local Modes.
tcflag_t ISTRIP
termios.h (POSIX.1):Input Modes.
ITIMER_PROF
sys/time.h (BSD):Setting an Alarm.
ITIMER_REAL
sys/time.h (BSD):Setting an Alarm.
ITIMER_VIRTUAL
sys/time.h (BSD):Setting an Alarm.
tcflag_t IXANY
termios.h (BSD):Input Modes.
tcflag_t IXOFF
termios.h (POSIX.1):Input Modes.
tcflag_t IXON
termios.h (POSIX.1):Input Modes.
LANG
locale.h (ISO):Locale Categories.
LC_ALL
locale.h (ISO):Locale Categories.
LC_COLLATE
locale.h (ISO):Locale Categories.
LC_CTYPE
locale.h (ISO):Locale Categories.
LC_MESSAGES
locale.h (XOPEN):Locale Categories.
LC_MONETARY
locale.h (ISO):Locale Categories.
LC_NUMERIC
locale.h (ISO):Locale Categories.
LC_TIME
locale.h (ISO):Locale Categories.
LDBL_DIG
float.h (C90):Floating Point Parameters.
LDBL_EPSILON
float.h (C90):Floating Point Parameters.
LDBL_MANT_DIG
float.h (C90):Floating Point Parameters.
LDBL_MAX
float.h (C90):Floating Point Parameters.
LDBL_MAX_10_EXP
float.h (C90):Floating Point Parameters.
LDBL_MAX_EXP
float.h (C90):Floating Point Parameters.
LDBL_MIN
float.h (C90):Floating Point Parameters.
LDBL_MIN_10_EXP
float.h (C90):Floating Point Parameters.
LDBL_MIN_EXP
float.h (C90):Floating Point Parameters.
int LINE_MAX
limits.h (POSIX.2):Utility Program Capacity Limits.
int LINK_MAX
limits.hoptional (POSIX.1):Limits on File System Capacity.
LLONG_MAX
limits.h (ISO):Range of an Integer Type.
LLONG_MIN
limits.h (ISO):Range of an Integer Type.
LLONG_WIDTH
limits.h (ISO):Width of an Integer Type.
LOGIN_PROCESS
utmp.h (SVID):Manipulating the User Accounting Database.
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
LONG_LONG_MAX
limits.h (GNU):Range of an Integer Type.
LONG_LONG_MIN
limits.h (GNU):Range of an Integer Type.
LONG_MAX
limits.h (ISO):Range of an Integer Type.
LONG_MIN
limits.h (ISO):Range of an Integer Type.
LONG_WIDTH
limits.h (ISO):Width of an Integer Type.
L_INCR
sys/file.h (BSD):File Positioning.
L_SET
sys/file.h (BSD):File Positioning.
L_XTND
sys/file.h (BSD):File Positioning.
int L_ctermid
stdio.h (POSIX.1):Identifying the Controlling Terminal.
int L_cuserid
stdio.h (POSIX.1):Identifying Who Logged In.
int L_tmpnam
stdio.h (ISO):Temporary Files.
MADV_HUGEPAGE
sys/mman.h (Linux):Memory-mapped I/O.
MAP_ANON
sys/mman.h (POSIX.1-2024):Memory-mapped I/O.
MAP_ANONYMOUS
sys/mman.h (POSIX.1-2024):Memory-mapped I/O.
MAP_HUGETLB
sys/mman.h (Linux):Memory-mapped I/O.
int MAXNAMLEN
dirent.h (BSD):Limits on File System Capacity.
int MAXSYMLINKS
sys/param.h (BSD):Symbolic Links.
int MAX_CANON
limits.h (POSIX.1):Limits on File System Capacity.
int MAX_INPUT
limits.h (POSIX.1):Limits on File System Capacity.
int MB_CUR_MAX
stdlib.h (ISO):Selecting the conversion and its properties.
int MB_LEN_MAX
limits.h (ISO):Selecting the conversion and its properties.
tcflag_t MDMBUF
termios.h (BSD):Control Modes.
MFD_ALLOW_SEALING
sys/mman.h (Linux):Memory-mapped I/O.
MFD_CLOEXEC
sys/mman.h (Linux):Memory-mapped I/O.
MFD_HUGETLB
sys/mman.h (Linux):Memory-mapped I/O.
MLOCK_ONFAULT
sys/mman.h (Linux):Functions To Lock And Unlock Pages.
int MSG_DONTROUTE
sys/socket.h (BSD):Socket Data Options.
int MSG_OOB
sys/socket.h (BSD):Socket Data Options.
int MSG_PEEK
sys/socket.h (BSD):Socket Data Options.
int NAME_MAX
limits.h (POSIX.1):Limits on File System Capacity.
float NAN
math.h (GNU):Infinity and NaN.
int NCCS
termios.h (POSIX.1):Terminal Mode Data Types.
NEW_TIME
utmp.h (SVID):Manipulating the User Accounting Database.
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
int NGROUPS_MAX
limits.h (POSIX.1):General Capacity Limits.
tcflag_t NOFLSH
termios.h (POSIX.1):Local Modes.
tcflag_t NOKERNINFO
termios.hoptional (BSD):Local Modes.
NO_ADDRESS
netdb.h (BSD):Host Names.
NO_RECOVERY
netdb.h (BSD):Host Names.
int NSIG
signal.h (BSD):Standard Signals.
void * NULL
stddef.h (ISO):Null Pointer Constant.
OLD_TIME
utmp.h (SVID):Manipulating the User Accounting Database.
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
ONCE_FLAG_INIT
threads.h (C11):Call Once.
tcflag_t ONLCR
termios.h (POSIX.1):Output Modes.
tcflag_t ONOEOT
termios.hoptional (BSD):Output Modes.
int OPEN_MAX
limits.h (POSIX.1):General Capacity Limits.
tcflag_t OPOST
termios.h (POSIX.1):Output Modes.
OPTION_ALIAS
argp.h (GNU):Flags for Argp Options.
OPTION_ARG_OPTIONAL
argp.h (GNU):Flags for Argp Options.
OPTION_DOC
argp.h (GNU):Flags for Argp Options.
OPTION_HIDDEN
argp.h (GNU):Flags for Argp Options.
OPTION_NO_USAGE
argp.h (GNU):Flags for Argp Options.
tcflag_t OXTABS
termios.hoptional (BSD):Output Modes.
int O_ACCMODE
fcntl.h (POSIX.1):File Access Modes.
int O_APPEND
fcntl.h (POSIX.1):I/O Operating Modes.
int O_ASYNC
fcntl.h (BSD):I/O Operating Modes.
int O_CREAT
fcntl.h (POSIX.1):Open-time Flags.
int O_DIRECTORY
fcntl.h (POSIX.1):Open-time Flags.
int O_EXCL
fcntl.h (POSIX.1):Open-time Flags.
int O_EXEC
fcntl.hoptional (GNU):File Access Modes.
int O_EXLOCK
fcntl.hoptional (BSD):Open-time Flags.
int O_FSYNC
fcntl.h (BSD):I/O Operating Modes.
int O_IGNORE_CTTY
fcntl.hoptional (GNU):Open-time Flags.
int O_NDELAY
fcntl.h (BSD):I/O Operating Modes.
int O_NOATIME
fcntl.h (GNU):I/O Operating Modes.
int O_NOCTTY
fcntl.h (POSIX.1):Open-time Flags.
int O_NOFOLLOW
fcntl.h (POSIX.1):Open-time Flags.
int O_NOLINK
fcntl.hoptional (GNU):Open-time Flags.
int O_NONBLOCK
fcntl.h (POSIX.1):Open-time Flags.
fcntl.h (POSIX.1):I/O Operating Modes.
int O_NOTRANS
fcntl.hoptional (GNU):Open-time Flags.
int O_PATH
fcntl.h (Linux):File Access Modes.
int O_RDONLY
fcntl.h (POSIX.1):File Access Modes.
int O_RDWR
fcntl.h (POSIX.1):File Access Modes.
int O_READ
fcntl.hoptional (GNU):File Access Modes.
int O_SHLOCK
fcntl.hoptional (BSD):Open-time Flags.
int O_SYNC
fcntl.h (BSD):I/O Operating Modes.
int O_TMPFILE
fcntl.h (GNU):Open-time Flags.
int O_TRUNC
fcntl.h (POSIX.1):Open-time Flags.
int O_WRITE
fcntl.hoptional (GNU):File Access Modes.
int O_WRONLY
fcntl.h (POSIX.1):File Access Modes.
tcflag_t PARENB
termios.h (POSIX.1):Control Modes.
tcflag_t PARMRK
termios.h (POSIX.1):Input Modes.
tcflag_t PARODD
termios.h (POSIX.1):Control Modes.
int PATH_MAX
limits.h (POSIX.1):Limits on File System Capacity.
PA_CHAR
printf.h (GNU):Parsing a Template String.
PA_DOUBLE
printf.h (GNU):Parsing a Template String.
PA_FLAG_LONG
printf.h (GNU):Parsing a Template String.
PA_FLAG_LONG_DOUBLE
printf.h (GNU):Parsing a Template String.
PA_FLAG_LONG_LONG
printf.h (GNU):Parsing a Template String.
int PA_FLAG_MASK
printf.h (GNU):Parsing a Template String.
PA_FLAG_PTR
printf.h (GNU):Parsing a Template String.
PA_FLAG_SHORT
printf.h (GNU):Parsing a Template String.
PA_FLOAT
printf.h (GNU):Parsing a Template String.
PA_INT
printf.h (GNU):Parsing a Template String.
PA_LAST
printf.h (GNU):Parsing a Template String.
PA_POINTER
printf.h (GNU):Parsing a Template String.
PA_STRING
printf.h (GNU):Parsing a Template String.
tcflag_t PENDIN
termios.h (BSD):Local Modes.
int PF_FILE
sys/socket.h (GNU):Details of Local Namespace.
int PF_INET
sys/socket.h (BSD):The Internet Namespace.
int PF_INET6
sys/socket.h (X/Open):The Internet Namespace.
int PF_LOCAL
sys/socket.h (POSIX):Details of Local Namespace.
int PF_UNIX
sys/socket.h (BSD):Details of Local Namespace.
int PIPE_BUF
limits.h (POSIX.1):Limits on File System Capacity.
PKEY_DISABLE_ACCESS
sys/mman.h (Linux):Memory Protection.
PKEY_DISABLE_EXECUTE
sys/mman.h (Linux):Memory Protection.
PKEY_DISABLE_READ
sys/mman.h (Linux):Memory Protection.
PKEY_DISABLE_WRITE
sys/mman.h (Linux):Memory Protection.
POSIX_REC_INCR_XFER_SIZE
limits.h (POSIX.1):Minimum Values for File System Limits.
POSIX_REC_MAX_XFER_SIZE
limits.h (POSIX.1):Minimum Values for File System Limits.
POSIX_REC_MIN_XFER_SIZE
limits.h (POSIX.1):Minimum Values for File System Limits.
POSIX_REC_XFER_ALIGN
limits.h (POSIX.1):Minimum Values for File System Limits.
PRIO_MAX
sys/resource.h (BSD):Functions For Traditional Scheduling.
PRIO_MIN
sys/resource.h (BSD):Functions For Traditional Scheduling.
PRIO_PGRP
sys/resource.h (BSD):Functions For Traditional Scheduling.
PRIO_PROCESS
sys/resource.h (BSD):Functions For Traditional Scheduling.
PRIO_USER
sys/resource.h (BSD):Functions For Traditional Scheduling.
PROT_EXEC
sys/mman.h (POSIX):Memory Protection.
PROT_NONE
sys/mman.h (POSIX):Memory Protection.
PROT_READ
sys/mman.h (POSIX):Memory Protection.
PROT_WRITE
sys/mman.h (POSIX):Memory Protection.
PTRDIFF_WIDTH
stdint.h (ISO):Width of an Integer Type.
char * P_tmpdir
stdio.h (SVID):Temporary Files.
int RAND_MAX
stdlib.h (ISO):ISO C Random Number Functions.
REG_BADBR
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_BADPAT
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_BADRPT
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_EBRACE
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_EBRACK
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_ECOLLATE
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_ECTYPE
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_EESCAPE
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_EPAREN
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_ERANGE
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_ESPACE
regex.h (POSIX.2):POSIX Regular Expression Compilation.
regex.h (POSIX.2):Matching a Compiled POSIX Regular Expression.
REG_ESUBREG
regex.h (POSIX.2):POSIX Regular Expression Compilation.
REG_EXTENDED
regex.h (POSIX.2):Flags for POSIX Regular Expressions.
REG_ICASE
regex.h (POSIX.2):Flags for POSIX Regular Expressions.
REG_NEWLINE
regex.h (POSIX.2):Flags for POSIX Regular Expressions.
REG_NOMATCH
regex.h (POSIX.2):Matching a Compiled POSIX Regular Expression.
REG_NOSUB
regex.h (POSIX.2):Flags for POSIX Regular Expressions.
REG_NOTBOL
regex.h (POSIX.2):Matching a Compiled POSIX Regular Expression.
REG_NOTEOL
regex.h (POSIX.2):Matching a Compiled POSIX Regular Expression.
int RE_DUP_MAX
limits.h (POSIX.2):General Capacity Limits.
RLIMIT_AS
sys/resource.h (Unix98):Limiting Resource Usage.
RLIMIT_CORE
sys/resource.h (BSD):Limiting Resource Usage.
RLIMIT_CPU
sys/resource.h (BSD):Limiting Resource Usage.
RLIMIT_DATA
sys/resource.h (BSD):Limiting Resource Usage.
RLIMIT_FSIZE
sys/resource.h (BSD):Limiting Resource Usage.
RLIMIT_MEMLOCK
sys/resource.h (BSD):Limiting Resource Usage.
RLIMIT_NOFILE
sys/resource.h (BSD):Limiting Resource Usage.
RLIMIT_NPROC
sys/resource.h (BSD):Limiting Resource Usage.
RLIMIT_RSS
sys/resource.h (BSD):Limiting Resource Usage.
RLIMIT_STACK
sys/resource.h (BSD):Limiting Resource Usage.
rlim_t RLIM_INFINITY
sys/resource.h (BSD):Limiting Resource Usage.
RLIM_NLIMITS
sys/resource.h (BSD):Limiting Resource Usage.
int RSEQ_SIG
sys/rseq.h (Linux):Restartable Sequences.
RUN_LVL
utmp.h (SVID):Manipulating the User Accounting Database.
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
RUSAGE_CHILDREN
sys/resource.h (BSD):Resource Usage.
RUSAGE_SELF
sys/resource.h (BSD):Resource Usage.
int R_OK
unistd.h (POSIX.1):Testing Permission to Access a File.
int SA_NOCLDSTOP
signal.h (POSIX.1):Flags forsigaction
.
int SA_ONSTACK
signal.h (BSD):Flags forsigaction
.
int SA_RESTART
signal.h (BSD):Flags forsigaction
.
SCHAR_MAX
limits.h (ISO):Range of an Integer Type.
SCHAR_MIN
limits.h (ISO):Range of an Integer Type.
SCHAR_WIDTH
limits.h (ISO):Width of an Integer Type.
int SEEK_CUR
stdio.h (ISO):File Positioning.
int SEEK_END
stdio.h (ISO):File Positioning.
int SEEK_SET
stdio.h (ISO):File Positioning.
SHRT_MAX
limits.h (ISO):Range of an Integer Type.
SHRT_MIN
limits.h (ISO):Range of an Integer Type.
SHRT_WIDTH
limits.h (ISO):Width of an Integer Type.
int SIGABRT
signal.h (ISO):Program Error Signals.
int SIGALRM
signal.h (POSIX.1):Alarm Signals.
int SIGBUS
signal.h (BSD):Program Error Signals.
int SIGCHLD
signal.h (POSIX.1):Job Control Signals.
int SIGCLD
signal.h (SVID):Job Control Signals.
int SIGCONT
signal.h (POSIX.1):Job Control Signals.
int SIGEMT
signal.h (BSD):Program Error Signals.
int SIGFPE
signal.h (ISO):Program Error Signals.
int SIGHUP
signal.h (POSIX.1):Termination Signals.
int SIGILL
signal.h (ISO):Program Error Signals.
int SIGINFO
signal.h (BSD):Miscellaneous Signals.
int SIGINT
signal.h (ISO):Termination Signals.
int SIGIO
signal.h (BSD):Asynchronous I/O Signals.
int SIGIOT
signal.h (Unix):Program Error Signals.
int SIGKILL
signal.h (POSIX.1):Termination Signals.
int SIGLOST
signal.h (GNU):Operation Error Signals.
int SIGPIPE
signal.h (POSIX.1):Operation Error Signals.
int SIGPOLL
signal.h (SVID):Asynchronous I/O Signals.
int SIGPROF
signal.h (BSD):Alarm Signals.
int SIGQUIT
signal.h (POSIX.1):Termination Signals.
int SIGSEGV
signal.h (ISO):Program Error Signals.
int SIGSTOP
signal.h (POSIX.1):Job Control Signals.
int SIGSYS
signal.h (Unix):Program Error Signals.
int SIGTERM
signal.h (ISO):Termination Signals.
int SIGTRAP
signal.h (BSD):Program Error Signals.
int SIGTSTP
signal.h (POSIX.1):Job Control Signals.
int SIGTTIN
signal.h (POSIX.1):Job Control Signals.
int SIGTTOU
signal.h (POSIX.1):Job Control Signals.
int SIGURG
signal.h (BSD):Asynchronous I/O Signals.
int SIGUSR1
signal.h (POSIX.1):Miscellaneous Signals.
int SIGUSR2
signal.h (POSIX.1):Miscellaneous Signals.
int SIGVTALRM
signal.h (BSD):Alarm Signals.
int SIGWINCH
signal.h (POSIX.1-2024):Miscellaneous Signals.
int SIGXCPU
signal.h (BSD):Operation Error Signals.
int SIGXFSZ
signal.h (BSD):Operation Error Signals.
SIG_ATOMIC_WIDTH
stdint.h (ISO):Width of an Integer Type.
SIG_BLOCK
signal.h (POSIX.1):Process Signal Mask.
sighandler_t SIG_ERR
signal.h (ISO):Basic Signal Handling.
SIG_SETMASK
signal.h (POSIX.1):Process Signal Mask.
SIG_UNBLOCK
signal.h (POSIX.1):Process Signal Mask.
SIZE_WIDTH
stdint.h (ISO):Width of an Integer Type.
double SNAN
math.h (TS 18661-1:2014):Infinity and NaN.
float SNANF
math.h (TS 18661-1:2014):Infinity and NaN.
_FloatN SNANFN
math.h (TS 18661-3:2015):Infinity and NaN.
_FloatNx SNANFNx
math.h (TS 18661-3:2015):Infinity and NaN.
long double SNANL
math.h (TS 18661-1:2014):Infinity and NaN.
int SOCK_DGRAM
sys/socket.h (BSD):Communication Styles.
int SOCK_RAW
sys/socket.h (BSD):Communication Styles.
int SOCK_STREAM
sys/socket.h (BSD):Communication Styles.
int SOL_SOCKET
sys/socket.h (BSD):Socket-Level Options.
SO_BROADCAST
sys/socket.h (BSD):Socket-Level Options.
SO_DEBUG
sys/socket.h (BSD):Socket-Level Options.
SO_DONTROUTE
sys/socket.h (BSD):Socket-Level Options.
SO_ERROR
sys/socket.h (BSD):Socket-Level Options.
SO_KEEPALIVE
sys/socket.h (BSD):Socket-Level Options.
SO_LINGER
sys/socket.h (BSD):Socket-Level Options.
SO_OOBINLINE
sys/socket.h (BSD):Socket-Level Options.
SO_RCVBUF
sys/socket.h (BSD):Socket-Level Options.
SO_REUSEADDR
sys/socket.h (BSD):Socket-Level Options.
SO_SNDBUF
sys/socket.h (BSD):Socket-Level Options.
SO_STYLE
sys/socket.h (GNU):Socket-Level Options.
SO_TYPE
sys/socket.h (BSD):Socket-Level Options.
speed_t SPEED_MAX
termios.h (GNU):Line Speed.
ssize_t SSIZE_MAX
limits.h (POSIX.1):General Capacity Limits.
STDERR_FILENO
unistd.h (POSIX.1):Descriptors and Streams.
STDIN_FILENO
unistd.h (POSIX.1):Descriptors and Streams.
STDOUT_FILENO
unistd.h (POSIX.1):Descriptors and Streams.
int STREAM_MAX
limits.h (POSIX.1):General Capacity Limits.
int SUN_LEN (struct sockaddr_un *ptr)
sys/un.h (BSD):Details of Local Namespace.
SYMLINK_MAX
limits.h (POSIX.1):Minimum Values for File System Limits.
S_IEXEC
sys/stat.h (BSD):The Mode Bits for Access Permission.
S_IFBLK
sys/stat.h (BSD):Testing the Type of a File.
S_IFCHR
sys/stat.h (BSD):Testing the Type of a File.
S_IFDIR
sys/stat.h (BSD):Testing the Type of a File.
S_IFIFO
sys/stat.h (BSD):Testing the Type of a File.
S_IFLNK
sys/stat.h (BSD):Testing the Type of a File.
int S_IFMT
sys/stat.h (BSD):Testing the Type of a File.
S_IFREG
sys/stat.h (BSD):Testing the Type of a File.
S_IFSOCK
sys/stat.h (BSD):Testing the Type of a File.
S_IREAD
sys/stat.h (BSD):The Mode Bits for Access Permission.
S_IRGRP
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
S_IROTH
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
S_IRUSR
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
S_IRWXG
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
S_IRWXO
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
S_IRWXU
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
int S_ISBLK (mode_tm)
sys/stat.h (POSIX):Testing the Type of a File.
int S_ISCHR (mode_tm)
sys/stat.h (POSIX):Testing the Type of a File.
int S_ISDIR (mode_tm)
sys/stat.h (POSIX):Testing the Type of a File.
int S_ISFIFO (mode_tm)
sys/stat.h (POSIX):Testing the Type of a File.
S_ISGID
sys/stat.h (POSIX):The Mode Bits for Access Permission.
int S_ISLNK (mode_tm)
sys/stat.h (GNU):Testing the Type of a File.
int S_ISREG (mode_tm)
sys/stat.h (POSIX):Testing the Type of a File.
int S_ISSOCK (mode_tm)
sys/stat.h (GNU):Testing the Type of a File.
S_ISUID
sys/stat.h (POSIX):The Mode Bits for Access Permission.
S_ISVTX
sys/stat.h (BSD):The Mode Bits for Access Permission.
S_IWGRP
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
S_IWOTH
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
S_IWRITE
sys/stat.h (BSD):The Mode Bits for Access Permission.
S_IWUSR
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
S_IXGRP
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
S_IXOTH
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
S_IXUSR
sys/stat.h (POSIX.1):The Mode Bits for Access Permission.
int S_TYPEISMQ (struct stat *s)
sys/stat.h (POSIX):Testing the Type of a File.
int S_TYPEISSEM (struct stat *s)
sys/stat.h (POSIX):Testing the Type of a File.
int S_TYPEISSHM (struct stat *s)
sys/stat.h (POSIX):Testing the Type of a File.
TCSADRAIN
termios.h (POSIX.1):Terminal Mode Functions.
TCSAFLUSH
termios.h (POSIX.1):Terminal Mode Functions.
TCSANOW
termios.h (POSIX.1):Terminal Mode Functions.
TCSASOFT
termios.h (BSD):Terminal Mode Functions.
TEMP_FAILURE_RETRY (expression)
unistd.h (GNU):Primitives Interrupted by Signals.
int TIME_UTC
time.h (ISO):Getting the Time.
int TMP_MAX
stdio.h (ISO):Temporary Files.
tcflag_t TOSTOP
termios.h (POSIX.1):Local Modes.
TRY_AGAIN
netdb.h (BSD):Host Names.
TSS_DTOR_ITERATIONS
threads.h (C11):Thread-local Storage.
int TZNAME_MAX
limits.h (POSIX.1):General Capacity Limits.
UCHAR_MAX
limits.h (ISO):Range of an Integer Type.
UCHAR_WIDTH
limits.h (ISO):Width of an Integer Type.
UINTPTR_WIDTH
stdint.h (ISO):Width of an Integer Type.
UINT_MAX
limits.h (ISO):Range of an Integer Type.
UINT_WIDTH
limits.h (ISO):Width of an Integer Type.
ULLONG_MAX
limits.h (ISO):Range of an Integer Type.
ULLONG_WIDTH
limits.h (ISO):Width of an Integer Type.
ULONG_LONG_MAX
limits.h (GNU):Range of an Integer Type.
ULONG_MAX
limits.h (ISO):Range of an Integer Type.
ULONG_WIDTH
limits.h (ISO):Width of an Integer Type.
USER_PROCESS
utmp.h (SVID):Manipulating the User Accounting Database.
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
USHRT_MAX
limits.h (ISO):Range of an Integer Type.
USHRT_WIDTH
limits.h (ISO):Width of an Integer Type.
int VDISCARD
termios.h (BSD):Other Special Characters.
int VDSUSP
termios.h (BSD):Characters that Cause Signals.
int VEOF
termios.h (POSIX.1):Characters for Input Editing.
int VEOL
termios.h (POSIX.1):Characters for Input Editing.
int VEOL2
termios.h (BSD):Characters for Input Editing.
int VERASE
termios.h (POSIX.1):Characters for Input Editing.
int VINTR
termios.h (POSIX.1):Characters that Cause Signals.
int VKILL
termios.h (POSIX.1):Characters for Input Editing.
int VLNEXT
termios.h (BSD):Other Special Characters.
int VMIN
termios.h (POSIX.1):Noncanonical Input.
int VQUIT
termios.h (POSIX.1):Characters that Cause Signals.
int VREPRINT
termios.h (BSD):Characters for Input Editing.
int VSTART
termios.h (POSIX.1):Special Characters for Flow Control.
int VSTATUS
termios.h (BSD):Other Special Characters.
int VSTOP
termios.h (POSIX.1):Special Characters for Flow Control.
int VSUSP
termios.h (POSIX.1):Characters that Cause Signals.
int VTIME
termios.h (POSIX.1):Noncanonical Input.
int VWERASE
termios.h (BSD):Characters for Input Editing.
WCHAR_MAX
limits.h (GNU):Range of an Integer Type.
wint_t WCHAR_MAX
wchar.h (ISO):Introduction to Extended Characters.
wint_t WCHAR_MIN
wchar.h (ISO):Introduction to Extended Characters.
WCHAR_WIDTH
stdint.h (ISO):Width of an Integer Type.
int WCOREDUMP (intstatus)
sys/wait.h (POSIX.1-2024):Process Completion Status.
int WEOF
wchar.h (ISO):End-Of-File and Errors.
wint_t WEOF
wchar.h (ISO):Introduction to Extended Characters.
int WEXITSTATUS (intstatus)
sys/wait.h (POSIX.1):Process Completion Status.
int WIFEXITED (intstatus)
sys/wait.h (POSIX.1):Process Completion Status.
int WIFSIGNALED (intstatus)
sys/wait.h (POSIX.1):Process Completion Status.
int WIFSTOPPED (intstatus)
sys/wait.h (POSIX.1):Process Completion Status.
WINT_WIDTH
stdint.h (ISO):Width of an Integer Type.
WRDE_APPEND
wordexp.h (POSIX.2):Flags for Word Expansion.
WRDE_BADCHAR
wordexp.h (POSIX.2):Callingwordexp
.
WRDE_BADVAL
wordexp.h (POSIX.2):Callingwordexp
.
WRDE_CMDSUB
wordexp.h (POSIX.2):Callingwordexp
.
WRDE_DOOFFS
wordexp.h (POSIX.2):Flags for Word Expansion.
WRDE_NOCMD
wordexp.h (POSIX.2):Flags for Word Expansion.
WRDE_NOSPACE
wordexp.h (POSIX.2):Callingwordexp
.
WRDE_REUSE
wordexp.h (POSIX.2):Flags for Word Expansion.
WRDE_SHOWERR
wordexp.h (POSIX.2):Flags for Word Expansion.
WRDE_SYNTAX
wordexp.h (POSIX.2):Callingwordexp
.
WRDE_UNDEF
wordexp.h (POSIX.2):Flags for Word Expansion.
int WSTOPSIG (intstatus)
sys/wait.h (POSIX.1):Process Completion Status.
int WTERMSIG (intstatus)
sys/wait.h (POSIX.1):Process Completion Status.
int W_OK
unistd.h (POSIX.1):Testing Permission to Access a File.
int X_OK
unistd.h (POSIX.1):Testing Permission to Access a File.
_ATFILE_SOURCE
no header (GNU):Feature Test Macros.
_CS_LFS64_CFLAGS
unistd.h (Unix98):String-Valued Parameters.
_CS_LFS64_LDFLAGS
unistd.h (Unix98):String-Valued Parameters.
_CS_LFS64_LIBS
unistd.h (Unix98):String-Valued Parameters.
_CS_LFS64_LINTFLAGS
unistd.h (Unix98):String-Valued Parameters.
_CS_LFS_CFLAGS
unistd.h (Unix98):String-Valued Parameters.
_CS_LFS_LDFLAGS
unistd.h (Unix98):String-Valued Parameters.
_CS_LFS_LIBS
unistd.h (Unix98):String-Valued Parameters.
_CS_LFS_LINTFLAGS
unistd.h (Unix98):String-Valued Parameters.
_CS_PATH
unistd.h (POSIX.2):String-Valued Parameters.
const float complex _Complex_I
complex.h (C99):Complex Numbers.
_DEFAULT_SOURCE
no header (GNU):Feature Test Macros.
_DYNAMIC_STACK_SIZE_SOURCE
no header (GNU):Feature Test Macros.
void _Exit (intstatus)
stdlib.h (ISO):Termination Internals.
_FILE_OFFSET_BITS
no header (X/Open):Feature Test Macros.
_FORTIFY_SOURCE
no header (GNU):Feature Test Macros.
pid_t _Fork (void)
unistd.h (POSIX.1-2024):Creating a Process.
_GNU_SOURCE
no header (GNU):Feature Test Macros.
int _IOFBF
stdio.h (ISO):Controlling Which Kind of Buffering.
int _IOLBF
stdio.h (ISO):Controlling Which Kind of Buffering.
int _IONBF
stdio.h (ISO):Controlling Which Kind of Buffering.
_ISOC11_SOURCE
no header (C11):Feature Test Macros.
_ISOC23_SOURCE
no header (C23):Feature Test Macros.
_ISOC2Y_SOURCE
no header (C2Y):Feature Test Macros.
_ISOC99_SOURCE
no header (GNU):Feature Test Macros.
_LARGEFILE64_SOURCE
no header (X/Open):Feature Test Macros.
_LARGEFILE_SOURCE
no header (X/Open):Feature Test Macros.
_PC_ASYNC_IO
unistd.h (POSIX.1):Usingpathconf
.
_PC_CHOWN_RESTRICTED
unistd.h (POSIX.1):Usingpathconf
.
_PC_FILESIZEBITS
unistd.h (LFS):Usingpathconf
.
_PC_LINK_MAX
unistd.h (POSIX.1):Usingpathconf
.
_PC_MAX_CANON
unistd.h (POSIX.1):Usingpathconf
.
_PC_MAX_INPUT
unistd.h (POSIX.1):Usingpathconf
.
_PC_NAME_MAX
unistd.h (POSIX.1):Usingpathconf
.
_PC_NO_TRUNC
unistd.h (POSIX.1):Usingpathconf
.
_PC_PATH_MAX
unistd.h (POSIX.1):Usingpathconf
.
_PC_PIPE_BUF
unistd.h (POSIX.1):Usingpathconf
.
_PC_PRIO_IO
unistd.h (POSIX.1):Usingpathconf
.
_PC_REC_INCR_XFER_SIZE
unistd.h (POSIX.1):Usingpathconf
.
_PC_REC_MAX_XFER_SIZE
unistd.h (POSIX.1):Usingpathconf
.
_PC_REC_MIN_XFER_SIZE
unistd.h (POSIX.1):Usingpathconf
.
_PC_REC_XFER_ALIGN
unistd.h (POSIX.1):Usingpathconf
.
_PC_SYNC_IO
unistd.h (POSIX.1):Usingpathconf
.
_PC_VDISABLE
unistd.h (POSIX.1):Usingpathconf
.
_POSIX2_BC_BASE_MAX
limits.h (POSIX.2):Minimum Values for Utility Limits.
_POSIX2_BC_DIM_MAX
limits.h (POSIX.2):Minimum Values for Utility Limits.
_POSIX2_BC_SCALE_MAX
limits.h (POSIX.2):Minimum Values for Utility Limits.
_POSIX2_BC_STRING_MAX
limits.h (POSIX.2):Minimum Values for Utility Limits.
_POSIX2_COLL_WEIGHTS_MAX
limits.h (POSIX.2):Minimum Values for Utility Limits.
int _POSIX2_C_DEV
unistd.h (POSIX.2):Overall System Options.
long int _POSIX2_C_VERSION
unistd.h (POSIX.2):Which Version of POSIX is Supported.
_POSIX2_EQUIV_CLASS_MAX
limits.h (POSIX.2):Minimum Values for Utility Limits.
_POSIX2_EXPR_NEST_MAX
limits.h (POSIX.2):Minimum Values for Utility Limits.
int _POSIX2_FORT_DEV
unistd.h (POSIX.2):Overall System Options.
int _POSIX2_FORT_RUN
unistd.h (POSIX.2):Overall System Options.
_POSIX2_LINE_MAX
limits.h (POSIX.2):Minimum Values for Utility Limits.
int _POSIX2_LOCALEDEF
unistd.h (POSIX.2):Overall System Options.
_POSIX2_RE_DUP_MAX
limits.h (POSIX.2):Minimum Values for General Capacity Limits.
int _POSIX2_SW_DEV
unistd.h (POSIX.2):Overall System Options.
_POSIX_AIO_LISTIO_MAX
limits.h (POSIX.1):Minimum Values for General Capacity Limits.
_POSIX_AIO_MAX
limits.h (POSIX.1):Minimum Values for General Capacity Limits.
_POSIX_ARG_MAX
limits.h (POSIX.1):Minimum Values for General Capacity Limits.
_POSIX_CHILD_MAX
limits.h (POSIX.1):Minimum Values for General Capacity Limits.
int _POSIX_CHOWN_RESTRICTED
unistd.h (POSIX.1):Optional Features in File Support.
_POSIX_C_SOURCE
no header (POSIX.2):Feature Test Macros.
int _POSIX_JOB_CONTROL
unistd.h (POSIX.1):Overall System Options.
_POSIX_LINK_MAX
limits.h (POSIX.1):Minimum Values for File System Limits.
_POSIX_MAX_CANON
limits.h (POSIX.1):Minimum Values for File System Limits.
_POSIX_MAX_INPUT
limits.h (POSIX.1):Minimum Values for File System Limits.
_POSIX_NAME_MAX
limits.h (POSIX.1):Minimum Values for File System Limits.
_POSIX_NGROUPS_MAX
limits.h (POSIX.1):Minimum Values for General Capacity Limits.
int _POSIX_NO_TRUNC
unistd.h (POSIX.1):Optional Features in File Support.
_POSIX_OPEN_MAX
limits.h (POSIX.1):Minimum Values for General Capacity Limits.
_POSIX_PATH_MAX
limits.h (POSIX.1):Minimum Values for File System Limits.
_POSIX_PIPE_BUF
limits.h (POSIX.1):Minimum Values for File System Limits.
int _POSIX_SAVED_IDS
unistd.h (POSIX.1):Overall System Options.
_POSIX_SOURCE
no header (POSIX.1):Feature Test Macros.
_POSIX_SSIZE_MAX
limits.h (POSIX.1):Minimum Values for General Capacity Limits.
_POSIX_STREAM_MAX
limits.h (POSIX.1):Minimum Values for General Capacity Limits.
_POSIX_TZNAME_MAX
limits.h (POSIX.1):Minimum Values for General Capacity Limits.
unsigned char _POSIX_VDISABLE
unistd.h (POSIX.1):Optional Features in File Support.
long int _POSIX_VERSION
unistd.h (POSIX.1):Which Version of POSIX is Supported.
_REENTRANT
no header (Obsolete):Feature Test Macros.
_SC_2_C_DEV
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_2_FORT_DEV
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_2_FORT_RUN
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_2_LOCALEDEF
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_2_SW_DEV
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_2_VERSION
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_AIO_LISTIO_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_AIO_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_AIO_PRIO_DELTA_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_ARG_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_ASYNCHRONOUS_IO
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_ATEXIT_MAX
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_AVPHYS_PAGES
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_BC_BASE_MAX
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_BC_DIM_MAX
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_BC_SCALE_MAX
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_BC_STRING_MAX
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_CHARCLASS_NAME_MAX
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_CHAR_BIT
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_CHAR_MAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_CHAR_MIN
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_CHILD_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_CLK_TCK
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_COLL_WEIGHTS_MAX
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_DELAYTIMER_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_EQUIV_CLASS_MAX
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_EXPR_NEST_MAX
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_FSYNC
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_GETGR_R_SIZE_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_GETPW_R_SIZE_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_INT_MAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_INT_MIN
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_JOB_CONTROL
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_LEVEL1_DCACHE_ASSOC
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL1_DCACHE_LINESIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL1_DCACHE_SIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL1_ICACHE_ASSOC
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL1_ICACHE_LINESIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL1_ICACHE_SIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL2_CACHE_ASSOC
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL2_CACHE_LINESIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL2_CACHE_SIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL3_CACHE_ASSOC
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL3_CACHE_LINESIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL3_CACHE_SIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL4_CACHE_ASSOC
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL4_CACHE_LINESIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LEVEL4_CACHE_SIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_LINE_MAX
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_LOGIN_NAME_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_LONG_BIT
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_MAPPED_FILES
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_MB_LEN_MAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_MEMLOCK
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_MEMLOCK_RANGE
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_MEMORY_PROTECTION
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_MESSAGE_PASSING
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_MINSIGSTKSZ
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_MQ_OPEN_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_MQ_PRIO_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_NGROUPS_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_NL_ARGMAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_NL_LANGMAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_NL_MSGMAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_NL_NMAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_NL_SETMAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_NL_TEXTMAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_NPROCESSORS_CONF
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_NPROCESSORS_ONLN
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_NZERO
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_OPEN_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_PAGESIZE
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_PHYS_PAGES
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_PII
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_PII_INTERNET
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_PII_INTERNET_DGRAM
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_PII_INTERNET_STREAM
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_PII_OSI
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_PII_OSI_CLTS
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_PII_OSI_COTS
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_PII_OSI_M
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_PII_SOCKET
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_PII_XTI
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_PRIORITIZED_IO
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_PRIORITY_SCHEDULING
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_REALTIME_SIGNALS
unistdh.h (POSIX.1):Constants forsysconf
Parameters.
_SC_RTSIG_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_SAVED_IDS
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_SCHAR_MAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_SCHAR_MIN
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_SELECT
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_SEMAPHORES
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_SEM_NSEMS_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_SEM_VALUE_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_SHARED_MEMORY_OBJECTS
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_SHRT_MAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_SHRT_MIN
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_SIGQUEUE_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_SIGSTKSZ
unistd.h (GNU):Constants forsysconf
Parameters.
_SC_SSIZE_MAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_STREAM_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_SYNCHRONIZED_IO
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREADS
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_ATTR_STACKADDR
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_ATTR_STACKSIZE
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_DESTRUCTOR_ITERATIONS
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_KEYS_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_PRIORITY_SCHEDULING
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_PRIO_INHERIT
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_PRIO_PROTECT
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_PROCESS_SHARED
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_SAFE_FUNCTIONS
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_STACK_MIN
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_THREAD_THREADS_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_TIMERS
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_TIMER_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_TTY_NAME_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_TZNAME_MAX
unistd.h (POSIX.1):Constants forsysconf
Parameters.
_SC_T_IOV_MAX
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_UCHAR_MAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_UINT_MAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_UIO_MAXIOV
unistd.h (POSIX.1g):Constants forsysconf
Parameters.
_SC_ULONG_MAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_USHRT_MAX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_VERSION
unistd.h (POSIX.1):Constants forsysconf
Parameters.
unistd.h (POSIX.2):Constants forsysconf
Parameters.
_SC_WORD_BIT
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_CRYPT
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_ENH_I18N
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_LEGACY
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_REALTIME
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_REALTIME_THREADS
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_SHM
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_UNIX
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_VERSION
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_XCU_VERSION
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_XPG2
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_XPG3
unistd.h (X/Open):Constants forsysconf
Parameters.
_SC_XOPEN_XPG4
unistd.h (X/Open):Constants forsysconf
Parameters.
_THREAD_SAFE
no header (Obsolete):Feature Test Macros.
_XOPEN_SOURCE
no header (X/Open):Feature Test Macros.
_XOPEN_SOURCE_EXTENDED
no header (X/Open):Feature Test Macros.
__STDC_WANT_IEC_60559_BFP_EXT__
no header (ISO):Feature Test Macros.
__STDC_WANT_IEC_60559_EXT__
no header (ISO):Feature Test Macros.
__STDC_WANT_IEC_60559_FUNCS_EXT__
no header (ISO):Feature Test Macros.
__STDC_WANT_IEC_60559_TYPES_EXT__
no header (ISO):Feature Test Macros.
__STDC_WANT_LIB_EXT2__
no header (ISO):Feature Test Macros.
size_t __fbufsize (FILE *stream)
stdio_ext.h (GNU):Controlling Which Kind of Buffering.
int __flbf (FILE *stream)
stdio_ext.h (GNU):Controlling Which Kind of Buffering.
size_t __fpending (FILE *stream)
stdio_ext.h (GNU):Controlling Which Kind of Buffering.
void __fpurge (FILE *stream)
stdio_ext.h (GNU):Flushing Buffers.
int __freadable (FILE *stream)
stdio_ext.h (GNU):Opening Streams.
int __freading (FILE *stream)
stdio_ext.h (GNU):Opening Streams.
int __fsetlocking (FILE *stream, inttype)
stdio_ext.h (GNU):Streams and Threads.
__ftw64_func_t
ftw.h (GNU):Working with Directory Trees.
__ftw_func_t
ftw.h (GNU):Working with Directory Trees.
int __fwritable (FILE *stream)
stdio_ext.h (GNU):Opening Streams.
int __fwriting (FILE *stream)
stdio_ext.h (GNU):Opening Streams.
void (*__gconv_end_fct) (struct gconv_step *)
gconv.h (GNU):Theiconv
Implementation in the GNU C Library.
int (*__gconv_fct) (struct __gconv_step *, struct __gconv_step_data *, const char **, const char *, size_t *, int)
gconv.h (GNU):Theiconv
Implementation in the GNU C Library.
int (*__gconv_init_fct) (struct __gconv_step *)
gconv.h (GNU):Theiconv
Implementation in the GNU C Library.
struct __gconv_step
gconv.h (GNU):Theiconv
Implementation in the GNU C Library.
struct __gconv_step_data
gconv.h (GNU):Theiconv
Implementation in the GNU C Library.
char __libc_single_threaded
sys/single_threaded.h (GNU):Detecting Single-Threaded Execution.
__nftw64_func_t
ftw.h (GNU):Working with Directory Trees.
__nftw_func_t
ftw.h (GNU):Working with Directory Trees.
unsigned int __rseq_flags
sys/rseq.h (Linux):Restartable Sequences.
ptrdiff_t __rseq_offset
sys/rseq.h (Linux):Restartable Sequences.
unsigned int __rseq_size
sys/rseq.h (Linux):Restartable Sequences.
void __va_copy (va_listdest, va_listsrc)
stdarg.h (GNU):Argument Access Macros.
int _dl_find_object (void *address, struct dl_find_object *result)
dlfcn.h (GNU):Dynamic Linker Introspection.
void _exit (intstatus)
unistd.h (POSIX.1):Termination Internals.
void _flushlbf (void)
stdio_ext.h (GNU):Flushing Buffers.
int _tolower (intc)
ctype.h (SVID):Case Conversion.
int _toupper (intc)
ctype.h (SVID):Case Conversion.
long int a64l (const char *string)
stdlib.h (XPG):Encode Binary Data.
void abort (void)
stdlib.h (ISO):Aborting a Program.
int abs (intnumber)
stdlib.h (ISO):Absolute Value.
int accept (intsocket, struct sockaddr *addr, socklen_t *length_ptr)
sys/socket.h (BSD):Accepting Connections.
int access (const char *filename, inthow)
unistd.h (POSIX.1):Testing Permission to Access a File.
double acos (doublex)
math.h (ISO):Inverse Trigonometric Functions.
float acosf (floatx)
math.h (ISO):Inverse Trigonometric Functions.
_FloatN acosfN (_FloatNx)
math.h (TS 18661-3:2015):Inverse Trigonometric Functions.
_FloatNx acosfNx (_FloatNxx)
math.h (TS 18661-3:2015):Inverse Trigonometric Functions.
double acosh (doublex)
math.h (ISO):Hyperbolic Functions.
float acoshf (floatx)
math.h (ISO):Hyperbolic Functions.
_FloatN acoshfN (_FloatNx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
_FloatNx acoshfNx (_FloatNxx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
long double acoshl (long doublex)
math.h (ISO):Hyperbolic Functions.
long double acosl (long doublex)
math.h (ISO):Inverse Trigonometric Functions.
double acospi (doublex)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
float acospif (floatx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
_FloatN acospifN (_FloatNx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
_FloatNx acospifNx (_FloatNxx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
long double acospil (long doublex)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
int addmntent (FILE *stream, const struct mntent *mnt)
mntent.h (BSD):Themtab file.
int adjtime (const struct timeval *delta, struct timeval *olddelta)
sys/time.h (BSD):Setting and Adjusting the Time.
int adjtimex (struct timex *timex)
sys/timex.h (GNU):Setting and Adjusting the Time.
int aio_cancel (intfildes, struct aiocb *aiocbp)
aio.h (POSIX.1b):Cancellation of AIO Operations.
int aio_cancel64 (intfildes, struct aiocb64 *aiocbp)
aio.h (Unix98):Cancellation of AIO Operations.
int aio_error (const struct aiocb *aiocbp)
aio.h (POSIX.1b):Getting the Status of AIO Operations.
int aio_error64 (const struct aiocb64 *aiocbp)
aio.h (Unix98):Getting the Status of AIO Operations.
int aio_fsync (intop, struct aiocb *aiocbp)
aio.h (POSIX.1b):Getting into a Consistent State.
int aio_fsync64 (intop, struct aiocb64 *aiocbp)
aio.h (Unix98):Getting into a Consistent State.
void aio_init (const struct aioinit *init)
aio.h (GNU):How to optimize the AIO implementation.
int aio_read (struct aiocb *aiocbp)
aio.h (POSIX.1b):Asynchronous Read and Write Operations.
int aio_read64 (struct aiocb64 *aiocbp)
aio.h (Unix98):Asynchronous Read and Write Operations.
ssize_t aio_return (struct aiocb *aiocbp)
aio.h (POSIX.1b):Getting the Status of AIO Operations.
ssize_t aio_return64 (struct aiocb64 *aiocbp)
aio.h (Unix98):Getting the Status of AIO Operations.
int aio_suspend (const struct aiocb *constlist[], intnent, const struct timespec *timeout)
aio.h (POSIX.1b):Getting into a Consistent State.
int aio_suspend64 (const struct aiocb64 *constlist[], intnent, const struct timespec *timeout)
aio.h (Unix98):Getting into a Consistent State.
int aio_write (struct aiocb *aiocbp)
aio.h (POSIX.1b):Asynchronous Read and Write Operations.
int aio_write64 (struct aiocb64 *aiocbp)
aio.h (Unix98):Asynchronous Read and Write Operations.
struct aiocb
aio.h (POSIX.1b):Perform I/O Operations in Parallel.
struct aiocb64
aio.h (POSIX.1b):Perform I/O Operations in Parallel.
struct aioinit
aio.h (GNU):How to optimize the AIO implementation.
unsigned int alarm (unsigned intseconds)
unistd.h (POSIX.1):Setting an Alarm.
void * aligned_alloc (size_talignment, size_tsize)
stdlib.h (???):Allocating Aligned Memory Blocks.
void * alloca (size_tsize)
stdlib.h (GNU):Automatic Storage with Variable Size.
stdlib.h (BSD):Automatic Storage with Variable Size.
int alphasort (const struct dirent **a, const struct dirent **b)
dirent.h (BSD):Scanning the Content of a Directory.
dirent.h (SVID):Scanning the Content of a Directory.
int alphasort64 (const struct dirent64 **a, const struct dirent **b)
dirent.h (GNU):Scanning the Content of a Directory.
uint32_t arc4random (void)
stdlib.h (BSD):High Quality Random Number Functions.
void arc4random_buf (void *buffer, size_tlength)
stdlib.h (BSD):High Quality Random Number Functions.
uint32_t arc4random_uniform (uint32_tupper_bound)
stdlib.h (BSD):High Quality Random Number Functions.
struct argp
argp.h (GNU):Specifying Argp Parsers.
struct argp_child
argp.h (GNU):Combining Multiple Argp Parsers.
error_t argp_err_exit_status
argp.h (GNU):Argp Global Variables.
void argp_error (const struct argp_state *state, const char *fmt, …)
argp.h (GNU):Functions For Use in Argp Parsers.
void argp_failure (const struct argp_state *state, intstatus, interrnum, const char *fmt, …)
argp.h (GNU):Functions For Use in Argp Parsers.
void argp_help (const struct argp *argp, FILE *stream, unsignedflags, char *name)
argp.h (GNU):Theargp_help
Function.
struct argp_option
argp.h (GNU):Specifying Options in an Argp Parser.
error_t argp_parse (const struct argp *argp, intargc, char **argv, unsignedflags, int *arg_index, void *input)
argp.h (GNU):Parsing Program Options with Argp.
const char * argp_program_bug_address
argp.h (GNU):Argp Global Variables.
const char * argp_program_version
argp.h (GNU):Argp Global Variables.
argp_program_version_hook
argp.h (GNU):Argp Global Variables.
struct argp_state
argp.h (GNU):Argp Parsing State.
void argp_state_help (const struct argp_state *state, FILE *stream, unsignedflags)
argp.h (GNU):Functions For Use in Argp Parsers.
void argp_usage (const struct argp_state *state)
argp.h (GNU):Functions For Use in Argp Parsers.
error_t argz_add (char **argz, size_t *argz_len, const char *str)
argz.h (GNU):Argz Functions.
error_t argz_add_sep (char **argz, size_t *argz_len, const char *str, intdelim)
argz.h (GNU):Argz Functions.
error_t argz_append (char **argz, size_t *argz_len, const char *buf, size_tbuf_len)
argz.h (GNU):Argz Functions.
size_t argz_count (const char *argz, size_targz_len)
argz.h (GNU):Argz Functions.
error_t argz_create (char *constargv[], char **argz, size_t *argz_len)
argz.h (GNU):Argz Functions.
error_t argz_create_sep (const char *string, intsep, char **argz, size_t *argz_len)
argz.h (GNU):Argz Functions.
void argz_delete (char **argz, size_t *argz_len, char *entry)
argz.h (GNU):Argz Functions.
void argz_extract (const char *argz, size_targz_len, char **argv)
argz.h (GNU):Argz Functions.
error_t argz_insert (char **argz, size_t *argz_len, char *before, const char *entry)
argz.h (GNU):Argz Functions.
char * argz_next (const char *argz, size_targz_len, const char *entry)
argz.h (GNU):Argz Functions.
error_t argz_replace (char **argz, size_t *argz_len, const char *str, const char *with, unsigned *replace_count)
argz.h (GNU):Argz Functions.
void argz_stringify (char *argz, size_tlen, intsep)
argz.h (GNU):Argz Functions.
char * asctime (const struct tm *brokentime)
time.h (ISO):Formatting Calendar Time.
char * asctime_r (const struct tm *brokentime, char *buffer)
time.h (???):Formatting Calendar Time.
double asin (doublex)
math.h (ISO):Inverse Trigonometric Functions.
float asinf (floatx)
math.h (ISO):Inverse Trigonometric Functions.
_FloatN asinfN (_FloatNx)
math.h (TS 18661-3:2015):Inverse Trigonometric Functions.
_FloatNx asinfNx (_FloatNxx)
math.h (TS 18661-3:2015):Inverse Trigonometric Functions.
double asinh (doublex)
math.h (ISO):Hyperbolic Functions.
float asinhf (floatx)
math.h (ISO):Hyperbolic Functions.
_FloatN asinhfN (_FloatNx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
_FloatNx asinhfNx (_FloatNxx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
long double asinhl (long doublex)
math.h (ISO):Hyperbolic Functions.
long double asinl (long doublex)
math.h (ISO):Inverse Trigonometric Functions.
double asinpi (doublex)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
float asinpif (floatx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
_FloatN asinpifN (_FloatNx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
_FloatNx asinpifNx (_FloatNxx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
long double asinpil (long doublex)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
int asprintf (char **ptr, const char *template, …)
stdio.h (GNU):Dynamically Allocating Formatted Output.
void assert (intexpression)
assert.h (ISO):Explicitly Checking Internal Consistency.
void assert_perror (interrnum)
assert.h (GNU):Explicitly Checking Internal Consistency.
double atan (doublex)
math.h (ISO):Inverse Trigonometric Functions.
double atan2 (doubley, doublex)
math.h (ISO):Inverse Trigonometric Functions.
float atan2f (floaty, floatx)
math.h (ISO):Inverse Trigonometric Functions.
_FloatN atan2fN (_FloatNy, _FloatNx)
math.h (TS 18661-3:2015):Inverse Trigonometric Functions.
_FloatNx atan2fNx (_FloatNxy, _FloatNxx)
math.h (TS 18661-3:2015):Inverse Trigonometric Functions.
long double atan2l (long doubley, long doublex)
math.h (ISO):Inverse Trigonometric Functions.
double atan2pi (doubley, doublex)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
float atan2pif (floaty, floatx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
_FloatN atan2pifN (_FloatNy, _FloatNx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
_FloatNx atan2pifNx (_FloatNxy, _FloatNxx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
long double atan2pil (long doubley, long doublex)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
float atanf (floatx)
math.h (ISO):Inverse Trigonometric Functions.
_FloatN atanfN (_FloatNx)
math.h (TS 18661-3:2015):Inverse Trigonometric Functions.
_FloatNx atanfNx (_FloatNxx)
math.h (TS 18661-3:2015):Inverse Trigonometric Functions.
double atanh (doublex)
math.h (ISO):Hyperbolic Functions.
float atanhf (floatx)
math.h (ISO):Hyperbolic Functions.
_FloatN atanhfN (_FloatNx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
_FloatNx atanhfNx (_FloatNxx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
long double atanhl (long doublex)
math.h (ISO):Hyperbolic Functions.
long double atanl (long doublex)
math.h (ISO):Inverse Trigonometric Functions.
double atanpi (doublex)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
float atanpif (floatx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
_FloatN atanpifN (_FloatNx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
_FloatNx atanpifNx (_FloatNxx)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
long double atanpil (long doublex)
math.h (TS 18661-4:2015):Inverse Trigonometric Functions.
int atexit (void (*function) (void))
stdlib.h (ISO):Cleanups on Exit.
double atof (const char *string)
stdlib.h (ISO):Parsing of Floats.
int atoi (const char *string)
stdlib.h (ISO):Parsing of Integers.
long int atol (const char *string)
stdlib.h (ISO):Parsing of Integers.
long long int atoll (const char *string)
stdlib.h (ISO):Parsing of Integers.
int backtrace (void **buffer, intsize)
execinfo.h (GNU):Backtraces.
char ** backtrace_symbols (void *const *buffer, intsize)
execinfo.h (GNU):Backtraces.
void backtrace_symbols_fd (void *const *buffer, intsize, intfd)
execinfo.h (GNU):Backtraces.
char * basename (char *path)
libgen.h (XPG):Finding Tokens in a String.
char * basename (const char *filename)
string.h (GNU):Finding Tokens in a String.
baud_t
termios.h (GNU):Line Speed.
int bcmp (const void *a1, const void *a2, size_tsize)
string.h (BSD):String/Array Comparison.
void bcopy (const void *from, void *to, size_tsize)
string.h (BSD):Copying Strings and Arrays.
int bind (intsocket, struct sockaddr *addr, socklen_tlength)
sys/socket.h (BSD):Setting the Address of a Socket.
char * bind_textdomain_codeset (const char *domainname, const char *codeset)
libintl.h (POSIX-1.2024):How to specify the output character setgettext
uses.
char * bindtextdomain (const char *domainname, const char *dirname)
libintl.h (POSIX-1.2024):How to determine which catalog to be used.
blkcnt64_t
sys/types.h (Unix98):The meaning of the File Attributes.
blkcnt_t
sys/types.h (Unix98):The meaning of the File Attributes.
int brk (void *addr)
unistd.h (BSD):Resizing the Data Segment.
void * bsearch (const void *key, const void *array, size_tcount, size_tsize, comparison_fn_tcompare)
stdlib.h (ISO):Array Search Function.
wint_t btowc (intc)
wchar.h (ISO):Converting Single Characters.
void bzero (void *block, size_tsize)
string.h (BSD):Copying Strings and Arrays.
double cabs (complex doublez)
complex.h (ISO):Absolute Value.
float cabsf (complex floatz)
complex.h (ISO):Absolute Value.
_FloatN cabsfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Absolute Value.
_FloatNx cabsfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Absolute Value.
long double cabsl (complex long doublez)
complex.h (ISO):Absolute Value.
complex double cacos (complex doublez)
complex.h (ISO):Inverse Trigonometric Functions.
complex float cacosf (complex floatz)
complex.h (ISO):Inverse Trigonometric Functions.
complex _FloatN cacosfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Inverse Trigonometric Functions.
complex _FloatNx cacosfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Inverse Trigonometric Functions.
complex double cacosh (complex doublez)
complex.h (ISO):Hyperbolic Functions.
complex float cacoshf (complex floatz)
complex.h (ISO):Hyperbolic Functions.
complex _FloatN cacoshfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex _FloatNx cacoshfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex long double cacoshl (complex long doublez)
complex.h (ISO):Hyperbolic Functions.
complex long double cacosl (complex long doublez)
complex.h (ISO):Inverse Trigonometric Functions.
void call_once (once_flag *flag, void (*func) (void))
threads.h (C11):Call Once.
void * calloc (size_tcount, size_teltsize)
malloc.h (ISO):Allocating Cleared Space.
stdlib.h (ISO):Allocating Cleared Space.
int canonicalize (double *cx, const double *x)
math.h (ISO):Setting and modifying single bits of FP values.
char * canonicalize_file_name (const char *name)
stdlib.h (GNU):Symbolic Links.
int canonicalizef (float *cx, const float *x)
math.h (ISO):Setting and modifying single bits of FP values.
int canonicalizefN (_FloatN *cx, const _FloatN *x)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
int canonicalizefNx (_FloatNx *cx, const _FloatNx *x)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
int canonicalizel (long double *cx, const long double *x)
math.h (ISO):Setting and modifying single bits of FP values.
double carg (complex doublez)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
float cargf (complex floatz)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
_FloatN cargfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Projections, Conjugates, and Decomposing of Complex Numbers.
_FloatNx cargfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Projections, Conjugates, and Decomposing of Complex Numbers.
long double cargl (complex long doublez)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
complex double casin (complex doublez)
complex.h (ISO):Inverse Trigonometric Functions.
complex float casinf (complex floatz)
complex.h (ISO):Inverse Trigonometric Functions.
complex _FloatN casinfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Inverse Trigonometric Functions.
complex _FloatNx casinfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Inverse Trigonometric Functions.
complex double casinh (complex doublez)
complex.h (ISO):Hyperbolic Functions.
complex float casinhf (complex floatz)
complex.h (ISO):Hyperbolic Functions.
complex _FloatN casinhfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex _FloatNx casinhfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex long double casinhl (complex long doublez)
complex.h (ISO):Hyperbolic Functions.
complex long double casinl (complex long doublez)
complex.h (ISO):Inverse Trigonometric Functions.
complex double catan (complex doublez)
complex.h (ISO):Inverse Trigonometric Functions.
complex float catanf (complex floatz)
complex.h (ISO):Inverse Trigonometric Functions.
complex _FloatN catanfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Inverse Trigonometric Functions.
complex _FloatNx catanfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Inverse Trigonometric Functions.
complex double catanh (complex doublez)
complex.h (ISO):Hyperbolic Functions.
complex float catanhf (complex floatz)
complex.h (ISO):Hyperbolic Functions.
complex _FloatN catanhfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex _FloatNx catanhfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex long double catanhl (complex long doublez)
complex.h (ISO):Hyperbolic Functions.
complex long double catanl (complex long doublez)
complex.h (ISO):Inverse Trigonometric Functions.
nl_catd catopen (const char *cat_name, intflag)
nl_types.h (X/Open):Thecatgets
function family.
double cbrt (doublex)
math.h (BSD):Exponentiation and Logarithms.
float cbrtf (floatx)
math.h (BSD):Exponentiation and Logarithms.
_FloatN cbrtfN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx cbrtfNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double cbrtl (long doublex)
math.h (BSD):Exponentiation and Logarithms.
cc_t
termios.h (POSIX.1):Terminal Mode Data Types.
complex double ccos (complex doublez)
complex.h (ISO):Trigonometric Functions.
complex float ccosf (complex floatz)
complex.h (ISO):Trigonometric Functions.
complex _FloatN ccosfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Trigonometric Functions.
complex _FloatNx ccosfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Trigonometric Functions.
complex double ccosh (complex doublez)
complex.h (ISO):Hyperbolic Functions.
complex float ccoshf (complex floatz)
complex.h (ISO):Hyperbolic Functions.
complex _FloatN ccoshfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex _FloatNx ccoshfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex long double ccoshl (complex long doublez)
complex.h (ISO):Hyperbolic Functions.
complex long double ccosl (complex long doublez)
complex.h (ISO):Trigonometric Functions.
double ceil (doublex)
math.h (ISO):Rounding Functions.
float ceilf (floatx)
math.h (ISO):Rounding Functions.
_FloatN ceilfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
_FloatNx ceilfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long double ceill (long doublex)
math.h (ISO):Rounding Functions.
complex double cexp (complex doublez)
complex.h (ISO):Exponentiation and Logarithms.
complex float cexpf (complex floatz)
complex.h (ISO):Exponentiation and Logarithms.
complex _FloatN cexpfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Exponentiation and Logarithms.
complex _FloatNx cexpfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Exponentiation and Logarithms.
complex long double cexpl (complex long doublez)
complex.h (ISO):Exponentiation and Logarithms.
baud_t cfgetibaud (const struct termios *termios-p)
termios.h (GNU):Line Speed.
speed_t cfgetispeed (const struct termios *termios-p)
termios.h (POSIX.1):Line Speed.
baud_t cfgetobaud (const struct termios *termios-p)
termios.h (GNU):Line Speed.
speed_t cfgetospeed (const struct termios *termios-p)
termios.h (POSIX.1):Line Speed.
void cfmakeraw (struct termios *termios-p)
termios.h (BSD):Noncanonical Input.
int cfsetbaud (struct termios *termios-p, baud_tbaud)
termios.h (GNU):Line Speed.
int cfsetibaud (struct termios *termios-p, baud_tbaud)
termios.h (GNU):Line Speed.
int cfsetispeed (struct termios *termios-p, speed_tspeed)
termios.h (POSIX.1):Line Speed.
int cfsetobaud (struct termios *termios-p, baud_tbaud)
termios.h (GNU):Line Speed.
int cfsetospeed (struct termios *termios-p, speed_tspeed)
termios.h (POSIX.1):Line Speed.
int cfsetspeed (struct termios *termios-p, speed_tspeed)
termios.h (BSD):Line Speed.
int chdir (const char *filename)
unistd.h (POSIX.1):Working Directory.
int chmod (const char *filename, mode_tmode)
sys/stat.h (POSIX.1):Assigning File Permissions.
int chown (const char *filename, uid_towner, gid_tgroup)
unistd.h (POSIX.1):File Owner.
double cimag (complex doublez)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
float cimagf (complex floatz)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
_FloatN cimagfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Projections, Conjugates, and Decomposing of Complex Numbers.
_FloatNx cimagfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Projections, Conjugates, and Decomposing of Complex Numbers.
long double cimagl (complex long doublez)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
int clearenv (void)
stdlib.h (GNU):Environment Access.
void clearerr (FILE *stream)
stdio.h (ISO):Recovering from errors.
void clearerr_unlocked (FILE *stream)
stdio.h (GNU):Recovering from errors.
clock_t clock (void)
time.h (ISO):CPU Time Inquiry.
int clock_getres (clockid_tclock, struct timespec *res)
time.h (POSIX.1):Getting the Time.
int clock_gettime (clockid_tclock, struct timespec *ts)
time.h (POSIX.1):Getting the Time.
int clock_nanosleep (clockid_tclock, intflags, const struct timespec *requested_time, struct timespec *remaining_time)
time.h (POSIX.1-2001):Sleeping.
int clock_settime (clockid_tclock, const struct timespec *ts)
time.h (POSIX):Setting and Adjusting the Time.
clock_t
time.h (ISO):Time Types.
clockid_t
time.h (POSIX.1):Getting the Time.
complex double clog (complex doublez)
complex.h (ISO):Exponentiation and Logarithms.
complex double clog10 (complex doublez)
complex.h (GNU):Exponentiation and Logarithms.
complex float clog10f (complex floatz)
complex.h (GNU):Exponentiation and Logarithms.
complex _FloatN clog10fN (complex _FloatNz)
complex.h (GNU):Exponentiation and Logarithms.
complex _FloatNx clog10fNx (complex _FloatNxz)
complex.h (GNU):Exponentiation and Logarithms.
complex long double clog10l (complex long doublez)
complex.h (GNU):Exponentiation and Logarithms.
complex float clogf (complex floatz)
complex.h (ISO):Exponentiation and Logarithms.
complex _FloatN clogfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Exponentiation and Logarithms.
complex _FloatNx clogfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Exponentiation and Logarithms.
complex long double clogl (complex long doublez)
complex.h (ISO):Exponentiation and Logarithms.
int close (intfiledes)
unistd.h (POSIX.1):Opening and Closing Files.
int close_range (unsigned intlowfd, unsigned intmaxfd, intflags)
unistd.h (Linux):Opening and Closing Files.
int closedir (DIR *dirstream)
dirent.h (POSIX.1):Reading and Closing a Directory Stream.
void closefrom (intlowfd)
unistd.h (GNU):Opening and Closing Files.
void closelog (void)
syslog.h (BSD):closelog.
int cnd_broadcast (cnd_t *cond)
threads.h (C11):Condition Variables.
void cnd_destroy (cnd_t *cond)
threads.h (C11):Condition Variables.
int cnd_init (cnd_t *cond)
threads.h (C11):Condition Variables.
int cnd_signal (cnd_t *cond)
threads.h (C11):Condition Variables.
cnd_t
threads.h (C11):Condition Variables.
int cnd_timedwait (cnd_t *restrictcond, mtx_t *restrictmutex, const struct timespec *restricttime_point)
threads.h (C11):Condition Variables.
int cnd_wait (cnd_t *cond, mtx_t *mutex)
threads.h (C11):Condition Variables.
double compoundn (doublex, long long intpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float compoundnf (floatx, long long intpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatN compoundnfN (_FloatNx, long long intpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx compoundnfNx (_FloatNxx, long long intpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double compoundnl (long doublex, long long intpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
size_t confstr (intparameter, char *buf, size_tlen)
unistd.h (POSIX.2):String-Valued Parameters.
complex double conj (complex doublez)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
complex float conjf (complex floatz)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
complex _FloatN conjfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Projections, Conjugates, and Decomposing of Complex Numbers.
complex _FloatNx conjfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Projections, Conjugates, and Decomposing of Complex Numbers.
complex long double conjl (complex long doublez)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
int connect (intsocket, struct sockaddr *addr, socklen_tlength)
sys/socket.h (BSD):Making a Connection.
cookie_close_function_t
stdio.h (GNU):Custom Stream Hook Functions.
cookie_io_functions_t
stdio.h (GNU):Custom Streams and Cookies.
cookie_read_function_t
stdio.h (GNU):Custom Stream Hook Functions.
cookie_seek_function_t
stdio.h (GNU):Custom Stream Hook Functions.
cookie_write_function_t
stdio.h (GNU):Custom Stream Hook Functions.
ssize_t copy_file_range (intinputfd, off64_t *inputpos, intoutputfd, off64_t *outputpos, ssize_tlength, unsigned intflags)
unistd.h (GNU):Copying data between two files.
double copysign (doublex, doubley)
math.h (ISO):Setting and modifying single bits of FP values.
float copysignf (floatx, floaty)
math.h (ISO):Setting and modifying single bits of FP values.
_FloatN copysignfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
_FloatNx copysignfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
long double copysignl (long doublex, long doubley)
math.h (ISO):Setting and modifying single bits of FP values.
double cos (doublex)
math.h (ISO):Trigonometric Functions.
float cosf (floatx)
math.h (ISO):Trigonometric Functions.
_FloatN cosfN (_FloatNx)
math.h (TS 18661-3:2015):Trigonometric Functions.
_FloatNx cosfNx (_FloatNxx)
math.h (TS 18661-3:2015):Trigonometric Functions.
double cosh (doublex)
math.h (ISO):Hyperbolic Functions.
float coshf (floatx)
math.h (ISO):Hyperbolic Functions.
_FloatN coshfN (_FloatNx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
_FloatNx coshfNx (_FloatNxx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
long double coshl (long doublex)
math.h (ISO):Hyperbolic Functions.
long double cosl (long doublex)
math.h (ISO):Trigonometric Functions.
double cospi (doublex)
math.h (TS 18661-4:2015):Trigonometric Functions.
float cospif (floatx)
math.h (TS 18661-4:2015):Trigonometric Functions.
_FloatN cospifN (_FloatNx)
math.h (TS 18661-4:2015):Trigonometric Functions.
_FloatNx cospifNx (_FloatNxx)
math.h (TS 18661-4:2015):Trigonometric Functions.
long double cospil (long doublex)
math.h (TS 18661-4:2015):Trigonometric Functions.
complex double cpow (complex doublebase, complex doublepower)
complex.h (ISO):Exponentiation and Logarithms.
complex float cpowf (complex floatbase, complex floatpower)
complex.h (ISO):Exponentiation and Logarithms.
complex _FloatN cpowfN (complex _FloatNbase, complex _FloatNpower)
complex.h (TS 18661-3:2015):Exponentiation and Logarithms.
complex _FloatNx cpowfNx (complex _FloatNxbase, complex _FloatNxpower)
complex.h (TS 18661-3:2015):Exponentiation and Logarithms.
complex long double cpowl (complex long doublebase, complex long doublepower)
complex.h (ISO):Exponentiation and Logarithms.
complex double cproj (complex doublez)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
complex float cprojf (complex floatz)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
complex _FloatN cprojfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Projections, Conjugates, and Decomposing of Complex Numbers.
complex _FloatNx cprojfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Projections, Conjugates, and Decomposing of Complex Numbers.
complex long double cprojl (complex long doublez)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
cpu_set_t
sched.h (GNU):Limiting execution to certain CPUs.
double creal (complex doublez)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
float crealf (complex floatz)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
_FloatN crealfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Projections, Conjugates, and Decomposing of Complex Numbers.
_FloatNx crealfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Projections, Conjugates, and Decomposing of Complex Numbers.
long double creall (complex long doublez)
complex.h (ISO):Projections, Conjugates, and Decomposing of Complex Numbers.
int creat (const char *filename, mode_tmode)
fcntl.h (POSIX.1):Opening and Closing Files.
int creat64 (const char *filename, mode_tmode)
fcntl.h (Unix98):Opening and Closing Files.
complex double csin (complex doublez)
complex.h (ISO):Trigonometric Functions.
complex float csinf (complex floatz)
complex.h (ISO):Trigonometric Functions.
complex _FloatN csinfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Trigonometric Functions.
complex _FloatNx csinfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Trigonometric Functions.
complex double csinh (complex doublez)
complex.h (ISO):Hyperbolic Functions.
complex float csinhf (complex floatz)
complex.h (ISO):Hyperbolic Functions.
complex _FloatN csinhfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex _FloatNx csinhfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex long double csinhl (complex long doublez)
complex.h (ISO):Hyperbolic Functions.
complex long double csinl (complex long doublez)
complex.h (ISO):Trigonometric Functions.
complex double csqrt (complex doublez)
complex.h (ISO):Exponentiation and Logarithms.
complex float csqrtf (complex floatz)
complex.h (ISO):Exponentiation and Logarithms.
complex _FloatN csqrtfN (_FloatNz)
complex.h (TS 18661-3:2015):Exponentiation and Logarithms.
complex _FloatNx csqrtfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Exponentiation and Logarithms.
complex long double csqrtl (complex long doublez)
complex.h (ISO):Exponentiation and Logarithms.
complex double ctan (complex doublez)
complex.h (ISO):Trigonometric Functions.
complex float ctanf (complex floatz)
complex.h (ISO):Trigonometric Functions.
complex _FloatN ctanfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Trigonometric Functions.
complex _FloatNx ctanfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Trigonometric Functions.
complex double ctanh (complex doublez)
complex.h (ISO):Hyperbolic Functions.
complex float ctanhf (complex floatz)
complex.h (ISO):Hyperbolic Functions.
complex _FloatN ctanhfN (complex _FloatNz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex _FloatNx ctanhfNx (complex _FloatNxz)
complex.h (TS 18661-3:2015):Hyperbolic Functions.
complex long double ctanhl (complex long doublez)
complex.h (ISO):Hyperbolic Functions.
complex long double ctanl (complex long doublez)
complex.h (ISO):Trigonometric Functions.
char * ctermid (char *string)
stdio.h (POSIX.1):Identifying the Controlling Terminal.
char * ctime (const time_t *time)
time.h (ISO):Formatting Calendar Time.
char * ctime_r (const time_t *time, char *buffer)
time.h (???):Formatting Calendar Time.
char * cuserid (char *string)
stdio.h (POSIX.1):Identifying Who Logged In.
double daddl (long doublex, long doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
int daylight
time.h (POSIX.1):State Variables for Time Zones.
char * dcgettext (const char *domainname, const char *msgid, intcategory)
libintl.h (POSIX-1.2024):What has to be done to translate a message?.
char * dcngettext (const char *domain, const char *msgid1, const char *msgid2, unsigned long intn, intcategory)
libintl.h (POSIX-1.2024):Additional functions for more complicated situations.
double ddivl (long doublex, long doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
dev_t
sys/types.h (POSIX.1):The meaning of the File Attributes.
double dfmal (long doublex, long doubley, long doublez)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
char * dgettext (const char *domainname, const char *msgid)
libintl.h (POSIX-1.2024):What has to be done to translate a message?.
double difftime (time_tend, time_tbegin)
time.h (ISO):Calculating Elapsed Time.
struct dirent
dirent.h (POSIX.1):Format of a Directory Entry.
int dirfd (DIR *dirstream)
dirent.h (GNU):Opening a Directory Stream.
char * dirname (char *path)
libgen.h (XPG):Finding Tokens in a String.
div_t div (intnumerator, intdenominator)
stdlib.h (ISO):Integer Division.
div_t
stdlib.h (ISO):Integer Division.
struct dl_find_object
dlfcn.h (GNU):Dynamic Linker Introspection.
double dmull (long doublex, long doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
char * dngettext (const char *domain, const char *msgid1, const char *msgid2, unsigned long intn)
libintl.h (POSIX-1.2024):Additional functions for more complicated situations.
int dprintf (intfd,template, ...)
stdio.h (POSIX):Formatted Output Functions.
double drand48 (void)
stdlib.h (SVID):SVID Random Number Function.
int drand48_r (struct drand48_data *buffer, double *result)
stdlib.h (GNU):SVID Random Number Function.
double drem (doublenumerator, doubledenominator)
math.h (BSD):Remainder Functions.
float dremf (floatnumerator, floatdenominator)
math.h (BSD):Remainder Functions.
long double dreml (long doublenumerator, long doubledenominator)
math.h (BSD):Remainder Functions.
double dsqrtl (long doublex)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
double dsubl (long doublex, long doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
int dup (intold)
unistd.h (POSIX.1):Duplicating Descriptors.
int dup2 (intold, intnew)
unistd.h (POSIX.1):Duplicating Descriptors.
int dup3 (intold, intnew, intflags)
unistd.h (POSIX.1-2024):Duplicating Descriptors.
char * ecvt (doublevalue, intndigit, int *decpt, int *neg)
stdlib.h (SVID):Old-fashioned System V number-to-string functions.
stdlib.h (Unix98):Old-fashioned System V number-to-string functions.
int ecvt_r (doublevalue, intndigit, int *decpt, int *neg, char *buf, size_tlen)
stdlib.h (GNU):Old-fashioned System V number-to-string functions.
void endfsent (void)
fstab.h (BSD):Thefstab file.
void endgrent (void)
grp.h (SVID):Scanning the List of All Groups.
grp.h (BSD):Scanning the List of All Groups.
void endhostent (void)
netdb.h (BSD):Host Names.
int endmntent (FILE *stream)
mntent.h (BSD):Themtab file.
void endnetent (void)
netdb.h (BSD):Networks Database.
void endnetgrent (void)
netdb.h (BSD):Looking up one Netgroup.
void endprotoent (void)
netdb.h (BSD):Protocols Database.
void endpwent (void)
pwd.h (SVID):Scanning the List of All Users.
pwd.h (BSD):Scanning the List of All Users.
void endservent (void)
netdb.h (BSD):The Services Database.
void endutent (void)
utmp.h (SVID):Manipulating the User Accounting Database.
void endutxent (void)
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
char ** environ
unistd.h (POSIX.1):Environment Access.
error_t envz_add (char **envz, size_t *envz_len, const char *name, const char *value)
envz.h (GNU):Envz Functions.
char * envz_entry (const char *envz, size_tenvz_len, const char *name)
envz.h (GNU):Envz Functions.
char * envz_get (const char *envz, size_tenvz_len, const char *name)
envz.h (GNU):Envz Functions.
error_t envz_merge (char **envz, size_t *envz_len, const char *envz2, size_tenvz2_len, intoverride)
envz.h (GNU):Envz Functions.
void envz_remove (char **envz, size_t *envz_len, const char *name)
envz.h (GNU):Envz Functions.
void envz_strip (char **envz, size_t *envz_len)
envz.h (GNU):Envz Functions.
double erand48 (unsigned short intxsubi[3])
stdlib.h (SVID):SVID Random Number Function.
int erand48_r (unsigned short intxsubi[3], struct drand48_data *buffer, double *result)
stdlib.h (GNU):SVID Random Number Function.
double erf (doublex)
math.h (SVID):Special Functions.
double erfc (doublex)
math.h (SVID):Special Functions.
float erfcf (floatx)
math.h (SVID):Special Functions.
_FloatN erfcfN (_FloatNx)
math.h (TS 18661-3:2015):Special Functions.
_FloatNx erfcfNx (_FloatNxx)
math.h (TS 18661-3:2015):Special Functions.
long double erfcl (long doublex)
math.h (SVID):Special Functions.
float erff (floatx)
math.h (SVID):Special Functions.
_FloatN erffN (_FloatNx)
math.h (TS 18661-3:2015):Special Functions.
_FloatNx erffNx (_FloatNxx)
math.h (TS 18661-3:2015):Special Functions.
long double erfl (long doublex)
math.h (SVID):Special Functions.
void err (intstatus, const char *format, …)
err.h (BSD):Error Messages.
volatile int errno
errno.h (ISO):Checking for Errors.
void error (intstatus, interrnum, const char *format, …)
error.h (GNU):Error Messages.
void error_at_line (intstatus, interrnum, const char *fname, unsigned intlineno, const char *format, …)
error.h (GNU):Error Messages.
unsigned int error_message_count
error.h (GNU):Error Messages.
int error_one_per_line
error.h (GNU):Error Messages.
void (*error_print_progname) (void)
error.h (GNU):Error Messages.
void errx (intstatus, const char *format, …)
err.h (BSD):Error Messages.
int execl (const char *filename, const char *arg0, …)
unistd.h (POSIX.1):Executing a File.
int execle (const char *filename, const char *arg0, …, char *constenv[]
)
unistd.h (POSIX.1):Executing a File.
int execlp (const char *filename, const char *arg0, …)
unistd.h (POSIX.1):Executing a File.
int execv (const char *filename, char *constargv[]
)
unistd.h (POSIX.1):Executing a File.
int execve (const char *filename, char *constargv[]
, char *constenv[]
)
unistd.h (POSIX.1):Executing a File.
int execvp (const char *filename, char *constargv[]
)
unistd.h (POSIX.1):Executing a File.
void exit (intstatus)
stdlib.h (ISO):Normal Termination.
struct exit_status
utmp.h (SVID):Manipulating the User Accounting Database.
double exp (doublex)
math.h (ISO):Exponentiation and Logarithms.
double exp10 (doublex)
math.h (ISO):Exponentiation and Logarithms.
float exp10f (floatx)
math.h (ISO):Exponentiation and Logarithms.
_FloatN exp10fN (_FloatNx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx exp10fNx (_FloatNxx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double exp10l (long doublex)
math.h (ISO):Exponentiation and Logarithms.
double exp10m1 (doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float exp10m1f (floatx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatN exp10m1fN (_FloatNx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx exp10m1fNx (_FloatNxx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double exp10m1l (long doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
double exp2 (doublex)
math.h (ISO):Exponentiation and Logarithms.
float exp2f (floatx)
math.h (ISO):Exponentiation and Logarithms.
_FloatN exp2fN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx exp2fNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double exp2l (long doublex)
math.h (ISO):Exponentiation and Logarithms.
double exp2m1 (doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float exp2m1f (floatx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatN exp2m1fN (_FloatNx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx exp2m1fNx (_FloatNxx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double exp2m1l (long doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float expf (floatx)
math.h (ISO):Exponentiation and Logarithms.
_FloatN expfN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx expfNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double expl (long doublex)
math.h (ISO):Exponentiation and Logarithms.
void explicit_bzero (void *block, size_tlen)
string.h (BSD):Erasing Sensitive Data.
double expm1 (doublex)
math.h (ISO):Exponentiation and Logarithms.
float expm1f (floatx)
math.h (ISO):Exponentiation and Logarithms.
_FloatN expm1fN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx expm1fNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double expm1l (long doublex)
math.h (ISO):Exponentiation and Logarithms.
_FloatM fMaddfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMaddfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMdivfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMdivfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMfmafN (_FloatNx, _FloatNy, _FloatNz)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMfmafNx (_FloatNxx, _FloatNxy, _FloatNxz)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMmulfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMmulfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMsqrtfN (_FloatNx)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMsqrtfNx (_FloatNxx)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMsubfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatM fMsubfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxaddfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxaddfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxdivfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxdivfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxfmafN (_FloatNx, _FloatNy, _FloatNz)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxfmafNx (_FloatNxx, _FloatNxy, _FloatNxz)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxmulfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxmulfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxsqrtfN (_FloatNx)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxsqrtfNx (_FloatNxx)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxsubfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatMx fMxsubfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
double fabs (doublenumber)
math.h (ISO):Absolute Value.
float fabsf (floatnumber)
math.h (ISO):Absolute Value.
_FloatN fabsfN (_FloatNnumber)
math.h (TS 18661-3:2015):Absolute Value.
_FloatNx fabsfNx (_FloatNxnumber)
math.h (TS 18661-3:2015):Absolute Value.
long double fabsl (long doublenumber)
math.h (ISO):Absolute Value.
int faccessat (intfiledes, const char *filename, inthow, intflags)
unistd.h (POSIX.1-2008):Testing Permission to Access a File.
float fadd (doublex, doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
float faddl (long doublex, long doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
int fchdir (intfiledes)
unistd.h (XPG):Working Directory.
int fchmod (intfiledes, mode_tmode)
sys/stat.h (BSD):Assigning File Permissions.
int fchown (intfiledes, uid_towner, gid_tgroup)
unistd.h (BSD):File Owner.
int fclose (FILE *stream)
stdio.h (ISO):Closing Streams.
int fcloseall (void)
stdio.h (GNU):Closing Streams.
int fcntl (intfiledes, intcommand, …)
fcntl.h (POSIX.1):Control Operations on Files.
char * fcvt (doublevalue, intndigit, int *decpt, int *neg)
stdlib.h (SVID):Old-fashioned System V number-to-string functions.
stdlib.h (Unix98):Old-fashioned System V number-to-string functions.
int fcvt_r (doublevalue, intndigit, int *decpt, int *neg, char *buf, size_tlen)
stdlib.h (SVID):Old-fashioned System V number-to-string functions.
stdlib.h (Unix98):Old-fashioned System V number-to-string functions.
fd_set
sys/types.h (BSD):Waiting for Input or Output.
int fdatasync (intfildes)
unistd.h (POSIX):Synchronizing I/O operations.
double fdim (doublex, doubley)
math.h (ISO):Miscellaneous FP arithmetic functions.
float fdimf (floatx, floaty)
math.h (ISO):Miscellaneous FP arithmetic functions.
_FloatN fdimfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatNx fdimfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
long double fdiml (long doublex, long doubley)
math.h (ISO):Miscellaneous FP arithmetic functions.
float fdiv (doublex, doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
float fdivl (long doublex, long doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
FILE * fdopen (intfiledes, const char *opentype)
stdio.h (POSIX.1):Descriptors and Streams.
DIR * fdopendir (intfd)
dirent.h (GNU):Opening a Directory Stream.
int feclearexcept (intexcepts)
fenv.h (ISO):Examining the FPU status word.
int fedisableexcept (intexcepts)
fenv.h (GNU):Floating-Point Control Functions.
int feenableexcept (intexcepts)
fenv.h (GNU):Floating-Point Control Functions.
int fegetenv (fenv_t *envp)
fenv.h (ISO):Floating-Point Control Functions.
int fegetexcept (void)
fenv.h (GNU):Floating-Point Control Functions.
int fegetexceptflag (fexcept_t *flagp, intexcepts)
fenv.h (ISO):Examining the FPU status word.
int fegetmode (femode_t *modep)
fenv.h (ISO):Floating-Point Control Functions.
int fegetround (void)
fenv.h (ISO):Rounding Modes.
int feholdexcept (fenv_t *envp)
fenv.h (ISO):Floating-Point Control Functions.
int feof (FILE *stream)
stdio.h (ISO):End-Of-File and Errors.
int feof_unlocked (FILE *stream)
stdio.h (GNU):End-Of-File and Errors.
int feraiseexcept (intexcepts)
fenv.h (ISO):Examining the FPU status word.
int ferror (FILE *stream)
stdio.h (ISO):End-Of-File and Errors.
int ferror_unlocked (FILE *stream)
stdio.h (GNU):End-Of-File and Errors.
int fesetenv (const fenv_t *envp)
fenv.h (ISO):Floating-Point Control Functions.
int fesetexcept (intexcepts)
fenv.h (ISO):Examining the FPU status word.
int fesetexceptflag (const fexcept_t *flagp, intexcepts)
fenv.h (ISO):Examining the FPU status word.
int fesetmode (const femode_t *modep)
fenv.h (ISO):Floating-Point Control Functions.
int fesetround (intround)
fenv.h (ISO):Rounding Modes.
int fetestexcept (intexcepts)
fenv.h (ISO):Examining the FPU status word.
int fetestexceptflag (const fexcept_t *flagp, intexcepts)
fenv.h (ISO):Examining the FPU status word.
int feupdateenv (const fenv_t *envp)
fenv.h (ISO):Floating-Point Control Functions.
int fexecve (intfd, char *constargv[]
, char *constenv[]
)
unistd.h (POSIX.1):Executing a File.
int fflush (FILE *stream)
stdio.h (ISO):Flushing Buffers.
int fflush_unlocked (FILE *stream)
stdio.h (POSIX):Flushing Buffers.
float ffma (doublex, doubley, doublez)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
float ffmal (long doublex, long doubley, long doublez)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
int fgetc (FILE *stream)
stdio.h (ISO):Character Input.
int fgetc_unlocked (FILE *stream)
stdio.h (POSIX):Character Input.
struct group * fgetgrent (FILE *stream)
grp.h (SVID):Scanning the List of All Groups.
int fgetgrent_r (FILE *stream, struct group *result_buf, char *buffer, size_tbuflen, struct group **result)
grp.h (GNU):Scanning the List of All Groups.
int fgetpos (FILE *stream, fpos_t *position)
stdio.h (ISO):Portable File-Position Functions.
int fgetpos64 (FILE *stream, fpos64_t *position)
stdio.h (Unix98):Portable File-Position Functions.
struct passwd * fgetpwent (FILE *stream)
pwd.h (SVID):Scanning the List of All Users.
int fgetpwent_r (FILE *stream, struct passwd *result_buf, char *buffer, size_tbuflen, struct passwd **result)
pwd.h (GNU):Scanning the List of All Users.
char * fgets (char *s, intcount, FILE *stream)
stdio.h (ISO):Line-Oriented Input.
char * fgets_unlocked (char *s, intcount, FILE *stream)
stdio.h (GNU):Line-Oriented Input.
wint_t fgetwc (FILE *stream)
wchar.h (ISO):Character Input.
wint_t fgetwc_unlocked (FILE *stream)
wchar.h (GNU):Character Input.
wchar_t * fgetws (wchar_t *ws, intcount, FILE *stream)
wchar.h (ISO):Line-Oriented Input.
wchar_t * fgetws_unlocked (wchar_t *ws, intcount, FILE *stream)
wchar.h (GNU):Line-Oriented Input.
int fileno (FILE *stream)
stdio.h (POSIX.1):Descriptors and Streams.
int fileno_unlocked (FILE *stream)
stdio.h (GNU):Descriptors and Streams.
int finite (doublex)
math.h (BSD):Floating-Point Number Classification Functions.
int finitef (floatx)
math.h (BSD):Floating-Point Number Classification Functions.
int finitel (long doublex)
math.h (BSD):Floating-Point Number Classification Functions.
struct flock
fcntl.h (POSIX.1):File Locks.
void flockfile (FILE *stream)
stdio.h (POSIX):Streams and Threads.
double floor (doublex)
math.h (ISO):Rounding Functions.
float floorf (floatx)
math.h (ISO):Rounding Functions.
_FloatN floorfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
_FloatNx floorfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long double floorl (long doublex)
math.h (ISO):Rounding Functions.
double fma (doublex, doubley, doublez)
math.h (ISO):Miscellaneous FP arithmetic functions.
float fmaf (floatx, floaty, floatz)
math.h (ISO):Miscellaneous FP arithmetic functions.
_FloatN fmafN (_FloatNx, _FloatNy, _FloatNz)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatNx fmafNx (_FloatNxx, _FloatNxy, _FloatNxz)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
long double fmal (long doublex, long doubley, long doublez)
math.h (ISO):Miscellaneous FP arithmetic functions.
double fmax (doublex, doubley)
math.h (ISO):Miscellaneous FP arithmetic functions.
float fmaxf (floatx, floaty)
math.h (ISO):Miscellaneous FP arithmetic functions.
_FloatN fmaxfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatNx fmaxfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
double fmaximum (doublex, doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
double fmaximum_mag (doublex, doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
double fmaximum_mag_num (doublex, doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
float fmaximum_mag_numf (floatx, floaty)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatN fmaximum_mag_numfN (_FloatNx, _FloatNy)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatNx fmaximum_mag_numfNx (_FloatNxx, _FloatNxy)
math.h (C23):Miscellaneous FP arithmetic functions.
long double fmaximum_mag_numl (long doublex, long doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
float fmaximum_magf (floatx, floaty)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatN fmaximum_magfN (_FloatNx, _FloatNy)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatNx fmaximum_magfNx (_FloatNxx, _FloatNxy)
math.h (C23):Miscellaneous FP arithmetic functions.
long double fmaximum_magl (long doublex, long doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
double fmaximum_num (doublex, doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
float fmaximum_numf (floatx, floaty)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatN fmaximum_numfN (_FloatNx, _FloatNy)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatNx fmaximum_numfNx (_FloatNxx, _FloatNxy)
math.h (C23):Miscellaneous FP arithmetic functions.
long double fmaximum_numl (long doublex, long doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
float fmaximumf (floatx, floaty)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatN fmaximumfN (_FloatNx, _FloatNy)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatNx fmaximumfNx (_FloatNxx, _FloatNxy)
math.h (C23):Miscellaneous FP arithmetic functions.
long double fmaximuml (long doublex, long doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
long double fmaxl (long doublex, long doubley)
math.h (ISO):Miscellaneous FP arithmetic functions.
double fmaxmag (doublex, doubley)
math.h (ISO):Miscellaneous FP arithmetic functions.
float fmaxmagf (floatx, floaty)
math.h (ISO):Miscellaneous FP arithmetic functions.
_FloatN fmaxmagfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatNx fmaxmagfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
long double fmaxmagl (long doublex, long doubley)
math.h (ISO):Miscellaneous FP arithmetic functions.
FILE * fmemopen (void *buf, size_tsize, const char *opentype)
stdio.h (GNU):String Streams.
double fmin (doublex, doubley)
math.h (ISO):Miscellaneous FP arithmetic functions.
float fminf (floatx, floaty)
math.h (ISO):Miscellaneous FP arithmetic functions.
_FloatN fminfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatNx fminfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
double fminimum (doublex, doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
double fminimum_mag (doublex, doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
double fminimum_mag_num (doublex, doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
float fminimum_mag_numf (floatx, floaty)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatN fminimum_mag_numfN (_FloatNx, _FloatNy)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatNx fminimum_mag_numfNx (_FloatNxx, _FloatNxy)
math.h (C23):Miscellaneous FP arithmetic functions.
long double fminimum_mag_numl (long doublex, long doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
float fminimum_magf (floatx, floaty)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatN fminimum_magfN (_FloatNx, _FloatNy)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatNx fminimum_magfNx (_FloatNxx, _FloatNxy)
math.h (C23):Miscellaneous FP arithmetic functions.
long double fminimum_magl (long doublex, long doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
double fminimum_num (doublex, doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
float fminimum_numf (floatx, floaty)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatN fminimum_numfN (_FloatNx, _FloatNy)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatNx fminimum_numfNx (_FloatNxx, _FloatNxy)
math.h (C23):Miscellaneous FP arithmetic functions.
long double fminimum_numl (long doublex, long doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
float fminimumf (floatx, floaty)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatN fminimumfN (_FloatNx, _FloatNy)
math.h (C23):Miscellaneous FP arithmetic functions.
_FloatNx fminimumfNx (_FloatNxx, _FloatNxy)
math.h (C23):Miscellaneous FP arithmetic functions.
long double fminimuml (long doublex, long doubley)
math.h (C23):Miscellaneous FP arithmetic functions.
long double fminl (long doublex, long doubley)
math.h (ISO):Miscellaneous FP arithmetic functions.
double fminmag (doublex, doubley)
math.h (ISO):Miscellaneous FP arithmetic functions.
float fminmagf (floatx, floaty)
math.h (ISO):Miscellaneous FP arithmetic functions.
_FloatN fminmagfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
_FloatNx fminmagfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Miscellaneous FP arithmetic functions.
long double fminmagl (long doublex, long doubley)
math.h (ISO):Miscellaneous FP arithmetic functions.
double fmod (doublenumerator, doubledenominator)
math.h (ISO):Remainder Functions.
float fmodf (floatnumerator, floatdenominator)
math.h (ISO):Remainder Functions.
_FloatN fmodfN (_FloatNnumerator, _FloatNdenominator)
math.h (TS 18661-3:2015):Remainder Functions.
_FloatNx fmodfNx (_FloatNxnumerator, _FloatNxdenominator)
math.h (TS 18661-3:2015):Remainder Functions.
long double fmodl (long doublenumerator, long doubledenominator)
math.h (ISO):Remainder Functions.
int fmtmsg (long intclassification, const char *label, intseverity, const char *text, const char *action, const char *tag)
fmtmsg.h (XPG):Printing Formatted Messages.
float fmul (doublex, doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
float fmull (long doublex, long doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
int fnmatch (const char *pattern, const char *string, intflags)
fnmatch.h (POSIX.2):Wildcard Matching.
FILE * fopen (const char *filename, const char *opentype)
stdio.h (ISO):Opening Streams.
FILE * fopen64 (const char *filename, const char *opentype)
stdio.h (Unix98):Opening Streams.
FILE * fopencookie (void *cookie, const char *opentype, cookie_io_functions_tio-functions)
stdio.h (GNU):Custom Streams and Cookies.
pid_t fork (void)
unistd.h (POSIX.1):Creating a Process.
int forkpty (int *amaster, char *name, const struct termios *termp, const struct winsize *winp)
pty.h (BSD):Opening a Pseudo-Terminal Pair.
long int fpathconf (intfiledes, intparameter)
unistd.h (POSIX.1):Usingpathconf
.
int fpclassify (float-typex)
math.h (ISO):Floating-Point Number Classification Functions.
fpos64_t
stdio.h (Unix98):Portable File-Position Functions.
fpos_t
stdio.h (ISO):Portable File-Position Functions.
int fprintf (FILE *stream, const char *template, …)
stdio.h (ISO):Formatted Output Functions.
int fputc (intc, FILE *stream)
stdio.h (ISO):Simple Output by Characters or Lines.
int fputc_unlocked (intc, FILE *stream)
stdio.h (POSIX):Simple Output by Characters or Lines.
int fputs (const char *s, FILE *stream)
stdio.h (ISO):Simple Output by Characters or Lines.
int fputs_unlocked (const char *s, FILE *stream)
stdio.h (GNU):Simple Output by Characters or Lines.
wint_t fputwc (wchar_twc, FILE *stream)
wchar.h (ISO):Simple Output by Characters or Lines.
wint_t fputwc_unlocked (wchar_twc, FILE *stream)
wchar.h (POSIX):Simple Output by Characters or Lines.
int fputws (const wchar_t *ws, FILE *stream)
wchar.h (ISO):Simple Output by Characters or Lines.
int fputws_unlocked (const wchar_t *ws, FILE *stream)
wchar.h (GNU):Simple Output by Characters or Lines.
size_t fread (void *data, size_tsize, size_tcount, FILE *stream)
stdio.h (ISO):Block Input/Output.
size_t fread_unlocked (void *data, size_tsize, size_tcount, FILE *stream)
stdio.h (GNU):Block Input/Output.
void free (void *ptr)
malloc.h (ISO):Freeing Memory Allocated withmalloc
.
stdlib.h (ISO):Freeing Memory Allocated withmalloc
.
FILE * freopen (const char *filename, const char *opentype, FILE *stream)
stdio.h (ISO):Opening Streams.
FILE * freopen64 (const char *filename, const char *opentype, FILE *stream)
stdio.h (Unix98):Opening Streams.
double frexp (doublevalue, int *exponent)
math.h (ISO):Normalization Functions.
float frexpf (floatvalue, int *exponent)
math.h (ISO):Normalization Functions.
_FloatN frexpfN (_FloatNvalue, int *exponent)
math.h (TS 18661-3:2015):Normalization Functions.
_FloatNx frexpfNx (_FloatNxvalue, int *exponent)
math.h (TS 18661-3:2015):Normalization Functions.
long double frexpl (long doublevalue, int *exponent)
math.h (ISO):Normalization Functions.
intmax_t fromfp (doublex, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
intmax_t fromfpf (floatx, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
intmax_t fromfpfN (_FloatNx, intround, unsigned intwidth)
math.h (TS 18661-3:2015):Rounding Functions.
intmax_t fromfpfNx (_FloatNxx, intround, unsigned intwidth)
math.h (TS 18661-3:2015):Rounding Functions.
intmax_t fromfpl (long doublex, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
intmax_t fromfpx (doublex, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
intmax_t fromfpxf (floatx, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
intmax_t fromfpxfN (_FloatNx, intround, unsigned intwidth)
math.h (TS 18661-3:2015):Rounding Functions.
intmax_t fromfpxfNx (_FloatNxx, intround, unsigned intwidth)
math.h (TS 18661-3:2015):Rounding Functions.
intmax_t fromfpxl (long doublex, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
int fscanf (FILE *stream, const char *template, …)
stdio.h (ISO):Formatted Input Functions.
int fseek (FILE *stream, long intoffset, intwhence)
stdio.h (ISO):File Positioning.
int fseeko (FILE *stream, off_toffset, intwhence)
stdio.h (Unix98):File Positioning.
int fseeko64 (FILE *stream, off64_toffset, intwhence)
stdio.h (Unix98):File Positioning.
int fsetpos (FILE *stream, const fpos_t *position)
stdio.h (ISO):Portable File-Position Functions.
int fsetpos64 (FILE *stream, const fpos64_t *position)
stdio.h (Unix98):Portable File-Position Functions.
float fsqrt (doublex)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
float fsqrtl (long doublex)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
struct fstab
fstab.h (BSD):Thefstab file.
int fstat (intfiledes, struct stat *buf)
sys/stat.h (POSIX.1):Reading the Attributes of a File.
int fstat64 (intfiledes, struct stat64 *buf)
sys/stat.h (Unix98):Reading the Attributes of a File.
int fstatat (intfiledes, const char *filename, struct stat *buf, intflags)
sys/stat.h (POSIX.1):Reading the Attributes of a File.
int fstatat64 (intfiledes, const char *filename, struct stat64 *buf, intflags)
sys/stat.h (GNU):Reading the Attributes of a File.
float fsub (doublex, doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
float fsubl (long doublex, long doubley)
math.h (TS 18661-1:2014):Miscellaneous FP arithmetic functions.
int fsync (intfildes)
unistd.h (POSIX):Synchronizing I/O operations.
long int ftell (FILE *stream)
stdio.h (ISO):File Positioning.
off_t ftello (FILE *stream)
stdio.h (Unix98):File Positioning.
off64_t ftello64 (FILE *stream)
stdio.h (Unix98):File Positioning.
int ftruncate (intfd, off_tlength)
unistd.h (POSIX):File Size.
int ftruncate64 (intid, off64_tlength)
unistd.h (Unix98):File Size.
int ftrylockfile (FILE *stream)
stdio.h (POSIX):Streams and Threads.
int ftw (const char *filename, __ftw_func_tfunc, intdescriptors)
ftw.h (SVID):Working with Directory Trees.
int ftw64 (const char *filename, __ftw64_func_tfunc, intdescriptors)
ftw.h (Unix98):Working with Directory Trees.
void funlockfile (FILE *stream)
stdio.h (POSIX):Streams and Threads.
int futimens (intfiledes, const struct timespectsp[2]
)
sys/stat.h (POSIX.1-2008):File Times.
int futimes (intfd, const struct timevaltvp[2]
)
sys/time.h (BSD):File Times.
int fwide (FILE *stream, intmode)
wchar.h (ISO):Streams in Internationalized Applications.
int fwprintf (FILE *stream, const wchar_t *template, …)
wchar.h (ISO):Formatted Output Functions.
size_t fwrite (const void *data, size_tsize, size_tcount, FILE *stream)
stdio.h (ISO):Block Input/Output.
size_t fwrite_unlocked (const void *data, size_tsize, size_tcount, FILE *stream)
stdio.h (GNU):Block Input/Output.
int fwscanf (FILE *stream, const wchar_t *template, …)
wchar.h (ISO):Formatted Input Functions.
double gamma (doublex)
math.h (SVID):Special Functions.
float gammaf (floatx)
math.h (SVID):Special Functions.
long double gammal (long doublex)
math.h (SVID):Special Functions.
char * gcvt (doublevalue, intndigit, char *buf)
stdlib.h (SVID):Old-fashioned System V number-to-string functions.
stdlib.h (Unix98):Old-fashioned System V number-to-string functions.
long int get_avphys_pages (void)
sys/sysinfo.h (GNU):How to get information about the memory subsystem?.
char * get_current_dir_name (void)
unistd.h (GNU):Working Directory.
int get_nprocs (void)
sys/sysinfo.h (GNU):Learn about the processors available.
int get_nprocs_conf (void)
sys/sysinfo.h (GNU):Learn about the processors available.
long int get_phys_pages (void)
sys/sysinfo.h (GNU):How to get information about the memory subsystem?.
unsigned long int getauxval (unsigned long inttype)
sys/auxv.h (???):Auxiliary Vector.
int getc (FILE *stream)
stdio.h (ISO):Character Input.
int getc_unlocked (FILE *stream)
stdio.h (POSIX):Character Input.
int getchar (void)
stdio.h (ISO):Character Input.
int getchar_unlocked (void)
stdio.h (POSIX):Character Input.
int getcontext (ucontext_t *ucp)
ucontext.h (SVID):Complete Context Control.
int getcpu (unsigned int *cpu, unsigned int *node)
<sched.h> (Linux):Limiting execution to certain CPUs.
char * getcwd (char *buffer, size_tsize)
unistd.h (POSIX.1):Working Directory.
struct tm * getdate (const char *string)
time.h (Unix98):A More User-friendly Way to Parse Times and Dates.
getdate_err
time.h (Unix98):A More User-friendly Way to Parse Times and Dates.
int getdate_r (const char *string, struct tm *tp)
time.h (GNU):A More User-friendly Way to Parse Times and Dates.
ssize_t getdelim (char **restrictlineptr, size_t *restrictn, intdelimiter, FILE *restrictstream)
stdio.h (POSIX.1-2008):Line-Oriented Input.
ssize_t getdents64 (intfd, void *buffer, size_tlength)
dirent.h (Linux):Low-level Directory Access.
int getdomainnname (char *name, size_tlength)
unistd.h (???):Host Identification.
gid_t getegid (void)
unistd.h (POSIX.1):Reading the Persona of a Process.
int getentropy (void *buffer, size_tlength)
sys/random.h (GNU):Generating Unpredictable Bytes.
char * getenv (const char *name)
stdlib.h (ISO):Environment Access.
uid_t geteuid (void)
unistd.h (POSIX.1):Reading the Persona of a Process.
struct fstab * getfsent (void)
fstab.h (BSD):Thefstab file.
struct fstab * getfsfile (const char *name)
fstab.h (BSD):Thefstab file.
struct fstab * getfsspec (const char *name)
fstab.h (BSD):Thefstab file.
gid_t getgid (void)
unistd.h (POSIX.1):Reading the Persona of a Process.
struct group * getgrent (void)
grp.h (SVID):Scanning the List of All Groups.
grp.h (BSD):Scanning the List of All Groups.
int getgrent_r (struct group *result_buf, char *buffer, size_tbuflen, struct group **result)
grp.h (GNU):Scanning the List of All Groups.
struct group * getgrgid (gid_tgid)
grp.h (POSIX.1):Looking Up One Group.
int getgrgid_r (gid_tgid, struct group *result_buf, char *buffer, size_tbuflen, struct group **result)
grp.h (POSIX.1c):Looking Up One Group.
struct group * getgrnam (const char *name)
grp.h (SVID):Looking Up One Group.
grp.h (BSD):Looking Up One Group.
int getgrnam_r (const char *name, struct group *result_buf, char *buffer, size_tbuflen, struct group **result)
grp.h (POSIX.1c):Looking Up One Group.
int getgrouplist (const char *user, gid_tgroup, gid_t *groups, int *ngroups)
grp.h (BSD):Setting the Group IDs.
int getgroups (intcount, gid_t *groups)
unistd.h (POSIX.1):Reading the Persona of a Process.
struct hostent * gethostbyaddr (const void *addr, socklen_tlength, intformat)
netdb.h (BSD):Host Names.
int gethostbyaddr_r (const void *addr, socklen_tlength, intformat, struct hostent *restrictresult_buf, char *restrictbuf, size_tbuflen, struct hostent **restrictresult, int *restricth_errnop)
netdb.h (GNU):Host Names.
struct hostent * gethostbyname (const char *name)
netdb.h (BSD):Host Names.
struct hostent * gethostbyname2 (const char *name, intaf)
netdb.h (IPv6 Basic API):Host Names.
int gethostbyname2_r (const char *name, intaf, struct hostent *restrictresult_buf, char *restrictbuf, size_tbuflen, struct hostent **restrictresult, int *restricth_errnop)
netdb.h (GNU):Host Names.
int gethostbyname_r (const char *restrictname, struct hostent *restrictresult_buf, char *restrictbuf, size_tbuflen, struct hostent **restrictresult, int *restricth_errnop)
netdb.h (GNU):Host Names.
struct hostent * gethostent (void)
netdb.h (BSD):Host Names.
long int gethostid (void)
unistd.h (BSD):Host Identification.
int gethostname (char *name, size_tsize)
unistd.h (BSD):Host Identification.
int getitimer (intwhich, struct itimerval *old)
sys/time.h (BSD):Setting an Alarm.
ssize_t getline (char **restrictlineptr, size_t *restrictn, FILE *restrictstream)
stdio.h (POSIX.1-2008):Line-Oriented Input.
int getloadavg (doubleloadavg[], intnelem)
stdlib.h (BSD):Learn about the processors available.
char * getlogin (void)
unistd.h (POSIX.1):Identifying Who Logged In.
struct mntent * getmntent (FILE *stream)
mntent.h (BSD):Themtab file.
struct mntent * getmntent_r (FILE *stream, struct mntent *result, char *buffer, intbufsize)
mntent.h (BSD):Themtab file.
struct netent * getnetbyaddr (uint32_tnet, inttype)
netdb.h (BSD):Networks Database.
struct netent * getnetbyname (const char *name)
netdb.h (BSD):Networks Database.
struct netent * getnetent (void)
netdb.h (BSD):Networks Database.
int getnetgrent (char **hostp, char **userp, char **domainp)
netdb.h (BSD):Looking up one Netgroup.
int getnetgrent_r (char **hostp, char **userp, char **domainp, char *buffer, size_tbuflen)
netdb.h (GNU):Looking up one Netgroup.
int getopt (intargc, char *const *argv, const char *options)
unistd.h (POSIX.2):Using thegetopt
function.
int getopt_long (intargc, char *const *argv, const char *shortopts, const struct option *longopts, int *indexptr)
getopt.h (GNU):Parsing Long Options withgetopt_long
.
int getopt_long_only (intargc, char *const *argv, const char *shortopts, const struct option *longopts, int *indexptr)
getopt.h (GNU):Parsing Long Options withgetopt_long
.
int getpagesize (void)
unistd.h (BSD):How to get information about the memory subsystem?.
char * getpass (const char *prompt)
unistd.h (BSD):Reading Passphrases.
double getpayload (const double *x)
math.h (ISO):Setting and modifying single bits of FP values.
float getpayloadf (const float *x)
math.h (ISO):Setting and modifying single bits of FP values.
_FloatN getpayloadfN (const _FloatN *x)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
_FloatNx getpayloadfNx (const _FloatNx *x)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
long double getpayloadl (const long double *x)
math.h (ISO):Setting and modifying single bits of FP values.
int getpeername (intsocket, struct sockaddr *addr, socklen_t *length-ptr)
sys/socket.h (BSD):Who is Connected to Me?.
int getpgid (pid_tpid)
unistd.h (POSIX.1):Process Group Functions.
pid_t getpgrp (void)
unistd.h (POSIX.1):Process Group Functions.
pid_t getpid (void)
unistd.h (POSIX.1):Process Identification.
pid_t getppid (void)
unistd.h (POSIX.1):Process Identification.
int getpriority (intclass, intid)
sys/resource.h (BSD):Functions For Traditional Scheduling.
sys/resource.h (POSIX):Functions For Traditional Scheduling.
struct protoent * getprotobyname (const char *name)
netdb.h (BSD):Protocols Database.
struct protoent * getprotobynumber (intprotocol)
netdb.h (BSD):Protocols Database.
struct protoent * getprotoent (void)
netdb.h (BSD):Protocols Database.
int getpt (void)
stdlib.h (GNU):Allocating Pseudo-Terminals.
struct passwd * getpwent (void)
pwd.h (POSIX.1):Scanning the List of All Users.
int getpwent_r (struct passwd *result_buf, char *buffer, size_tbuflen, struct passwd **result)
pwd.h (GNU):Scanning the List of All Users.
struct passwd * getpwnam (const char *name)
pwd.h (POSIX.1):Looking Up One User.
int getpwnam_r (const char *name, struct passwd *result_buf, char *buffer, size_tbuflen, struct passwd **result)
pwd.h (POSIX.1c):Looking Up One User.
struct passwd * getpwuid (uid_tuid)
pwd.h (POSIX.1):Looking Up One User.
int getpwuid_r (uid_tuid, struct passwd *result_buf, char *buffer, size_tbuflen, struct passwd **result)
pwd.h (POSIX.1c):Looking Up One User.
ssize_t getrandom (void *buffer, size_tlength, unsigned intflags)
sys/random.h (GNU):Generating Unpredictable Bytes.
int getrlimit (intresource, struct rlimit *rlp)
sys/resource.h (BSD):Limiting Resource Usage.
int getrlimit64 (intresource, struct rlimit64 *rlp)
sys/resource.h (Unix98):Limiting Resource Usage.
int getrusage (intprocesses, struct rusage *rusage)
sys/resource.h (BSD):Resource Usage.
char * gets (char *s)
stdio.h (ISO):Line-Oriented Input.
struct servent * getservbyname (const char *name, const char *proto)
netdb.h (BSD):The Services Database.
struct servent * getservbyport (intport, const char *proto)
netdb.h (BSD):The Services Database.
struct servent * getservent (void)
netdb.h (BSD):The Services Database.
pid_t getsid (pid_tpid)
unistd.h (SVID):Process Group Functions.
int getsockname (intsocket, struct sockaddr *addr, socklen_t *length-ptr)
sys/socket.h (BSD):Reading the Address of a Socket.
int getsockopt (intsocket, intlevel, intoptname, void *optval, socklen_t *optlen-ptr)
sys/socket.h (BSD):Socket Option Functions.
int getsubopt (char **optionp, char *const *tokens, char **valuep)
stdlib.h (???):Parsing of Suboptions.
char * gettext (const char *msgid)
libintl.h (POSIX-1.2024):What has to be done to translate a message?.
pid_t gettid (void)
unistd.h (Linux):Process Identification.
int gettimeofday (struct timeval *tp, void *tzp)
sys/time.h (BSD):Getting the Time.
uid_t getuid (void)
unistd.h (POSIX.1):Reading the Persona of a Process.
mode_t getumask (void)
sys/stat.h (GNU):Assigning File Permissions.
struct utmp * getutent (void)
utmp.h (SVID):Manipulating the User Accounting Database.
int getutent_r (struct utmp *buffer, struct utmp **result)
utmp.h (GNU):Manipulating the User Accounting Database.
struct utmp * getutid (const struct utmp *id)
utmp.h (SVID):Manipulating the User Accounting Database.
int getutid_r (const struct utmp *id, struct utmp *buffer, struct utmp **result)
utmp.h (GNU):Manipulating the User Accounting Database.
struct utmp * getutline (const struct utmp *line)
utmp.h (SVID):Manipulating the User Accounting Database.
int getutline_r (const struct utmp *line, struct utmp *buffer, struct utmp **result)
utmp.h (GNU):Manipulating the User Accounting Database.
int getutmp (const struct utmpx *utmpx, struct utmp *utmp)
utmp.h (GNU):XPG User Accounting Database Functions.
utmpx.h (GNU):XPG User Accounting Database Functions.
int getutmpx (const struct utmp *utmp, struct utmpx *utmpx)
utmp.h (GNU):XPG User Accounting Database Functions.
utmpx.h (GNU):XPG User Accounting Database Functions.
struct utmpx * getutxent (void)
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
struct utmpx * getutxid (const struct utmpx *id)
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
struct utmpx * getutxline (const struct utmpx *line)
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
int getw (FILE *stream)
stdio.h (SVID):Character Input.
wint_t getwc (FILE *stream)
wchar.h (ISO):Character Input.
wint_t getwc_unlocked (FILE *stream)
wchar.h (GNU):Character Input.
wint_t getwchar (void)
wchar.h (ISO):Character Input.
wint_t getwchar_unlocked (void)
wchar.h (GNU):Character Input.
char * getwd (char *buffer)
unistd.h (BSD):Working Directory.
gid_t
sys/types.h (POSIX.1):Reading the Persona of a Process.
int glob (const char *pattern, intflags, int (*errfunc) (const char *filename, interror-code), glob_t *vector-ptr)
glob.h (POSIX.2):Callingglob
.
int glob64 (const char *pattern, intflags, int (*errfunc) (const char *filename, interror-code), glob64_t *vector-ptr)
glob.h (GNU):Callingglob
.
glob64_t
glob.h (GNU):Callingglob
.
glob_t
glob.h (POSIX.2):Callingglob
.
void globfree (glob_t *pglob)
glob.h (POSIX.2):More Flags for Globbing.
void globfree64 (glob64_t *pglob)
glob.h (GNU):More Flags for Globbing.
struct tm * gmtime (const time_t *time)
time.h (ISO):Broken-down Time.
struct tm * gmtime_r (const time_t *time, struct tm *resultp)
time.h (POSIX.1c):Broken-down Time.
int grantpt (intfiledes)
stdlib.h (SVID):Allocating Pseudo-Terminals.
stdlib.h (XPG4.2):Allocating Pseudo-Terminals.
struct group
grp.h (POSIX.1):The Data Structure for a Group.
int gsignal (intsignum)
signal.h (SVID):Signaling Yourself.
int gtty (intfiledes, struct sgttyb *attributes)
sgtty.h (BSD):BSD Terminal Modes.
char * hasmntopt (const struct mntent *mnt, const char *opt)
mntent.h (BSD):Themtab file.
int hcreate (size_tnel)
search.h (SVID):Thehsearch
function..
int hcreate_r (size_tnel, struct hsearch_data *htab)
search.h (GNU):Thehsearch
function..
void hdestroy (void)
search.h (SVID):Thehsearch
function..
void hdestroy_r (struct hsearch_data *htab)
search.h (GNU):Thehsearch
function..
struct hostent
netdb.h (BSD):Host Names.
ENTRY * hsearch (ENTRYitem, ACTIONaction)
search.h (SVID):Thehsearch
function..
int hsearch_r (ENTRYitem, ACTIONaction, ENTRY **retval, struct hsearch_data *htab)
search.h (GNU):Thehsearch
function..
uint32_t htonl (uint32_thostlong)
netinet/in.h (BSD):Byte Order Conversion.
uint16_t htons (uint16_thostshort)
netinet/in.h (BSD):Byte Order Conversion.
double hypot (doublex, doubley)
math.h (ISO):Exponentiation and Logarithms.
float hypotf (floatx, floaty)
math.h (ISO):Exponentiation and Logarithms.
_FloatN hypotfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx hypotfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double hypotl (long doublex, long doubley)
math.h (ISO):Exponentiation and Logarithms.
size_t iconv (iconv_tcd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft)
iconv.h (XPG2):Generic Character Set Conversion Interface.
int iconv_close (iconv_tcd)
iconv.h (XPG2):Generic Character Set Conversion Interface.
iconv_t iconv_open (const char *tocode, const char *fromcode)
iconv.h (XPG2):Generic Character Set Conversion Interface.
iconv_t
iconv.h (XPG2):Generic Character Set Conversion Interface.
void if_freenameindex (struct if_nameindex *ptr)
net/if.h (IPv6 basic API):Interface Naming.
char * if_indextoname (unsigned intifindex, char *ifname)
net/if.h (IPv6 basic API):Interface Naming.
struct if_nameindex
net/if.h (IPv6 basic API):Interface Naming.
struct if_nameindex * if_nameindex (void)
net/if.h (IPv6 basic API):Interface Naming.
unsigned int if_nametoindex (const char *ifname)
net/if.h (IPv6 basic API):Interface Naming.
int ilogb (doublex)
math.h (ISO):Exponentiation and Logarithms.
int ilogbf (floatx)
math.h (ISO):Exponentiation and Logarithms.
int ilogbfN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
int ilogbfNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
int ilogbl (long doublex)
math.h (ISO):Exponentiation and Logarithms.
intmax_t imaxabs (intmax_tnumber)
inttypes.h (ISO):Absolute Value.
imaxdiv_t imaxdiv (intmax_tnumerator, intmax_tdenominator)
inttypes.h (ISO):Integer Division.
imaxdiv_t
inttypes.h (ISO):Integer Division.
struct in6_addr
netinet/in.h (IPv6 basic API):Host Address Data Type.
struct in6_addr in6addr_any
netinet/in.h (IPv6 basic API):Host Address Data Type.
struct in6_addr in6addr_loopback
netinet/in.h (IPv6 basic API):Host Address Data Type.
struct in_addr
netinet/in.h (BSD):Host Address Data Type.
char * index (const char *string, intc)
string.h (BSD):Search Functions.
uint32_t inet_addr (const char *name)
arpa/inet.h (BSD):Host Address Functions.
int inet_aton (const char *name, struct in_addr *addr)
arpa/inet.h (BSD):Host Address Functions.
uint32_t inet_lnaof (struct in_addraddr)
arpa/inet.h (BSD):Host Address Functions.
struct in_addr inet_makeaddr (uint32_tnet, uint32_tlocal)
arpa/inet.h (BSD):Host Address Functions.
uint32_t inet_netof (struct in_addraddr)
arpa/inet.h (BSD):Host Address Functions.
uint32_t inet_network (const char *name)
arpa/inet.h (BSD):Host Address Functions.
char * inet_ntoa (struct in_addraddr)
arpa/inet.h (BSD):Host Address Functions.
const char * inet_ntop (intaf, const void *cp, char *buf, socklen_tlen)
arpa/inet.h (IPv6 basic API):Host Address Functions.
int inet_pton (intaf, const char *cp, void *buf)
arpa/inet.h (IPv6 basic API):Host Address Functions.
int initgroups (const char *user, gid_tgroup)
grp.h (BSD):Setting the Group IDs.
char * initstate (unsigned intseed, char *state, size_tsize)
stdlib.h (BSD):BSD Random Number Functions.
int initstate_r (unsigned intseed, char *restrictstatebuf, size_tstatelen, struct random_data *restrictbuf)
stdlib.h (GNU):BSD Random Number Functions.
int innetgr (const char *netgroup, const char *host, const char *user, const char *domain)
netdb.h (BSD):Testing for Netgroup Membership.
ino64_t
sys/types.h (Unix98):The meaning of the File Attributes.
ino_t
sys/types.h (POSIX.1):The meaning of the File Attributes.
int ioctl (intfiledes, intcommand, …)
sys/ioctl.h (BSD):Generic I/O Control operations.
struct iovec
sys/uio.h (BSD):Fast Scatter-Gather I/O.
int isalnum (intc)
ctype.h (ISO):Classification of Characters.
int isalpha (intc)
ctype.h (ISO):Classification of Characters.
int isascii (intc)
ctype.h (SVID):Classification of Characters.
ctype.h (BSD):Classification of Characters.
int isatty (intfiledes)
unistd.h (POSIX.1):Identifying Terminals.
int isblank (intc)
ctype.h (ISO):Classification of Characters.
int iscanonical (float-typex)
math.h (ISO):Floating-Point Number Classification Functions.
int iscntrl (intc)
ctype.h (ISO):Classification of Characters.
int isdigit (intc)
ctype.h (ISO):Classification of Characters.
int iseqsig (real-floatingx,real-floatingy)
math.h (ISO):Floating-Point Comparison Functions.
int isfinite (float-typex)
math.h (ISO):Floating-Point Number Classification Functions.
int isgraph (intc)
ctype.h (ISO):Classification of Characters.
int isgreater (real-floatingx,real-floatingy)
math.h (ISO):Floating-Point Comparison Functions.
int isgreaterequal (real-floatingx,real-floatingy)
math.h (ISO):Floating-Point Comparison Functions.
int isinf (doublex)
math.h (BSD):Floating-Point Number Classification Functions.
int isinff (floatx)
math.h (BSD):Floating-Point Number Classification Functions.
int isinfl (long doublex)
math.h (BSD):Floating-Point Number Classification Functions.
int isless (real-floatingx,real-floatingy)
math.h (ISO):Floating-Point Comparison Functions.
int islessequal (real-floatingx,real-floatingy)
math.h (ISO):Floating-Point Comparison Functions.
int islessgreater (real-floatingx,real-floatingy)
math.h (ISO):Floating-Point Comparison Functions.
int islower (intc)
ctype.h (ISO):Classification of Characters.
int isnan (float-typex)
math.h (ISO):Floating-Point Number Classification Functions.
int isnan (doublex)
math.h (BSD):Floating-Point Number Classification Functions.
int isnanf (floatx)
math.h (BSD):Floating-Point Number Classification Functions.
int isnanl (long doublex)
math.h (BSD):Floating-Point Number Classification Functions.
int isnormal (float-typex)
math.h (ISO):Floating-Point Number Classification Functions.
int isprint (intc)
ctype.h (ISO):Classification of Characters.
int ispunct (intc)
ctype.h (ISO):Classification of Characters.
int issignaling (float-typex)
math.h (ISO):Floating-Point Number Classification Functions.
int isspace (intc)
ctype.h (ISO):Classification of Characters.
int issubnormal (float-typex)
math.h (ISO):Floating-Point Number Classification Functions.
int isunordered (real-floatingx,real-floatingy)
math.h (ISO):Floating-Point Comparison Functions.
int isupper (intc)
ctype.h (ISO):Classification of Characters.
int iswalnum (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int iswalpha (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int iswblank (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int iswcntrl (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int iswctype (wint_twc, wctype_tdesc)
wctype.h (ISO):Character class determination for wide characters.
int iswdigit (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int iswgraph (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int iswlower (wint_twc)
ctype.h (ISO):Character class determination for wide characters.
int iswprint (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int iswpunct (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int iswspace (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int iswupper (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int iswxdigit (wint_twc)
wctype.h (ISO):Character class determination for wide characters.
int isxdigit (intc)
ctype.h (ISO):Classification of Characters.
int iszero (float-typex)
math.h (ISO):Floating-Point Number Classification Functions.
struct itimerval
sys/time.h (BSD):Setting an Alarm.
double j0 (doublex)
math.h (SVID):Special Functions.
float j0f (floatx)
math.h (SVID):Special Functions.
_FloatN j0fN (_FloatNx)
math.h (GNU):Special Functions.
_FloatNx j0fNx (_FloatNxx)
math.h (GNU):Special Functions.
long double j0l (long doublex)
math.h (SVID):Special Functions.
double j1 (doublex)
math.h (SVID):Special Functions.
float j1f (floatx)
math.h (SVID):Special Functions.
_FloatN j1fN (_FloatNx)
math.h (GNU):Special Functions.
_FloatNx j1fNx (_FloatNxx)
math.h (GNU):Special Functions.
long double j1l (long doublex)
math.h (SVID):Special Functions.
jmp_buf
setjmp.h (ISO):Details of Non-Local Exits.
double jn (intn, doublex)
math.h (SVID):Special Functions.
float jnf (intn, floatx)
math.h (SVID):Special Functions.
_FloatN jnfN (intn, _FloatNx)
math.h (GNU):Special Functions.
_FloatNx jnfNx (intn, _FloatNxx)
math.h (GNU):Special Functions.
long double jnl (intn, long doublex)
math.h (SVID):Special Functions.
long int jrand48 (unsigned short intxsubi[3])
stdlib.h (SVID):SVID Random Number Function.
int jrand48_r (unsigned short intxsubi[3], struct drand48_data *buffer, long int *result)
stdlib.h (GNU):SVID Random Number Function.
int kill (pid_tpid, intsignum)
signal.h (POSIX.1):Signaling Another Process.
int killpg (intpgid, intsignum)
signal.h (BSD):Signaling Another Process.
char * l64a (long intn)
stdlib.h (XPG):Encode Binary Data.
long int labs (long intnumber)
stdlib.h (ISO):Absolute Value.
void lcong48 (unsigned short intparam[7])
stdlib.h (SVID):SVID Random Number Function.
int lcong48_r (unsigned short intparam[7], struct drand48_data *buffer)
stdlib.h (GNU):SVID Random Number Function.
struct lconv
locale.h (ISO):localeconv
: It is portable but ….
double ldexp (doublevalue, intexponent)
math.h (ISO):Normalization Functions.
float ldexpf (floatvalue, intexponent)
math.h (ISO):Normalization Functions.
_FloatN ldexpfN (_FloatNvalue, intexponent)
math.h (TS 18661-3:2015):Normalization Functions.
_FloatNx ldexpfNx (_FloatNxvalue, intexponent)
math.h (TS 18661-3:2015):Normalization Functions.
long double ldexpl (long doublevalue, intexponent)
math.h (ISO):Normalization Functions.
ldiv_t ldiv (long intnumerator, long intdenominator)
stdlib.h (ISO):Integer Division.
ldiv_t
stdlib.h (ISO):Integer Division.
void * lfind (const void *key, const void *base, size_t *nmemb, size_tsize, comparison_fn_tcompar)
search.h (SVID):Array Search Function.
double lgamma (doublex)
math.h (SVID):Special Functions.
double lgamma_r (doublex, int *signp)
math.h (XPG):Special Functions.
float lgammaf (floatx)
math.h (SVID):Special Functions.
_FloatN lgammafN (_FloatNx)
math.h (TS 18661-3:2015):Special Functions.
_FloatN lgammafN_r (_FloatNx, int *signp)
math.h (GNU):Special Functions.
_FloatNx lgammafNx (_FloatNxx)
math.h (TS 18661-3:2015):Special Functions.
_FloatNx lgammafNx_r (_FloatNxx, int *signp)
math.h (GNU):Special Functions.
float lgammaf_r (floatx, int *signp)
math.h (XPG):Special Functions.
long double lgammal (long doublex)
math.h (SVID):Special Functions.
long double lgammal_r (long doublex, int *signp)
math.h (XPG):Special Functions.
struct linger
sys/socket.h (BSD):Socket-Level Options.
int link (const char *oldname, const char *newname)
unistd.h (POSIX.1):Hard Links.
int linkat (int oldfd, const char *oldname, int newfd, const char *newname, int flags)
unistd.h (POSIX.1):Hard Links.
int lio_listio (intmode, struct aiocb *constlist[], intnent, struct sigevent *sig)
aio.h (POSIX.1b):Asynchronous Read and Write Operations.
int lio_listio64 (intmode, struct aiocb64 *constlist[], intnent, struct sigevent *sig)
aio.h (Unix98):Asynchronous Read and Write Operations.
int listen (intsocket, intn)
sys/socket.h (BSD):Listening for Connections.
long long int llabs (long long intnumber)
stdlib.h (ISO):Absolute Value.
lldiv_t lldiv (long long intnumerator, long long intdenominator)
stdlib.h (ISO):Integer Division.
lldiv_t
stdlib.h (ISO):Integer Division.
long int llogb (doublex)
math.h (ISO):Exponentiation and Logarithms.
long int llogbf (floatx)
math.h (ISO):Exponentiation and Logarithms.
long int llogbfN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long int llogbfNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long int llogbl (long doublex)
math.h (ISO):Exponentiation and Logarithms.
long long int llrint (doublex)
math.h (ISO):Rounding Functions.
long long int llrintf (floatx)
math.h (ISO):Rounding Functions.
long long int llrintfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
long long int llrintfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long long int llrintl (long doublex)
math.h (ISO):Rounding Functions.
long long int llround (doublex)
math.h (ISO):Rounding Functions.
long long int llroundf (floatx)
math.h (ISO):Rounding Functions.
long long int llroundfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
long long int llroundfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long long int llroundl (long doublex)
math.h (ISO):Rounding Functions.
struct lconv * localeconv (void)
locale.h (ISO):localeconv
: It is portable but ….
struct tm * localtime (const time_t *time)
time.h (ISO):Broken-down Time.
struct tm * localtime_r (const time_t *time, struct tm *resultp)
time.h (POSIX.1c):Broken-down Time.
double log (doublex)
math.h (ISO):Exponentiation and Logarithms.
double log10 (doublex)
math.h (ISO):Exponentiation and Logarithms.
float log10f (floatx)
math.h (ISO):Exponentiation and Logarithms.
_FloatN log10fN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx log10fNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double log10l (long doublex)
math.h (ISO):Exponentiation and Logarithms.
double log10p1 (doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float log10p1f (floatx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatN log10p1fN (_FloatNx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx log10p1fNx (_FloatNxx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double log10p1l (long doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
double log1p (doublex)
math.h (ISO):Exponentiation and Logarithms.
float log1pf (floatx)
math.h (ISO):Exponentiation and Logarithms.
_FloatN log1pfN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx log1pfNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double log1pl (long doublex)
math.h (ISO):Exponentiation and Logarithms.
double log2 (doublex)
math.h (ISO):Exponentiation and Logarithms.
float log2f (floatx)
math.h (ISO):Exponentiation and Logarithms.
_FloatN log2fN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx log2fNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double log2l (long doublex)
math.h (ISO):Exponentiation and Logarithms.
double log2p1 (doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float log2p1f (floatx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatN log2p1fN (_FloatNx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx log2p1fNx (_FloatNxx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double log2p1l (long doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
double logb (doublex)
math.h (ISO):Exponentiation and Logarithms.
float logbf (floatx)
math.h (ISO):Exponentiation and Logarithms.
_FloatN logbfN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx logbfNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double logbl (long doublex)
math.h (ISO):Exponentiation and Logarithms.
float logf (floatx)
math.h (ISO):Exponentiation and Logarithms.
_FloatN logfN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx logfNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
void login (const struct utmp *entry)
utmp.h (BSD):Logging In and Out.
int login_tty (intfiledes)
utmp.h (BSD):Logging In and Out.
long double logl (long doublex)
math.h (ISO):Exponentiation and Logarithms.
int logout (const char *ut_line)
utmp.h (BSD):Logging In and Out.
double logp1 (doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float logp1f (floatx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatN logp1fN (_FloatNx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx logp1fNx (_FloatNxx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double logp1l (long doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
void logwtmp (const char *ut_line, const char *ut_name, const char *ut_host)
utmp.h (BSD):Logging In and Out.
void longjmp (jmp_bufstate, intvalue)
setjmp.h (ISO):Details of Non-Local Exits.
long int lrand48 (void)
stdlib.h (SVID):SVID Random Number Function.
int lrand48_r (struct drand48_data *buffer, long int *result)
stdlib.h (GNU):SVID Random Number Function.
long int lrint (doublex)
math.h (ISO):Rounding Functions.
long int lrintf (floatx)
math.h (ISO):Rounding Functions.
long int lrintfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
long int lrintfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long int lrintl (long doublex)
math.h (ISO):Rounding Functions.
long int lround (doublex)
math.h (ISO):Rounding Functions.
long int lroundf (floatx)
math.h (ISO):Rounding Functions.
long int lroundfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
long int lroundfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long int lroundl (long doublex)
math.h (ISO):Rounding Functions.
void * lsearch (const void *key, void *base, size_t *nmemb, size_tsize, comparison_fn_tcompar)
search.h (SVID):Array Search Function.
off_t lseek (intfiledes, off_toffset, intwhence)
unistd.h (POSIX.1):Setting the File Position of a Descriptor.
off64_t lseek64 (intfiledes, off64_toffset, intwhence)
unistd.h (Unix98):Setting the File Position of a Descriptor.
int lstat (const char *filename, struct stat *buf)
sys/stat.h (BSD):Reading the Attributes of a File.
int lstat64 (const char *filename, struct stat64 *buf)
sys/stat.h (Unix98):Reading the Attributes of a File.
int lutimes (const char *filename, const struct timevaltvp[2]
)
sys/time.h (BSD):File Times.
int madvise (void *addr, size_tlength, intadvice)
sys/mman.h (POSIX):Memory-mapped I/O.
void makecontext (ucontext_t *ucp, void (*func) (void), intargc, …)
ucontext.h (SVID):Complete Context Control.
struct mallinfo2
malloc.h (GNU):Statistics for Memory Allocation withmalloc
.
struct mallinfo2 mallinfo2 (void)
malloc.h (SVID):Statistics for Memory Allocation withmalloc
.
void * malloc (size_tsize)
malloc.h (ISO):Basic Memory Allocation.
stdlib.h (ISO):Basic Memory Allocation.
int mblen (const char *string, size_tsize)
stdlib.h (ISO):Non-reentrant Conversion of Single Characters.
size_t mbrlen (const char *restricts, size_tn, mbstate_t *ps)
wchar.h (ISO):Converting Single Characters.
size_t mbrtowc (wchar_t *restrictpwc, const char *restricts, size_tn, mbstate_t *restrictps)
wchar.h (ISO):Converting Single Characters.
int mbsinit (const mbstate_t *ps)
wchar.h (ISO):Representing the state of the conversion.
size_t mbsnrtowcs (wchar_t *restrictdst, const char **restrictsrc, size_tnmc, size_tlen, mbstate_t *restrictps)
wchar.h (GNU):Converting Multibyte and Wide Character Strings.
size_t mbsrtowcs (wchar_t *restrictdst, const char **restrictsrc, size_tlen, mbstate_t *restrictps)
wchar.h (ISO):Converting Multibyte and Wide Character Strings.
mbstate_t
wchar.h (ISO):Representing the state of the conversion.
size_t mbstowcs (wchar_t *wstring, const char *string, size_tsize)
stdlib.h (ISO):Non-reentrant Conversion of Strings.
int mbtowc (wchar_t *restrictresult, const char *restrictstring, size_tsize)
stdlib.h (ISO):Non-reentrant Conversion of Single Characters.
int mcheck (void (*abortfn) (enum mcheck_statusstatus))
mcheck.h (GNU):Heap Consistency Checking.
void * memalign (size_tboundary, size_tsize)
malloc.h (BSD):Allocating Aligned Memory Blocks.
void * memccpy (void *restrictto, const void *restrictfrom, intc, size_tsize)
string.h (SVID):Copying Strings and Arrays.
void * memchr (const void *block, intc, size_tsize)
string.h (ISO):Search Functions.
int memcmp (const void *a1, const void *a2, size_tsize)
string.h (ISO):String/Array Comparison.
void * memcpy (void *restrictto, const void *restrictfrom, size_tsize)
string.h (ISO):Copying Strings and Arrays.
int memfd_create (const char *name, unsigned intflags)
sys/mman.h (Linux):Memory-mapped I/O.
void * memfrob (void *mem, size_tlength)
string.h (GNU):Obfuscating Data.
void * memmem (const void *haystack, size_thaystack-len,
const void *needle, size_tneedle-len)
string.h (POSIX.1-2024):Search Functions.
void * memmove (void *to, const void *from, size_tsize)
string.h (ISO):Copying Strings and Arrays.
void * mempcpy (void *restrictto, const void *restrictfrom, size_tsize)
string.h (GNU):Copying Strings and Arrays.
void * memrchr (const void *block, intc, size_tsize)
string.h (GNU):Search Functions.
void * memset (void *block, intc, size_tsize)
string.h (ISO):Copying Strings and Arrays.
int mkdir (const char *filename, mode_tmode)
sys/stat.h (POSIX.1):Creating Directories.
int mkdirat (intfiledes, const char *filename, mode_tmode)
sys/stat.h (POSIX.1-2008):Creating Directories.
char * mkdtemp (char *template)
stdlib.h (BSD):Temporary Files.
int mkfifo (const char *filename, mode_tmode)
sys/stat.h (POSIX.1):FIFO Special Files.
int mknod (const char *filename, mode_tmode, dev_tdev)
sys/stat.h (BSD):Making Special Files.
int mkstemp (char *template)
stdlib.h (BSD):Temporary Files.
char * mktemp (char *template)
stdlib.h (Unix):Temporary Files.
time_t mktime (struct tm *brokentime)
time.h (ISO):Broken-down Time.
int mlock (const void *addr, size_tlen)
sys/mman.h (POSIX.1b):Functions To Lock And Unlock Pages.
int mlock2 (const void *addr, size_tlen, unsigned intflags)
sys/mman.h (Linux):Functions To Lock And Unlock Pages.
int mlockall (intflags)
sys/mman.h (POSIX.1b):Functions To Lock And Unlock Pages.
void * mmap (void *address, size_tlength, intprotect, intflags, intfiledes, off_toffset)
sys/mman.h (POSIX):Memory-mapped I/O.
void * mmap64 (void *address, size_tlength, intprotect, intflags, intfiledes, off64_toffset)
sys/mman.h (LFS):Memory-mapped I/O.
struct mntent
mntent.h (BSD):Themtab file.
mode_t
sys/types.h (POSIX.1):The meaning of the File Attributes.
double modf (doublevalue, double *integer-part)
math.h (ISO):Rounding Functions.
float modff (floatvalue, float *integer-part)
math.h (ISO):Rounding Functions.
_FloatN modffN (_FloatNvalue, _FloatN *integer-part)
math.h (TS 18661-3:2015):Rounding Functions.
_FloatNx modffNx (_FloatNxvalue, _FloatNx *integer-part)
math.h (TS 18661-3:2015):Rounding Functions.
long double modfl (long doublevalue, long double *integer-part)
math.h (ISO):Rounding Functions.
int mount (const char *special_file, const char *dir, const char *fstype, unsigned long intoptions, const void *data)
sys/mount.h (SVID):Mount, Unmount, Remount.
sys/mount.h (BSD):Mount, Unmount, Remount.
int mprotect (void *address, size_tlength, intprotection)
sys/mman.h (POSIX):Memory Protection.
long int mrand48 (void)
stdlib.h (SVID):SVID Random Number Function.
int mrand48_r (struct drand48_data *buffer, long int *result)
stdlib.h (GNU):SVID Random Number Function.
void * mremap (void *address, size_tlength, size_tnew_length, intflag, ... /* void *new_address */)
sys/mman.h (GNU):Memory-mapped I/O.
struct msghdr
sys/socket.h (BSD):Other Socket APIs.
int msync (void *address, size_tlength, intflags)
sys/mman.h (POSIX):Memory-mapped I/O.
void mtrace (void)
mcheck.h (GNU):How to install the tracing functionality.
void mtx_destroy (mtx_t *mutex)
threads.h (C11):Mutexes.
int mtx_init (mtx_t *mutex, inttype)
threads.h (C11):Mutexes.
int mtx_lock (mtx_t *mutex)
threads.h (C11):Mutexes.
mtx_plain
threads.h (C11):Mutexes.
mtx_recursive
threads.h (C11):Mutexes.
mtx_t
threads.h (C11):Mutexes.
mtx_timed
threads.h (C11):Mutexes.
int mtx_timedlock (mtx_t *restrictmutex, const struct timespec *restricttime_point)
threads.h (C11):Mutexes.
int mtx_trylock (mtx_t *mutex)
threads.h (C11):Mutexes.
int mtx_unlock (mtx_t *mutex)
threads.h (C11):Mutexes.
int munlock (const void *addr, size_tlen)
sys/mman.h (POSIX.1b):Functions To Lock And Unlock Pages.
int munlockall (void)
sys/mman.h (POSIX.1b):Functions To Lock And Unlock Pages.
int munmap (void *addr, size_tlength)
sys/mman.h (POSIX):Memory-mapped I/O.
void muntrace (void)
mcheck.h (GNU):How to install the tracing functionality.
double nan (const char *tagp)
math.h (ISO):Setting and modifying single bits of FP values.
float nanf (const char *tagp)
math.h (ISO):Setting and modifying single bits of FP values.
_FloatN nanfN (const char *tagp)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
_FloatNx nanfNx (const char *tagp)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
long double nanl (const char *tagp)
math.h (ISO):Setting and modifying single bits of FP values.
int nanosleep (const struct timespec *requested_time, struct timespec *remaining_time)
time.h (POSIX.1):Sleeping.
double nearbyint (doublex)
math.h (ISO):Rounding Functions.
float nearbyintf (floatx)
math.h (ISO):Rounding Functions.
_FloatN nearbyintfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
_FloatNx nearbyintfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long double nearbyintl (long doublex)
math.h (ISO):Rounding Functions.
struct netent
netdb.h (BSD):Networks Database.
double nextafter (doublex, doubley)
math.h (ISO):Setting and modifying single bits of FP values.
float nextafterf (floatx, floaty)
math.h (ISO):Setting and modifying single bits of FP values.
_FloatN nextafterfN (_FloatNx, _FloatNy)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
_FloatNx nextafterfNx (_FloatNxx, _FloatNxy)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
long double nextafterl (long doublex, long doubley)
math.h (ISO):Setting and modifying single bits of FP values.
double nextdown (doublex)
math.h (ISO):Setting and modifying single bits of FP values.
float nextdownf (floatx)
math.h (ISO):Setting and modifying single bits of FP values.
_FloatN nextdownfN (_FloatNx)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
_FloatNx nextdownfNx (_FloatNxx)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
long double nextdownl (long doublex)
math.h (ISO):Setting and modifying single bits of FP values.
double nexttoward (doublex, long doubley)
math.h (ISO):Setting and modifying single bits of FP values.
float nexttowardf (floatx, long doubley)
math.h (ISO):Setting and modifying single bits of FP values.
long double nexttowardl (long doublex, long doubley)
math.h (ISO):Setting and modifying single bits of FP values.
double nextup (doublex)
math.h (ISO):Setting and modifying single bits of FP values.
float nextupf (floatx)
math.h (ISO):Setting and modifying single bits of FP values.
_FloatN nextupfN (_FloatNx)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
_FloatNx nextupfNx (_FloatNxx)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
long double nextupl (long doublex)
math.h (ISO):Setting and modifying single bits of FP values.
int nftw (const char *filename, __nftw_func_tfunc, intdescriptors, intflag)
ftw.h (XPG4.2):Working with Directory Trees.
int nftw64 (const char *filename, __nftw64_func_tfunc, intdescriptors, intflag)
ftw.h (Unix98):Working with Directory Trees.
char * ngettext (const char *msgid1, const char *msgid2, unsigned long intn)
libintl.h (POSIX-1.2024):Additional functions for more complicated situations.
int nice (intincrement)
unistd.h (BSD):Functions For Traditional Scheduling.
char * nl_langinfo (nl_itemitem)
langinfo.h (XOPEN):Pinpoint Access to Locale Data.
nlink_t
sys/types.h (POSIX.1):The meaning of the File Attributes.
long int nrand48 (unsigned short intxsubi[3])
stdlib.h (SVID):SVID Random Number Function.
int nrand48_r (unsigned short intxsubi[3], struct drand48_data *buffer, long int *result)
stdlib.h (GNU):SVID Random Number Function.
uint32_t ntohl (uint32_tnetlong)
netinet/in.h (BSD):Byte Order Conversion.
uint16_t ntohs (uint16_tnetshort)
netinet/in.h (BSD):Byte Order Conversion.
int ntp_adjtime (struct timex *tptr)
sys/timex.h (GNU):Setting and Adjusting the Time.
int ntp_gettime (struct ntptimeval *tptr)
sys/timex.h (GNU):Setting and Adjusting the Time.
struct obstack
obstack.h (GNU):Creating Obstacks.
void obstack_1grow (struct obstack *obstack-ptr, charc)
obstack.h (GNU):Growing Objects.
void obstack_1grow_fast (struct obstack *obstack-ptr, charc)
obstack.h (GNU):Extra Fast Growing Objects.
int obstack_alignment_mask (struct obstack *obstack-ptr)
obstack.h (GNU):Alignment of Data in Obstacks.
void * obstack_alloc (struct obstack *obstack-ptr, intsize)
obstack.h (GNU):Allocation in an Obstack.
obstack_alloc_failed_handler
obstack.h (GNU):Preparing for Using Obstacks.
void * obstack_base (struct obstack *obstack-ptr)
obstack.h (GNU):Status of an Obstack.
void obstack_blank (struct obstack *obstack-ptr, intsize)
obstack.h (GNU):Growing Objects.
void obstack_blank_fast (struct obstack *obstack-ptr, intsize)
obstack.h (GNU):Extra Fast Growing Objects.
int obstack_chunk_size (struct obstack *obstack-ptr)
obstack.h (GNU):Obstack Chunks.
void * obstack_copy (struct obstack *obstack-ptr, void *address, intsize)
obstack.h (GNU):Allocation in an Obstack.
void * obstack_copy0 (struct obstack *obstack-ptr, void *address, intsize)
obstack.h (GNU):Allocation in an Obstack.
void * obstack_finish (struct obstack *obstack-ptr)
obstack.h (GNU):Growing Objects.
void obstack_free (struct obstack *obstack-ptr, void *object)
obstack.h (GNU):Freeing Objects in an Obstack.
void obstack_grow (struct obstack *obstack-ptr, void *data, intsize)
obstack.h (GNU):Growing Objects.
void obstack_grow0 (struct obstack *obstack-ptr, void *data, intsize)
obstack.h (GNU):Growing Objects.
int obstack_init (struct obstack *obstack-ptr)
obstack.h (GNU):Preparing for Using Obstacks.
void obstack_int_grow (struct obstack *obstack-ptr, intdata)
obstack.h (GNU):Growing Objects.
void obstack_int_grow_fast (struct obstack *obstack-ptr, intdata)
obstack.h (GNU):Extra Fast Growing Objects.
void * obstack_next_free (struct obstack *obstack-ptr)
obstack.h (GNU):Status of an Obstack.
int obstack_object_size (struct obstack *obstack-ptr)
obstack.h (GNU):Growing Objects.
obstack.h (GNU):Status of an Obstack.
int obstack_printf (struct obstack *obstack, const char *template, …)
stdio.h (GNU):Dynamically Allocating Formatted Output.
void obstack_ptr_grow (struct obstack *obstack-ptr, void *data)
obstack.h (GNU):Growing Objects.
void obstack_ptr_grow_fast (struct obstack *obstack-ptr, void *data)
obstack.h (GNU):Extra Fast Growing Objects.
int obstack_room (struct obstack *obstack-ptr)
obstack.h (GNU):Extra Fast Growing Objects.
int obstack_vprintf (struct obstack *obstack, const char *template, va_listap)
stdio.h (GNU):Variable Arguments Output Functions.
off64_t
sys/types.h (Unix98):Setting the File Position of a Descriptor.
off_t
sys/types.h (POSIX.1):Setting the File Position of a Descriptor.
size_t offsetof (type,member)
stddef.h (ISO):Structure Field Offset Measurement.
int on_exit (void (*function)(intstatus, void *arg), void *arg)
stdlib.h (SunOS):Cleanups on Exit.
once_flag
threads.h (C11):Call Once.
int open (const char *filename, intflags[, mode_tmode])
fcntl.h (POSIX.1):Opening and Closing Files.
int open64 (const char *filename, intflags[, mode_tmode])
fcntl.h (Unix98):Opening and Closing Files.
FILE * open_memstream (char **ptr, size_t *sizeloc)
stdio.h (GNU):String Streams.
int openat (intfiledes, const char *filename, intflags[, mode_tmode])
fcntl.h (POSIX.1):Opening and Closing Files.
int openat64 (intfiledes, const char *filename, intflags[, mode_tmode])
fcntl.h (GNU):Opening and Closing Files.
DIR * opendir (const char *dirname)
dirent.h (POSIX.1):Opening a Directory Stream.
void openlog (const char *ident, intoption, intfacility)
syslog.h (BSD):openlog.
int openpty (int *amaster, int *aslave, char *name, const struct termios *termp, const struct winsize *winp)
pty.h (BSD):Opening a Pseudo-Terminal Pair.
char * optarg
unistd.h (POSIX.2):Using thegetopt
function.
int opterr
unistd.h (POSIX.2):Using thegetopt
function.
int optind
unistd.h (POSIX.2):Using thegetopt
function.
struct option
getopt.h (GNU):Parsing Long Options withgetopt_long
.
int optopt
unistd.h (POSIX.2):Using thegetopt
function.
size_t parse_printf_format (const char *template, size_tn, int *argtypes)
printf.h (GNU):Parsing a Template String.
struct passwd
pwd.h (POSIX.1):The Data Structure that Describes a User.
long int pathconf (const char *filename, intparameter)
unistd.h (POSIX.1):Usingpathconf
.
int pause (void)
unistd.h (POSIX.1):Usingpause
.
int pclose (FILE *stream)
stdio.h (POSIX.2):Pipe to a Subprocess.
stdio.h (SVID):Pipe to a Subprocess.
stdio.h (BSD):Pipe to a Subprocess.
void perror (const char *message)
stdio.h (ISO):Error Messages.
pid_t
sys/types.h (POSIX.1):Process Identification.
pid_t pidfd_getpid (intfd)
sys/pidfd.h (GNU):Querying a Process.
int pipe (intfiledes[2]
)
unistd.h (POSIX.1):Creating a Pipe.
int pkey_alloc (unsigned intflags, unsigned intaccess_restrictions)
sys/mman.h (Linux):Memory Protection.
int pkey_free (intkey)
sys/mman.h (Linux):Memory Protection.
int pkey_get (intkey)
sys/mman.h (Linux):Memory Protection.
int pkey_mprotect (void *address, size_tlength, intprotection, intkey)
sys/mman.h (Linux):Memory Protection.
int pkey_set (intkey, unsigned intaccess_restrictions)
sys/mman.h (Linux):Memory Protection.
FILE * popen (const char *command, const char *mode)
stdio.h (POSIX.2):Pipe to a Subprocess.
stdio.h (SVID):Pipe to a Subprocess.
stdio.h (BSD):Pipe to a Subprocess.
int posix_memalign (void **memptr, size_talignment, size_tsize)
stdlib.h (POSIX):Allocating Aligned Memory Blocks.
int posix_openpt (intflags)
stdlib.h (POSIX.1):Allocating Pseudo-Terminals.
double pow (doublebase, doublepower)
math.h (ISO):Exponentiation and Logarithms.
float powf (floatbase, floatpower)
math.h (ISO):Exponentiation and Logarithms.
_FloatN powfN (_FloatNbase, _FloatNpower)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx powfNx (_FloatNxbase, _FloatNxpower)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double powl (long doublebase, long doublepower)
math.h (ISO):Exponentiation and Logarithms.
double pown (doublebase, long long intpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float pownf (floatbase, long long intpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatN pownfN (_FloatNbase, long long intpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx pownfNx (_FloatNxbase, long long intpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double pownl (long doublebase, long long intpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
double powr (doublebase, doublepower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float powrf (floatbase, floatpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatN powrfN (_FloatNbase, _FloatNpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx powrfNx (_FloatNxbase, _FloatNxpower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double powrl (long doublebase, long doublepower)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
ssize_t pread (intfiledes, void *buffer, size_tsize, off_toffset)
unistd.h (Unix98):Input and Output Primitives.
ssize_t pread64 (intfiledes, void *buffer, size_tsize, off64_toffset)
unistd.h (Unix98):Input and Output Primitives.
ssize_t preadv (intfd, const struct iovec *iov, intiovcnt, off_toffset)
sys/uio.h (BSD):Fast Scatter-Gather I/O.
ssize_t preadv2 (intfd, const struct iovec *iov, intiovcnt, off_toffset, intflags)
sys/uio.h (GNU):Fast Scatter-Gather I/O.
ssize_t preadv64 (intfd, const struct iovec *iov, intiovcnt, off64_toffset)
unistd.h (BSD):Fast Scatter-Gather I/O.
ssize_t preadv64v2 (intfd, const struct iovec *iov, intiovcnt, off64_toffset, intflags)
unistd.h (GNU):Fast Scatter-Gather I/O.
int printf (const char *template, …)
stdio.h (ISO):Formatted Output Functions.
printf_arginfo_function
printf.h (GNU):Defining the Output Handler.
printf_function
printf.h (GNU):Defining the Output Handler.
struct printf_info
printf.h (GNU):Conversion Specifier Options.
int printf_size (FILE *fp, const struct printf_info *info, const void *const *args)
printf.h (GNU):Predefinedprintf
Handlers.
int printf_size_info (const struct printf_info *info, size_tn, int *argtypes)
printf.h (GNU):Predefinedprintf
Handlers.
char * program_invocation_name
errno.h (GNU):Error Messages.
char * program_invocation_short_name
errno.h (GNU):Error Messages.
struct protoent
netdb.h (BSD):Protocols Database.
void psignal (intsignum, const char *message)
signal.h (BSD):Signal Messages.
int pthread_attr_getsigmask_np (const pthread_attr_t *attr, sigset_t *sigmask)
pthread.h (GNU):Controlling the Initial Signal Mask of a New Thread.
int pthread_attr_setsigmask_np (pthread_attr_t *attr, const sigset_t *sigmask)
pthread.h (GNU):Controlling the Initial Signal Mask of a New Thread.
int pthread_barrier_destroy (pthread_barrier_t *barrier)
pthread.h (POSIX):POSIX Barriers.
int pthread_barrier_init (pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned intcount)
pthread.h (POSIX):POSIX Barriers.
int pthread_barrier_wait (pthread_barrier_t *barrier)
pthread.h (POSIX):POSIX Barriers.
int pthread_clockjoin_np (pthread_t *thread, void **thread_return, clockid_tclockid, const struct timespec *abstime)
pthread.h (GNU):Wait for a thread to terminate.
int pthread_cond_clockwait (pthread_cond_t *cond, pthread_mutex_t *mutex, clockid_tclockid, const struct timespec *abstime)
pthread.h (POSIX-1.2024):Functions for Waiting According to a Specific Clock.
int pthread_getattr_default_np (pthread_attr_t *attr)
pthread.h (GNU):Setting Process-wide defaults for thread attributes.
void * pthread_getspecific (pthread_key_tkey)
pthread.h (POSIX):Thread-specific Data.
pid_t pthread_gettid_np (pthread_tthread)
pthread.h (Linux):Process Identification.
int pthread_key_create (pthread_key_t *key, void (*destructor)(void*))
pthread.h (POSIX):Thread-specific Data.
int pthread_key_delete (pthread_key_tkey)
pthread.h (POSIX):Thread-specific Data.
int pthread_rwlock_clockrdlock (pthread_rwlock_t *rwlock, clockid_tclockid, const struct timespec *abstime)
pthread.h (POSIX-1.2024):Functions for Waiting According to a Specific Clock.
int pthread_rwlock_clockwrlock (pthread_rwlock_t *rwlock, clockid_tclockid, const struct timespec *abstime)
pthread.h (POSIX-1.2024):Functions for Waiting According to a Specific Clock.
int pthread_setattr_default_np (pthread_attr_t *attr)
pthread.h (GNU):Setting Process-wide defaults for thread attributes.
int pthread_setspecific (pthread_key_tkey, const void *value)
pthread.h (POSIX):Thread-specific Data.
int pthread_timedjoin_np (pthread_t *thread, void **thread_return, const struct timespec *abstime)
pthread.h (GNU):Wait for a thread to terminate.
int pthread_tryjoin_np (pthread_t *thread, void **thread_return)
pthread.h (GNU):Wait for a thread to terminate.
ptrdiff_t
stddef.h (ISO):Important Data Types.
char * ptsname (intfiledes)
stdlib.h (SVID):Allocating Pseudo-Terminals.
stdlib.h (XPG4.2):Allocating Pseudo-Terminals.
int ptsname_r (intfiledes, char *buf, size_tlen)
stdlib.h (POSIX.1-2024):Allocating Pseudo-Terminals.
int putc (intc, FILE *stream)
stdio.h (ISO):Simple Output by Characters or Lines.
int putc_unlocked (intc, FILE *stream)
stdio.h (POSIX):Simple Output by Characters or Lines.
int putchar (intc)
stdio.h (ISO):Simple Output by Characters or Lines.
int putchar_unlocked (intc)
stdio.h (POSIX):Simple Output by Characters or Lines.
int putenv (char *string)
stdlib.h (SVID):Environment Access.
int putpwent (const struct passwd *p, FILE *stream)
pwd.h (SVID):Writing a User Entry.
int puts (const char *s)
stdio.h (ISO):Simple Output by Characters or Lines.
struct utmp * pututline (const struct utmp *utmp)
utmp.h (SVID):Manipulating the User Accounting Database.
struct utmpx * pututxline (const struct utmpx *utmp)
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
int putw (intw, FILE *stream)
stdio.h (SVID):Simple Output by Characters or Lines.
wint_t putwc (wchar_twc, FILE *stream)
wchar.h (ISO):Simple Output by Characters or Lines.
wint_t putwc_unlocked (wchar_twc, FILE *stream)
wchar.h (GNU):Simple Output by Characters or Lines.
wint_t putwchar (wchar_twc)
wchar.h (ISO):Simple Output by Characters or Lines.
wint_t putwchar_unlocked (wchar_twc)
wchar.h (GNU):Simple Output by Characters or Lines.
ssize_t pwrite (intfiledes, const void *buffer, size_tsize, off_toffset)
unistd.h (Unix98):Input and Output Primitives.
ssize_t pwrite64 (intfiledes, const void *buffer, size_tsize, off64_toffset)
unistd.h (Unix98):Input and Output Primitives.
ssize_t pwritev (intfd, const struct iovec *iov, intiovcnt, off_toffset)
sys/uio.h (BSD):Fast Scatter-Gather I/O.
ssize_t pwritev2 (intfd, const struct iovec *iov, intiovcnt, off_toffset, intflags)
sys/uio.h (GNU):Fast Scatter-Gather I/O.
ssize_t pwritev64 (intfd, const struct iovec *iov, intiovcnt, off64_toffset)
unistd.h (BSD):Fast Scatter-Gather I/O.
ssize_t pwritev64v2 (intfd, const struct iovec *iov, intiovcnt, off64_toffset, intflags)
unistd.h (GNU):Fast Scatter-Gather I/O.
char * qecvt (long doublevalue, intndigit, int *decpt, int *neg)
stdlib.h (GNU):Old-fashioned System V number-to-string functions.
int qecvt_r (long doublevalue, intndigit, int *decpt, int *neg, char *buf, size_tlen)
stdlib.h (GNU):Old-fashioned System V number-to-string functions.
char * qfcvt (long doublevalue, intndigit, int *decpt, int *neg)
stdlib.h (GNU):Old-fashioned System V number-to-string functions.
int qfcvt_r (long doublevalue, intndigit, int *decpt, int *neg, char *buf, size_tlen)
stdlib.h (GNU):Old-fashioned System V number-to-string functions.
char * qgcvt (long doublevalue, intndigit, char *buf)
stdlib.h (GNU):Old-fashioned System V number-to-string functions.
void qsort (void *array, size_tcount, size_tsize, comparison_fn_tcompare)
stdlib.h (ISO):Array Sort Function.
int raise (intsignum)
signal.h (ISO):Signaling Yourself.
int rand (void)
stdlib.h (ISO):ISO C Random Number Functions.
int rand_r (unsigned int *seed)
stdlib.h (POSIX.1):ISO C Random Number Functions.
long int random (void)
stdlib.h (BSD):BSD Random Number Functions.
struct random_data
stdlib.h (GNU):BSD Random Number Functions.
int random_r (struct random_data *restrictbuf, int32_t *restrictresult)
stdlib.h (GNU):BSD Random Number Functions.
void * rawmemchr (const void *block, intc)
string.h (GNU):Search Functions.
ssize_t read (intfiledes, void *buffer, size_tsize)
unistd.h (POSIX.1):Input and Output Primitives.
struct dirent * readdir (DIR *dirstream)
dirent.h (POSIX.1):Reading and Closing a Directory Stream.
struct dirent64 * readdir64 (DIR *dirstream)
dirent.h (LFS):Reading and Closing a Directory Stream.
int readdir64_r (DIR *dirstream, struct dirent64 *entry, struct dirent64 **result)
dirent.h (LFS):Reading and Closing a Directory Stream.
int readdir_r (DIR *dirstream, struct dirent *entry, struct dirent **result)
dirent.h (GNU):Reading and Closing a Directory Stream.
ssize_t readlink (const char *filename, char *buffer, size_tsize)
unistd.h (BSD):Symbolic Links.
ssize_t readv (intfiledes, const struct iovec *vector, intcount)
sys/uio.h (BSD):Fast Scatter-Gather I/O.
void * realloc (void *ptr, size_tnewsize)
malloc.h (ISO):Changing the Size of a Block.
stdlib.h (ISO):Changing the Size of a Block.
void * reallocarray (void *ptr, size_tnmemb, size_tsize)
malloc.h (POSIX.1-2024):Changing the Size of a Block.
stdlib.h (POSIX.1-2024):Changing the Size of a Block.
char * realpath (const char *restrictname, char *restrictresolved)
stdlib.h (XPG):Symbolic Links.
ssize_t recv (intsocket, void *buffer, size_tsize, intflags)
sys/socket.h (BSD):Receiving Data.
ssize_t recvfrom (intsocket, void *buffer, size_tsize, intflags, struct sockaddr *addr, socklen_t *length-ptr)
sys/socket.h (BSD):Receiving Datagrams.
int regcomp (regex_t *restrictcompiled, const char *restrictpattern, intcflags)
regex.h (POSIX.2):POSIX Regular Expression Compilation.
size_t regerror (interrcode, const regex_t *restrictcompiled, char *restrictbuffer, size_tlength)
regex.h (POSIX.2):POSIX Regexp Matching Cleanup.
regex_t
regex.h (POSIX.2):POSIX Regular Expression Compilation.
int regexec (const regex_t *restrictcompiled, const char *restrictstring, size_tnmatch, regmatch_tmatchptr[restrict], inteflags)
regex.h (POSIX.2):Matching a Compiled POSIX Regular Expression.
void regfree (regex_t *compiled)
regex.h (POSIX.2):POSIX Regexp Matching Cleanup.
int register_printf_function (intspec, printf_functionhandler-function, printf_arginfo_functionarginfo-function)
printf.h (GNU):Registering New Conversions.
regmatch_t
regex.h (POSIX.2):Match Results with Subexpressions.
regoff_t
regex.h (POSIX.2):Match Results with Subexpressions.
double remainder (doublenumerator, doubledenominator)
math.h (ISO):Remainder Functions.
float remainderf (floatnumerator, floatdenominator)
math.h (ISO):Remainder Functions.
_FloatN remainderfN (_FloatNnumerator, _FloatNdenominator)
math.h (TS 18661-3:2015):Remainder Functions.
_FloatNx remainderfNx (_FloatNxnumerator, _FloatNxdenominator)
math.h (TS 18661-3:2015):Remainder Functions.
long double remainderl (long doublenumerator, long doubledenominator)
math.h (ISO):Remainder Functions.
int remove (const char *filename)
stdio.h (ISO):Deleting Files.
int rename (const char *oldname, const char *newname)
stdio.h (ISO):Renaming Files.
int renameat (intoldfiledes, const char *oldname, intnewfiledes, const char *newname)
stdio.h (POSIX.1-2008):Renaming Files.
void rewind (FILE *stream)
stdio.h (ISO):File Positioning.
void rewinddir (DIR *dirstream)
dirent.h (POSIX.1):Random Access in a Directory Stream.
char * rindex (const char *string, intc)
string.h (BSD):Search Functions.
double rint (doublex)
math.h (ISO):Rounding Functions.
float rintf (floatx)
math.h (ISO):Rounding Functions.
_FloatN rintfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
_FloatNx rintfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long double rintl (long doublex)
math.h (ISO):Rounding Functions.
struct rlimit
sys/resource.h (BSD):Limiting Resource Usage.
struct rlimit64
sys/resource.h (Unix98):Limiting Resource Usage.
int rmdir (const char *filename)
unistd.h (POSIX.1):Deleting Files.
double rootn (doublex, long long intn)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float rootnf (floatx, long long intn)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatN rootnfN (_FloatNx, long long intn)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx rootnfNx (_FloatNxx, long long intn)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double rootnl (long doublex, long long intn)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
double round (doublex)
math.h (ISO):Rounding Functions.
double roundeven (doublex)
math.h (ISO):Rounding Functions.
float roundevenf (floatx)
math.h (ISO):Rounding Functions.
_FloatN roundevenfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
_FloatNx roundevenfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long double roundevenl (long doublex)
math.h (ISO):Rounding Functions.
float roundf (floatx)
math.h (ISO):Rounding Functions.
_FloatN roundfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
_FloatNx roundfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long double roundl (long doublex)
math.h (ISO):Rounding Functions.
int rpmatch (const char *response)
stdlib.h (GNU):Yes-or-No Questions.
struct rseq
sys/rseq.h (Linux):Restartable Sequences.
double rsqrt (doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
float rsqrtf (floatx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatN rsqrtfN (_FloatNx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
_FloatNx rsqrtfNx (_FloatNxx)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
long double rsqrtl (long doublex)
math.h (TS 18661-4:2015):Exponentiation and Logarithms.
struct rusage
sys/resource.h (BSD):Resource Usage.
void * sbrk (ptrdiff_tdelta)
unistd.h (BSD):Resizing the Data Segment.
double scalb (doublevalue, doubleexponent)
math.h (BSD):Normalization Functions.
float scalbf (floatvalue, floatexponent)
math.h (BSD):Normalization Functions.
long double scalbl (long doublevalue, long doubleexponent)
math.h (BSD):Normalization Functions.
double scalbln (doublex, long intn)
math.h (BSD):Normalization Functions.
float scalblnf (floatx, long intn)
math.h (BSD):Normalization Functions.
_FloatN scalblnfN (_FloatNx, long intn)
math.h (TS 18661-3:2015):Normalization Functions.
_FloatNx scalblnfNx (_FloatNxx, long intn)
math.h (TS 18661-3:2015):Normalization Functions.
long double scalblnl (long doublex, long intn)
math.h (BSD):Normalization Functions.
double scalbn (doublex, intn)
math.h (BSD):Normalization Functions.
float scalbnf (floatx, intn)
math.h (BSD):Normalization Functions.
_FloatN scalbnfN (_FloatNx, intn)
math.h (TS 18661-3:2015):Normalization Functions.
_FloatNx scalbnfNx (_FloatNxx, intn)
math.h (TS 18661-3:2015):Normalization Functions.
long double scalbnl (long doublex, intn)
math.h (BSD):Normalization Functions.
int scandir (const char *dir, struct dirent ***namelist, int (*selector) (const struct dirent *), int (*cmp) (const struct dirent **, const struct dirent **))
dirent.h (BSD):Scanning the Content of a Directory.
dirent.h (SVID):Scanning the Content of a Directory.
int scandir64 (const char *dir, struct dirent64 ***namelist, int (*selector) (const struct dirent64 *), int (*cmp) (const struct dirent64 **, const struct dirent64 **))
dirent.h (GNU):Scanning the Content of a Directory.
int scanf (const char *template, …)
stdio.h (ISO):Formatted Input Functions.
struct sched_attr
sched.h (Linux):Extensible Scheduling.
int sched_get_priority_max (intpolicy)
sched.h (POSIX):Basic Scheduling Functions.
int sched_get_priority_min (intpolicy)
sched.h (POSIX):Basic Scheduling Functions.
int sched_getaffinity (pid_tpid, size_tcpusetsize, cpu_set_t *cpuset)
sched.h (GNU):Limiting execution to certain CPUs.
int sched_getattr (pid_ttid, struct sched_attr *attr, unsigned int size, unsigned int flags)
sched.h (Linux):Extensible Scheduling.
int sched_getcpu (void)
<sched.h> (Linux):Limiting execution to certain CPUs.
int sched_getparam (pid_tpid, struct sched_param *param)
sched.h (POSIX):Basic Scheduling Functions.
int sched_getscheduler (pid_tpid)
sched.h (POSIX):Basic Scheduling Functions.
struct sched_param
sched.h (POSIX):Basic Scheduling Functions.
int sched_rr_get_interval (pid_tpid, struct timespec *interval)
sched.h (POSIX):Basic Scheduling Functions.
int sched_setaffinity (pid_tpid, size_tcpusetsize, const cpu_set_t *cpuset)
sched.h (GNU):Limiting execution to certain CPUs.
int sched_setattr (pid_ttid, struct sched_attr *attr, unsigned int flags)
sched.h (Linux):Extensible Scheduling.
int sched_setparam (pid_tpid, const struct sched_param *param)
sched.h (POSIX):Basic Scheduling Functions.
int sched_setscheduler (pid_tpid, intpolicy, const struct sched_param *param)
sched.h (POSIX):Basic Scheduling Functions.
int sched_yield (void)
sched.h (POSIX):Basic Scheduling Functions.
char * secure_getenv (const char *name)
stdlib.h (POSIX.1-2024):Environment Access.
unsigned short int * seed48 (unsigned short intseed16v[3])
stdlib.h (SVID):SVID Random Number Function.
int seed48_r (unsigned short intseed16v[3], struct drand48_data *buffer)
stdlib.h (GNU):SVID Random Number Function.
void seekdir (DIR *dirstream, long intpos)
dirent.h (BSD):Random Access in a Directory Stream.
int select (intnfds, fd_set *read-fds, fd_set *write-fds, fd_set *except-fds, struct timeval *timeout)
sys/types.h (BSD):Waiting for Input or Output.
int sem_clockwait (sem_t *sem, clockid_tclockid, const struct timespec *abstime)
semaphore.h (POSIX.1-2024):POSIX Semaphores.
int sem_close (sem_t *sem)
semaphore.h (POSIX.1-2008):POSIX Semaphores.
int sem_destroy (sem_t *sem)
semaphore.h (POSIX.1-2008):POSIX Semaphores.
int sem_getvalue (sem_t *sem, int *sval)
semaphore.h (POSIX.1-2008):POSIX Semaphores.
int sem_init (sem_t *sem, intpshared, unsigned intvalue)
semaphore.h (POSIX.1-2008):POSIX Semaphores.
sem_t * sem_open (const char *name, intoflag, ...)
semaphore.h (POSIX.1-2008):POSIX Semaphores.
int sem_post (sem_t *sem)
semaphore.h (POSIX.1-2008):POSIX Semaphores.
int sem_timedwait (sem_t *sem, const struct timespec *abstime)
semaphore.h (POSIX.1-2008):POSIX Semaphores.
int sem_trywait (sem_t *sem)
semaphore.h (POSIX.1-2008):POSIX Semaphores.
int sem_unlink (const char *name)
semaphore.h (POSIX.1-2008):POSIX Semaphores.
int sem_wait (sem_t *sem)
semaphore.h (POSIX.1-2008):POSIX Semaphores.
ssize_t send (intsocket, const void *buffer, size_tsize, intflags)
sys/socket.h (BSD):Sending Data.
ssize_t sendto (intsocket, const void *buffer, size_tsize, intflags, struct sockaddr *addr, socklen_tlength)
sys/socket.h (BSD):Sending Datagrams.
struct servent
netdb.h (BSD):The Services Database.
void setbuf (FILE *stream, char *buf)
stdio.h (ISO):Controlling Which Kind of Buffering.
void setbuffer (FILE *stream, char *buf, size_tsize)
stdio.h (BSD):Controlling Which Kind of Buffering.
int setcontext (const ucontext_t *ucp)
ucontext.h (SVID):Complete Context Control.
int setdomainname (const char *name, size_tlength)
unistd.h (???):Host Identification.
int setegid (gid_tnewgid)
unistd.h (POSIX.1):Setting the Group IDs.
int setenv (const char *name, const char *value, intreplace)
stdlib.h (BSD):Environment Access.
int seteuid (uid_tneweuid)
unistd.h (POSIX.1):Setting the User ID.
int setfsent (void)
fstab.h (BSD):Thefstab file.
int setgid (gid_tnewgid)
unistd.h (POSIX.1):Setting the Group IDs.
void setgrent (void)
grp.h (SVID):Scanning the List of All Groups.
grp.h (BSD):Scanning the List of All Groups.
int setgroups (size_tcount, const gid_t *groups)
grp.h (BSD):Setting the Group IDs.
void sethostent (intstayopen)
netdb.h (BSD):Host Names.
int sethostid (long intid)
unistd.h (BSD):Host Identification.
int sethostname (const char *name, size_tlength)
unistd.h (BSD):Host Identification.
int setitimer (intwhich, const struct itimerval *new, struct itimerval *old)
sys/time.h (BSD):Setting an Alarm.
int setjmp (jmp_bufstate)
setjmp.h (ISO):Details of Non-Local Exits.
void setlinebuf (FILE *stream)
stdio.h (BSD):Controlling Which Kind of Buffering.
char * setlocale (intcategory, const char *locale)
locale.h (ISO):How Programs Set the Locale.
int setlogmask (intmask)
syslog.h (BSD):setlogmask.
FILE * setmntent (const char *file, const char *mode)
mntent.h (BSD):Themtab file.
void setnetent (intstayopen)
netdb.h (BSD):Networks Database.
int setnetgrent (const char *netgroup)
netdb.h (BSD):Looking up one Netgroup.
int setpayload (double *x, doublepayload)
math.h (ISO):Setting and modifying single bits of FP values.
int setpayloadf (float *x, floatpayload)
math.h (ISO):Setting and modifying single bits of FP values.
int setpayloadfN (_FloatN *x, _FloatNpayload)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
int setpayloadfNx (_FloatNx *x, _FloatNxpayload)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
int setpayloadl (long double *x, long doublepayload)
math.h (ISO):Setting and modifying single bits of FP values.
int setpayloadsig (double *x, doublepayload)
math.h (ISO):Setting and modifying single bits of FP values.
int setpayloadsigf (float *x, floatpayload)
math.h (ISO):Setting and modifying single bits of FP values.
int setpayloadsigfN (_FloatN *x, _FloatNpayload)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
int setpayloadsigfNx (_FloatNx *x, _FloatNxpayload)
math.h (TS 18661-3:2015):Setting and modifying single bits of FP values.
int setpayloadsigl (long double *x, long doublepayload)
math.h (ISO):Setting and modifying single bits of FP values.
int setpgid (pid_tpid, pid_tpgid)
unistd.h (POSIX.1):Process Group Functions.
int setpgrp (pid_tpid, pid_tpgid)
unistd.h (BSD):Process Group Functions.
int setpriority (intclass, intid, intniceval)
sys/resource.h (BSD):Functions For Traditional Scheduling.
sys/resource.h (POSIX):Functions For Traditional Scheduling.
void setprotoent (intstayopen)
netdb.h (BSD):Protocols Database.
void setpwent (void)
pwd.h (SVID):Scanning the List of All Users.
pwd.h (BSD):Scanning the List of All Users.
int setregid (gid_trgid, gid_tegid)
unistd.h (BSD):Setting the Group IDs.
int setreuid (uid_truid, uid_teuid)
unistd.h (BSD):Setting the User ID.
int setrlimit (intresource, const struct rlimit *rlp)
sys/resource.h (BSD):Limiting Resource Usage.
int setrlimit64 (intresource, const struct rlimit64 *rlp)
sys/resource.h (Unix98):Limiting Resource Usage.
void setservent (intstayopen)
netdb.h (BSD):The Services Database.
pid_t setsid (void)
unistd.h (POSIX.1):Process Group Functions.
int setsockopt (intsocket, intlevel, intoptname, const void *optval, socklen_toptlen)
sys/socket.h (BSD):Socket Option Functions.
char * setstate (char *state)
stdlib.h (BSD):BSD Random Number Functions.
int setstate_r (char *restrictstatebuf, struct random_data *restrictbuf)
stdlib.h (GNU):BSD Random Number Functions.
int settimeofday (const struct timeval *tp, const void *tzp)
sys/time.h (BSD):Setting and Adjusting the Time.
int setuid (uid_tnewuid)
unistd.h (POSIX.1):Setting the User ID.
void setutent (void)
utmp.h (SVID):Manipulating the User Accounting Database.
void setutxent (void)
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
int setvbuf (FILE *stream, char *buf, intmode, size_tsize)
stdio.h (ISO):Controlling Which Kind of Buffering.
struct sgttyb
termios.h (BSD):BSD Terminal Modes.
int shm_open (const char *name, intoflag, mode_tmode)
sys/mman.h (POSIX):Memory-mapped I/O.
int shutdown (intsocket, inthow)
sys/socket.h (BSD):Closing a Socket.
sig_atomic_t
signal.h (ISO):Atomic Types.
const char * sigabbrev_np (intsignum)
string.h (GNU):Signal Messages.
int sigaction (intsignum, const struct sigaction *restrictaction, struct sigaction *restrictold-action)
signal.h (POSIX.1):Advanced Signal Handling.
struct sigaction
signal.h (POSIX.1):Advanced Signal Handling.
int sigaddset (sigset_t *set, intsignum)
signal.h (POSIX.1):Signal Sets.
int sigaltstack (const stack_t *restrictstack, stack_t *restrictoldstack)
signal.h (XPG):Using a Separate Signal Stack.
int sigblock (intmask)
signal.h (BSD):BSD Signal Handling.
int sigdelset (sigset_t *set, intsignum)
signal.h (POSIX.1):Signal Sets.
const char * sigdescr_np (intsignum)
string.h (GNU):Signal Messages.
int sigemptyset (sigset_t *set)
signal.h (POSIX.1):Signal Sets.
int sigfillset (sigset_t *set)
signal.h (POSIX.1):Signal Sets.
sighandler_t
signal.h (GNU):Basic Signal Handling.
int siginterrupt (intsignum, intfailflag)
signal.h (XPG):BSD Signal Handling.
int sigismember (const sigset_t *set, intsignum)
signal.h (POSIX.1):Signal Sets.
sigjmp_buf
setjmp.h (POSIX.1):Non-Local Exits and Signals.
void siglongjmp (sigjmp_bufstate, intvalue)
setjmp.h (POSIX.1):Non-Local Exits and Signals.
int sigmask (intsignum)
signal.h (BSD):BSD Signal Handling.
sighandler_t signal (intsignum, sighandler_taction)
signal.h (ISO):Basic Signal Handling.
int signbit (float-typex)
math.h (ISO):Setting and modifying single bits of FP values.
double significand (doublex)
math.h (BSD):Normalization Functions.
float significandf (floatx)
math.h (BSD):Normalization Functions.
long double significandl (long doublex)
math.h (BSD):Normalization Functions.
int sigpause (intmask)
signal.h (BSD):BSD Signal Handling.
int sigpending (sigset_t *set)
signal.h (POSIX.1):Checking for Pending Signals.
int sigprocmask (inthow, const sigset_t *restrictset, sigset_t *restrictoldset)
signal.h (POSIX.1):Process Signal Mask.
sigset_t
signal.h (POSIX.1):Signal Sets.
int sigsetjmp (sigjmp_bufstate, intsavesigs)
setjmp.h (POSIX.1):Non-Local Exits and Signals.
int sigsetmask (intmask)
signal.h (BSD):BSD Signal Handling.
int sigstack (struct sigstack *stack, struct sigstack *oldstack)
signal.h (BSD):Using a Separate Signal Stack.
struct sigstack
signal.h (BSD):Using a Separate Signal Stack.
int sigsuspend (const sigset_t *set)
signal.h (POSIX.1):Usingsigsuspend
.
double sin (doublex)
math.h (ISO):Trigonometric Functions.
void sincos (doublex, double *sinx, double *cosx)
math.h (GNU):Trigonometric Functions.
void sincosf (floatx, float *sinx, float *cosx)
math.h (GNU):Trigonometric Functions.
_FloatN sincosfN (_FloatNx, _FloatN *sinx, _FloatN *cosx)
math.h (GNU):Trigonometric Functions.
_FloatNx sincosfNx (_FloatNxx, _FloatNx *sinx, _FloatNx *cosx)
math.h (GNU):Trigonometric Functions.
void sincosl (long doublex, long double *sinx, long double *cosx)
math.h (GNU):Trigonometric Functions.
float sinf (floatx)
math.h (ISO):Trigonometric Functions.
_FloatN sinfN (_FloatNx)
math.h (TS 18661-3:2015):Trigonometric Functions.
_FloatNx sinfNx (_FloatNxx)
math.h (TS 18661-3:2015):Trigonometric Functions.
double sinh (doublex)
math.h (ISO):Hyperbolic Functions.
float sinhf (floatx)
math.h (ISO):Hyperbolic Functions.
_FloatN sinhfN (_FloatNx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
_FloatNx sinhfNx (_FloatNxx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
long double sinhl (long doublex)
math.h (ISO):Hyperbolic Functions.
long double sinl (long doublex)
math.h (ISO):Trigonometric Functions.
double sinpi (doublex)
math.h (TS 18661-4:2015):Trigonometric Functions.
float sinpif (floatx)
math.h (TS 18661-4:2015):Trigonometric Functions.
_FloatN sinpifN (_FloatNx)
math.h (TS 18661-4:2015):Trigonometric Functions.
_FloatNx sinpifNx (_FloatNxx)
math.h (TS 18661-4:2015):Trigonometric Functions.
long double sinpil (long doublex)
math.h (TS 18661-4:2015):Trigonometric Functions.
size_t
stddef.h (ISO):Important Data Types.
unsigned int sleep (unsigned intseconds)
unistd.h (POSIX.1):Sleeping.
int snprintf (char *s, size_tsize, const char *template, …)
stdio.h (GNU):Formatted Output Functions.
struct sockaddr
sys/socket.h (BSD):Address Formats.
struct sockaddr_in
netinet/in.h (BSD):Internet Socket Address Formats.
struct sockaddr_un
sys/un.h (BSD):Details of Local Namespace.
int socket (intnamespace, intstyle, intprotocol)
sys/socket.h (BSD):Creating a Socket.
int socketpair (intnamespace, intstyle, intprotocol, intfiledes[2]
)
sys/socket.h (BSD):Socket Pairs.
speed_t
termios.h (POSIX.1):Line Speed.
int sprintf (char *s, const char *template, …)
stdio.h (ISO):Formatted Output Functions.
double sqrt (doublex)
math.h (ISO):Exponentiation and Logarithms.
float sqrtf (floatx)
math.h (ISO):Exponentiation and Logarithms.
_FloatN sqrtfN (_FloatNx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
_FloatNx sqrtfNx (_FloatNxx)
math.h (TS 18661-3:2015):Exponentiation and Logarithms.
long double sqrtl (long doublex)
math.h (ISO):Exponentiation and Logarithms.
void srand (unsigned intseed)
stdlib.h (ISO):ISO C Random Number Functions.
void srand48 (long intseedval)
stdlib.h (SVID):SVID Random Number Function.
int srand48_r (long intseedval, struct drand48_data *buffer)
stdlib.h (GNU):SVID Random Number Function.
void srandom (unsigned intseed)
stdlib.h (BSD):BSD Random Number Functions.
int srandom_r (unsigned intseed, struct random_data *buf)
stdlib.h (GNU):BSD Random Number Functions.
int sscanf (const char *s, const char *template, …)
stdio.h (ISO):Formatted Input Functions.
sighandler_t ssignal (intsignum, sighandler_taction)
signal.h (SVID):Basic Signal Handling.
ssize_t
unistd.h (POSIX.1):Input and Output Primitives.
stack_t
signal.h (XPG):Using a Separate Signal Stack.
int stat (const char *filename, struct stat *buf)
sys/stat.h (POSIX.1):Reading the Attributes of a File.
struct stat
sys/stat.h (POSIX.1):The meaning of the File Attributes.
int stat64 (const char *filename, struct stat64 *buf)
sys/stat.h (Unix98):Reading the Attributes of a File.
struct stat64
sys/stat.h (LFS):The meaning of the File Attributes.
unsigned char stdc_bit_ceil_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_bit_ceil_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned long int stdc_bit_ceil_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned long long int stdc_bit_ceil_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned short stdc_bit_ceil_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned char stdc_bit_floor_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_bit_floor_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned long int stdc_bit_floor_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned long long int stdc_bit_floor_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned short stdc_bit_floor_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_bit_width_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_bit_width_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_bit_width_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_bit_width_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_bit_width_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_count_ones_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_count_ones_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_count_ones_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_count_ones_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_count_ones_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_count_zeros_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_count_zeros_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_count_zeros_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_count_zeros_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_count_zeros_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_leading_one_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_leading_one_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_leading_one_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_leading_one_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_leading_one_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_leading_zero_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_leading_zero_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_leading_zero_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_leading_zero_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_leading_zero_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_trailing_one_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_trailing_one_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_trailing_one_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_trailing_one_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_trailing_one_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_trailing_zero_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_trailing_zero_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_trailing_zero_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_trailing_zero_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_first_trailing_zero_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
_Bool stdc_has_single_bit_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
_Bool stdc_has_single_bit_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
_Bool stdc_has_single_bit_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
_Bool stdc_has_single_bit_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
_Bool stdc_has_single_bit_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_leading_ones_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_leading_ones_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_leading_ones_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_leading_ones_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_leading_ones_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_leading_zeros_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_leading_zeros_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_leading_zeros_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_leading_zeros_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_leading_zeros_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_trailing_ones_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_trailing_ones_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_trailing_ones_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_trailing_ones_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_trailing_ones_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_trailing_zeros_uc (unsigned charx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_trailing_zeros_ui (unsigned intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_trailing_zeros_ul (unsigned long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_trailing_zeros_ull (unsigned long long intx)
stdbit.h (C23):Bit Manipulation.
unsigned int stdc_trailing_zeros_us (unsigned shortx)
stdbit.h (C23):Bit Manipulation.
FILE * stderr
stdio.h (ISO):Standard Streams.
FILE * stdin
stdio.h (ISO):Standard Streams.
FILE * stdout
stdio.h (ISO):Standard Streams.
int stime (const time_t *newtime)
time.h (SVID):Setting and Adjusting the Time.
time.h (XPG):Setting and Adjusting the Time.
char * stpcpy (char *restrictto, const char *restrictfrom)
string.h (Unknown origin):Copying Strings and Arrays.
char * stpncpy (char *restrictto, const char *restrictfrom, size_tsize)
string.h (GNU):Truncating Strings while Copying.
int strcasecmp (const char *s1, const char *s2)
string.h (BSD):String/Array Comparison.
char * strcasestr (const char *haystack, const char *needle)
string.h (GNU):Search Functions.
char * strcat (char *restrictto, const char *restrictfrom)
string.h (ISO):Concatenating Strings.
char * strchr (const char *string, intc)
string.h (ISO):Search Functions.
char * strchrnul (const char *string, intc)
string.h (GNU):Search Functions.
int strcmp (const char *s1, const char *s2)
string.h (ISO):String/Array Comparison.
int strcoll (const char *s1, const char *s2)
string.h (ISO):Collation Functions.
char * strcpy (char *restrictto, const char *restrictfrom)
string.h (ISO):Copying Strings and Arrays.
size_t strcspn (const char *string, const char *stopset)
string.h (ISO):Search Functions.
char * strdup (const char *s)
string.h (SVID):Copying Strings and Arrays.
char * strdupa (const char *s)
string.h (GNU):Copying Strings and Arrays.
char * strerror (interrnum)
string.h (ISO):Error Messages.
char * strerror_l (interrnum, locale_tlocale)
string.h (POSIX):Error Messages.
char * strerror_r (interrnum, char *buf, size_tn)
string.h (GNU):Error Messages.
int strerror_r (interrnum, char *buf, size_tn)
string.h (POSIX):Error Messages.
const char * strerrordesc_np (interrnum)
string.h (GNU):Error Messages.
const char * strerrorname_np (interrnum)
string.h (GNU):Error Messages.
int strfromd (char *restrictstring, size_tsize, const char *restrictformat, doublevalue)
stdlib.h (ISO/IEC TS 18661-1):Printing of Floats.
int strfromf (char *restrictstring, size_tsize, const char *restrictformat, floatvalue)
stdlib.h (ISO/IEC TS 18661-1):Printing of Floats.
int strfromfN (char *restrictstring, size_tsize, const char *restrictformat, _FloatNvalue)
stdlib.h (ISO/IEC TS 18661-3):Printing of Floats.
int strfromfNx (char *restrictstring, size_tsize, const char *restrictformat, _FloatNxvalue)
stdlib.h (ISO/IEC TS 18661-3):Printing of Floats.
int strfroml (char *restrictstring, size_tsize, const char *restrictformat, long doublevalue)
stdlib.h (ISO/IEC TS 18661-1):Printing of Floats.
char * strfry (char *string)
string.h (GNU):Shuffling Bytes.
size_t strftime (char *s, size_tsize, const char *template, const struct tm *brokentime)
time.h (ISO):Formatting Calendar Time.
size_t strftime_l (char *restricts, size_tsize, const char *restricttemplate, const struct tm *brokentime, locale_tlocale)
time.h (POSIX.1):Formatting Calendar Time.
size_t strlcat (char *restrictto, const char *restrictfrom, size_tsize)
string.h (POSIX-1.2024):Truncating Strings while Copying.
size_t strlcpy (char *restrictto, const char *restrictfrom, size_tsize)
string.h (POSIX-1.2024):Truncating Strings while Copying.
size_t strlen (const char *s)
string.h (ISO):String Length.
int strncasecmp (const char *s1, const char *s2, size_tn)
string.h (BSD):String/Array Comparison.
char * strncat (char *restrictto, const char *restrictfrom, size_tsize)
string.h (ISO):Truncating Strings while Copying.
int strncmp (const char *s1, const char *s2, size_tsize)
string.h (ISO):String/Array Comparison.
char * strncpy (char *restrictto, const char *restrictfrom, size_tsize)
string.h (C90):Truncating Strings while Copying.
char * strndup (const char *s, size_tsize)
string.h (GNU):Truncating Strings while Copying.
char * strndupa (const char *s, size_tsize)
string.h (GNU):Truncating Strings while Copying.
size_t strnlen (const char *s, size_tmaxlen)
string.h (POSIX.1):String Length.
char * strpbrk (const char *string, const char *stopset)
string.h (ISO):Search Functions.
char * strptime (const char *s, const char *fmt, struct tm *tp)
time.h (XPG4):Interpret string according to given format.
char * strrchr (const char *string, intc)
string.h (ISO):Search Functions.
char * strsep (char **string_ptr, const char *delimiter)
string.h (BSD):Finding Tokens in a String.
char * strsignal (intsignum)
string.h (GNU):Signal Messages.
size_t strspn (const char *string, const char *skipset)
string.h (ISO):Search Functions.
char * strstr (const char *haystack, const char *needle)
string.h (ISO):Search Functions.
double strtod (const char *restrictstring, char **restricttailptr)
stdlib.h (ISO):Parsing of Floats.
float strtof (const char *string, char **tailptr)
stdlib.h (ISO):Parsing of Floats.
_FloatN strtofN (const char *string, char **tailptr)
stdlib.h (ISO/IEC TS 18661-3):Parsing of Floats.
_FloatNx strtofNx (const char *string, char **tailptr)
stdlib.h (ISO/IEC TS 18661-3):Parsing of Floats.
intmax_t strtoimax (const char *restrictstring, char **restricttailptr, intbase)
inttypes.h (ISO):Parsing of Integers.
char * strtok (char *restrictnewstring, const char *restrictdelimiters)
string.h (ISO):Finding Tokens in a String.
char * strtok_r (char *newstring, const char *delimiters, char **save_ptr)
string.h (POSIX):Finding Tokens in a String.
long int strtol (const char *restrictstring, char **restricttailptr, intbase)
stdlib.h (ISO):Parsing of Integers.
long double strtold (const char *string, char **tailptr)
stdlib.h (ISO):Parsing of Floats.
long long int strtoll (const char *restrictstring, char **restricttailptr, intbase)
stdlib.h (ISO):Parsing of Integers.
long long int strtoq (const char *restrictstring, char **restricttailptr, intbase)
stdlib.h (BSD):Parsing of Integers.
unsigned long int strtoul (const char *restrictstring, char **restricttailptr, intbase)
stdlib.h (ISO):Parsing of Integers.
unsigned long long int strtoull (const char *restrictstring, char **restricttailptr, intbase)
stdlib.h (ISO):Parsing of Integers.
uintmax_t strtoumax (const char *restrictstring, char **restricttailptr, intbase)
inttypes.h (ISO):Parsing of Integers.
unsigned long long int strtouq (const char *restrictstring, char **restricttailptr, intbase)
stdlib.h (BSD):Parsing of Integers.
int strverscmp (const char *s1, const char *s2)
string.h (GNU):String/Array Comparison.
size_t strxfrm (char *restrictto, const char *restrictfrom, size_tsize)
string.h (ISO):Collation Functions.
int stty (intfiledes, const struct sgttyb *attributes)
sgtty.h (BSD):BSD Terminal Modes.
int swapcontext (ucontext_t *restrictoucp, const ucontext_t *restrictucp)
ucontext.h (SVID):Complete Context Control.
int swprintf (wchar_t *ws, size_tsize, const wchar_t *template, …)
wchar.h (GNU):Formatted Output Functions.
int swscanf (const wchar_t *ws, const wchar_t *template, …)
wchar.h (ISO):Formatted Input Functions.
int symlink (const char *oldname, const char *newname)
unistd.h (BSD):Symbolic Links.
void sync (void)
unistd.h (X/Open):Synchronizing I/O operations.
long int syscall (long intsysno, …)
unistd.h (???):System Calls.
long int sysconf (intparameter)
unistd.h (POSIX.1):Definition ofsysconf
.
void syslog (intfacility_priority, const char *format, …)
syslog.h (BSD):syslog, vsyslog.
int system (const char *command)
stdlib.h (ISO):Running a Command.
sighandler_t sysv_signal (intsignum, sighandler_taction)
signal.h (GNU):Basic Signal Handling.
double tan (doublex)
math.h (ISO):Trigonometric Functions.
float tanf (floatx)
math.h (ISO):Trigonometric Functions.
_FloatN tanfN (_FloatNx)
math.h (TS 18661-3:2015):Trigonometric Functions.
_FloatNx tanfNx (_FloatNxx)
math.h (TS 18661-3:2015):Trigonometric Functions.
double tanh (doublex)
math.h (ISO):Hyperbolic Functions.
float tanhf (floatx)
math.h (ISO):Hyperbolic Functions.
_FloatN tanhfN (_FloatNx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
_FloatNx tanhfNx (_FloatNxx)
math.h (TS 18661-3:2015):Hyperbolic Functions.
long double tanhl (long doublex)
math.h (ISO):Hyperbolic Functions.
long double tanl (long doublex)
math.h (ISO):Trigonometric Functions.
double tanpi (doublex)
math.h (TS 18661-4:2015):Trigonometric Functions.
float tanpif (floatx)
math.h (TS 18661-4:2015):Trigonometric Functions.
_FloatN tanpifN (_FloatNx)
math.h (TS 18661-4:2015):Trigonometric Functions.
_FloatNx tanpifNx (_FloatNxx)
math.h (TS 18661-4:2015):Trigonometric Functions.
long double tanpil (long doublex)
math.h (TS 18661-4:2015):Trigonometric Functions.
int tcdrain (intfiledes)
termios.h (POSIX.1):Line Control Functions.
tcflag_t
termios.h (POSIX.1):Terminal Mode Data Types.
int tcflow (intfiledes, intaction)
termios.h (POSIX.1):Line Control Functions.
int tcflush (intfiledes, intqueue)
termios.h (POSIX.1):Line Control Functions.
int tcgetattr (intfiledes, struct termios *termios-p)
termios.h (POSIX.1):Terminal Mode Functions.
pid_t tcgetpgrp (intfiledes)
unistd.h (POSIX.1):Functions for Controlling Terminal Access.
pid_t tcgetsid (intfildes)
termios.h (Unix98):Functions for Controlling Terminal Access.
int tcsendbreak (intfiledes, intduration)
termios.h (POSIX.1):Line Control Functions.
int tcsetattr (intfiledes, intwhen, const struct termios *termios-p)
termios.h (POSIX.1):Terminal Mode Functions.
int tcsetpgrp (intfiledes, pid_tpgid)
unistd.h (POSIX.1):Functions for Controlling Terminal Access.
void * tdelete (const void *key, void **rootp, comparison_fn_tcompar)
search.h (SVID):Thetsearch
function..
void tdestroy (void *vroot, __free_fn_tfreefct)
search.h (GNU):Thetsearch
function..
long int telldir (DIR *dirstream)
dirent.h (BSD):Random Access in a Directory Stream.
char * tempnam (const char *dir, const char *prefix)
stdio.h (SVID):Temporary Files.
struct termios
termios.h (POSIX.1):Terminal Mode Data Types.
char * textdomain (const char *domainname)
libintl.h (POSIX-1.2024):How to determine which catalog to be used.
void * tfind (const void *key, void *const *rootp, comparison_fn_tcompar)
search.h (SVID):Thetsearch
function..
double tgamma (doublex)
math.h (XPG):Special Functions.
math.h (ISO):Special Functions.
float tgammaf (floatx)
math.h (XPG):Special Functions.
math.h (ISO):Special Functions.
_FloatN tgammafN (_FloatNx)
math.h (TS 18661-3:2015):Special Functions.
_FloatNx tgammafNx (_FloatNxx)
math.h (TS 18661-3:2015):Special Functions.
long double tgammal (long doublex)
math.h (XPG):Special Functions.
math.h (ISO):Special Functions.
int tgkill (pid_tpid, pid_ttid, intsignum)
signal.h (Linux):Signaling Another Process.
thrd_busy
threads.h (C11):Return Values.
int thrd_create (thrd_t *thr, thrd_start_tfunc, void *arg)
threads.h (C11):Creation and Control.
thrd_t thrd_current (void)
threads.h (C11):Creation and Control.
int thrd_detach (thrd_tthr)
threads.h (C11):Creation and Control.
int thrd_equal (thrd_tlhs, thrd_trhs)
threads.h (C11):Creation and Control.
thrd_error
threads.h (C11):Return Values.
_Noreturn void thrd_exit (intres)
threads.h (C11):Creation and Control.
int thrd_join (thrd_tthr, int *res)
threads.h (C11):Creation and Control.
thrd_nomem
threads.h (C11):Return Values.
int thrd_sleep (const struct timespec *time_point, struct timespec *remaining)
threads.h (C11):Creation and Control.
thrd_start_t
threads.h (C11):Creation and Control.
thrd_success
threads.h (C11):Return Values.
thrd_t
threads.h (C11):Creation and Control.
thrd_timedout
threads.h (C11):Return Values.
void thrd_yield (void)
threads.h (C11):Creation and Control.
thread_local
threads.h (C11):Thread-local Storage.
time_t time (time_t *result)
time.h (ISO):Getting the Time.
time_t
time.h (ISO):Time Types.
time_t timegm (struct tm *brokentime)
time.h (ISO):Broken-down Time.
time_t timelocal (struct tm *brokentime)
time.h (???):Broken-down Time.
clock_t times (struct tms *buffer)
sys/times.h (POSIX.1):Processor Time Inquiry.
struct timespec
time.h (POSIX.1):Time Types.
int timespec_get (struct timespec *ts, intbase)
time.h (ISO):Getting the Time.
int timespec_getres (struct timespec *res, intbase)
time.h (ISO):Getting the Time.
struct timeval
sys/time.h (BSD):Time Types.
long int timezone
time.h (POSIX.1):State Variables for Time Zones.
struct tm
time.h (ISO):Time Types.
time.h (ISO):Broken-down Time.
FILE * tmpfile (void)
stdio.h (ISO):Temporary Files.
FILE * tmpfile64 (void)
stdio.h (Unix98):Temporary Files.
char * tmpnam (char *result)
stdio.h (ISO):Temporary Files.
char * tmpnam_r (char *result)
stdio.h (GNU):Temporary Files.
struct tms
sys/times.h (POSIX.1):Processor Time Inquiry.
int toascii (intc)
ctype.h (SVID):Case Conversion.
ctype.h (BSD):Case Conversion.
int tolower (intc)
ctype.h (ISO):Case Conversion.
int totalorder (const double *x, const double *y)
math.h (TS 18661-1:2014):Floating-Point Comparison Functions.
int totalorderf (const float *x, const float *y)
math.h (TS 18661-1:2014):Floating-Point Comparison Functions.
int totalorderfN (const _FloatN *x, const _FloatN *y)
math.h (TS 18661-3:2015):Floating-Point Comparison Functions.
int totalorderfNx (const _FloatNx *x, const _FloatNx *y)
math.h (TS 18661-3:2015):Floating-Point Comparison Functions.
int totalorderl (const long double *x, const long double *y)
math.h (TS 18661-1:2014):Floating-Point Comparison Functions.
int totalordermag (const double *x, const double *y)
math.h (TS 18661-1:2014):Floating-Point Comparison Functions.
int totalordermagf (const float *x, const float *y)
math.h (TS 18661-1:2014):Floating-Point Comparison Functions.
int totalordermagfN (const _FloatN *x, const _FloatN *y)
math.h (TS 18661-3:2015):Floating-Point Comparison Functions.
int totalordermagfNx (const _FloatNx *x, const _FloatNx *y)
math.h (TS 18661-3:2015):Floating-Point Comparison Functions.
int totalordermagl (const long double *x, const long double *y)
math.h (TS 18661-1:2014):Floating-Point Comparison Functions.
int toupper (intc)
ctype.h (ISO):Case Conversion.
wint_t towctrans (wint_twc, wctrans_tdesc)
wctype.h (ISO):Mapping of wide characters..
wint_t towlower (wint_twc)
wctype.h (ISO):Mapping of wide characters..
wint_t towupper (wint_twc)
wctype.h (ISO):Mapping of wide characters..
double trunc (doublex)
math.h (ISO):Rounding Functions.
int truncate (const char *filename, off_tlength)
unistd.h (X/Open):File Size.
int truncate64 (const char *name, off64_tlength)
unistd.h (Unix98):File Size.
float truncf (floatx)
math.h (ISO):Rounding Functions.
_FloatN truncfN (_FloatNx)
math.h (TS 18661-3:2015):Rounding Functions.
_FloatNx truncfNx (_FloatNxx)
math.h (TS 18661-3:2015):Rounding Functions.
long double truncl (long doublex)
math.h (ISO):Rounding Functions.
void * tsearch (const void *key, void **rootp, comparison_fn_tcompar)
search.h (SVID):Thetsearch
function..
int tss_create (tss_t *tss_key, tss_dtor_tdestructor)
threads.h (C11):Thread-local Storage.
void tss_delete (tss_ttss_key)
threads.h (C11):Thread-local Storage.
tss_dtor_t
threads.h (C11):Thread-local Storage.
void * tss_get (tss_ttss_key)
threads.h (C11):Thread-local Storage.
int tss_set (tss_ttss_key, void *val)
threads.h (C11):Thread-local Storage.
tss_t
threads.h (C11):Thread-local Storage.
char * ttyname (intfiledes)
unistd.h (POSIX.1):Identifying Terminals.
int ttyname_r (intfiledes, char *buf, size_tlen)
unistd.h (POSIX.1):Identifying Terminals.
void twalk (const void *root, __action_fn_taction)
search.h (SVID):Thetsearch
function..
void twalk_r (const void *root, void (*action) (const void *key, VISITwhich, void *closure), void *closure)
search.h (GNU):Thetsearch
function..
char * tzname [2]
time.h (POSIX.1):State Variables for Time Zones.
void tzset (void)
time.h (POSIX.1):State Variables for Time Zones.
unsigned int uabs (intnumber)
stdlib.h (ISO):Absolute Value.
ucontext_t
ucontext.h (SVID):Complete Context Control.
uintmax_t ufromfp (doublex, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
uintmax_t ufromfpf (floatx, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
uintmax_t ufromfpfN (_FloatNx, intround, unsigned intwidth)
math.h (TS 18661-3:2015):Rounding Functions.
uintmax_t ufromfpfNx (_FloatNxx, intround, unsigned intwidth)
math.h (TS 18661-3:2015):Rounding Functions.
uintmax_t ufromfpl (long doublex, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
uintmax_t ufromfpx (doublex, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
uintmax_t ufromfpxf (floatx, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
uintmax_t ufromfpxfN (_FloatNx, intround, unsigned intwidth)
math.h (TS 18661-3:2015):Rounding Functions.
uintmax_t ufromfpxfNx (_FloatNxx, intround, unsigned intwidth)
math.h (TS 18661-3:2015):Rounding Functions.
uintmax_t ufromfpxl (long doublex, intround, unsigned intwidth)
math.h (ISO):Rounding Functions.
uid_t
sys/types.h (POSIX.1):Reading the Persona of a Process.
uintmax_t uimaxabs (intmax_tnumber)
inttypes.h (ISO):Absolute Value.
unsigned long int ulabs (long intnumber)
stdlib.h (ISO):Absolute Value.
long int ulimit (intcmd, …)
ulimit.h (BSD):Limiting Resource Usage.
unsigned long long int ullabs (long long intnumber)
stdlib.h (ISO):Absolute Value.
mode_t umask (mode_tmask)
sys/stat.h (POSIX.1):Assigning File Permissions.
int umount (const char *file)
sys/mount.h (SVID):Mount, Unmount, Remount.
sys/mount.h (GNU):Mount, Unmount, Remount.
int umount2 (const char *file, intflags)
sys/mount.h (GNU):Mount, Unmount, Remount.
int uname (struct utsname *info)
sys/utsname.h (POSIX.1):Platform Type Identification.
int ungetc (intc, FILE *stream)
stdio.h (ISO):Usingungetc
To Do Unreading.
wint_t ungetwc (wint_twc, FILE *stream)
wchar.h (ISO):Usingungetc
To Do Unreading.
int unlink (const char *filename)
unistd.h (POSIX.1):Deleting Files.
int unlinkat (intfiledes, const char *filename, intflags)
unistd.h (POSIX.1-2008):Deleting Files.
int unlockpt (intfiledes)
stdlib.h (SVID):Allocating Pseudo-Terminals.
stdlib.h (XPG4.2):Allocating Pseudo-Terminals.
int unsetenv (const char *name)
stdlib.h (BSD):Environment Access.
void updwtmp (const char *wtmp_file, const struct utmp *utmp)
utmp.h (SVID):Manipulating the User Accounting Database.
struct utimbuf
utime.h (POSIX.1):File Times.
int utime (const char *filename, const struct utimbuf *times)
utime.h (POSIX.1):File Times.
int utimensat (intfiledes, const char *filename, const struct timespectsp[2]
, intflags)
sys/stat.h (POSIX.1-2008):File Times.
int utimes (const char *filename, const struct timevaltvp[2]
)
sys/time.h (BSD):File Times.
int utmpname (const char *file)
utmp.h (SVID):Manipulating the User Accounting Database.
int utmpxname (const char *file)
utmpx.h (XPG4.2):XPG User Accounting Database Functions.
struct utsname
sys/utsname.h (POSIX.1):Platform Type Identification.
type va_arg (va_listap,type)
stdarg.h (ISO):Argument Access Macros.
void va_copy (va_listdest, va_listsrc)
stdarg.h (C99):Argument Access Macros.
void va_end (va_listap)
stdarg.h (ISO):Argument Access Macros.
va_list
stdarg.h (ISO):Argument Access Macros.
void va_start (va_listap,last-required)
stdarg.h (ISO):Argument Access Macros.
void * valloc (size_tsize)
malloc.h (BSD):Allocating Aligned Memory Blocks.
stdlib.h (BSD):Allocating Aligned Memory Blocks.
int vasprintf (char **ptr, const char *template, va_listap)
stdio.h (GNU):Variable Arguments Output Functions.
int vdprintf (intfd, const char *template, va_listap)
stdio.h (POSIX):Variable Arguments Output Functions.
void verr (intstatus, const char *format, va_listap)
err.h (BSD):Error Messages.
void verrx (intstatus, const char *format, va_listap)
err.h (BSD):Error Messages.
int versionsort (const struct dirent **a, const struct dirent **b)
dirent.h (GNU):Scanning the Content of a Directory.
int versionsort64 (const struct dirent64 **a, const struct dirent64 **b)
dirent.h (GNU):Scanning the Content of a Directory.
pid_t vfork (void)
unistd.h (BSD):Creating a Process.
int vfprintf (FILE *stream, const char *template, va_listap)
stdio.h (ISO):Variable Arguments Output Functions.
int vfscanf (FILE *stream, const char *template, va_listap)
stdio.h (ISO):Variable Arguments Input Functions.
int vfwprintf (FILE *stream, const wchar_t *template, va_listap)
wchar.h (ISO):Variable Arguments Output Functions.
int vfwscanf (FILE *stream, const wchar_t *template, va_listap)
wchar.h (ISO):Variable Arguments Input Functions.
int vlimit (intresource, intlimit)
sys/vlimit.h (BSD):Limiting Resource Usage.
int vprintf (const char *template, va_listap)
stdio.h (ISO):Variable Arguments Output Functions.
int vscanf (const char *template, va_listap)
stdio.h (ISO):Variable Arguments Input Functions.
int vsnprintf (char *s, size_tsize, const char *template, va_listap)
stdio.h (GNU):Variable Arguments Output Functions.
int vsprintf (char *s, const char *template, va_listap)
stdio.h (ISO):Variable Arguments Output Functions.
int vsscanf (const char *s, const char *template, va_listap)
stdio.h (ISO):Variable Arguments Input Functions.
int vswprintf (wchar_t *ws, size_tsize, const wchar_t *template, va_listap)
wchar.h (GNU):Variable Arguments Output Functions.
int vswscanf (const wchar_t *s, const wchar_t *template, va_listap)
wchar.h (ISO):Variable Arguments Input Functions.
void vsyslog (intfacility_priority, const char *format, va_listarglist)
syslog.h (BSD):syslog, vsyslog.
void vwarn (const char *format, va_listap)
err.h (BSD):Error Messages.
void vwarnx (const char *format, va_listap)
err.h (BSD):Error Messages.
int vwprintf (const wchar_t *template, va_listap)
wchar.h (ISO):Variable Arguments Output Functions.
int vwscanf (const wchar_t *template, va_listap)
wchar.h (ISO):Variable Arguments Input Functions.
pid_t wait (int *status-ptr)
sys/wait.h (POSIX.1):Process Completion.
pid_t wait3 (int *status-ptr, intoptions, struct rusage *usage)
sys/wait.h (BSD):BSD Process Wait Function.
pid_t wait4 (pid_tpid, int *status-ptr, intoptions, struct rusage *usage)
sys/wait.h (BSD):Process Completion.
pid_t waitpid (pid_tpid, int *status-ptr, intoptions)
sys/wait.h (POSIX.1):Process Completion.
void warn (const char *format, …)
err.h (BSD):Error Messages.
void warnx (const char *format, …)
err.h (BSD):Error Messages.
wchar_t
stddef.h (ISO):Introduction to Extended Characters.
wchar_t * wcpcpy (wchar_t *restrictwto, const wchar_t *restrictwfrom)
wchar.h (GNU):Copying Strings and Arrays.
wchar_t * wcpncpy (wchar_t *restrictwto, const wchar_t *restrictwfrom, size_tsize)
wchar.h (GNU):Truncating Strings while Copying.
size_t wcrtomb (char *restricts, wchar_twc, mbstate_t *restrictps)
wchar.h (ISO):Converting Single Characters.
int wcscasecmp (const wchar_t *ws1, const wchar_t *ws2)
wchar.h (GNU):String/Array Comparison.
wchar_t * wcscat (wchar_t *restrictwto, const wchar_t *restrictwfrom)
wchar.h (ISO):Concatenating Strings.
wchar_t * wcschr (const wchar_t *wstring, wchar_twc)
wchar.h (ISO):Search Functions.
wchar_t * wcschrnul (const wchar_t *wstring, wchar_twc)
wchar.h (GNU):Search Functions.
int wcscmp (const wchar_t *ws1, const wchar_t *ws2)
wchar.h (ISO):String/Array Comparison.
int wcscoll (const wchar_t *ws1, const wchar_t *ws2)
wchar.h (ISO):Collation Functions.
wchar_t * wcscpy (wchar_t *restrictwto, const wchar_t *restrictwfrom)
wchar.h (ISO):Copying Strings and Arrays.
size_t wcscspn (const wchar_t *wstring, const wchar_t *stopset)
wchar.h (ISO):Search Functions.
wchar_t * wcsdup (const wchar_t *ws)
wchar.h (GNU):Copying Strings and Arrays.
size_t wcsftime (wchar_t *s, size_tsize, const wchar_t *template, const struct tm *brokentime)
time.h (ISO):Formatting Calendar Time.
size_t wcslcat (wchar_t *restrictto, const wchar_t *restrictfrom, size_tsize)
string.h (POSIX.1-2024):Truncating Strings while Copying.
size_t wcslcpy (wchar_t *restrictto, const wchar_t *restrictfrom, size_tsize)
string.h (POSIX.1-2024):Truncating Strings while Copying.
size_t wcslen (const wchar_t *ws)
wchar.h (ISO):String Length.
int wcsncasecmp (const wchar_t *ws1, const wchar_t *s2, size_tn)
wchar.h (GNU):String/Array Comparison.
wchar_t * wcsncat (wchar_t *restrictwto, const wchar_t *restrictwfrom, size_tsize)
wchar.h (ISO):Truncating Strings while Copying.
int wcsncmp (const wchar_t *ws1, const wchar_t *ws2, size_tsize)
wchar.h (ISO):String/Array Comparison.
wchar_t * wcsncpy (wchar_t *restrictwto, const wchar_t *restrictwfrom, size_tsize)
wchar.h (ISO):Truncating Strings while Copying.
size_t wcsnlen (const wchar_t *ws, size_tmaxlen)
wchar.h (GNU):String Length.
size_t wcsnrtombs (char *restrictdst, const wchar_t **restrictsrc, size_tnwc, size_tlen, mbstate_t *restrictps)
wchar.h (GNU):Converting Multibyte and Wide Character Strings.
wchar_t * wcspbrk (const wchar_t *wstring, const wchar_t *stopset)
wchar.h (ISO):Search Functions.
wchar_t * wcsrchr (const wchar_t *wstring, wchar_twc)
wchar.h (ISO):Search Functions.
size_t wcsrtombs (char *restrictdst, const wchar_t **restrictsrc, size_tlen, mbstate_t *restrictps)
wchar.h (ISO):Converting Multibyte and Wide Character Strings.
size_t wcsspn (const wchar_t *wstring, const wchar_t *skipset)
wchar.h (ISO):Search Functions.
wchar_t * wcsstr (const wchar_t *haystack, const wchar_t *needle)
wchar.h (ISO):Search Functions.
double wcstod (const wchar_t *restrictstring, wchar_t **restricttailptr)
wchar.h (ISO):Parsing of Floats.
float wcstof (const wchar_t *string, wchar_t **tailptr)
wchar.h (ISO):Parsing of Floats.
_FloatN wcstofN (const wchar_t *string, wchar_t **tailptr)
wchar.h (GNU):Parsing of Floats.
_FloatNx wcstofNx (const wchar_t *string, wchar_t **tailptr)
wchar.h (GNU):Parsing of Floats.
intmax_t wcstoimax (const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
wchar.h (ISO):Parsing of Integers.
wchar_t * wcstok (wchar_t *newstring, const wchar_t *delimiters, wchar_t **save_ptr)
wchar.h (ISO):Finding Tokens in a String.
long int wcstol (const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
wchar.h (ISO):Parsing of Integers.
long double wcstold (const wchar_t *string, wchar_t **tailptr)
wchar.h (ISO):Parsing of Floats.
long long int wcstoll (const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
wchar.h (ISO):Parsing of Integers.
size_t wcstombs (char *string, const wchar_t *wstring, size_tsize)
stdlib.h (ISO):Non-reentrant Conversion of Strings.
long long int wcstoq (const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
wchar.h (GNU):Parsing of Integers.
unsigned long int wcstoul (const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
wchar.h (ISO):Parsing of Integers.
unsigned long long int wcstoull (const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
wchar.h (ISO):Parsing of Integers.
uintmax_t wcstoumax (const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
wchar.h (ISO):Parsing of Integers.
unsigned long long int wcstouq (const wchar_t *restrictstring, wchar_t **restricttailptr, intbase)
wchar.h (GNU):Parsing of Integers.
wchar_t * wcswcs (const wchar_t *haystack, const wchar_t *needle)
wchar.h (XPG):Search Functions.
size_t wcsxfrm (wchar_t *restrictwto, const wchar_t *wfrom, size_tsize)
wchar.h (ISO):Collation Functions.
int wctob (wint_tc)
wchar.h (ISO):Converting Single Characters.
int wctomb (char *string, wchar_twchar)
stdlib.h (ISO):Non-reentrant Conversion of Single Characters.
wctrans_t wctrans (const char *property)
wctype.h (ISO):Mapping of wide characters..
wctrans_t
wctype.h (ISO):Mapping of wide characters..
wctype_t wctype (const char *property)
wctype.h (ISO):Character class determination for wide characters.
wctype_t
wctype.h (ISO):Character class determination for wide characters.
wint_t
wchar.h (ISO):Introduction to Extended Characters.
wchar_t * wmemchr (const wchar_t *block, wchar_twc, size_tsize)
wchar.h (ISO):Search Functions.
int wmemcmp (const wchar_t *a1, const wchar_t *a2, size_tsize)
wchar.h (ISO):String/Array Comparison.
wchar_t * wmemcpy (wchar_t *restrictwto, const wchar_t *restrictwfrom, size_tsize)
wchar.h (ISO):Copying Strings and Arrays.
wchar_t * wmemmove (wchar_t *wto, const wchar_t *wfrom, size_tsize)
wchar.h (ISO):Copying Strings and Arrays.
wchar_t * wmempcpy (wchar_t *restrictwto, const wchar_t *restrictwfrom, size_tsize)
wchar.h (GNU):Copying Strings and Arrays.
wchar_t * wmemset (wchar_t *block, wchar_twc, size_tsize)
wchar.h (ISO):Copying Strings and Arrays.
int wordexp (const char *words, wordexp_t *word-vector-ptr, intflags)
wordexp.h (POSIX.2):Callingwordexp
.
wordexp_t
wordexp.h (POSIX.2):Callingwordexp
.
void wordfree (wordexp_t *word-vector-ptr)
wordexp.h (POSIX.2):Callingwordexp
.
int wprintf (const wchar_t *template, …)
wchar.h (ISO):Formatted Output Functions.
ssize_t write (intfiledes, const void *buffer, size_tsize)
unistd.h (POSIX.1):Input and Output Primitives.
ssize_t writev (intfiledes, const struct iovec *vector, intcount)
sys/uio.h (BSD):Fast Scatter-Gather I/O.
int wscanf (const wchar_t *template, …)
wchar.h (ISO):Formatted Input Functions.
double y0 (doublex)
math.h (SVID):Special Functions.
float y0f (floatx)
math.h (SVID):Special Functions.
_FloatN y0fN (_FloatNx)
math.h (GNU):Special Functions.
_FloatNx y0fNx (_FloatNxx)
math.h (GNU):Special Functions.
long double y0l (long doublex)
math.h (SVID):Special Functions.
double y1 (doublex)
math.h (SVID):Special Functions.
float y1f (floatx)
math.h (SVID):Special Functions.
_FloatN y1fN (_FloatNx)
math.h (GNU):Special Functions.
_FloatNx y1fNx (_FloatNxx)
math.h (GNU):Special Functions.
long double y1l (long doublex)
math.h (SVID):Special Functions.
double yn (intn, doublex)
math.h (SVID):Special Functions.
float ynf (intn, floatx)
math.h (SVID):Special Functions.
_FloatN ynfN (intn, _FloatNx)
math.h (GNU):Special Functions.
_FloatNx ynfNx (intn, _FloatNxx)
math.h (GNU):Special Functions.
long double ynl (intn, long doublex)
math.h (SVID):Special Functions.
Next:Library Maintenance, Previous:Summary of Library Facilities, Up:Main Menu [Contents][Index]
Before you do anything else, you should read the FAQ athttps://sourceware.org/glibc/wiki/FAQ. It answers commonquestions and describes problems you may experience with compilationand installation.
You will need recent versions of several GNU tools: definitely GCC andGNU Make, and possibly others. SeeRecommended Tools for Compilation, below.
The GNU C Library cannot be compiled in the source directory. You must buildit in a separate build directory. For example, if you have unpackedthe GNU C Library sources in/src/gnu/glibc-version,create a directory/src/gnu/glibc-build to put the object files in. This allowsremoving the whole build directory in case an error occurs, which isthe safest way to get a fresh start and should always be done.
From your object directory, run the shell scriptconfigure locatedat the top level of the source tree. In the scenario above, you’d type
$ ../glibc-version/configureargs...
Please note that even though you’re building in a separate builddirectory, the compilation may need to create or modify files anddirectories in the source directory.
configure
takes many options, but the only one that is usuallymandatory is ‘--prefix’. This option tellsconfigure
where you want the GNU C Library installed. This defaults to/usr/local,but the normal setting to install as the standard system library is‘--prefix=/usr’ for GNU/Linux systems and ‘--prefix=’ (anempty prefix) for GNU/Hurd systems.
It may also be useful to pass ‘CC=compiler’ andCFLAGS=flags
arguments toconfigure
.CC
selects the C compiler that will be used, andCFLAGS
setsoptimization options for the compiler. Any compiler options requiredfor all compilations, such as options selecting an ABI or a processorfor which to generate code, should be included inCC
. Optionsthat may be overridden by the GNU C Library build system for particularfiles, such as for optimization and debugging, should go inCFLAGS
. The default value ofCFLAGS
is ‘-g -O2’,and the GNU C Library cannot be compiled without optimization, so ifCFLAGS
is specified it must enable optimization. For example:
$ ../glibc-version/configure CC="gcc -m32" CFLAGS="-O3"
To test the GNU C Library with a different set of C and C++ compilers,‘TEST_CC=compiler’ and ‘TEST_CXX=compiler’arguments can be passed toconfigure
. For example:
$ ../glibc-version/configure TEST_CC="gcc-6.4.1" TEST_CXX="g++-6.4.1"
The following list describes all of the available options forconfigure
:
Install machine-independent data files in subdirectories ofdirectory. The default is to install in/usr/local.
Install the library and other machine-dependent files in subdirectoriesofdirectory. The default is to the ‘--prefix’directory if that option is specified, or/usr/local otherwise.
Look for kernel header files indirectory, not/usr/include. The GNU C Library needs information from the kernel’s headerfiles describing the interface to the kernel. The GNU C Library will normallylook in/usr/include for them,but if you specify this option, it will look inDIRECTORY instead.
This option is primarily of use on a system where the headers in/usr/include come from an older version of the GNU C Library. Conflicts canoccasionally happen in this case. You can also use this option if you want tocompile the GNU C Library with a newer set of kernel headers than the ones found in/usr/include.
This option is currently only useful on GNU/Linux systems. Theversion parameter should have the form X.Y.Z and describes thesmallest version of the Linux kernel the generated library is expectedto support. The higher theversion number is, the lesscompatibility code is added, and the faster the code gets.
Use the binutils (assembler and linker) indirectory, notthe ones the C compiler would default to. You can use this option ifthe default binutils on your system cannot deal with all the constructsin the GNU C Library. In that case,configure
will detect theproblem and suppress these constructs, so that the library will still beusable, but functionality may be lost—for example, you can’t build ashared libc with old binutils.
Use additional compiler flagscflags to build the parts of thelibrary which are always statically linked into applications andlibraries even with shared linking (that is, the object files containedinlib*_nonshared.a libraries). The build process willautomatically use the appropriate flags, but this option can be used toset additional flags required for building applications and libraries,to match local policy. For example, if such a policy requires that allcode linked into applications must be built with source fortification,‘--with-nonshared-cflags=-Wp,-D_FORTIFY_SOURCE=2’ will make surethat the objects inlibc_nonshared.a are compiled with this flag(although this will not affect the generated code in this particularcase and potentially change debugging information and metadata only).
Use additional compiler flagscflags to build the early startupcode of the dynamic linker. These flags can be used to enable earlydynamic linker diagnostics to run on CPUs which are not compatible withthe rest of the GNU C Library, for example, due to compiler flags which targeta later instruction set architecture (ISA).
Specify an integerNUM to scale the timeout of test programs.This factor can be changed at run time usingTIMEOUTFACTOR
environment variable.
Don’t build shared libraries even if it is possible. Not all systemssupport shared libraries; you need ELF support and (currently) the GNUlinker.
Don’t build glibc programs and the testsuite as position independentexecutables (PIE). By default, glibc programs and tests are created asposition independent executables on targets that support it. If the toolchainand architecture support it, static executables are built as static PIE and theresulting glibc can be used with the GCC option, -static-pie, which isavailable with GCC 8 or above, to create static PIE.
Enable Intel Control-flow Enforcement Technology (CET) support. Whenthe GNU C Library is built with--enable-cet or--enable-cet=permissive, the resulting libraryis protected with indirect branch tracking (IBT) and shadow stack(SHSTK). When CET is enabled, the GNU C Library is compatible with allexisting executables and shared libraries. This feature is currentlysupported on x86_64 and x32 with GCC 8 and binutils 2.29 or later.With--enable-cet, it is an error to dlopen a non CETenabled shared library in CET enabled application. With--enable-cet=permissive, CET is disabled when dlopening anon CET enabled shared library in CET enabled application.
NOTE:--enable-cet is only supported on x86_64 and x32.
Enable memory tagging support if the architecture supports it. Whenthe GNU C Library is built with this option then the resulting library willbe able to control the use of tagged memory when hardware support ispresent by use of the tunable ‘glibc.mem.tagging’. This includesthe generation of tagged memory when using themalloc
APIs.
At present only AArch64 platforms with MTE provide this functionality,although the library will still operate (without memory tagging) onolder versions of the architecture.
The default is to disable support for memory tagging.
Don’t build libraries with profiling information. You may want to usethis option if you don’t plan to do profiling.
Compile static versions of the NSS (Name Service Switch) libraries.This is not recommended because it defeats the purpose of NSS; a programlinked statically with the NSS libraries cannot be dynamicallyreconfigured to use a different name database.
By default, dynamic tests are linked to run with the installed C library.This option hardcodes the newly built C library path in dynamic testsso that they can be invoked directly.
By default, time zone related utilities (zic
,zdump
,andtzselect
) are installed with the GNU C Library. If you are buildingthese independently (e.g. by using the ‘tzcode’ package), then thisoption will allow disabling the install of these.
Note that you need to make sure the external tools are kept in sync withthe versions that the GNU C Library expects as the data formats may change overtime. Consult thetimezone subdirectory for more details.
Compile the C library and all other parts of the glibc package(including the threading and math libraries, NSS modules, andtransliteration modules) using the GCC-fstack-protector,-fstack-protector-strong or-fstack-protector-alloptions to detect stack overruns. Only the dynamic linker and a smallnumber of routines called directly from assembler are excluded from thisprotection.
Disable lazy binding for installed shared objects and programs. Thisprovides additional security hardening because it enables full RELROand a read-only global offset table (GOT), at the cost of slightlyincreased program load times.
The filept_chown is a helper binary forgrantpt
(seePseudo-Terminals) that is installed setuid root tofix up pseudo-terminal ownership on GNU/Hurd. It is not required onGNU/Linux, and the GNU C Library will not use the installedpt_chownprogram when configured with--enable-pt_chown.
By default, the GNU C Library is built with-Werror. If you wishto build without this option (for example, if building with a newerversion of GCC than this version of the GNU C Library was tested with, sonew warnings cause the build with-Werror to fail), you canconfigure with--disable-werror.
By default for x86_64, the GNU C Library is built with the vector math library.Use this option to disable the vector math library.
By default, if the C++ toolchain lacks support for static linking,configure fails to find the C++ header files and the glibc build fails.--disable-static-c++-link-check allows the glibc build to finish,but static C++ tests will fail if the C++ toolchain doesn’t have thenecessary static C++ libraries. Use this option to skip the static C++tests. This option implies--disable-static-c++-link-check.
By default, if the C++ toolchain lacks support for static linking,configure fails to find the C++ header files and the glibc build fails.Use this option to disable the static C++ link check so that the C++header files can be located. The newly built libc.a can be used tocreate static C++ tests if the C++ toolchain has the necessary staticC++ libraries.
Disable usingscv
instruction for syscalls. All syscalls will usesc
instead, even if the kernel supportsscv
. PowerPC only.
These options are for cross-compiling. If you specify both options andbuild-system is different fromhost-system,configure
will prepare to cross-compile the GNU C Library frombuild-system to be usedonhost-system. You’ll probably need the ‘--with-headers’option too, and you may have to overrideconfigure’s selection ofthe compiler and/or binutils.
If you only specify ‘--host’,configure
will prepare for anative compile but use what you specify instead of guessing what yoursystem is. This is most useful to change the CPU submodel. For example,ifconfigure
guesses your machine asi686-pc-linux-gnu
butyou want to compile a library for 586es, give‘--host=i586-pc-linux-gnu’ or just ‘--host=i586-linux’ and addthe appropriate compiler flags (‘-mcpu=i586’ will do the trick) toCC
.
If you specify just ‘--build’,configure
will get confused.
Specify a description, possibly including a build number or builddate, of the binaries being built, to be included in--version output from programs installed with the GNU C Library.For example,--with-pkgversion='FooBar GNU/Linux glibc build123'. The default value is ‘GNU libc’.
Specify the URL that users should visit if they wish to report a bug,to be included in--help output from programs installed withthe GNU C Library. The default value refers to the main bug-reportinginformation for the GNU C Library.
Use -D_FORTIFY_SOURCE=LEVEL to control hardening in the GNU C Library.If not provided,LEVEL defaults to highest possible value supported bythe build compiler.
Default is to disable fortification.
Experimental option supported by some architectures, where the GNU C Libraryis built with-Wa,--gsframe ifbinutils
supports it.Currently this is only supported on x86_64 and aarch64. The optionenables SFrame support onbacktrace
.
Default is to disable SFrame support.
To build the library and related programs, typemake
. This willproduce a lot of output, some of which may look like errors frommake
but aren’t. Look for error messages frommake
containing ‘***’. Those indicate that something is seriously wrong.
The compilation process can take a long time, depending on theconfiguration and the speed of your machine. Some complex modules maytake a very long time to compile, as much as several minutes on slowermachines. Do not panic if the compiler appears to hang.
If you want to run a parallel make, simply pass the ‘-j’ optionwith an appropriate numeric parameter tomake
. You need a recentGNUmake
version, though.
To build and run test programs which exercise some of the libraryfacilities, typemake check
. If it does not completesuccessfully, do not use the built library, and report a bug afterverifying that the problem is not already known. SeeReporting Bugs,for instructions on reporting bugs. Note that some of the tests assumethey are not being run byroot
. We recommend you compile andtest the GNU C Library as an unprivileged user.
Before reporting bugs make sure there is no problem with your system.The tests (and later installation) use some pre-existing files of thesystem such as/etc/passwd,/etc/nsswitch.conf and others.These files must all contain correct and sensible content.
Normally,make check
will run all the tests before reportingall problems found and exiting with error status if any problemsoccurred. You can specify ‘stop-on-test-failure=y’ when runningmake check
to make the test run stop and exit with an errorstatus immediately when a failure occurs.
To format theGNU C Library Reference Manual for printing, typemake dvi
. You need a working TeX installation to dothis. The distribution builds the on-line formatted version of themanual, as Info files, as part of the build process. You can buildthem manually withmake info
.
The library has a number of special-purpose configuration parameterswhich you can find inMakeconfig. These can be overwritten withthe fileconfigparms. To change them, create aconfigparms in your build directory and add values as appropriatefor your system. The file is included and parsed bymake
and hasto follow the conventions for makefiles.
It is easy to configure the GNU C Library for cross-compilation bysetting a few variables inconfigparms. SetCC
to thecross-compiler for the target you configured the library for; it isimportant to use this sameCC
value when runningconfigure
, like this: ‘configuretargetCC=target-gcc’. SetBUILD_CC
to the compiler to use for programsrun on the build system as part of compiling the library. You may need tosetAR
to cross-compiling versions ofar
if the native tools are not configured to work withobject files for the target you configured for. When cross-compilingthe GNU C Library, it may be tested using ‘make checktest-wrapper="srcdir/scripts/cross-test-ssh.shhostname"’,wheresrcdir is the absolute directory name for the main sourcedirectory andhostname is the host name of a system that can runthe newly built binaries of the GNU C Library. The source and builddirectories must be visible at the same locations on both the buildsystem andhostname.The ‘cross-test-ssh.sh’ script requires ‘flock’ from‘util-linux’ to work whenglibc_test_allow_time_settingenvironment variable is set.
It is also possible to execute tests, which require setting the date onthe target machine. Following use cases are supported:
GLIBC_TEST_ALLOW_TIME_SETTING
is set in the environment inwhich eligible tests are executed and have the privilege to runclock_settime
. In this case, nothing prevents those tests fromrunning in parallel, so the caller shall assure that those testsare serialized or provide a proper wrapper script for them.cross-test-ssh.sh
script is used and one passes the--allow-time-setting flag. In this case, both setsGLIBC_TEST_ALLOW_TIME_SETTING
and serialization of testexecution are assured automatically.In general, when testing the GNU C Library, ‘test-wrapper’ may be setto the name and arguments of any program to run newly built binaries.This program must preserve the arguments to the binary being run, itsworking directory and the standard input, output and error filedescriptors. If ‘test-wrapper env’ will not work to run aprogram with environment variables set, then ‘test-wrapper-env’must be set to a program that runs a newly built program withenvironment variable assignments in effect, those assignments beingspecified as ‘var=value’ before the name of theprogram to be run. If multiple assignments to the same variable arespecified, the last assignment specified must take precedence.Similarly, if ‘test-wrapper env -i’ will not work to run aprogram with an environment completely empty of variables except thosedirectly assigned, then ‘test-wrapper-env-only’ must be set; itsuse has the same syntax as ‘test-wrapper-env’, the onlydifference in its semantics being starting with an empty set ofenvironment variables rather than the ambient set.
For AArch64 with SVE, when testing the GNU C Library, ‘test-wrapper’may be set to "srcdir/sysdeps/unix/sysv/linux/aarch64/vltest.pyvector-length" to change Vector Length.
Next:Recommended Tools for Compilation, Previous:Configuring and compiling the GNU C Library, Up:Installing the GNU C Library [Contents][Index]
To install the library and its header files, and the Info files of themanual, typemake install
. This willbuild things, if necessary, before installing them; however, you shouldstill compile everything first. If you are installing the GNU C Library as yourprimary C library, we recommend that you shut the system down tosingle-user mode first, and reboot afterward. This minimizes the riskof breaking things when the library changes out from underneath.
‘make install’ will do the entire job of upgrading from aprevious installation of the GNU C Library version 2.x. There may sometimesbe headersleft behind from the previous installation, but those are generallyharmless. If you want to avoid leaving headers behind you can dothings in the following order.
You must first build the library (‘make’), optionally check it(‘make check’), switch the include directories and then install(‘make install’). The steps must be done in this order. Not movingthe directory before install will result in an unusable mixture of headerfiles from both libraries, but configuring, building, and checking thelibrary requires the ability to compile and run programs against the oldlibrary. The new/usr/include, after switching the includedirectories and before installing the library should contain the Linuxheaders, but nothing else. If you do this, you will need to restoreany headers from libraries other than the GNU C Library yourself after installing thelibrary.
You can install the GNU C Library somewhere other than where you configuredit to go by setting theDESTDIR
GNU standard make variable onthe command line for ‘make install’. The value of this variableis prepended to all the paths for installation. This is useful whensetting up a chroot environment or preparing a binary distribution.The directory should be specified with an absolute file name. Installingwith theprefix
andexec_prefix
GNU standard make variablesset is not supported.
The GNU C Library includes a daemon callednscd
, which youmay or may not want to run.nscd
caches name service lookups; itcan dramatically improve performance with NIS+, and may help with DNS aswell.
One auxiliary program,/usr/libexec/pt_chown, is installed setuidroot
if the ‘--enable-pt_chown’ configuration option is used.This program is invoked by thegrantpt
function; it sets thepermissions on a pseudoterminal so it can be used by the calling process.If you are using a Linux kernel with thedevpts
filesystem enabledand mounted at/dev/pts, you don’t need this program.
After installation you should configure the time zone ruleset and installlocales for your system. The time zone ruleset ensures that timestampsare processed correctly for your location. The locales ensure thatthe display of information on your system matches the expectations ofyour language and geographic region.
The GNU C Library is able to use two kinds of localization information sources, thefirst is a locale database namedlocale-archive which is generallyinstalled as/usr/lib/locale/locale-archive. The locale archive has thebenefit of taking up less space and being very fast to load, but only if youplan to install sixty or more locales. If you plan to install one or twolocales you can instead install individual locales into their self-nameddirectories e.g./usr/lib/locale/en_US.utf8. For example to installthe German locale using the character set for UTF-8 with namede_DE
intothe locale archive issue the command ‘localedef -i de_DE -f UTF-8 de_DE’,and to install just the one locale issue the command ‘localedef--no-archive -i de_DE -f UTF-8 de_DE’. To configure all locales that aresupported by the GNU C Library, you can issue from your build directory the command‘make localedata/install-locales’ to install all locales into the localearchive or ‘make localedata/install-locale-files’ to install all localesas files in the default configured locale installation directory (derived from‘--prefix’ or--localedir
). To install into an alternative systemroot use ‘DESTDIR’ e.g. ‘make localedata/install-locale-filesDESTDIR=/opt/glibc’, but note that this does not change the configured prefix.
To configure the time zone ruleset, set theTZ
environmentvariable. The scripttzselect
helps you to select the right value.As an example, for Germany,tzselect
would tell you to use‘TZ='Europe/Berlin'’. For a system wide installation (the givenpaths are for an installation with ‘--prefix=/usr’), link thetime zone file which is in/usr/share/zoneinfo to the file/etc/localtime. For Germany, you might execute ‘ln -s/usr/share/zoneinfo/Europe/Berlin /etc/localtime’.
Next:Specific advice for GNU/Linux systems, Previous:Installing the C Library, Up:Installing the GNU C Library [Contents][Index]
We recommend installing the following GNU tools before attempting tobuild the GNU C Library:
make
4.0 or newerAs of release time, GNUmake
4.4.1 is the newest verified to workto build the GNU C Library.
GCC 12.1 or higher is required. In general it is recommended to usethe newest version of the compiler that is known to work for buildingthe GNU C Library, as newer compilers usually produce better code. As ofrelease time, GCC 15.1.1 is the newest compiler verified to work to buildthe GNU C Library.
For multi-arch support it is recommended to use a GCC which has been built withsupport for GNU indirect functions. This ensures that correct debugginginformation is generated for functions selected by IFUNC resolvers. Thissupport can either be enabled by configuring GCC with‘--enable-gnu-indirect-function’, or by enabling it by default by setting‘default_gnu_indirect_function’ variable for a particular architecture inthe GCC source filegcc/config.gcc.
You can use whatever compiler you like to compile programs that usethe GNU C Library.
Check the FAQ for any special compiler issues on particular platforms.
binutils
2.39 or laterYou must use GNUbinutils
(as and ld) to build the GNU C Library.No other assembler or linker has the necessary functionality at themoment. As of release time, GNUbinutils
2.45 is the newestverified to work to build the GNU C Library.
texinfo
4.7 or laterTo correctly translate and install the Texinfo documentation you needthis version of thetexinfo
package. Earlier versions do notunderstand all the tags used in the document, and the installationmechanism for the info files is not present or works differently.As of release time,texinfo
7.2 is the newest verified to workto build the GNU C Library.
awk
3.1.2, or higherawk
is used in several places to generate files.Somegawk
extensions are used, including theasorti
function, which was introduced in version 3.1.2 ofgawk
.As of release time,gawk
version 5.3.2 is the newest verifiedto work to build the GNU C Library.
Testing the GNU C Library requiresgawk
to be compiled withsupport for high precision arithmetic via theMPFR
multiple-precision floating-point computation library.
bison
2.7 or laterbison
is used to generate theyacc
parser code in theintlsubdirectory. As of release time,bison
version 3.8.2 is the newestverified to work to build the GNU C Library.
Perl is not required, but if present it is used in some tests and themtrace
program, to build the GNU C Library manual. As of releasetimeperl
version 5.42.0 is the newest verified to work tobuild the GNU C Library.
sed
3.02 or newerSed
is used in several places to generate files. Most scripts workwith any version ofsed
. As of release time,sed
version4.9 is the newest verified to work to build the GNU C Library.
Python is required to build the GNU C Library. As of release time, Python3.13.5 is the newest verified to work for building and testingthe GNU C Library.
The pretty printer tests drive GDB through test programs and compareits output to the printers’. PExpect is used to capture the output ofGDB, and should be compatible with the Python version in your system.As of release time PExpect 4.9.0 is the newest verified to work to testthe pretty printers.
abnf
module.This module is optional and used to verify some ABNF grammars in themanual. Version 2.2.0 has been confirmed to work as expected. Amissingabnf
module does not reduce the test coverage of thelibrary itself.
GDB itself needs to be configured with Python support in order to usethe pretty printers. Notice that your system having Python availabledoesn’t imply that GDB supports it, nor that your system’s Python andGDB’s have the same version. As of release time GNUdebugger
14.2 is the newest verified to work to test the pretty printers.
Unless Python, PExpect and GDB with Python support are present, theprinter tests will report themselves asUNSUPPORTED
. Noticethat some of the printer tests require the GNU C Library to be compiled withdebugging symbols.
If you change any of theconfigure.ac files you will also need
autoconf
2.72 (exactly)and if you change any of the message translation files you will need
gettext
0.10.36 or laterAs of release time, GNUgettext
version 0.23.2 is the newestversion verified to work to build the GNU C Library.
You may also need these packages if you upgrade your source tree usingpatches, although we try to avoid this.
Next:Reporting Bugs, Previous:Recommended Tools for Compilation, Up:Installing the GNU C Library [Contents][Index]
If you are installing the GNU C Library on GNU/Linux systems, you need to havethe header files from a 3.2 or newer kernel around for reference.These headers must be installed using ‘make headers_install’; theheaders present in the kernel source directory are not suitable fordirect use by the GNU C Library. You do not need to use that kernel, just haveits headers installed where the GNU C Library can access them, referred to here asinstall-directory. The easiest way to do this is to unpack itin a directory such as/usr/src/linux-version. In thatdirectory, run ‘make headers_installINSTALL_HDR_PATH=install-directory’. Finally, configure the GNU C Librarywith the option ‘--with-headers=install-directory/include’.Use the most recent kernel you can get your hands on. (If you arecross-compiling the GNU C Library, you need to specify‘ARCH=architecture’ in the ‘make headers_install’command, wherearchitecture is the architecture name used by theLinux kernel, such as ‘x86’ or ‘powerpc’.)
After installing the GNU C Library, you may need to remove or renamedirectories such as/usr/include/linux and/usr/include/asm, and replace them with copies of directoriessuch aslinux andasm frominstall-directory/include. All directories present ininstall-directory/include should be copied, except thatthe GNU C Library provides its own version of/usr/include/scsi; thefiles provided by the kernel should be copied without replacing thoseprovided by the GNU C Library. Thelinux,asm andasm-generic directories are required to compile programs usingthe GNU C Library; the other directories describe interfaces to the kernel butare not required if not compiling programs using those interfaces.You do not need to copy kernel headers if you did not specify analternate kernel header source using ‘--with-headers’.
The Filesystem Hierarchy Standard for GNU/Linux systems expects somecomponents of the GNU C Library installation to be in/lib and some in/usr/lib. This is handled automaticallyif you configure the GNU C Library with ‘--prefix=/usr’. If you set some otherprefix or allow it to default to/usr/local, then all thecomponents are installed there.
As of release time, Linux version 6.12 is the newest stable version verifiedto work to build the GNU C Library.
There are probably bugs in the GNU C Library. There are certainlyerrors and omissions in this manual. If you report them, they will getfixed. If you don’t, no one will ever know about them and they willremain unfixed for all eternity, if not longer.
It is a good idea to verify that the problem has not already beenreported. Bugs are documented in two places: The fileBUGSdescribes a number of well known bugs and the central GNU C Librarybug tracking system has aWWW interface athttps://sourceware.org/bugzilla/. The WWWinterface gives you access to open and closed reports. A closed reportnormally includes a patch or a hint on solving the problem.
To report a bug, first you must find it. With any luck, this will be thehard part. Once you’ve found a bug, make sure it’s really a bug. Agood way to do this is to see if the GNU C Library behaves the same waysome other C library does. If so, probably you are wrong and thelibraries are right (but not necessarily). If not, one of the librariesis probably wrong. It might not be the GNU C Library. Many historicalUnix C libraries permit things that we don’t, such as closing a filetwice.
If you think you have found some way in which the GNU C Library does notconform to the ISO and POSIX standards (seeStandards and Portability), that is definitely a bug. Report it!
Once you’re sure you’ve found a bug, try to narrow it down to thesmallest test case that reproduces the problem. In the case of a Clibrary, you really only need to narrow it down to one libraryfunction call, if possible. This should not be too difficult.
The final step when you have a simple test case is to report the bug.Do this athttps://www.gnu.org/software/libc/bugs.html.
If you are not sure how a function should behave, and this manualdoesn’t tell you, that’s a bug in the manual. Report that too! If thefunction’s behavior disagrees with the manual, then either the libraryor the manual has a bug, so report the disagreement. If you find anyerrors or omissions in this manual, please report them to thebug database. If you refer to specificsections of the manual, please include the section names for easieridentification.
Next:Platform-specific facilities, Previous:Installing the GNU C Library, Up:Main Menu [Contents][Index]
The process of building the library is driven by the makefiles, whichmake heavy use of special features of GNUmake
. The makefilesare very complex, and you probably don’t want to try to understand them.But what they do is fairly straightforward, and only requires that youdefine a few variables in the right places.
The library sources are divided into subdirectories, grouped by topic.
Thestring subdirectory has all the string-manipulationfunctions,math has all the mathematical functions, etc.
Each subdirectory contains a simple makefile, calledMakefile,which defines a fewmake
variables and then includes the globalmakefileRules with a line like:
include ../Rules
The basic variables that a subdirectory makefile defines are:
subdir
The name of the subdirectory, for examplestdio.This variablemust be defined.
headers
The names of the header files in this section of the library,such asstdio.h.
routines
aux
The names of the modules (source files) in this section of the library.These should be simple names, such as ‘strlen’ (rather thancomplete file names, such asstrlen.c). Useroutines
formodules that define functions in the library, andaux
forauxiliary modules containing things like data definitions. But thevalues ofroutines
andaux
are just concatenated, so therereally is no practical difference.
tests
The names of test programs for this section of the library. Theseshould be simple names, such as ‘tester’ (rather than complete filenames, such astester.c). ‘make tests’ will build andrun all the test programs. If a test program needs input, put the testdata in a file calledtest-program.input; it will be given tothe test program on its standard input. If a test program wants to berun with arguments, put the arguments (all on a single line) in a filecalledtest-program.args. Test programs should exit withzero status when the test passes, and nonzero status when the testindicates a bug in the library or error in building.
others
The names of “other” programs associated with this section of thelibrary. These are programs which are not tests per se, but are othersmall programs included with the library. They are built by‘make others’.
install-lib
install-data
install
Files to be installed by ‘make install’. Files listed in‘install-lib’ are installed in the directory specified by‘libdir’ inconfigparms orMakeconfig(seeInstalling the GNU C Library). Files listed ininstall-data
areinstalled in the directory specified by ‘datadir’ inconfigparms orMakeconfig. Files listed ininstall
are installed in the directory specified by ‘bindir’ inconfigparms orMakeconfig.
distribute
Other files from this subdirectory which should be put into adistribution tar file. You need not list here the makefile itself orthe source and header files listed in the other standard variables.Only definedistribute
if there are files used in an unusual waythat should go into the distribution.
generated
Files which are generated byMakefile in this subdirectory.These files will be removed by ‘make clean’, and they willnever go into a distribution.
extra-objs
Extra object files which are built byMakefile in thissubdirectory. This should be a list of file names likefoo.o;the files will actually be found in whatever directory object files arebeing built in. These files will be removed by ‘make clean’.This variable is used for secondary object files needed to buildothers
ortests
.
It’s sometimes necessary to provide nonstandard, platform-specificfeatures to developers. The C library is traditionally thelowest library layer, so it makes sense for it to provide theselow-level features. However, including these features in the Clibrary may be a disadvantage if another package provides themas well as there will be two conflicting versions of them. Also,the features won’t be available to projects that do not usethe GNU C Library but use other GNU tools, like GCC.
The current guidelines are:
The general solution for providing low-level features is to export them asfollows:
__arch_
, such as__ppc_get_timebase
.The easiest way to provide a header file is to add it to thesysdep_headers
variable. For example, the combination ofLinux-specific header files on PowerPC could be provided like this:
sysdep_headers += sys/platform/ppc.h
Then ensure that you have added asys/platform/ppc.hheader file in the machine-specific directory, e.g.,sysdeps/powerpc/sys/platform/ppc.h.
Next:Symbol handling in the GNU C Library, Previous:Adding New Functions, Up:Library Maintenance [Contents][Index]
This section contains implementation details of the GNU C Library and may notremain stable across releases.
The_FORTIFY_SOURCE
macro may be defined by users to controlhardening of calls into some functions in the GNU C Library. The definitionshould be at the top of the source file before any headers are includedor at the pre-processor commandline using the-D
switch. Thehardening primarily focuses on accesses to buffers passed to thefunctions but may also include checks for validity of other inputs tothe functions.
When the_FORTIFY_SOURCE
macro is defined, it enables code thatvalidates inputs passed to some functions in the GNU C Library to determine ifthey are safe. If the compiler is unable to determine that the inputsto the function call are safe, the call may be replaced by a call to itshardened variant that does additional safety checks at runtime. Somehardened variants need the size of the buffer to perform accessvalidation and this is provided by the__builtin_object_size
orthe__builtin_dynamic_object_size
builtin functions._FORTIFY_SOURCE
also enables additional compile time diagnostics,such as unchecked return values from some functions, to encouragedevelopers to add error checking for those functions.
At runtime, if any of those safety checks fail, the program willterminate with aSIGABRT
signal._FORTIFY_SOURCE
may bedefined to one of the following values:
__builtin_object_size
compiler builtin function.If the function returns(size_t) -1
, the function call is leftuntouched. Additionally, this level also enables validation of flags totheopen
,open64
,openat
andopenat64
functions.%n
only in read-only format strings.__builtin_dynamic_object_size
compiler builtinfunction. If the function returns(size_t) -1
, the function callis left untouched. Fortification at this level may have a impact onprogram performance if the function call that is fortified is frequentlyencountered and the size expression returned by__builtin_dynamic_object_size
is complex.In general, the fortified variants of the function calls use the name ofthe function with a__
prefix and a_chk
suffix. Thereare some exceptions, e.g. theprintf
family of functions where,depending on the architecture, one may also see fortified variants havethe_chkieee128
suffix or the__nldbl___
prefix to theirnames.
Another exception is theopen
family of functions, where theirfortified replacements have the__
prefix and a_2
suffix.TheFD_SET
,FD_CLR
andFD_ISSET
macros use the__fdelt_chk
function on fortification.
The following functions and macros are fortified in the GNU C Library:
asprintf
confstr
dprintf
explicit_bzero
FD_SET
FD_CLR
FD_ISSET
fgets
fgets_unlocked
fgetws
fgetws_unlocked
fprintf
fread
fread_unlocked
fwprintf
getcwd
getdomainname
getgroups
gethostname
getlogin_r
gets
getwd
inet_ntop
inet_pton
longjmp
mbsnrtowcs
mbsrtowcs
mbstowcs
memcpy
memmove
mempcpy
memset
mq_open
obstack_printf
obstack_vprintf
open
open64
openat
openat64
poll
ppoll64
ppoll
pread64
pread
printf
ptsname_r
read
readlinkat
readlink
realpath
recv
recvfrom
snprintf
sprintf
stpcpy
stpncpy
strcat
strcpy
strlcat
strlcpy
strncat
strncpy
swprintf
syslog
ttyname_r
vasprintf
vdprintf
vfprintf
vfwprintf
vprintf
vsnprintf
vsprintf
vswprintf
vsyslog
vwprintf
wcpcpy
wcpncpy
wcrtomb
wcscat
wcscpy
wcslcat
wcslcpy
wcsncat
wcsncpy
wcsnrtombs
wcsrtombs
wcstombs
wctomb
wmemcpy
wmemmove
wmempcpy
wmemset
wprintf
Next:Porting the GNU C Library, Previous:Fortification of function calls, Up:Library Maintenance [Contents][Index]
With respect to time handling, GNU C Library configurations fall in twoclasses depending on the value of__TIMESIZE
:
__TIMESIZE == 32
Thesedual-time configurations have both 32-bit and 64-bit timesupport. 32-bit time support provides typetime_t
and cannothandle dates beyondY2038. 64-bit time support provides type__time64_t
and can handle dates beyondY2038.
In these configurations, time-related types have two declarations,a 64-bit one, and a 32-bit one; and time-related functions generallyhave two definitions: a 64-bit one, and a 32-bit one which is a wrapperaround the former. Therefore, for everytime_t
-related symbol,there is a corresponding__time64_t
-related symbol, the name ofwhich is usually the 32-bit symbol’s name with__
(a doubleunderscore) prepended and64
appended. For instance, the64-bit-time counterpart ofclock_gettime
is__clock_gettime64
.
__TIMESIZE == 64
Thesesingle-time configurations only have a 64-bittime_t
and related functions, which can handle dates beyond 2038-01-1903:14:07 (akaY2038).
In these configurations, time-related types only have a 64-bitdeclaration; and time-related functions only have one 64-bit definition.However, for everytime_t
-related symbol, there is acorresponding__time64_t
-related macro, the name of which isderived as in the dual-time configuration case, and which expands tothe symbol’s name. For instance, the macro__clock_gettime64
expands toclock_gettime
.
When__TIMESIZE
is set to 64, the GNU C Library will also definethe__USE_TIME_BITS64
macro. It is used by the Linux kernel ABIto set the expectedtime_t
size used on some syscalls.
These macros are purely internal to the GNU C Library and exist only so thata single definition of the 64-bit time functions can be used on bothsingle-time and dual-time configurations, and so that glibc code canfreely call the 64-bit functions internally in all configurations.
Note: at this point, 64-bit time support in dual-time configurations iswork-in-progress, so for these configurations, the public API only makesthe 32-bit time support available. In a later change, the public APIwill allow user code to choose the time size for a given compilationunit.
64-bit variants of time-related types or functions are defined for allconfigurations and use 64-bit-time symbol names (for dual-timeconfigurations) or macros (for single-time configurations).
32-bit variants of time-related types or functions are defined only fordual-time configurations.
Here is an example withlocaltime
:
Functionlocaltime
is declared intime/time.h as
extern struct tm *localtime (const time_t *__timer) __THROW;libc_hidden_proto (localtime)
For single-time configurations,__localtime64
is a macro whichevaluates tolocaltime
; for dual-time configurations,__localtime64
is a function similar tolocaltime
exceptit uses Y2038-proof types:
#if __TIMESIZE == 64# define __localtime64 localtime#elseextern struct tm *__localtime64 (const __time64_t *__timer) __THROW;libc_hidden_proto (__localtime64)#endif
(note: typetime_t
is replaced with__time64_t
becausetime_t
is not Y2038-proof, butstruct tm
is notreplaced because it is already Y2038-proof.)
The 64-bit-time implementation oflocaltime
is written as followsand is compiled for both dual-time and single-time configuration classes.
struct tm *__localtime64 (const __time64_t *t){ return __tz_convert (*t, 1, &_tmbuf);}libc_hidden_def (__localtime64)
The 32-bit-time implementation is a wrapper and is only compiled fordual-time configurations:
#if __TIMESIZE != 64struct tm *localtime (const time_t *t){ __time64_t t64 = *t; return __localtime64 (&t64);}libc_hidden_def (localtime)#endif
Previous:Symbol handling in the GNU C Library, Up:Library Maintenance [Contents][Index]
The GNU C Library is written to be easily portable to a variety ofmachines and operating systems. Machine- and operating system-dependentfunctions are well separated to make it easy to add implementations fornew machines or operating systems. This section describes the layout ofthe library source tree and explains the mechanisms used to selectmachine-dependent code to use.
All the machine-dependent and operating system-dependent files in thelibrary are in the subdirectorysysdeps under the top-levellibrary source directory. This directory contains a hierarchy ofsubdirectories (seeLayout of thesysdeps Directory Hierarchy).
Each subdirectory ofsysdeps contains source files for aparticular machine or operating system, or for a class of machine oroperating system (for example, systems by a particular vendor, or allmachines that use IEEE 754 floating-point format). A configurationspecifies an ordered list of these subdirectories. Each subdirectoryimplicitly appends its parent directory to the list. For example,specifying the listunix/bsd/vax is equivalent to specifying thelistunix/bsd/vax unix/bsd unix. A subdirectory can also specifythat it implies other subdirectories which are not directly above it inthe directory hierarchy. If the fileImplies exists in asubdirectory, it lists other subdirectories ofsysdeps which areappended to the list, appearing after the subdirectory containing theImplies file. Lines in anImplies file that begin with a‘#’ character are ignored as comments. For example,unix/bsd/Implies contains:
# BSD has Internet-related things.unix/inet
andunix/Implies contains:
posix
So the final list isunix/bsd/vax unix/bsd unix/inet unix posix.
sysdeps has a “special” subdirectory calledgeneric. Itis always implicitly appended to the list of subdirectories, so youneedn’t put it in anImplies file, and you should not create anysubdirectories under it intended to be new specific categories.generic serves two purposes. First, the makefiles do not botherto look for a system-dependent version of a file that’s not ingeneric. This means that any system-dependent source file musthave an analogue ingeneric, even if the routines defined by thatfile are not implemented on other platforms. Second, thegenericversion of a system-dependent file is used if the makefiles do not finda version specific to the system you’re compiling for.
If it is possible to implement the routines in ageneric file inmachine-independent C, using only other machine-independent functions inthe C library, then you should do so. Otherwise, make them stubs. Astub function is a function which cannot be implemented on aparticular machine or operating system. Stub functions always return anerror, and seterrno
toENOSYS
(Function not implemented).SeeError Reporting. If you define a stub function, you must placethe statementstub_warning(function)
, wherefunctionis the name of your function, after its definition. This causes thefunction to be listed in the installed<gnu/stubs.h>
, andmakes GNU ld warn when the function is used.
Some rare functions are only useful on specific systems and aren’tdefined at all on others; these do not appear anywhere in thesystem-independent source code or makefiles (including thegeneric directory), only in the system-dependentMakefilein the specific system’s subdirectory.
If you come across a file that is in one of the main source directories(string,stdio, etc.), and you want to write a machine- oroperating system-dependent version of it, move the file intosysdeps/generic and write your new implementation in theappropriate system-specific subdirectory. Note that if a file is to besystem-dependent, itmust not appear in one of the main sourcedirectories.
There are a few special files that may exist in each subdirectory ofsysdeps:
A makefile for this machine or operating system, or class of machine oroperating system. This file is included by the library makefileMakerules, which is used by the top-level makefile and thesubdirectory makefiles. It can change the variables set in theincluding makefile or add new rules. It can use GNUmake
conditional directives based on the variable ‘subdir’ (see above) toselect different sets of variables and rules for different sections ofthe library. It can also set themake
variable‘sysdep-routines’, to specify extra modules to be included in thelibrary. You should use ‘sysdep-routines’ rather than addingmodules to ‘routines’ because the latter is used in determiningwhat to distribute for each subdirectory of the main source tree.
Each makefile in a subdirectory in the ordered list of subdirectories tobe searched is included in order. Since several system-dependentmakefiles may be included, each should append to ‘sysdep-routines’rather than simply setting it:
sysdep-routines := $(sysdep-routines) foo bar
This file contains the names of new whole subdirectories under thetop-level library source tree that should be included for this system.These subdirectories are treated just like the system-independentsubdirectories in the library source tree, such asstdio andmath.
Use this when there are completely new sets of functions and headerfiles that should go into the library for the system this subdirectoryofsysdeps implements. For example,sysdeps/unix/inet/Subdirs containsinet; theinetdirectory contains various network-oriented operations which only makesense to put in the library on systems that support the Internet.
This file is a shell script fragment to be run at configuration time.The top-levelconfigure script uses the shell.
command toread theconfigure file in each system-dependent directorychosen, in order. Theconfigure files are often generated fromconfigure.ac files using Autoconf.
A system-dependentconfigure script will usually add things tothe shell variables ‘DEFS’ and ‘config_vars’; see thetop-levelconfigure script for details. The script can check for‘--with-package’ options that were passed to thetop-levelconfigure. For an option‘--with-package=value’configure sets theshell variable ‘with_package’ (with any dashes inpackage converted to underscores) tovalue; if the option isjust ‘--with-package’ (no argument), then it sets‘with_package’ to ‘yes’.
This file is an Autoconf input fragment to be processed into the fileconfigure in this subdirectory. SeeIntroduction inAutoconf: Generating Automatic Configuration Scripts,for a description of Autoconf. You should write eitherconfigureorconfigure.ac, but not both. The first line ofconfigure.ac should invoke them4
macro‘GLIBC_PROVIDES’. This macro does severalAC_PROVIDE
callsfor Autoconf macros which are used by the top-levelconfigurescript; without this, those macros might be invoked again unnecessarilyby Autoconf.
That is the general system for how system-dependencies are isolated.
A GNU configuration name has three parts: the CPU type, themanufacturer’s name, and the operating system.configure usesthese to pick the list of system-dependent directories to look for. Ifthe ‘--nfp’ option isnot passed toconfigure, thedirectorymachine/fpu is also used. The operating systemoften has abase operating system; for example, if the operatingsystem is ‘Linux’, the base operating system is ‘unix/sysv’.The algorithm used to pick the list of directories is simple:configure makes a list of the base operating system,manufacturer, CPU type, and operating system, in that order. It thenconcatenates all these together with slashes in between, to produce adirectory name; for example, the configuration ‘i686-linux-gnu’results inunix/sysv/linux/i386/i686.configure thentries removing each element of the list in turn, sounix/sysv/linux andunix/sysv are also tried, among others.Since the precise version number of the operating system is often notimportant, and it would be very inconvenient, for example, to haveidenticalirix6.2 andirix6.3 directories,configure tries successively less specific operating system namesby removing trailing suffixes starting with a period.
As an example, here is the complete list of directories that would betried for the configuration ‘i686-linux-gnu’:
sysdeps/i386/elfsysdeps/unix/sysv/linux/i386sysdeps/unix/sysv/linuxsysdeps/gnusysdeps/unix/commonsysdeps/unix/mmansysdeps/unix/inetsysdeps/unix/sysv/i386/i686sysdeps/unix/sysv/i386sysdeps/unix/sysvsysdeps/unix/i386sysdeps/unixsysdeps/posixsysdeps/i386/i686sysdeps/i386/i486sysdeps/libm-i387/i686sysdeps/i386/fpusysdeps/libm-i387sysdeps/i386sysdeps/wordsize-32sysdeps/ieee754sysdeps/libm-ieee754sysdeps/generic
Different machine architectures are conventionally subdirectories at thetop level of thesysdeps directory tree. For example,sysdeps/sparc andsysdeps/m68k. These containfiles specific to those machine architectures, but not specific to anyparticular operating system. There might be subdirectories forspecializations of those architectures, such assysdeps/m68k/68020. Code which is specific to thefloating-point coprocessor used with a particular machine should go insysdeps/machine/fpu.
There are a few directories at the top level of thesysdepshierarchy that are not for particular machine architectures.
As described above (seePorting the GNU C Library), this is the subdirectorythat every configuration implicitly uses after all others.
This directory is for code using the IEEE 754 floating-point format,where the C typefloat
is IEEE 754 single-precision format, anddouble
is IEEE 754 double-precision format. Usually thisdirectory is referred to in theImplies file in a machinearchitecture-specific directory, such asm68k/Implies.
This directory contains an implementation of a mathematical libraryusable on platforms which use IEEE 754 conformant floating-pointarithmetic.
This is a special case. Ideally the code should be insysdeps/i386/fpu but for various reasons it is kept aside.
This directory contains implementations of things in the library interms ofPOSIX.1 functions. This includes some of thePOSIX.1functions themselves. Of course,POSIX.1 cannot be completelyimplemented in terms of itself, so a configuration using justposix cannot be complete.
This is the directory for Unix-like things. SeePorting the GNU C Library to Unix Systems.unix impliesposix. There are some special-purposesubdirectories ofunix:
This directory is for things common to both BSD and System V release 4.Bothunix/bsd andunix/sysv/sysv4 implyunix/common.
This directory is forsocket
and related functions on Unix systems.unix/inet/Subdirs enables theinet top-level subdirectory.unix/common impliesunix/inet.
This is the directory for things based on the Mach microkernel from CMU(including GNU/Hurd systems). Other basic operating systems(VMS, for example) would have their own directories at the top level ofthesysdeps hierarchy, parallel tounix andmach.
Most Unix systems are fundamentally very similar. There are variationsbetween different machines, and variations in what facilities areprovided by the kernel. But the interface to the operating systemfacilities is, for the most part, pretty uniform and simple.
The code for Unix systems is in the directoryunix, at the toplevel of thesysdeps hierarchy. This directory containssubdirectories (and subdirectory trees) for various Unix variants.
The functions which are system calls in most Unix systems areimplemented in assembly code, which is generated automatically fromspecifications in files namedsyscalls.list. There are severalsuch files, one insysdeps/unix and others in its subdirectories.Some special system calls are implemented in files that are named with asuffix of ‘.S’; for example,_exit.S. Files ending in‘.S’ are run through the C preprocessor before being fed to theassembler.
These files all use a set of macros that should be defined insysdep.h. Thesysdep.h file insysdeps/unixpartially defines them; asysdep.h file in another directory mustfinish defining them for the particular machine and operating systemvariant. Seesysdeps/unix/sysdep.h and the machine-specificsysdep.h implementations to see what these macros are and whatthey should do.
The system-specific makefile for theunix directory(sysdeps/unix/Makefile) gives rules to generate several filesfrom the Unix system you are building the library on (which is assumedto be the target system you are building the libraryfor). Allthe generated files are put in the directory where the object files arekept; they should not affect the source tree itself. The filesgenerated areioctls.h,errnos.h,sys/param.h, anderrlist.c (for thestdio section of the library).
Next:Contributors to the GNU C Library, Previous:Library Maintenance, Up:Main Menu [Contents][Index]
The GNU C Library can provide machine-specific functionality.
Facilities specific to PowerPC that are not specific to a particularoperating system are declared insys/platform/ppc.h.
uint64_t
__ppc_get_timebase(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Read the current value of the Time Base Register.
TheTime Base Register is a 64-bit register that stores a monotonicallyincremented value updated at a system-dependent frequency that may bedifferent from the processor frequency. More information is available inPower ISA 2.06b - Book II - Section 5.2.
__ppc_get_timebase
uses the processor’s time base facility directlywithout requiring assistance from the operating system, so it is veryefficient.
uint64_t
__ppc_get_timebase_freq(void)
¶Preliminary:| MT-Unsafe init| AS-Unsafe corrupt:init| AC-Unsafe corrupt:init| SeePOSIX Safety Concepts.
Read the current frequency at which the Time Base Register is updated.
This frequency is not related to the processor clock or the bus clock.It is also possible that this frequency is not constant. More information isavailable inPower ISA 2.06b - Book II - Section 5.2.
The following functions provide hints about the usage of resources that areshared with other processors. They can be used, for example, if a programwaiting on a lock intends to divert the shared resources to be used by otherprocessors. More information is available inPower ISA 2.06b - Book II -Section 3.2.
void
__ppc_yield(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Provide a hint that performance will probably be improved if shared resourcesdedicated to the executing processor are released for use by other processors.
void
__ppc_mdoio(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Provide a hint that performance will probably be improved if shared resourcesdedicated to the executing processor are released until all outstanding storageaccesses to caching-inhibited storage have been completed.
void
__ppc_mdoom(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Provide a hint that performance will probably be improved if shared resourcesdedicated to the executing processor are released until all outstanding storageaccesses to cacheable storage for which the data is not in the cache have beencompleted.
void
__ppc_set_ppr_med(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Set the Program Priority Register to medium value (default).
TheProgram Priority Register (PPR) is a 64-bit register that controlsthe program’s priority. By adjusting the PPR value the programmer mayimprove system throughput by causing the system resources to be usedmore efficiently, especially in contention situations.The three unprivileged states available are covered by the functions__ppc_set_ppr_med
(medium – default),__ppc_set_ppc_low
(low)and__ppc_set_ppc_med_low
(medium low). More informationavailable inPower ISA 2.06b - Book II - Section 3.1.
void
__ppc_set_ppr_low(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Set the Program Priority Register to low value.
void
__ppc_set_ppr_med_low(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Set the Program Priority Register to medium low value.
Power ISA 2.07 extends the priorities that can be set to the Program PriorityRegister (PPR). The following functions implement the new priority levels:very low and medium high.
void
__ppc_set_ppr_very_low(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Set the Program Priority Register to very low value.
void
__ppc_set_ppr_med_high(void)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Set the Program Priority Register to medium high value. The medium highpriority is privileged and may only be set during certain time intervals byproblem-state programs. If the program priority is medium high when the timeinterval expires or if an attempt is made to set the priority to medium highwhen it is not allowed, the priority is set to medium.
Next:X86-specific Facilities, Previous:PowerPC-specific Facilities, Up:Platform-specific facilities [Contents][Index]
Cache management facilities specific to RISC-V systems that implement the LinuxABI are declared insys/cachectl.h.
void
__riscv_flush_icache(void *start, void *end, unsigned long intflags)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Enforce ordering between stores and instruction cache fetches. The range ofaddresses over which ordering is enforced is specified bystart andend. Theflags argument controls the extent of this ordering, withthe default behavior (aflags value of 0) being to enforce the fence onall threads in the current process. Setting theSYS_RISCV_FLUSH_ICACHE_LOCAL
bit allows users to indicate that enforcingordering on only the current thread is necessary. All other flag bits arereserved.
Previous:RISC-V-specific Facilities, Up:Platform-specific facilities [Contents][Index]
Facilities specific to X86 that are not specific to a particularoperating system are declared insys/platform/x86.h.
const struct cpuid_feature *
__x86_get_cpuid_feature_leaf(unsigned intleaf)
¶Preliminary:| MT-Safe | AS-Safe | AC-Safe | SeePOSIX Safety Concepts.
Return a pointer to x86 CPU feature structure used by query macros for x86CPU featureleaf.
int
CPU_FEATURE_PRESENT(name)
¶This macro returns a nonzero value (true) if the processor has the featurename.
int
CPU_FEATURE_ACTIVE(name)
¶This macro returns a nonzero value (true) if the processor has the featurename and the feature is active. There may be other preconditions,like sufficient stack space or further setup for AMX, which must besatisfied before the feature can be used.
The supported processor features are:
ACPI
– Thermal Monitor and Software Controlled Clock Facilities.ADX
– ADX instruction extensions.APIC
– APIC On-Chip.AES
– The AES instruction extensions.AESKLE
– AES Key Locker instructions are enabled by OS.AMD_IBPB
– Indirect branch predictor barrier (IBPB) for AMD cpus.AMD_IBRS
– Indirect branch restricted speculation (IBPB) for AMD cpus.AMD_SSBD
– Speculative Store Bypass Disable (SSBD) for AMD cpus.AMD_STIBP
– Single thread indirect branch predictors (STIBP) for AMD cpus.AMD_VIRT_SSBD
– Speculative Store Bypass Disable (SSBD) for AMD cpus (older systems).AMX_BF16
– Tile computational operations on bfloat16 numbers.AMX_COMPLEX
– Tile computational operations on complex FP16 numbers.AMX_INT8
– Tile computational operations on 8-bit numbers.AMX_FP16
– Tile computational operations on FP16 numbers.AMX_TILE
– Tile architecture.APX_F
– The APX instruction extensions.ARCH_CAPABILITIES
– IA32_ARCH_CAPABILITIES MSR.ArchPerfmonExt
– Architectural Performance Monitoring ExtendedLeaf (EAX = 23H).AVX
– The AVX instruction extensions.AVX10
– The AVX10 instruction extensions.AVX10_XMM
– Whether AVX10 includes xmm registers.AVX10_YMM
– Whether AVX10 includes ymm registers.AVX10_ZMM
– Whether AVX10 includes zmm registers.AVX2
– The AVX2 instruction extensions.AVX_IFMA
– The AVX-IFMA instruction extensions.AVX_NE_CONVERT
– The AVX-NE-CONVERT instruction extensions.AVX_VNNI
– The AVX-VNNI instruction extensions.AVX_VNNI_INT8
– The AVX-VNNI-INT8 instruction extensions.AVX512_4FMAPS
– The AVX512_4FMAPS instruction extensions.AVX512_4VNNIW
– The AVX512_4VNNIW instruction extensions.AVX512_BF16
– The AVX512_BF16 instruction extensions.AVX512_BITALG
– The AVX512_BITALG instruction extensions.AVX512_FP16
– The AVX512_FP16 instruction extensions.AVX512_IFMA
– The AVX512_IFMA instruction extensions.AVX512_VBMI
– The AVX512_VBMI instruction extensions.AVX512_VBMI2
– The AVX512_VBMI2 instruction extensions.AVX512_VNNI
– The AVX512_VNNI instruction extensions.AVX512_VP2INTERSECT
– The AVX512_VP2INTERSECT instructionextensions.AVX512_VPOPCNTDQ
– The AVX512_VPOPCNTDQ instruction extensions.AVX512BW
– The AVX512BW instruction extensions.AVX512CD
– The AVX512CD instruction extensions.AVX512ER
– The AVX512ER instruction extensions.AVX512DQ
– The AVX512DQ instruction extensions.AVX512F
– The AVX512F instruction extensions.AVX512PF
– The AVX512PF instruction extensions.AVX512VL
– The AVX512VL instruction extensions.BMI1
– BMI1 instructions.BMI2
– BMI2 instructions.BUS_LOCK_DETECT
– Bus lock debug exceptions.CLDEMOTE
– CLDEMOTE instruction.CLFLUSHOPT
– CLFLUSHOPT instruction.CLFSH
– CLFLUSH instruction.CLWB
– CLWB instruction.CMOV
– Conditional Move instructions.CMPCCXADD
– CMPccXADD instruction.CMPXCHG16B
– CMPXCHG16B instruction.CNXT_ID
– L1 Context ID.CORE_CAPABILITIES
– IA32_CORE_CAPABILITIES MSR.CX8
– CMPXCHG8B instruction.DCA
– Data prefetch from a memory mapped device.DE
– Debugging Extensions.DEPR_FPU_CS_DS
– Deprecates FPU CS and FPU DS values.DS
– Debug Store.DS_CPL
– CPL Qualified Debug Store.DTES64
– 64-bit DS Area.EIST
– Enhanced Intel SpeedStep technology.ENQCMD
– Enqueue Stores instructions.ERMS
– Enhanced REP MOVSB/STOSB.F16C
– 16-bit floating-point conversion instructions.FMA
– FMA extensions using YMM state.FMA4
– FMA4 instruction extensions.FPU
– X87 Floating Point Unit On-Chip.FSGSBASE
– RDFSBASE/RDGSBASE/WRFSBASE/WRGSBASE instructions.FSRCS
– Fast Short REP CMP and SCA.FSRM
– Fast Short REP MOV.FSRS
– Fast Short REP STO.FXSR
– FXSAVE and FXRSTOR instructions.FZLRM
– Fast Zero-Length REP MOV.GFNI
– GFNI instruction extensions.HLE
– HLE instruction extensions.HTT
– Max APIC IDs reserved field is Valid.HRESET
– History reset.HYBRID
– Hybrid processor.IBRS_IBPB
– Indirect branch restricted speculation (IBRS) andthe indirect branch predictor barrier (IBPB).IBT
– Intel Indirect Branch Tracking instruction extensions.INVARIANT_TSC
– Invariant TSC.INVPCID
– INVPCID instruction.KL
– AES Key Locker instructions.L1D_FLUSH
– IA32_FLUSH_CMD MSR.LA57
– 57-bit linear addresses and five-level paging.LAHF64_SAHF64
– LAHF/SAHF available in 64-bit mode.LAM
– Linear Address Masking.LASS
– Linear Address Space Separation.LBR
– Architectural LBR.LM
– Long mode.LWP
– Lightweight profiling.LZCNT
– LZCNT instruction.MCA
– Machine Check Architecture.MCE
– Machine Check Exception.MD_CLEAR
– MD_CLEAR.MMX
– Intel MMX Technology.MONITOR
– MONITOR/MWAIT instructions.MOVBE
– MOVBE instruction.MOVDIRI
– MOVDIRI instruction.MOVDIR64B
– MOVDIR64B instruction.MPX
– Intel Memory Protection Extensions.MSR
– Model Specific Registers RDMSR and WRMSR instructions.MSRLIST
– RDMSRLIST/WRMSRLIST instructions and IA32_BARRIERMSR.MTRR
– Memory Type Range Registers.NX
– No-execute page protection.OSPKE
– OS has set CR4.PKE to enable protection keys.OSXSAVE
– The OS has set CR4.OSXSAVE[bit 18] to enableXSETBV/XGETBV instructions to access XCR0 and to support processorextended state management using XSAVE/XRSTOR.PAE
– Physical Address Extension.PAGE1GB
– 1-GByte page.PAT
– Page Attribute Table.PBE
– Pending Break Enable.PCID
– Process-context identifiers.PCLMULQDQ
– PCLMULQDQ instruction.PCONFIG
– PCONFIG instruction.PDCM
– Perfmon and Debug Capability.PGE
– Page Global Bit.PKS
– Protection keys for supervisor-mode pages.PKU
– Protection keys for user-mode pages.POPCNT
– POPCNT instruction.PREFETCHW
– PREFETCHW instruction.PREFETCHWT1
– PREFETCHWT1 instruction.PREFETCHI
– PREFETCHIT0/1 instructions.PSE
– Page Size Extension.PSE_36
– 36-Bit Page Size Extension.PSN
– Processor Serial Number.PTWRITE
– PTWRITE instruction.RAO_INT
– RAO-INT instructions.RDPID
– RDPID instruction.RDRAND
– RDRAND instruction.RDSEED
– RDSEED instruction.RDT_A
– Intel Resource Director Technology (Intel RDT) Allocationcapability.RDT_M
– Intel Resource Director Technology (Intel RDT) Monitoringcapability.RDTSCP
– RDTSCP instruction.RTM
– RTM instruction extensions.RTM_ALWAYS_ABORT
– Transactions always abort, making RTM unusable.RTM_FORCE_ABORT
– TSX_FORCE_ABORT MSR.SDBG
– IA32_DEBUG_INTERFACE MSR for silicon debug.SEP
– SYSENTER and SYSEXIT instructions.SERIALIZE
– SERIALIZE instruction.SGX
– Intel Software Guard Extensions.SGX_KEYS
– Attestation Services for SGX.SGX_LC
– SGX Launch Configuration.SHA
– SHA instruction extensions.SHSTK
– Intel Shadow Stack instruction extensions.SMAP
– Supervisor-Mode Access Prevention.SMEP
– Supervisor-Mode Execution Prevention.SMX
– Safer Mode Extensions.SS
– Self Snoop.SSBD
– Speculative Store Bypass Disable (SSBD).SSE
– Streaming SIMD Extensions.SSE2
– Streaming SIMD Extensions 2.SSE3
– Streaming SIMD Extensions 3.SSE4_1
– Streaming SIMD Extensions 4.1.SSE4_2
– Streaming SIMD Extensions 4.2.SSE4A
– SSE4A instruction extensions.SSSE3
– Supplemental Streaming SIMD Extensions 3.STIBP
– Single thread indirect branch predictors (STIBP).SVM
– Secure Virtual Machine.SYSCALL_SYSRET
– SYSCALL/SYSRET instructions.TBM
– Trailing bit manipulation instructions.TM
– Thermal Monitor.TM2
– Thermal Monitor 2.TRACE
– Intel Processor Trace.TSC
– Time Stamp Counter. RDTSC instruction.TSC_ADJUST
– IA32_TSC_ADJUST MSR.TSC_DEADLINE
– Local APIC timer supports one-shot operationusing a TSC deadline value.TSXLDTRK
– TSXLDTRK instructions.UINTR
– User interrupts.UMIP
– User-mode instruction prevention.VAES
– VAES instruction extensions.VME
– Virtual 8086 Mode Enhancements.VMX
– Virtual Machine Extensions.VPCLMULQDQ
– VPCLMULQDQ instruction.WAITPKG
– WAITPKG instruction extensions.WBNOINVD
– WBINVD/WBNOINVD instructions.WIDE_KL
– AES wide Key Locker instructions.WRMSRNS
– WRMSRNS instruction.X2APIC
– x2APIC.XFD
– Extended Feature Disable (XFD).XGETBV_ECX_1
– XGETBV with ECX = 1.XOP
– XOP instruction extensions.XSAVE
– The XSAVE/XRSTOR processor extended states feature, theXSETBV/XGETBV instructions, and XCR0.XSAVEC
– XSAVEC instruction.XSAVEOPT
– XSAVEOPT instruction.XSAVES
– XSAVES/XRSTORS instructions.XTPRUPDCTRL
– xTPR Update Control.You could query if a processor supportsAVX
with:
#include <sys/platform/x86.h>intavx_present (void){ return CPU_FEATURE_PRESENT (AVX);}
and ifAVX
is active and may be used with:
#include <sys/platform/x86.h>intavx_active (void){ return CPU_FEATURE_ACTIVE (AVX);}
Next:Free Software Needs Free Documentation, Previous:Platform-specific facilities, Up:Main Menu [Contents][Index]
The GNU C Library project would like to thank its many contributors.Without them the project would not have been nearly as successful asit has been. Any omissions in this list are accidental. Feel free tofile a bug in bugzilla if you have been left out or some of yourcontributions are not listed. Please keep this list in alphabeticalorder.
argp
argument-parsing package, and theargz
/envz
interfaces.strstr
function.memmem
,strstr
andstrcasestr
.arm-ANYTHING-linuxaout
) and ARM standalone(arm-ANYTHING-none
), as well as for parts of the IPv6support code.libio
library whichis used to implementstdio
functions.locale
andlocaledef
utilities.hsearch
anddrand48
families of functions,reentrant ‘…_r
’ versions of therandom
family; System V shared memory and IPC support codeiconv
)ftw
andnftw
functionsprintf
and friendsand the floating-point reading function used byscanf
,strtod
and friendscatgets
support and the entire suite of multi-byteand wide-character support functions (wctype.h,wchar.h, etc.).mktime
function, for his direction aspart of the GNU C Library steering committee, and numerous fixes.crypt
and relatedfunctions (no longer part of glibc, but we still appreciate his work).malloc
,realloc
andfree
and relatedcode.memcpy
,strlen
, etc.).qsort
and malloc checking functions likemcheck
.iconv
and localeimplementations and various fixes.alpha-anything-linux
) and software floating-point support.x86_64-anything-linux
and his work on Linux for MIPS(mips-anything-linux
), implementing theldconfigprogram, providing a test suite for the math library and for hisdirection as part of the GNU C Library steering committee.libidn
add-on.powerpc-anything-linux
).mips-dec-ultrix4
) and the port to the DEC Alpharunning OSF/1 (alpha-dec-osf1
).utmpx
interface and a utmpdaemon, and for a Hesiod NSS module.mips-anything-gnu
) and for his work on theSH architecture.malloc
,realloc
andfree
and relatedcode.getopt
function and writing thetar.h header.i386-sequent-bsd
).tilegx-anything-linux
andtilepro-anything-linux
) and support for the generic Linuxkernel syscall interface used by several newer ports.sparc*-anything-linux
).alpha-anything-linux
).powerpc64-anything-linux
) and for adding optimizedimplementations for PowerPC.mips-sgi-irix4
).qsort
.m68k-anything-linux
), for his direction as part ofthe GNU C Library steering committee, and for various bug fixes.s390-anything-linux
) and s390x(s390x-anything-linux
).ia64-anything-linux
).getopt
function.mips-dec-ultrix4
).wordexp
function family.explicit_bzero
implementation and for variousfixes.Some code in the GNU C Library comes from other projects and might be undera different license:
random
,srandom
,setstate
andinitstate
, which are also the basis for therand
andsrand
functions, were written by Earl T. Cohenfor the University of California at Berkeley and are copyrighted by theRegents of the University of California. They have undergone minorchanges to fit into the GNU C Library and to fit the ISO C standard,but the functional code is Berkeley’s.getaddrinfo
andgetnameinfo
functions and supportingcode were written by Craig Metz; see the fileLICENSES fordetails on their licensing.fdlibm-5.1
by SunMicrosystems, as modified by J.T. Conklin, Ian Lance Taylor,Ulrich Drepper, Andreas Schwab, and Roland McGrath.CORE-MATH
project with main developers Paul Zimmermann andAlexei Sibidanov, see again the fileLICENSES.Next:GNU Lesser General Public License, Previous:Contributors to the GNU C Library, Up:Main Menu [Contents][Index]
The biggest deficiency in the free software community today is not inthe software—it is the lack of good free documentation that we caninclude with the free software. Many of our most importantprograms do not come with free reference manuals and free introductorytexts. Documentation is an essential part of any software package;when an important free software package does not come with a freemanual and a free tutorial, that is a major gap. We have many suchgaps today.
Consider Perl, for instance. The tutorial manuals that peoplenormally use are non-free. How did this come about? Because theauthors of those manuals published them with restrictive terms—nocopying, no modification, source files not available—which excludethem from the free software world.
That wasn’t the first time this sort of thing happened, and it was farfrom the last. Many times we have heard a GNU user eagerly describe amanual that he is writing, his intended contribution to the community,only to learn that he had ruined everything by signing a publicationcontract to make it non-free.
Free documentation, like free software, is a matter of freedom, notprice. The problem with the non-free manual is not that publisherscharge a price for printed copies—that in itself is fine. (The FreeSoftware Foundation sells printed copies of manuals, too.) Theproblem is the restrictions on the use of the manual. Free manualsare available in source code form, and give you permission to copy andmodify. Non-free manuals do not allow this.
The criteria of freedom for a free manual are roughly the same as forfree software. Redistribution (including the normal kinds ofcommercial redistribution) must be permitted, so that the manual canaccompany every copy of the program, both on-line and on paper.
Permission for modification of the technical content is crucial too.When people modify the software, adding or changing features, if theyare conscientious they will change the manual too—so they canprovide accurate and clear documentation for the modified program. Amanual that leaves you no choice but to write a new manual to documenta changed version of the program is not really available to ourcommunity.
Some kinds of limits on the way modification is handled areacceptable. For example, requirements to preserve the originalauthor’s copyright notice, the distribution terms, or the list ofauthors, are ok. It is also no problem to require modified versionsto include notice that they were modified. Even entire sections thatmay not be deleted or changed are acceptable, as long as they dealwith nontechnical topics (like this one). These kinds of restrictionsare acceptable because they don’t obstruct the community’s normal useof the manual.
However, it must be possible to modify all thetechnicalcontent of the manual, and then distribute the result in all the usualmedia, through all the usual channels. Otherwise, the restrictionsobstruct the use of the manual, it is not free, and we need anothermanual to replace it.
Please spread the word about this issue. Our community continues tolose manuals to proprietary publishing. If we spread the word thatfree software needs free reference manuals and free tutorials, perhapsthe next person who wants to contribute by writing documentation willrealize, before it is too late, that only free manuals contribute tothe free software community.
If you are writing documentation, please insist on publishing it underthe GNU Free Documentation License or another free documentationlicense. Remember that this decision requires your approval—youdon’t have to let the publisher decide. Some commercial publisherswill use a free license if you insist, but they will not propose theoption; it is up to you to raise the issue and say firmly that this iswhat you want. If the publisher you are dealing with refuses, pleasetry other publishers. If you’re not sure whether a proposed licenseis free, write tolicensing@gnu.org.
You can encourage commercial publishers to sell more free, copyleftedmanuals and tutorials by buying them, and particularly by buyingcopies from the publishers that paid for their writing or for majorimprovements. Meanwhile, try to avoid buying non-free documentationat all. Check the distribution terms of a manual before you buy it,and insist that whoever seeks your business must respect your freedom.Check the history of the book, and try reward the publishers that havepaid or pay the authors to work on it.
The Free Software Foundation maintains a list of free documentationpublished by other publishers, athttps://www.fsf.org/doc/other-free-books.html.
Next:GNU Free Documentation License, Previous:Free Software Needs Free Documentation, Up:Main Menu [Contents][Index]
Copyright © 1991, 1999 Free Software Foundation, Inc.51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USAEveryone is permitted to copy and distribute verbatim copiesof this license document, but changing it is not allowed.[This is the first released version of the Lesser GPL. It also countsas the successor of the GNU Library Public License, version 2, hence theversion number 2.1.]
The licenses for most software are designed to take away yourfreedom to share and change it. By contrast, the GNU General PublicLicenses are intended to guarantee your freedom to share and changefree software—to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to somespecially designated software—typically libraries—of the FreeSoftware Foundation and other authors who decide to use it. You can useit too, but we suggest you first think carefully about whether thislicense or the ordinary General Public License is the better strategy touse in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,not price. Our General Public Licenses are designed to make sure thatyou have the freedom to distribute copies of free software (and chargefor this service if you wish); that you receive source code or can getit if you want it; that you can change the software and use pieces of itin new free programs; and that you are informed that you can do thesethings.
To protect your rights, we need to make restrictions that forbiddistributors to deny you these rights or to ask you to surrender theserights. These restrictions translate to certain responsibilities foryou if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratisor for a fee, you must give the recipients all the rights that we gaveyou. You must make sure that they, too, receive or can get the sourcecode. If you link other code with the library, you must providecomplete object files to the recipients, so that they can relink themwith the library after making changes to the library and recompilingit. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright thelibrary, and (2) we offer you this license, which gives you legalpermission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear thatthere is no warranty for the free library. Also, if the library ismodified by someone else and passed on, the recipients should knowthat what they have is not the original version, so that the originalauthor’s reputation will not be affected by problems that might beintroduced by others.
Finally, software patents pose a constant threat to the existence ofany free program. We wish to make sure that a company cannoteffectively restrict the users of a free program by obtaining arestrictive license from a patent holder. Therefore, we insist thatany patent license obtained for a version of the library must beconsistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by theordinary GNU General Public License. This license, the GNU LesserGeneral Public License, applies to certain designated libraries, andis quite different from the ordinary General Public License. We usethis license for certain libraries in order to permit linking thoselibraries into non-free programs.
When a program is linked with a library, whether statically or usinga shared library, the combination of the two is legally speaking acombined work, a derivative of the original library. The ordinaryGeneral Public License therefore permits such linking only if theentire combination fits its criteria of freedom. The Lesser GeneralPublic License permits more lax criteria for linking other code withthe library.
We call this license theLesser General Public License because itdoesLess to protect the user’s freedom than the ordinary GeneralPublic License. It also provides other free software developers Lessof an advantage over competing non-free programs. These disadvantagesare the reason we use the ordinary General Public License for manylibraries. However, the Lesser license provides advantages in certainspecial circumstances.
For example, on rare occasions, there may be a special need toencourage the widest possible use of a certain library, so that it becomesa de-facto standard. To achieve this, non-free programs must beallowed to use the library. A more frequent case is that a freelibrary does the same job as widely used non-free libraries. In thiscase, there is little to gain by limiting the free library to freesoftware only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-freeprograms enables a greater number of people to use a large body offree software. For example, permission to use the GNU C Library innon-free programs enables many more people to use the whole GNUoperating system, as well as its variant, the GNU/Linux operatingsystem.
Although the Lesser General Public License is Less protective of theusers’ freedom, it does ensure that the user of a program that islinked with the Library has the freedom and the wherewithal to runthat program using a modified version of the Library.
The precise terms and conditions for copying, distribution andmodification follow. Pay close attention to the difference between a“work based on the library” and a “work that uses the library”. Theformer contains code derived from the library, whereas the latter mustbe combined with the library in order to run.
A “library” means a collection of software functions and/or dataprepared so as to be conveniently linked with application programs(which use some of those functions and data) to form executables.
The “Library”, below, refers to any such software library or workwhich has been distributed under these terms. A “work based on theLibrary” means either the Library or any derivative work undercopyright law: that is to say, a work containing the Library or aportion of it, either verbatim or with modifications and/or translatedstraightforwardly into another language. (Hereinafter, translation isincluded without limitation in the term “modification”.)
“Source code” for a work means the preferred form of the work formaking modifications to it. For a library, complete source code meansall the source code for all modules it contains, plus any associatedinterface definition files, plus the scripts used to control compilationand installation of the library.
Activities other than copying, distribution and modification are notcovered by this License; they are outside its scope. The act ofrunning a program using the Library is not restricted, and output fromsuch a program is covered only if its contents constitute a work basedon the Library (independent of the use of the Library in a tool forwriting it). Whether that is true depends on what the Library doesand what the program that uses the Library does.
You may charge a fee for the physical act of transferring a copy,and you may at your option offer warranty protection in exchange for afee.
(For example, a function in a library to compute square roots hasa purpose that is entirely well-defined independent of theapplication. Therefore, Subsection 2d requires that anyapplication-supplied function or table used by this function mustbe optional: if the application does not supply it, the squareroot function must still compute square roots.)
These requirements apply to the modified work as a whole. Ifidentifiable sections of that work are not derived from the Library,and can be reasonably considered independent and separate works inthemselves, then this License, and its terms, do not apply to thosesections when you distribute them as separate works. But when youdistribute the same sections as part of a whole which is a work basedon the Library, the distribution of the whole must be on the terms ofthis License, whose permissions for other licensees extend to theentire whole, and thus to each and every part regardless of who wroteit.
Thus, it is not the intent of this section to claim rights or contestyour rights to work written entirely by you; rather, the intent is toexercise the right to control the distribution of derivative orcollective works based on the Library.
In addition, mere aggregation of another work not based on the Librarywith the Library (or with a work based on the Library) on a volume ofa storage or distribution medium does not bring the other work underthe scope of this License.
Once this change is made in a given copy, it is irreversible forthat copy, so the ordinary GNU General Public License applies to allsubsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code ofthe Library into a program that is not a library.
If distribution of object code is made by offering access to copyfrom a designated place, then offering equivalent access to copy thesource code from the same place satisfies the requirement todistribute the source code, even though third parties are notcompelled to copy the source along with the object code.
However, linking a “work that uses the Library” with the Librarycreates an executable that is a derivative of the Library (because itcontains portions of the Library), rather than a “work that uses thelibrary”. The executable is therefore covered by this License.Section 6 states terms for distribution of such executables.
When a “work that uses the Library” uses material from a header filethat is part of the Library, the object code for the work may be aderivative work of the Library even though the source code is not.Whether this is true is especially significant if the work can belinked without the Library, or if the work is itself a library. Thethreshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, datastructure layouts and accessors, and small macros and small inlinefunctions (ten lines or less in length), then the use of the objectfile is unrestricted, regardless of whether it is legally a derivativework. (Executables containing this object code plus portions of theLibrary will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you maydistribute the object code for the work under the terms of Section 6.Any executables containing that work also fall under Section 6,whether or not they are linked directly with the Library itself.
You must give prominent notice with each copy of the work that theLibrary is used in it and that the Library and its use are covered bythis License. You must supply a copy of this License. If the workduring execution displays copyright notices, you must include thecopyright notice for the Library among them, as well as a referencedirecting the user to the copy of this License. Also, you must do oneof these things:
For an executable, the required form of the “work that uses theLibrary” must include any data and utility programs needed forreproducing the executable from it. However, as a special exception,the materials to be distributed need not include anything that isnormally distributed (in either source or binary form) with the majorcomponents (compiler, kernel, and so on) of the operating system onwhich the executable runs, unless that component itself accompanies theexecutable.
It may happen that this requirement contradicts the licenserestrictions of other proprietary libraries that do not normallyaccompany the operating system. Such a contradiction means you cannotuse both them and the Library together in an executable that youdistribute.
If any portion of this section is held invalid or unenforceable under anyparticular circumstance, the balance of the section is intended to apply,and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe anypatents or other property right claims or to contest validity of anysuch claims; this section has the sole purpose of protecting theintegrity of the free software distribution system which isimplemented by public license practices. Many people have madegenerous contributions to the wide range of software distributedthrough that system in reliance on consistent application of thatsystem; it is up to the author/donor to decide if he or she is willingto distribute software through any other system and a licensee cannotimpose that choice.
This section is intended to make thoroughly clear what is believed tobe a consequence of the rest of this License.
Each version is given a distinguishing version number. If the Libraryspecifies a version number of this License which applies to it and“any later version”, you have the option of following the terms andconditions either of that version or of any later version published bythe Free Software Foundation. If the Library does not specify alicense version number, you may choose any version ever published bythe Free Software Foundation.
If you develop a new library, and you want it to be of the greatestpossible use to the public, we recommend making it free software thateveryone can redistribute and change. You can do so by permittingredistribution under these terms (or, alternatively, under the terms of theordinary General Public License).
To apply these terms, attach the following notices to the library. It issafest to attach them to the start of each source file to most effectivelyconvey the exclusion of warranty; and each file should have at least the“copyright” line and a pointer to where the full notice is found.
one line to give the library's name and an idea of what it does.Copyright (C)yearname of authorThis library is free software; you can redistribute it and/or modify itunder the terms of the GNU Lesser General Public License as published bythe Free Software Foundation; either version 2.1 of the License, or (atyour option) any later version.This library is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNULesser General Public License for more details.You should have received a copy of the GNU Lesser General PublicLicense along with this library; if not, write to the Free SoftwareFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,USA.
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or yourschool, if any, to sign a “copyright disclaimer” for the library, ifnecessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the library`Frob' (a library for tweaking knobs) written by James Random Hacker.signature of Ty Coon, 1 April 1990Ty Coon, President of Vice
That’s all there is to it!
Next:Concept Index, Previous:GNU Lesser General Public License, Up:Main Menu [Contents][Index]
Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc.https://fsf.org/Everyone is permitted to copy and distribute verbatim copiesof this license document, but changing it is not allowed.
The purpose of this License is to make a manual, textbook, or otherfunctional and useful documentfree in the sense of freedom: toassure everyone the effective freedom to copy and redistribute it,with or without modifying it, either commercially or noncommercially.Secondarily, this License preserves for the author and publisher a wayto get credit for their work, while not being considered responsiblefor modifications made by others.
This License is a kind of “copyleft”, which means that derivativeworks of the document must themselves be free in the same sense. Itcomplements the GNU General Public License, which is a copyleftlicense designed for free software.
We have designed this License in order to use it for manuals for freesoftware, because free software needs free documentation: a freeprogram should come with manuals providing the same freedoms that thesoftware does. But this License is not limited to software manuals;it can be used for any textual work, regardless of subject matter orwhether it is published as a printed book. We recommend this Licenseprincipally for works whose purpose is instruction or reference.
This License applies to any manual or other work, in any medium, thatcontains a notice placed by the copyright holder saying it can bedistributed under the terms of this License. Such a notice grants aworld-wide, royalty-free license, unlimited in duration, to use thatwork under the conditions stated herein. The “Document”, below,refers to any such manual or work. Any member of the public is alicensee, and is addressed as “you”. You accept the license if youcopy, modify or distribute the work in a way requiring permissionunder copyright law.
A “Modified Version” of the Document means any work containing theDocument or a portion of it, either copied verbatim, or withmodifications and/or translated into another language.
A “Secondary Section” is a named appendix or a front-matter sectionof the Document that deals exclusively with the relationship of thepublishers or authors of the Document to the Document’s overallsubject (or to related matters) and contains nothing that could falldirectly within that overall subject. (Thus, if the Document is inpart a textbook of mathematics, a Secondary Section may not explainany mathematics.) The relationship could be a matter of historicalconnection with the subject or with related matters, or of legal,commercial, philosophical, ethical or political position regardingthem.
The “Invariant Sections” are certain Secondary Sections whose titlesare designated, as being those of Invariant Sections, in the noticethat says that the Document is released under this License. If asection does not fit the above definition of Secondary then it is notallowed to be designated as Invariant. The Document may contain zeroInvariant Sections. If the Document does not identify any InvariantSections then there are none.
The “Cover Texts” are certain short passages of text that are listed,as Front-Cover Texts or Back-Cover Texts, in the notice that says thatthe Document is released under this License. A Front-Cover Text maybe at most 5 words, and a Back-Cover Text may be at most 25 words.
A “Transparent” copy of the Document means a machine-readable copy,represented in a format whose specification is available to thegeneral public, that is suitable for revising the documentstraightforwardly with generic text editors or (for images composed ofpixels) generic paint programs or (for drawings) some widely availabledrawing editor, and that is suitable for input to text formatters orfor automatic translation to a variety of formats suitable for inputto text formatters. A copy made in an otherwise Transparent fileformat whose markup, or absence of markup, has been arranged to thwartor discourage subsequent modification by readers is not Transparent.An image format is not Transparent if used for any substantial amountof text. A copy that is not “Transparent” is called “Opaque”.
Examples of suitable formats for Transparent copies include plainASCII without markup, Texinfo input format, LaTeX inputformat, SGML or XML using a publicly availableDTD, and standard-conforming simple HTML,PostScript or PDF designed for human modification. Examplesof transparent image formats include PNG, XCF andJPG. Opaque formats include proprietary formats that can beread and edited only by proprietary word processors, SGML orXML for which the DTD and/or processing tools arenot generally available, and the machine-generated HTML,PostScript or PDF produced by some word processors foroutput purposes only.
The “Title Page” means, for a printed book, the title page itself,plus such following pages as are needed to hold, legibly, the materialthis License requires to appear in the title page. For works informats which do not have any title page as such, “Title Page” meansthe text near the most prominent appearance of the work’s title,preceding the beginning of the body of the text.
The “publisher” means any person or entity that distributes copiesof the Document to the public.
A section “Entitled XYZ” means a named subunit of the Document whosetitle either is precisely XYZ or contains XYZ in parentheses followingtext that translates XYZ in another language. (Here XYZ stands for aspecific section name mentioned below, such as “Acknowledgements”,“Dedications”, “Endorsements”, or “History”.) To “Preserve the Title”of such a section when you modify the Document means that it remains asection “Entitled XYZ” according to this definition.
The Document may include Warranty Disclaimers next to the notice whichstates that this License applies to the Document. These WarrantyDisclaimers are considered to be included by reference in thisLicense, but only as regards disclaiming warranties: any otherimplication that these Warranty Disclaimers may have is void and hasno effect on the meaning of this License.
You may copy and distribute the Document in any medium, eithercommercially or noncommercially, provided that this License, thecopyright notices, and the license notice saying this License appliesto the Document are reproduced in all copies, and that you add no otherconditions whatsoever to those of this License. You may not usetechnical measures to obstruct or control the reading or furthercopying of the copies you make or distribute. However, you may acceptcompensation in exchange for copies. If you distribute a large enoughnumber of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, andyou may publicly display copies.
If you publish printed copies (or copies in media that commonly haveprinted covers) of the Document, numbering more than 100, and theDocument’s license notice requires Cover Texts, you must enclose thecopies in covers that carry, clearly and legibly, all these CoverTexts: Front-Cover Texts on the front cover, and Back-Cover Texts onthe back cover. Both covers must also clearly and legibly identifyyou as the publisher of these copies. The front cover must presentthe full title with all words of the title equally prominent andvisible. You may add other material on the covers in addition.Copying with changes limited to the covers, as long as they preservethe title of the Document and satisfy these conditions, can be treatedas verbatim copying in other respects.
If the required texts for either cover are too voluminous to fitlegibly, you should put the first ones listed (as many as fitreasonably) on the actual cover, and continue the rest onto adjacentpages.
If you publish or distribute Opaque copies of the Document numberingmore than 100, you must either include a machine-readable Transparentcopy along with each Opaque copy, or state in or with each Opaque copya computer-network location from which the general network-usingpublic has access to download using public-standard network protocolsa complete Transparent copy of the Document, free of added material.If you use the latter option, you must take reasonably prudent steps,when you begin distribution of Opaque copies in quantity, to ensurethat this Transparent copy will remain thus accessible at the statedlocation until at least one year after the last time you distribute anOpaque copy (directly or through your agents or retailers) of thatedition to the public.
It is requested, but not required, that you contact the authors of theDocument well before redistributing any large number of copies, to givethem a chance to provide you with an updated version of the Document.
You may copy and distribute a Modified Version of the Document underthe conditions of sections 2 and 3 above, provided that you releasethe Modified Version under precisely this License, with the ModifiedVersion filling the role of the Document, thus licensing distributionand modification of the Modified Version to whoever possesses a copyof it. In addition, you must do these things in the Modified Version:
If the Modified Version includes new front-matter sections orappendices that qualify as Secondary Sections and contain no materialcopied from the Document, you may at your option designate some or allof these sections as invariant. To do this, add their titles to thelist of Invariant Sections in the Modified Version’s license notice.These titles must be distinct from any other section titles.
You may add a section Entitled “Endorsements”, provided it containsnothing but endorsements of your Modified Version by variousparties—for example, statements of peer review or that the text hasbeen approved by an organization as the authoritative definition of astandard.
You may add a passage of up to five words as a Front-Cover Text, and apassage of up to 25 words as a Back-Cover Text, to the end of the listof Cover Texts in the Modified Version. Only one passage ofFront-Cover Text and one of Back-Cover Text may be added by (orthrough arrangements made by) any one entity. If the Document alreadyincludes a cover text for the same cover, previously added by you orby arrangement made by the same entity you are acting on behalf of,you may not add another; but you may replace the old one, on explicitpermission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this Licensegive permission to use their names for publicity for or to assert orimply endorsement of any Modified Version.
You may combine the Document with other documents released under thisLicense, under the terms defined in section 4 above for modifiedversions, provided that you include in the combination all of theInvariant Sections of all of the original documents, unmodified, andlist them all as Invariant Sections of your combined work in itslicense notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, andmultiple identical Invariant Sections may be replaced with a singlecopy. If there are multiple Invariant Sections with the same name butdifferent contents, make the title of each such section unique byadding at the end of it, in parentheses, the name of the originalauthor or publisher of that section if known, or else a unique number.Make the same adjustment to the section titles in the list ofInvariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled “History”in the various original documents, forming one section Entitled“History”; likewise combine any sections Entitled “Acknowledgements”,and any sections Entitled “Dedications”. You must delete allsections Entitled “Endorsements.”
You may make a collection consisting of the Document and other documentsreleased under this License, and replace the individual copies of thisLicense in the various documents with a single copy that is included inthe collection, provided that you follow the rules of this License forverbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distributeit individually under this License, provided you insert a copy of thisLicense into the extracted document, and follow this License in allother respects regarding verbatim copying of that document.
A compilation of the Document or its derivatives with other separateand independent documents or works, in or on a volume of a storage ordistribution medium, is called an “aggregate” if the copyrightresulting from the compilation is not used to limit the legal rightsof the compilation’s users beyond what the individual works permit.When the Document is included in an aggregate, this License does notapply to the other works in the aggregate which are not themselvesderivative works of the Document.
If the Cover Text requirement of section 3 is applicable to thesecopies of the Document, then if the Document is less than one half ofthe entire aggregate, the Document’s Cover Texts may be placed oncovers that bracket the Document within the aggregate, or theelectronic equivalent of covers if the Document is in electronic form.Otherwise they must appear on printed covers that bracket the wholeaggregate.
Translation is considered a kind of modification, so you maydistribute translations of the Document under the terms of section 4.Replacing Invariant Sections with translations requires specialpermission from their copyright holders, but you may includetranslations of some or all Invariant Sections in addition to theoriginal versions of these Invariant Sections. You may include atranslation of this License, and all the license notices in theDocument, and any Warranty Disclaimers, provided that you also includethe original English version of this License and the original versionsof those notices and disclaimers. In case of a disagreement betweenthe translation and the original version of this License or a noticeor disclaimer, the original version will prevail.
If a section in the Document is Entitled “Acknowledgements”,“Dedications”, or “History”, the requirement (section 4) to Preserveits Title (section 1) will typically require changing the actualtitle.
You may not copy, modify, sublicense, or distribute the Documentexcept as expressly provided under this License. Any attemptotherwise to copy, modify, sublicense, or distribute it is void, andwill automatically terminate your rights under this License.
However, if you cease all violation of this License, then your licensefrom a particular copyright holder is reinstated (a) provisionally,unless and until the copyright holder explicitly and finallyterminates your license, and (b) permanently, if the copyright holderfails to notify you of the violation by some reasonable means prior to60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, receipt of a copy of some or all of the same material doesnot give you any rights to use it.
The Free Software Foundation may publish new, revised versionsof the GNU Free Documentation License from time to time. Such newversions will be similar in spirit to the present version, but maydiffer in detail to address new problems or concerns. Seehttps://www.gnu.org/licenses/.
Each version of the License is given a distinguishing version number.If the Document specifies that a particular numbered version of thisLicense “or any later version” applies to it, you have the option offollowing the terms and conditions either of that specified version orof any later version that has been published (not as a draft) by theFree Software Foundation. If the Document does not specify a versionnumber of this License, you may choose any version ever published (notas a draft) by the Free Software Foundation. If the Documentspecifies that a proxy can decide which future versions of thisLicense can be used, that proxy’s public statement of acceptance of aversion permanently authorizes you to choose that version for theDocument.
“Massive Multiauthor Collaboration Site” (or “MMC Site”) means anyWorld Wide Web server that publishes copyrightable works and alsoprovides prominent facilities for anybody to edit those works. Apublic wiki that anybody can edit is an example of such a server. A“Massive Multiauthor Collaboration” (or “MMC”) contained in thesite means any set of copyrightable works thus published on the MMCsite.
“CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0license published by Creative Commons Corporation, a not-for-profitcorporation with a principal place of business in San Francisco,California, as well as future copyleft versions of that licensepublished by that same organization.
“Incorporate” means to publish or republish a Document, in whole orin part, as part of another Document.
An MMC is “eligible for relicensing” if it is licensed under thisLicense, and if all works that were first published under this Licensesomewhere other than this MMC, and subsequently incorporated in wholeor in part into the MMC, (1) had no cover texts or invariant sections,and (2) were thus incorporated prior to November 1, 2008.
The operator of an MMC Site may republish an MMC contained in the siteunder CC-BY-SA on the same site at any time before August 1, 2009,provided the MMC is eligible for relicensing.
To use this License in a document you have written, include a copy ofthe License in the document and put the following copyright andlicense notices just after the title page:
Copyright (C)yearyour name. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''.
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,replace the “with…Texts.” line with this:
with the Invariant Sections beinglist their titles, with the Front-Cover Texts beinglist, and with the Back-Cover Texts beinglist.
If you have Invariant Sections without Cover Texts, or some othercombination of the three, merge those two alternatives to suit thesituation.
If your document contains nontrivial examples of program code, werecommend releasing these examples in parallel under your choice offree software license, such as the GNU General Public License,to permit their use in free software.
Next:Type Index, Previous:GNU Free Documentation License, Up:Main Menu [Contents][Index]
Jump to: | _ : ! ? . ... / 4 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z |
---|
Jump to: | _ : ! ? . ... / 4 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z |
---|
Next:Function and Macro Index, Previous:Concept Index, Up:Main Menu [Contents][Index]
Jump to: | _ B C D E F G I J L M N O P R S T U V W |
---|
Jump to: | _ B C D E F G I J L M N O P R S T U V W |
---|
Next:Variable and Constant Macro Index, Previous:Type Index, Up:Main Menu [Contents][Index]
Jump to: | _ A B C D E F G H I J K L M N O P Q R S T U V W Y |
---|
Jump to: | _ A B C D E F G H I J K L M N O P Q R S T U V W Y |
---|
Next:Program and File Index, Previous:Function and Macro Index, Up:Main Menu [Contents][Index]
Jump to: | _ ( A B C D E F G H I L M N O P R S T U V W X Y |
---|
Jump to: | _ ( A B C D E F G H I L M N O P R S T U V W X Y |
---|
Previous:Variable and Constant Macro Index, Up:Main Menu [Contents][Index]
Jump to: | / A C D E F G H I K L M N O P S T U W Z |
---|
Jump to: | / A C D E F G H I K L M N O P S T U W Z |
---|
Versions of the GNU C Library before 2.25 required that acustommalloc
defines__libc_memalign
(with the sameinterface as thememalign
function).
Additions are welcome. Send appropriate information tobug-glibc-manual@gnu.org.
Actually, the terminal-specific functions are implemented withIOCTLs on many platforms.
Now you might ask why this information isduplicated. The answer is that we want to make it possible to linkdirectly with these shared objects.
There is a second explanation: we were toolazy to change the Makefiles to allow the generation of shared objectsnot starting withlib but don’t tell this to anybody.