Portable Operating System Interface (POSIX ) System

Portable Operating System Interface (POSIX ) System
IEEE Std 1003.1-2001
(Revision of IEEE Std 1003.1-1996
and IEEE Std 1003.2-1992)
Open Group Technical Standard
Base Specifications, Issue 6
1003.1 TM
Standard for Information Technology —
Portable Operating System Interface (POSIX)
System Interfaces, Issue 6
Approved 12 September 2001
The Open Group
IEEE Sponsor
Portable Applications Standards Committee
of the
IEEE Computer Society
Approved 6 December 2001
IEEE-SA Standards Board
Abstract
This standard defines a standard operating system interface and environment, including a command interpreter (or ‘‘shell’’), and
common utility programs to support applications portability at the source code level. It is the single common revision to IEEE Std
1003.1-1996, IEEE Std 1003.2-1992, and the Base Specifications of The Open Group Single UNIX† Specification, Version 2. This
standard is intended to be used by both applications developers and system implementors and comprises four major components
(each in an associated volume):
•
General terms, concepts, and interfaces common to all volumes of this standard, including utility conventions and C-language
header definitions, are included in the Base Definitions volume.
•
Definitions for system service functions and subroutines, language-specific system services for the C programming language,
function issues, including portability, error handling, and error recovery, are included in the System Interfaces volume.
•
Definitions for a standard source code-level interface to command interpretation services (a ‘‘shell’’) and common utility
programs for application programs are included in the Shell and Utilities volume.
•
Extended rationale that did not fit well into the rest of the document structure, containing historical information concerning the
contents of this standard and why features were included or discarded by the standard developers, is included in the Rationale
(Informative) volume.
The following areas are outside the scope of this standard:
•
Graphics interfaces
•
Database management system interfaces
•
Record I/O considerations
•
Object or binary code portability
•
System configuration and resource availability
This standard describes the external characteristics and facilities that are of importance to applications developers, rather than the
internal construction techniques employed to achieve these capabilities. Special emphasis is placed on those functions and facilities
that are needed in a wide variety of commercial applications.
Keywords
application program interface (API), argument, asynchronous, basic regular expression (BRE), batch job, batch system, built-in
utility, byte, child, command language interpreter, CPU, extended regular expression (ERE), FIFO, file access control mechanism,
input/output (I/O), job control, network, portable operating system interface (POSIX†), parent, shell, stream, string, synchronous,
system, thread, X/Open System Interface (XSI)
_ ______________________
†
ii
See Trademarks (on page xl).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Copyright  2001 by the Institute of Electrical and Electronics Engineers, Inc. and The Open Group
System Interfaces, Issue 6
Published 6 December 2001 by the Institute of Electrical and Electronics Engineers, Inc.
3 Park Avenue, New York, NY 10016-5997, U.S.A.
ISBN: 0-7381-3048-6 PDF 0-7381-3010-9/SS94956 CD-ROM 0-7381-3129-6/SE94956
Printed in the United States of America by the IEEE.
Published 6 December 2001 by The Open Group
Apex Plaza, Forbury Road, Reading, Berkshire RG1 1AX, U.K.
Document Number: C951
ISBN: U.K. 1-85912-252-3 U.S. 1-931624-08-9
Printed in the U.K. by The Open Group.
All rights reserved. No part of this publication may be reproduced in any form, in an electronic retrieval system or otherwise,
without prior written permission from both the IEEE and The Open Group.
Portions of this standard are derived with permission from copyrighted material owned by Hewlett-Packard Company,
International Business Machines Corporation, Novell Inc., The Open Software Foundation, and Sun Microsystems, Inc.
Permissions
Authorization to photocopy portions of this standard for internal or personal use is granted provided that the appropriate fee is paid
to the Copyright Clearance Center or the equivalent body outside of the U.S. Permission to make multiple copies for educational
purposes in the U.S. requires agreement and a license fee to be paid to the Copyright Clearance Center.
Beyond these provisions, permission to reproduce all or any part of this standard must be with the consent of both copyright holders
and may be subject to a license fee. Both copyright holders will need to be satisfied that the other has granted permission. Requests
to the copyright holders should be sent by email to [email protected]
Feedback
This standard has been prepared by the Austin Group. Feedback relating to the material contained in this standard may be
submitted using the Austin Group web site at http://www.opengroup.org/austin/defectform.html.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
iii
IEEE
IEEE Standards documents are developed within the IEEE Societies and the Standards Coordinating Committees of the IEEE
Standards Association (IEEE-SA) Standards Board. The IEEE develops its standards through a consensus development process,
approved by the American National Standards Institute, which brings together volunteers representing varied viewpoints and
interests to achieve the final product. Volunteers are not necessarily members of the Institute and serve without compensation.
While the IEEE administers the process and establishes rules to promote fairness in the consensus development process, the IEEE
does not independently evaluate, test, or verify the accuracy of any of the information contained in its standards.
Use of an IEEE Standard is wholly voluntary. The IEEE disclaims liability for any personal injury, property, or other damage, of any
nature whatsoever, whether special, indirect, consequential, or compensatory, directly or indirectly resulting from the publication,
use of, or reliance upon this, or any other IEEE Standard document.
The IEEE does not warrant or represent the accuracy or content of the material contained herein, and expressly disclaims any
express or implied warranty, including any implied warranty of merchantability or fitness for a specific purpose, or that the use
of the material contained herein is free from patent infringement. IEEE Standards documents are supplied ‘‘AS IS’’.
The existence of an IEEE Standard does not imply that there are no other ways to produce, test, measure, purchase, market, or
provide other goods and services related to the scope of the IEEE Standard. Furthermore, the viewpoint expressed at the time a
standard is approved and issued is subject to change brought about through developments in the state of the art and comments
received from users of the standard. Every IEEE Standard is subjected to review at least every five years for revision or
reaffirmation. When a document is more than five years old and has not been reaffirmed, it is reasonable to conclude that its
contents, although still of some value, do not wholly reflect the present state of the art. Users are cautioned to check to determine
that they have the latest edition of any IEEE Standard.
In publishing and making this document available, the IEEE is not suggesting or rendering professional or other services for, or on
behalf of, any person or entity. Nor is the IEEE undertaking to perform any duty owed by any other person or entity to another. Any
person utilizing this, and any other IEEE Standards document, should rely upon the advice of a competent professional in
determining the exercise of reasonable care in any given circumstances.
Interpretations: Occasionally questions may arise regarding the meaning of portions of standards as they relate to specific
applications. When the need for interpretations is brought to the attention of the IEEE, the Institute will initiate action to prepare
appropriate responses. Since IEEE Standards represent a consensus of concerned interests, it is important to ensure that any
interpretation has also received the concurrence of a balance of interests. For this reason, IEEE and the members of its societies and
Standards Coordinating Committees are not able to provide an instant response to interpretation requests except in those cases
where the matter has previously received formal consideration.
Comments for revision of IEEE Standards are welcome from any interested party, regardless of membership affiliation with the
IEEE.1 Suggestions for changes in documents should be in the form of a proposed change of text, together with appropriate
supporting comments. Comments on standards and requests for interpretations should be addressed to:
Secretary, IEEE-SA Standards Board, 445 Hoes Lane, P.O. Box 1331, Piscataway, NJ 08855-1331, U.S.A.
_ ________________________________________________________________________________________________________________
L Attention is called to the possibility that implementation of this standard may require use of subject matter covered by patent
L
L rights. By publication of this standard, no position is taken with respect to the existence or validity of any patent rights in
L
L
L
L connection therewith. The IEEE shall not be responsible for identifying patents for which a license may be required by an IEEE
L
L
L Standard or for conducting inquiries into the legal validity or scope of those patents that are brought to its attention.
L
L
L A patent holder has filed a statement of assurance that it will grant licenses under these rights without compensation or under
L
L reasonable rates and non-discriminatory, reasonable terms and conditions to all applicants desiring to obtain such licenses. The L
L IEEE makes no representation as to the reasonableness of rates and/or terms and conditions of the license agreements offered by L
L
L
holders. Further information may be obtained from the IEEE Standards Department.
________________________________________________________________________________________________________________
L
L_patent
The IEEE and its designees are the sole entities that may authorize the use of IEEE-owned certification marks and/or trademarks to
indicate compliance with the materials set forth herein. Authorization to photocopy portions of any individual standard for internal
or personal use is granted in the U.S. by the Institute of Electrical and Electronics Engineers, Inc., provided that the appropriate fee is
paid to the Copyright Clearance Center.2 Permission to photocopy portions of any individual standard for educational classroom
use can also be obtained through the Copyright Clearance Center. To arrange for payment of the licensing fee, please contact:
Copyright Clearance Center, Customer Service, 222 Rosewood Drive, Danvers, MA 01923, U.S.A., Tel.: +1 978 750 8400
Amendments, corrigenda, and interpretations for this standard, or information about the IEEE standards development process, may
be found at http://standards.ieee.org.
Full catalog and ordering information on all IEEE publications is available from the IEEE Online Catalog & Store at
http://shop.ieee.org/store.
_ ______________________
1. For this standard, please send comments via the Austin Group as requested on page iii.
2. Please refer to the special provisions for this standard on page iii concerning permissions from both copyright holders and arrangements to cover photocopying and
reproduction across the world, as well as by commercial organizations wishing to license the material for use in product documentation.
iv
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
The Open Group
The Open Group, a vendor and technology-neutral consortium, is committed to delivering greater business efficiency by bringing
together buyers and suppliers of information technology to lower the time, cost, and risks associated with integrating new
technology across the enterprise.
The Open Group’s mission is to offer all organizations concerned with open information infrastructures a forum to share knowledge,
integrate open initiatives, and certify approved products and processes in a manner in which they continue to trust our impartiality.
In the global eCommerce world of today, no single economic entity can achieve independence while still ensuring interoperability.
The assurance that products will interoperate with each other across differing systems and platforms is essential to the success of
eCommerce and business workflow. The Open Group, with its proven testing and certification program, is the international
guarantor of interoperability in the new century.
The Open Group provides opportunities to exchange information and shape the future of IT. The Open Group’s members include
some of the largest and most influential organizations in the world. The flexible structure of The Open Groups membership allows
for almost any organization, no matter what their size, to join and have a voice in shaping the future of the IT world.
More information is available on The Open Group web site at http://www.opengroup.org.
The Open Group has over 15 years’ experience in developing and operating certification programs and has extensive experience
developing and facilitating industry adoption of test suites used to validate conformance to an open standard or specification. The
Open Group portfolio of test suites includes the Westwood family of tests for this standard and the associated certification program
for Version 3 of the Single UNIX Specification, as well tests for CDE, CORBA, Motif, Linux, LDAP, POSIX.1, POSIX.2, POSIX
Realtime, Sockets, UNIX, XPG4, XNFS, XTI, and X11. The Open Group test tools are essential for proper development and
maintenance of standards-based products, ensuring conformance of products to industry-standard APIs, applications portability,
and interoperability. In-depth testing identifies defects at the earliest possible point in the development cycle, saving costs in
development and quality assurance.
More information is available at http://www.opengroup.org/testing.
The Open Group publishes a wide range of technical documentation, the main part of which is focused on development of Technical
and Product Standards and Guides, but which also includes white papers, technical studies, branding and testing documentation,
and business titles. Full details and a catalog are available at http://www.opengroup.org/pubs.
As with all live documents, Technical Standards and Specifications require revision to align with new developments and associated
international standards. To distinguish between revised specifications which are fully backwards compatible and those which are
not:
•
A new Version indicates there is no change to the definitive information contained in the previous publication of that title, but
additions/extensions are included. As such, it replaces the previous publication.
•
A new Issue indicates there is substantive change to the definitive information contained in the previous publication of that title,
and there may also be additions/extensions. As such, both previous and new documents are maintained as current publications.
Readers should note that Corrigenda may
http://www.opengroup.org/corrigenda.
apply
to
any
publication.
Corrigenda information
is
published
at
Full catalog and ordering information on all Open Group publications is available at http://www.opengroup.org/pubs.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
v
vi
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Contents
Chapter
1
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.8.1
1.9
Chapter
2
2.1
2.2
2.2.1
2.2.1.1
2.2.1.2
2.2.2
2.3
2.3.1
2.4
2.4.1
2.4.2
2.4.3
2.4.4
2.5
2.5.1
2.5.2
2.6
2.6.1
2.7
2.7.1
2.8
2.8.1
2.8.2
2.8.3
2.8.3.1
2.8.3.2
2.8.3.3
2.8.3.4
2.8.4
Introduction...............................................................................................
Scope..............................................................................................................
Conformance ...............................................................................................
Normative References ...............................................................................
Change History ...........................................................................................
Terminology.................................................................................................
Definitions ....................................................................................................
Relationship to Other Formal Standards ...............................................
Portability .....................................................................................................
Codes ..........................................................................................................
Format of Entries.........................................................................................
General Information ............................................................................
Use and Implementation of Functions ...................................................
The Compilation Environment ................................................................
POSIX.1 Symbols .....................................................................................
The _POSIX_C_SOURCE Feature Test Macro ................................
The _XOPEN_SOURCE Feature Test Macro...................................
The Name Space.......................................................................................
Error Numbers.............................................................................................
Additional Error Numbers.....................................................................
Signal Concepts...........................................................................................
Signal Generation and Delivery............................................................
Realtime Signal Generation and Delivery ..........................................
Signal Actions ...........................................................................................
Signal Effects on Other Functions ........................................................
Standard I/O Streams................................................................................
Interaction of File Descriptors and Standard I/O Streams .............
Stream Orientation and Encoding Rules ............................................
STREAMS .....................................................................................................
Accessing STREAMS...............................................................................
XSI Interprocess Communication ...........................................................
IPC General Description.........................................................................
Realtime ........................................................................................................
Realtime Signals .......................................................................................
Asynchronous I/O ..................................................................................
Memory Management ............................................................................
Memory Locking...................................................................................
Memory Mapped Files.........................................................................
Memory Protection...............................................................................
Typed Memory Objects .......................................................................
Process Scheduling ..................................................................................
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
1
1
1
1
1
1
3
3
3
3
11
13
13
13
13
14
14
14
21
28
28
28
29
31
34
34
35
37
38
39
39
40
41
41
41
43
43
43
44
44
44
vii
Contents
2.8.5
2.9
2.9.1
2.9.2
2.9.3
2.9.4
2.9.5
2.9.5.1
2.9.5.2
2.9.5.3
2.9.5.4
2.9.6
2.9.7
2.10
2.10.1
2.10.2
2.10.3
2.10.4
2.10.5
2.10.6
2.10.7
2.10.8
2.10.9
2.10.10
2.10.11
2.10.12
2.10.13
2.10.14
2.10.15
2.10.16
2.10.17
2.10.17.1
2.10.18
2.10.19
2.10.19.1
2.10.20
2.10.20.1
2.10.20.2
2.10.20.3
2.10.20.4
2.10.20.5
2.11
2.11.1
2.11.1.1
2.11.1.2
2.11.2
2.11.2.1
2.11.2.2
viii
Clocks and Timers ...................................................................................
Threads..........................................................................................................
Thread-Safety............................................................................................
Thread IDs .................................................................................................
Thread Mutexes........................................................................................
Thread Scheduling...................................................................................
Thread Cancelation .................................................................................
Cancelability States ..............................................................................
Cancelation Points ................................................................................
Thread Cancelation Cleanup Handlers............................................
Async-Cancel Safety.............................................................................
Thread Read-Write Locks.......................................................................
Thread Interactions with Regular File Operations ...........................
Sockets...........................................................................................................
Address Families......................................................................................
Addressing ................................................................................................
Protocols ....................................................................................................
Routing.......................................................................................................
Interfaces....................................................................................................
Socket Types..............................................................................................
Socket I/O Mode......................................................................................
Socket Owner............................................................................................
Socket Queue Limits ...............................................................................
Pending Error............................................................................................
Socket Receive Queue.............................................................................
Socket Out-of-Band Data State .............................................................
Connection Indication Queue ...............................................................
Signals ........................................................................................................
Asynchronous Errors ..............................................................................
Use of Options ..........................................................................................
Use of Sockets for Local UNIX Connections......................................
Headers ...................................................................................................
Use of Sockets over Internet Protocols................................................
Use of Sockets over Internet Protocols Based on IPv4.....................
Headers ...................................................................................................
Use of Sockets over Internet Protocols Based on IPv6.....................
Addressing .............................................................................................
Compatibility with IPv4......................................................................
Interface Identification.........................................................................
Options....................................................................................................
Headers ...................................................................................................
Tracing...........................................................................................................
Tracing Data Definitions.........................................................................
Structures................................................................................................
Trace Stream Attributes.......................................................................
Trace Event Type Definitions ................................................................
System Trace Event Type Definitions ...............................................
User Trace Event Type Definitions....................................................
48
50
50
51
51
52
54
54
55
57
57
58
58
58
58
59
59
59
59
59
60
60
60
60
61
61
62
62
62
63
66
66
66
67
67
67
67
68
68
69
70
70
71
71
75
76
76
79
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Contents
2.11.3
2.12
Chapter
3
Trace Functions.........................................................................................
Data Types....................................................................................................
79
80
System Interfaces ...................................................................................
83
Index............................................................................................................... 1663
List of Tables
2-1
2-2
2-3
2-4
2-5
2-6
2-7
Value of Level for Socket Options.................................................................. 63
Socket-Level Options ........................................................................................ 64
Trace Option: System Trace Events................................................................ 77
Trace and Trace Event Filter Options: System Trace Events..................... 78
Trace and Trace Log Options: System Trace Events................................... 78
Trace, Trace Log, and Trace Event Filter Options: System Trace Events.........
79
Trace Option: User Trace Event ...................................................................... 79
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
ix
Contents
x
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Introduction
Note:
This introduction is not part of IEEE Std 1003.1-2001, Standard for Information Technology —
Portable Operating System Interface (POSIX).
This standard has been jointly developed by the IEEE and The Open Group. It is both an IEEE
Standard and an Open Group Technical Standard.
The Austin Group
This standard was developed, and is maintained, by a joint working group of members of the
IEEE Portable Applications Standards Committee, members of The Open Group, and members
of ISO/IEC Joint Technical Committee 1. This joint working group is known as the Austin
Group.3 The Austin Group arose out of discussions amongst the parties which started in early
1998, leading to an initial meeting and formation of the group in September 1998. The purpose of
the Austin Group has been to revise, combine, and update the following standards: ISO/IEC
9945-1, ISO/IEC 9945-2, IEEE Std 1003.1, IEEE Std 1003.2, and the Base Specifications of The
Open Group Single UNIX Specification.
After two initial meetings, an agreement was signed in July 1999 between The Open Group and
the Institute of Electrical and Electronics Engineers (IEEE), Inc., to formalize the project with the
first draft of the revised specifications being made available at the same time. Under this
agreement, The Open Group and IEEE agreed to share joint copyright of the resulting work. The
Open Group has provided the chair and secretariat for the Austin Group.
The base document for the revision was The Open Group’s Base volumes of its Single UNIX
Specification, Version 2. These were selected since they were a superset of the existing POSIX.1
and POSIX.2 specifications and had some organizational aspects that would benefit the audience
for the new revision.
The approach to specification development has been one of ‘‘write once, adopt everywhere’’,
with the deliverables being a set of specifications that carry the IEEE POSIX designation and The
Open Group’s Technical Standard designation, and, if approved, an ISO/IEC designation. This
set of specifications forms the core of the Single UNIX Specification, Version 3.
This unique development has combined both the industry-led efforts and the formal
standardization activities into a single initiative, and included a wide spectrum of participants.
The Austin Group continues as the maintenance body for this document.
Anyone wishing to participate in the Austin Group should contact the chair with their request.
There are no fees for participation or membership. You may participate as an observer or as a
contributor. You do not have to attend face-to-face meetings to participate; electronic
participation is most welcome. For more information on the Austin Group and how to
participate, see http://www.opengroup.org/austin.
__________________
3. The Austin Group is named after the location of the inaugural meeting held at the IBM facility in Austin, Texas in September
1998.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
xi
Introduction
Background
The developers of this standard represent a cross section of hardware manufacturers, vendors of
operating systems and other software development tools, software designers, consultants,
academics, authors, applications programmers, and others.
Conceptually, this standard describes a set of fundamental services needed for the efficient
construction of application programs. Access to these services has been provided by defining an
interface, using the C programming language, a command interpreter, and common utility
programs that establish standard semantics and syntax. Since this interface enables application
writers to write portable applications—it was developed with that goal in mind—it has been
designated POSIX,4 an acronym for Portable Operating System Interface.
Although originated to refer to the original IEEE Std 1003.1-1988, the name POSIX more correctly
refers to a family of related standards: IEEE Std 1003.n and the parts of ISO/IEC 9945. In earlier
editions of the IEEE standard, the term POSIX was used as a synonym for IEEE Std 1003.1-1988.
A preferred term, POSIX.1, emerged. This maintained the advantages of readability of the
symbol ‘‘POSIX’’ without being ambiguous with the POSIX family of standards.
Audience
The intended audience for this standard is all persons concerned with an industry-wide standard
operating system based on the UNIX system. This includes at least four groups of people:
1. Persons buying hardware and software systems
2. Persons managing companies that are deciding on future corporate computing directions
3. Persons implementing operating systems, and especially
4. Persons developing applications where portability is an objective
Purpose
Several principles guided the development of this standard:
•
Application-Oriented
The basic goal was to promote portability of application programs across UNIX system
environments by developing a clear, consistent, and unambiguous standard for the interface
specification of a portable operating system based on the UNIX system documentation. This
standard codifies the common, existing definition of the UNIX system.
•
Interface, Not Implementation
This standard defines an interface, not an implementation. No distinction is made between
library functions and system calls; both are referred to as functions. No details of the
implementation of any function are given (although historical practice is sometimes
indicated in the RATIONALE section). Symbolic names are given for constants (such as
signals and error numbers) rather than numbers.
__________________
4. The name POSIX was suggested by Richard Stallman. It is expected to be pronounced pahz-icks , as in positive , not poh-six , or
other variations. The pronunciation has been published in an attempt to promulgate a standardized way of referring to a
standard operating system interface.
xii
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Introduction
•
Source, Not Object, Portability
This standard has been written so that a program written and translated for execution on one
conforming implementation may also be translated for execution on another conforming
implementation. This standard does not guarantee that executable (object or binary) code
will execute under a different conforming implementation than that for which it was
translated, even if the underlying hardware is identical.
•
The C Language
The system interfaces and header definitions are written in terms of the standard C language
as specified in the ISO C standard.
•
No Superuser, No System Administration
There was no intention to specify all aspects of an operating system. System administration
facilities and functions are excluded from this standard, and functions usable only by the
superuser have not been included. Still, an implementation of the standard interface may also
implement features not in this standard. This standard is also not concerned with hardware
constraints or system maintenance.
•
Minimal Interface, Minimally Defined
In keeping with the historical design principles of the UNIX system, the mandatory core
facilities of this standard have been kept as minimal as possible. Additional capabilities have
been added as optional extensions.
•
Broadly Implementable
The developers of this standard endeavored to make all specified functions implementable
across a wide range of existing and potential systems, including:
1. All of the current major systems that are ultimately derived from the original UNIX
system code (Version 7 or later)
2. Compatible systems that are not derived from the original UNIX system code
3. Emulations hosted on entirely different operating systems
4. Networked systems
5. Distributed systems
6. Systems running on a broad range of hardware
No direct references to this goal appear in this standard, but some results of it are mentioned
in the Rationale (Informative) volume.
•
Minimal Changes to Historical Implementations
When the original version of IEEE Std 1003.1 was published, there were no known historical
implementations that did not have to change. However, there was a broad consensus on a set
of functions, types, definitions, and concepts that formed an interface that was common to
most historical implementations.
The adoption of the 1988 and 1990 IEEE system interface standards, the 1992 IEEE shell and
utilities standard, the various Open Group (formerly X/Open) specifications, and the
subsequent revisions and addenda to all of them have consolidated this consensus, and this
revision reflects the significantly increased level of consensus arrived at since the original
versions. The earlier standards and their modifications specified a number of areas where
consensus had not been reached before, and these are now reflected in this revision. The
authors of the original versions tried, as much as possible, to follow the principles below
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
xiii
Introduction
when creating new specifications:
1. By standardizing an interface like one in an historical implementation; for example,
directories
2. By specifying an interface that is readily implementable in terms of, and backwardscompatible with, historical implementations, such as the extended tar format defined in
the pax utility
3. By specifying an interface that, when added to an historical implementation, will not
conflict with it; for example, the sigaction ( ) function
This revision tries to minimize the number of changes required to implementations which
conform to the earlier versions of the approved standards to bring them into conformance
with the current standard. Specifically, the scope of this work excluded doing any ‘‘new’’
work, but rather collecting into a single document what had been spread across a number of
documents, and presenting it in what had been proven in practice to be a more effective way.
Some changes to prior conforming implementations were unavoidable, primarily as a
consequence of resolving conflicts found in prior revisions, or which became apparent when
bringing the various pieces together.
However, since it references the 1999 version of the ISO C standard, and no longer supports
‘‘Common Usage C’’, there are a number of unavoidable changes. Applications portability is
similarly affected.
This standard is specifically not a codification of a particular vendor’s product.
It should be noted that implementations will have different kinds of extensions. Some will
reflect ‘‘historical usage’’ and will be preserved for execution of pre-existing applications.
These functions should be considered ‘‘obsolescent’’ and the standard functions used for
new applications. Some extensions will represent functions beyond the scope of this
standard. These need to be used with careful management to be able to adapt to future
extensions of this standard and/or port to implementations that provide these services in a
different manner.
•
Minimal Changes to Existing Application Code
A goal of this standard was to minimize additional work for the developers of applications.
However, because every known historical implementation will have to change at least
slightly to conform, some applications will have to change.
This Standard
This standard defines the Portable Operating System Interface (POSIX) requirements and
consists of the following volumes:
xiv
•
Base Definitions
•
Shell and Utilities
•
System Interfaces (this volume)
•
Rationale (Informative)
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Introduction
This Volume
The System Interfaces volume describes the interfaces offered to application programs by
POSIX-conformant systems. Readers are expected to be experienced C language programmers,
and to be familiar with the Base Definitions volume.
This volume is structured as follows:
•
Chapter 1 explains the status of this volume and its relationship to other formal standards.
•
Chapter 2 contains important concepts, terms, and caveats relating to the rest of this volume.
•
Chapter 3 defines the functional interfaces to the POSIX-conformant system.
Comprehensive references are available in the index.
Typographical Conventions
The following typographical conventions are used throughout this standard. In the text, this
standard is referred to as IEEE Std 1003.1-2001, which is technically identical to The Open Group
Base Specifications, Issue 6.
The typographical conventions listed here are for ease of reading only. Editorial inconsistencies
in the use of typography are unintentional and have no normative meaning in this standard.
___________________________________________________________________________________
LL___________________________________________________________________________________
LL
LL Notes LL
Reference
Example
L
L
L aiocb
L C-Language Data Structure
L
L
L aio_lio_opcode
L C-Language Data Structure Member
L
L
L
L
L
L
L long
L C-Language Data Type
L
L
L errno
L C-Language External Variable
L
L
L system( )
L C-Language Function
L
L
L arg1
L C-Language Function Argument
L
L
L exec
L C-Language Function Family
L
L
L
L
L
L
L <sys/stat.h>
L C-Language Header
L
L
L return
L C-Language Keyword
L
L
L assert( )
L C-Language Macro with Argument
L
L
L INET_ADDRSTRLEN
L C-Language Macro with No Argument
L
L
L #define
L C-Language Preprocessing Directive
L
L
L a, c
L Commands within a Utility
L
L
L
L
L 1 L
L Conversion Specification, Specifier/Modifier Character L %A, g, E
L
L
L PATH
L Environment Variable
L
L
L [EINTR]
L Error Number
L
L
L Hello, World
L Example Output
L
L
L /tmp
L Filename
L
L
L
L
L 2 L
L ’c’, ’\r’, ’\’
L Literal Character
L 2 L
L "abcde"
L Literal String
L
L
L []
L Optional Items in Utility Syntax
L
L
L <directory pathname>
L Parameter
L 3 L
L <newline>
L Special Character
L
L
L
L
L
L
L _POSIX_VDISABLE
L Symbolic Constant
L 4 L
L {LINE_MAX}
L Symbolic Limit, Configuration Value
Syntax
L
L #include <sys/stat.h> L
L___________________________________________________________________________________
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
xv
Introduction
___________________________________________________________________________________
LL___________________________________________________________________________________
LL
LL Notes LL
Reference
Example
L User Input and Example Code
L echo Hello, World
L 5 L
L Utility Name
L awk
L
L
L
L
L
L
L Utility Operand
L file_name
L
L
L Utility Option
L −c
L
L
Utility Option with Option-Argument
L −w width
L
L
L___________________________________________________________________________________
Notes:
1.
Conversion specifications, specifier characters, and modifier characters are used primarily
in date-related functions and utilities and the fprintf and fscanf formatting functions.
2.
Unless otherwise noted, the quotes shall not be used as input or output. When used in a
list item, the quotes are omitted. For literal characters, ’\’ (or any of the other sequences
such as ’’’) is the same as the C constant ’\\’ (or ’\’’).
3.
The style selected for some of the special characters, such as <newline>, matches the form
of the input given to the localedef utility. Generally, the characters selected for this special
treatment are those that are not visually distinct, such as the control characters <tab> or
<newline>.
4.
Names surrounded by braces represent symbolic limits or configuration values which
may be declared in appropriate headers by means of the C #define construct.
5.
Brackets shown in this font, "[ ]", are part of the syntax and do not indicate optional
items. In syntax the ’|’ symbol is used to separate alternatives, and ellipses ("...") are
used to show that additional arguments are optional.
Shading is used to identify extensions and options; see Section 1.8.1 (on page 3).
Footnotes and notes within the body of the normative text are for information only
(informative).
Informative sections (such as Rationale, Change History, Application Usage, and so on) are
denoted by continuous shading bars in the margins.
Ranges of values are indicated with parentheses or brackets as follows:
•
(a,b) means the range of all values from a to b, including neither a nor b.
•
[a,b] means the range of all values from a to b, including a and b.
•
[a,b) means the range of all values from a to b, including a, but not b.
•
(a,b] means the range of all values from a to b, including b, but not a.
Notes:
xvi
1.
Symbolic limits are used in this volume instead of fixed values for portability. The values
of most of these constants are defined in the Base Definitions volume, <limits.h> or
<unistd.h>.
2.
The values of errors are defined in the Base Definitions volume, <errno.h>.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Participants
The Austin Group
This standard was prepared by the Austin Group, sponsored by the Portable Applications
Standards Committee of the IEEE Computer Society, The Open Group, and ISO/SC22 WG15. At
the time of approval, the membership of the Austin Group was as follows.
Andrew Josey, Chair
Donald W. Cragun, Organizational Representative, IEEE PASC
Nicholas Stoughton, Organizational Representative, ISO/SC22 WG15
Mark Brown, Organizational Representative, The Open Group
Cathy Hughes, Technical Editor
Austin Group Technical Reviewers
Peter Anvin
Bouazza Bachar
Theodore P. Baker
Walter Briscoe
Mark Brown
Dave Butenhof
Geoff Clare
Donald W. Cragun
Lee Damico
Ulrich Drepper
Paul Eggert
Joanna Farley
Clive D.W. Feather
Andrew Gollan
Michael Gonzalez
Joseph M. Gwinn
Jon Hitchcock
Yvette Ho Sang
Cathy Hughes
Lowell G. Johnson
Andrew Josey
Michael Kavanaugh
David Korn
Marc Aurele La France
Jim Meyering
Gary Miller
Finnbarr P. Murphy
Joseph S. Myers
Sandra O’Donnell
Frank Prindle
Curtis Royster Jr.
Glen Seeds
Keld Jorn Simonsen
Raja Srinivasan
Nicholas Stoughton
Donn S. Terry
Fred Tydeman
Peter Van Der Veen
James Youngman
Jim Zepeda
Jason Zions
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
xvii
Participants
Austin Group Working Group Members
Harold C. Adams
Peter Anvin
Pierre-Jean Arcos
Jay Ashford
Bouazza Bachar
Theodore P. Baker
Robert Barned
Joel Berman
David J. Blackwood
Shirley Bockstahler-Brandt
James Bottomley
Walter Briscoe
Andries Brouwer
Mark Brown
Eric W. Burger
Alan Burns
Andries Brouwer
Dave Butenhof
Keith Chow
Geoff Clare
Donald W. Cragun
Lee Damico
Juan Antonio De La Puente
Ming De Zhou
Steven J. Dovich
Richard P. Draves
Ulrich Drepper
Paul Eggert
Philip H. Enslow
Joanna Farley
Clive D.W. Feather
Pete Forman
Mark Funkenhauser
Lois Goldthwaite
Andrew Gollan
xviii
Michael Gonzalez
Karen D. Gordon
Joseph M. Gwinn
Steven A. Haaser
Charles E. Hammons
Chris J. Harding
Barry Hedquist
Vincent E. Henley
Karl Heubaum
Jon Hitchcock
Yvette Ho Sang
Niklas Holsti
Thomas Hosmer
Cathy Hughes
Jim D. Isaak
Lowell G. Johnson
Michael B. Jones
Andrew Josey
Michael J. Karels
Michael Kavanaugh
David Korn
Steven Kramer
Thomas M. Kurihara
Marc Aurele La France
C. Douglass Locke
Nick Maclaren
Roger J. Martin
Craig H. Meyer
Jim Meyering
Gary Miller
Finnbarr P. Murphy
Joseph S. Myers
John Napier
Peter E. Obermayer
James T. Oblinger
Sandra O’Donnell
Frank Prindle
Francois Riche
John D. Riley
Andrew K. Roach
Helmut Roth
Jaideep Roy
Curtis Royster Jr.
Stephen C. Schwarm
Glen Seeds
Richard Seibel
David L. Shroads Jr.
W. Olin Sibert
Keld Jorn Simonsen
Curtis Smith
Raja Srinivasan
Nicholas Stoughton
Marc J. Teller
Donn S. Terry
Fred Tydeman
Mark-Rene Uchida
Scott A. Valcourt
Peter Van Der Veen
Michael W. Vannier
Eric Vought
Frederick N. Webb
Paul A.T. Wolfgang
Garrett Wollman
James Youngman
Oren Yuen
Janusz Zalewski
Jim Zepeda
Jason Zions
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Participants
The Open Group
When The Open Group approved the Base Specifications, Issue 6 on 12 September 2001, the
membership of The Open Group Base Working Group was as follows.
Andrew Josey, Chair
Finnbarr P. Murphy, Vice-Chair
Mark Brown, Austin Group Liaison
Cathy Hughes, Technical Editor
Base Working Group Members
Bouazza Bachar
Mark Brown
Dave Butenhof
Donald W. Cragun
Larry Dwyer
Joanna Farley
Andrew Gollan
Karen D. Gordon
Gary Miller
Finnbarr P. Murphy
Frank Prindle
Andrew K. Roach
Curtis Royster Jr.
Nicholas Stoughton
Kenjiro Tsuji
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
xix
Participants
IEEE
When the IEEE Standards Board approved IEEE Std 1003.1-2001 on 6 December 2001, the
membership of the committees was as follows.
Portable Applications Standards Committee (PASC)
Lowell G. Johnson, Chair
Joseph M. Gwinn, Vice-Chair
Jay Ashford, Functional Chair
Andrew Josey, Functional Chair
Curtis Royster Jr., Functional Chair
Nicholas Stoughton, Secretary
Balloting Committee
The following members of the balloting committee voted on IEEE Std 1003.1-2001. Balloters may
have voted for approval, disapproval, or abstention.
Harold C. Adams
Pierre-Jean Arcos
Jay Ashford
Theodore P. Baker
Robert Barned
David J. Blackwood
Shirley Bockstahler-Brandt
James Bottomley
Mark Brown
Eric W. Burger
Alan Burns
Dave Butenhof
Keith Chow
Donald W. Cragun
Juan Antonio De La Puente
Ming De Zhou
Steven J. Dovich
Richard P. Draves
Philip H. Enslow
Michael Gonzalez
Karen D. Gordon
Joseph M. Gwinn
Steven A. Haaser
Charles E. Hammons
Chris J. Harding
Barry Hedquist
Vincent E. Henley
Karl Heubaum
Niklas Holsti
Thomas Hosmer
Jim D. Isaak
Lowell G. Johnson
Michael B. Jones
Andrew Josey
Michael J. Karels
Steven Kramer
Thomas M. Kurihara
C. Douglass Locke
Roger J. Martin
Craig H. Meyer
Finnbarr P. Murphy
John Napier
Peter E. Obermayer
James T. Oblinger
Frank Prindle
Francois Riche
John D. Riley
Andrew K. Roach
Helmut Roth
Jaideep Roy
Curtis Royster Jr.
Stephen C. Schwarm
Richard Seibel
David L. Shroads Jr.
W. Olin Sibert
Keld Jorn Simonsen
Nicholas Stoughton
Donn S. Terry
Mark-Rene Uchida
Scott A. Valcourt
Michael W. Vannier
Frederick N. Webb
Paul A.T. Wolfgang
Oren Yuen
Janusz Zalewski
The following organizational representative voted on this standard:
Andrew Josey, X/Open Company Ltd.
xx
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Participants
IEEE-SA Standards Board
When the IEEE-SA Standards Board approved IEEE Std 1003.1-2001 on 6 December 2001, it had
the following membership:
Donald N. Heirman, Chair
James T. Carlo, Vice-Chair
Judith Gorman, Secretary
Satish K. Aggarwal
Mark D. Bowman
Gary R. Engmann
Harold E. Epstein
H. Landis Floyd
Jay Forster*
Howard M. Frazier
Ruben D. Garzon
James H. Gurney
Richard J. Holleman
Lowell G. Johnson
Robert J. Kennelly
Joseph L. Koepfinger*
Peter H. Lips
L. Bruce McClung
Daleep C. Mohla
James W. Moore
Robert F. Munzner
Ronald C. Petersen
Gerald H. Peterson
John B. Posey
Gary S. Robinson
Akio Tojo
Donald W. Zipse
Also included are the following non-voting IEEE-SA Standards Board liaisons:
Alan Cookson, NIST Representative
Donald R. Volzka, TAB Representative
Yvette Ho Sang, Don Messina, Savoula Amanatidis, IEEE Project Editors
__________________
*
Member Emeritus
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
xxi
Trademarks
The following information is given for the convenience of users of this standard and does not
constitute endorsement of these products by The Open Group or the IEEE. There may be other
products mentioned in the text that might be covered by trademark protection and readers are
advised to verify them independently.
TM
1003.1 is a trademark of the Institute of Electrical and Electronic Engineers, Inc.

AIX is a registered trademark of IBM Corporation.

AT&T is a registered trademark of AT&T in the U.S.A. and other countries.
TM
BSD
is a trademark of the University of California, Berkeley, U.S.A.



Hewlett-Packard , HP , and HP-UX are registered trademarks of Hewlett-Packard Company.

IBM is a registered trademark of International Business Machines Corporation.
TM



Motif , OSF/1 , UNIX , and the ‘‘X Device’’ are registered trademarks and IT DialTone and
TM
The Open Group are trademarks of The Open Group in the U.S. and other countries.

POSIX is a registered trademark of the Institute of Electrical and Electronic Engineers, Inc.


Sun and Sun Microsystems are registered trademarks of Sun Microsystems, Inc.

/usr/group is a registered trademark of UniForum, the International Network of UNIX System
Users.
xxii
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Acknowledgements
The contributions of the following organizations to the development of IEEE Std 1003.1-2001 are
gratefully acknowledged:
•
AT&T for permission to reproduce portions of its copyrighted System V Interface Definition
(SVID) and material from the UNIX System V Release 2.0 documentation.
•
The SC22 WG14 Committees.
This standard was prepared by the Austin Group, a joint working group of the IEEE, The Open
Group, and ISO SC22 WG15.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
xxiii
Referenced Documents
Normative References
Normative references for this standard are defined in the Base Definitions volume.
Informative References
The following documents are referenced in this standard:
1984 /usr/group Standard
/usr/group Standards Committee, Santa Clara, CA, UniForum 1984.
Almasi and Gottlieb
George S. Almasi and Allan Gottlieb, Highly Parallel Computing, The Benjamin/Cummings
Publishing Company, Inc., 1989, ISBN: 0-8053-0177-1.
ANSI C
American National Standard for Information Systems: Standard X3.159-1989, Programming
Language C.
ANSI X3.226-1994
American National Standard for Information Systems: Standard X3.226-1994, Programming
Language Common LISP.
Brawer
Steven Brawer, Introduction
ISBN: 0-12-128470-0.
to
Parallel
Programming,
Academic
Press,
1989,
DeRemer and Pennello Article
DeRemer, Frank and Pennello, Thomas J., Efficient Computation of LALR(1) Look-Ahead Sets,
SigPlan Notices, Volume 15, No. 8, August 1979.
Draft ANSI X3J11.1
IEEE Floating Point draft report of ANSI X3J11.1 (NCEG).
FIPS 151-1
Federal Information Procurement Standard (FIPS) 151-1. Portable Operating System
Interface (POSIX)—Part 1: System Application Program Interface (API) [C Language].
FIPS 151-2
Federal Information Procurement Standards (FIPS) 151-2, Portable Operating System
Interface (POSIX)—Part 1: System Application Program Interface (API) [C Language].
HP-UX Manual
Hewlett-Packard HP-UX Release 9.0 Reference Manual, Third Edition, August 1992.
IEC 60559: 1989
IEC 60559: 1989, Binary Floating-Point Arithmetic for Microprocessor Systems (previously
designated IEC 559: 1989).
IEEE Std 754-1985
IEEE Std 754-1985, IEEE Standard for Binary Floating-Point Arithmetic.
IEEE Std 854-1987
IEEE Std 854-1987, IEEE Standard for Radix-Independent Floating-Point Arithmetic.
xxiv
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Referenced Documents
IEEE Std 1003.9-1992
IEEE Std 1003.9-1992, IEEE Standard for Information Technology — POSIX FORTRAN 77
Language Interfaces — Part 1: Binding for System Application Program Interface API.
IETF RFC 791
Internet Protocol, Version 4 (IPv4), September 1981.
IETF RFC 819
The Domain Naming Convention for Internet User Applications, Z. Su, J. Postel, August
1982.
IETF RFC 822
Standard for the Format of ARPA Internet Text Messages, D.H. Crocker, August 1982.
IETF RFC 919
Broadcasting Internet Datagrams, J. Mogul, October 1984.
IETF RFC 920
Domain Requirements, J. Postel, J. Reynolds, October 1984.
IETF RFC 921
Domain Name System Implementation Schedule, J. Postel, October 1984.
IETF RFC 922
Broadcasting Internet Datagrams in the Presence of Subnets, J. Mogul, October 1984.
IETF RFC 1034
Domain Names — Concepts and Facilities, P. Mockapetris, November 1987.
IETF RFC 1035
Domain Names — Implementation and Specification, P. Mockapetris, November 1987.
IETF RFC 1123
Requirements for Internet Hosts — Application and Support, R. Braden, October 1989.
IETF RFC 1886
DNS Extensions to Support Internet Protocol, Version 6 (IPv6), C. Huitema, S. Thomson,
December 1995.
IETF RFC 2045
Multipurpose Internet Mail Extensions (MIME), Part 1: Format of Internet Message Bodies,
N. Freed, N. Borenstein, November 1996.
IETF RFC 2373
Internet Protocol, Version 6 (IPv6) Addressing Architecture, S. Deering, R. Hinden, July
1998.
IETF RFC 2460
Internet Protocol, Version 6 (IPv6), S. Deering, R. Hinden, December 1998.
Internationalisation Guide
Guide, July 1993, Internationalisation Guide, Version 2 (ISBN: 1-859120-02-4, G304),
published by The Open Group.
ISO C (1990)
ISO/IEC 9899: 1990, Programming Languages — C, including Amendment 1: 1995 (E), C
Integrity (Multibyte Support Extensions (MSE) for ISO C).
ISO 2375: 1985
ISO 2375: 1985, Data Processing — Procedure for Registration of Escape Sequences.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
xxv
Referenced Documents
ISO 8652: 1987
ISO 8652: 1987, Programming Languages — Ada (technically identical to ANSI standard
1815A-1983).
ISO/IEC 1539: 1990
ISO/IEC 1539: 1990, Information Technology — Programming Languages — Fortran
(technically identical to the ANSI X3.9-1978 standard [FORTRAN 77]).
ISO/IEC 4873: 1991
ISO/IEC 4873: 1991, Information Technology — ISO 8-bit Code for Information Interchange
— Structure and Rules for Implementation.
ISO/IEC 6429: 1992
ISO/IEC 6429: 1992, Information Technology — Control Functions for Coded Character
Sets.
ISO/IEC 6937: 1994
ISO/IEC 6937: 1994, Information Technology — Coded Character Set for Text
Communication — Latin Alphabet.
ISO/IEC 8802-3: 1996
ISO/IEC 8802-3: 1996, Information Technology — Telecommunications and Information
Exchange Between Systems — Local and Metropolitan Area Networks — Specific
Requirements — Part 3: Carrier Sense Multiple Access with Collision Detection
(CSMA/CD) Access Method and Physical Layer Specifications.
ISO/IEC 8859
ISO/IEC 8859, Information Technology — 8-Bit Single-Byte Coded Graphic Character Sets:
Part 1: Latin Alphabet No. 1
Part 2: Latin Alphabet No. 2
Part 3: Latin Alphabet No. 3
Part 4: Latin Alphabet No. 4
Part 5: Latin/Cyrillic Alphabet
Part 6: Latin/Arabic Alphabet
Part 7: Latin/Greek Alphabet
Part 8: Latin/Hebrew Alphabet
Part 9: Latin Alphabet No. 5
Part 10: Latin Alphabet No. 6
Part 13: Latin Alphabet No. 7
Part 14: Latin Alphabet No. 8
Part 15: Latin Alphabet No. 9
ISO POSIX-1: 1996
ISO/IEC 9945-1: 1996, Information Technology — Portable Operating System Interface
(POSIX) — Part 1: System Application Program Interface (API) [C Language] (identical to
ANSI/IEEE Std 1003.1-1996). Incorporating ANSI/IEEE Stds 1003.1-1990, 1003.1b-1993,
1003.1c-1995, and 1003.1i-1995.
ISO POSIX-2: 1993
ISO/IEC 9945-2: 1993, Information Technology — Portable Operating System Interface
(POSIX) — Part 2: Shell and Utilities (identical to ANSI/IEEE Std 1003.2-1992, as amended
by ANSI/IEEE Std 1003.2a-1992).
Issue 1
X/Open Portability Guide, July 1985 (ISBN: 0-444-87839-4).
xxvi
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Referenced Documents
Issue 2
X/Open Portability Guide, January 1987:
•
Volume 1: XVS Commands and Utilities (ISBN: 0-444-70174-5)
•
Volume 2: XVS System Calls and Libraries (ISBN: 0-444-70175-3)
Issue 3
X/Open Specification, 1988, 1989, February 1992:
•
Commands and Utilities, Issue 3 (ISBN: 1-872630-36-7, C211); this specification was
formerly X/Open Portability Guide, Issue 3, Volume 1, January 1989, XSI Commands
and Utilities (ISBN: 0-13-685835-X, XO/XPG/89/002)
•
System Interfaces and Headers, Issue 3 (ISBN: 1-872630-37-5, C212); this specification
was formerly X/Open Portability Guide, Issue 3, Volume 2, January 1989, XSI System
Interface and Headers (ISBN: 0-13-685843-0, XO/XPG/89/003)
•
Curses Interface, Issue 3, contained in Supplementary Definitions, Issue 3
(ISBN: 1-872630-38-3, C213), Chapters 9 to 14 inclusive; this specification was formerly
X/Open Portability Guide, Issue 3, Volume 3, January 1989, XSI Supplementary
Definitions (ISBN: 0-13-685850-3, XO/XPG/89/004)
•
Headers Interface, Issue 3, contained in Supplementary Definitions, Issue 3
(ISBN: 1-872630-38-3, C213), Chapter 19, Cpio and Tar Headers; this specification was
formerly X/Open Portability Guide Issue 3, Volume 3, January 1989, XSI Supplementary
Definitions (ISBN: 0-13-685850-3, XO/XPG/89/004)
Issue 4
CAE Specification, July 1992, published by The Open Group:
•
System Interface Definitions (XBD), Issue 4 (ISBN: 1-872630-46-4, C204)
•
Commands and Utilities (XCU), Issue 4 (ISBN: 1-872630-48-0, C203)
•
System Interfaces and Headers (XSH), Issue 4 (ISBN: 1-872630-47-2, C202)
Issue 4, Version 2
CAE Specification, August 1994, published by The Open Group:
•
System Interface Definitions (XBD), Issue 4, Version 2 (ISBN: 1-85912-036-9, C434)
•
Commands and Utilities (XCU), Issue 4, Version 2 (ISBN: 1-85912-034-2, C436)
•
System Interfaces and Headers (XSH), Issue 4, Version 2 (ISBN: 1-85912-037-7, C435)
Issue 5
Technical Standard, February 1997, published by The Open Group:
•
System Interface Definitions (XBD), Issue 5 (ISBN: 1-85912-186-1, C605)
•
Commands and Utilities (XCU), Issue 5 (ISBN: 1-85912-191-8, C604)
•
System Interfaces and Headers (XSH), Issue 5 (ISBN: 1-85912-181-0, C606)
Knuth Article
Knuth, Donald E., On the Translation of Languages from Left to Right, Information and Control,
Volume 8, No. 6, October 1965.
KornShell
Bolsky, Morris I. and Korn, David G., The New KornShell Command and Programming
Language, March 1995, Prentice Hall.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
xxvii
Referenced Documents
MSE Working Draft
Working draft of ISO/IEC 9899: 1990/Add3: Draft, Addendum 3 — Multibyte Support
Extensions (MSE) as documented in the ISO Working Paper SC22/WG14/N205 dated 31
March 1992.
POSIX.0: 1995
IEEE Std 1003.0-1995, IEEE Guide to the POSIX Open System Environment (OSE) (identical
to ISO/IEC TR 14252).
POSIX.1: 1988
IEEE Std 1003.1-1988, IEEE Standard for Information Technology — Portable Operating
System Interface (POSIX) — Part 1: System Application Program Interface (API) [C
Language].
POSIX.1: 1990
IEEE Std 1003.1-1990, IEEE Standard for Information Technology — Portable Operating
System Interface (POSIX) — Part 1: System Application Program Interface (API) [C
Language].
POSIX.1a
P1003.1a, Standard for Information Technology — Portable Operating System Interface
(POSIX) — Part 1: System Application Program Interface (API) — (C Language)
Amendment
POSIX.1d: 1999
IEEE Std 1003.1d-1999, IEEE Standard for Information Technology — Portable Operating
System Interface (POSIX) — Part 1: System Application Program Interface (API) —
Amendment 4: Additional Realtime Extensions [C Language].
POSIX.1g: 2000
IEEE Std 1003.1g-2000, IEEE Standard for Information Technology — Portable Operating
System Interface (POSIX) — Part 1: System Application Program Interface (API) —
Amendment 6: Protocol-Independent Interfaces (PII).
POSIX.1j: 2000
IEEE Std 1003.1j-2000, IEEE Standard for Information Technology — Portable Operating
System Interface (POSIX) — Part 1: System Application Program Interface (API) —
Amendment 5: Advanced Realtime Extensions [C Language].
POSIX.1q: 2000
IEEE Std 1003.1q-2000, IEEE Standard for Information Technology — Portable Operating
System Interface (POSIX) — Part 1: System Application Program Interface (API) —
Amendment 7: Tracing [C Language].
POSIX.2b
P1003.2b, Standard for Information Technology — Portable Operating System Interface
(POSIX) — Part 2: Shell and Utilities — Amendment
POSIX.2d:-1994
IEEE Std 1003.2d: 1994, IEEE Standard for Information Technology — Portable Operating
System Interface (POSIX) — Part 2: Shell and Utilities — Amendment 1: Batch
Environment.
POSIX.13:-1998
IEEE Std 1003.13: 1998, IEEE Standard for Information Technology — Standardized
Application Environment Profile (AEP) — POSIX Realtime Application Support.
xxviii
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Referenced Documents
Sarwate Article
Sarwate, Dilip V., Computation of Cyclic Redundancy Checks via Table Lookup, Communications
of the ACM, Volume 30, No. 8, August 1988.
Sprunt, Sha, and Lehoczky
Sprunt, B., Sha, L., and Lehoczky, J.P., Aperiodic Task Scheduling for Hard Real-Time Systems,
The Journal of Real-Time Systems, Volume 1, 1989, Pages 27-60.
SVID, Issue 1
American Telephone and Telegraph Company, System V Interface Definition (SVID), Issue
1; Morristown, NJ, UNIX Press, 1985.
SVID, Issue 2
American Telephone and Telegraph Company, System V Interface Definition (SVID), Issue
2; Morristown, NJ, UNIX Press, 1986.
SVID, Issue 3
American Telephone and Telegraph Company, System V Interface Definition (SVID), Issue
3; Morristown, NJ, UNIX Press, 1989.
The AWK Programming Language
Aho, Alfred V., Kernighan, Brian W., and Weinberger, Peter J., The AWK Programming
Language, Reading, MA, Addison-Wesley 1988.
UNIX Programmer’s Manual
American Telephone and Telegraph Company, UNIX Time-Sharing System: UNIX
Programmer’s Manual, 7th Edition, Murray Hill, NJ, Bell Telephone Laboratories, January
1979.
XNS, Issue 4
CAE Specification, August 1994, Networking Services, Issue 4 (ISBN: 1-85912-049-0, C438),
published by The Open Group.
XNS, Issue 5
CAE Specification, February 1997, Networking Services, Issue 5 (ISBN: 1-85912-165-9, C523),
published by The Open Group.
XNS, Issue 5.2
Technical Standard, January 2000, Networking Services
(ISBN: 1-85912-241-8, C808), published by The Open Group.
(XNS),
Issue
5.2
X/Open Curses, Issue 4, Version 2
CAE Specification, May 1996, X/Open Curses, Issue 4, Version 2 (ISBN: 1-85912-171-3,
C610), published by The Open Group.
Yacc
Yacc: Yet Another Compiler Compiler, Stephen C. Johnson, 1978.
Source Documents
Parts of the following documents were used to create the base documents for this standard:
AIX 3.2 Manual
AIX Version 3.2 For RISC System/6000, Technical Reference: Base Operating System and
Extensions, 1990, 1992 (Part No. SC23-2382-00).
OSF/1
OSF/1 Programmer’s Reference, Release 1.2 (ISBN: 0-13-020579-6).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
xxix
Referenced Documents
OSF AES
Application Environment Specification (AES) Operating System Programming Interfaces
Volume, Revision A (ISBN: 0-13-043522-8).
System V Release 2.0
— UNIX System V Release 2.0 Programmer’s Reference Manual (April 1984 - Issue 2).
— UNIX System V Release 2.0 Programming Guide (April 1984 - Issue 2).
System V Release 4.2
Operating System API Reference, UNIX SVR4.2 (1992) (ISBN: 0-13-017658-3).
xxx
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Chapter 1
Introduction
1
2
1.1
The scope of IEEE Std 1003.1-2001 is described in the Base Definitions volume of
IEEE Std 1003.1-2001.
3
4
5
1.2
1.3
1.4
Change History
Change history is described in the Rationale (Informative) volume of IEEE Std 1003.1-2001, and
in the CHANGE HISTORY section of reference pages.
12
13
14
Normative References
Normative references for IEEE Std 1003.1-2001 are defined in the Base Definitions volume of
IEEE Std 1003.1-2001.
9
10
11
Conformance
Conformance requirements for IEEE Std 1003.1-2001 are defined in the Base Definitions volume
of IEEE Std 1003.1-2001, Chapter 2, Conformance.
6
7
8
Scope
1.5
Terminology
15
16
This section appears in the Base Definitions volume of IEEE Std 1003.1-2001, but is repeated here
for convenience:
17
For the purposes of IEEE Std 1003.1-2001, the following terminology definitions apply:
18
19
20
21
can
22
23
24
25
26
27
implementation-defined
Describes a value or behavior that is not defined by IEEE Std 1003.1-2001 but is selected by
an implementor. The value or behavior may vary among implementations that conform to
IEEE Std 1003.1-2001. An application should not rely on the existence of the value or
behavior. An application that relies on such a value or behavior cannot be assured to be
portable across conforming implementations.
28
29
The implementor shall document such a value or behavior so that it can be used correctly
by an application.
30
31
32
legacy
Describes a feature or behavior that is being retained for compatibility with older
applications, but which has limitations which make it inappropriate for developing portable
Describes a permissible optional feature or behavior available to the user or application. The
feature or behavior is mandatory for an implementation that conforms to
IEEE Std 1003.1-2001. An application can rely on the existence of the feature or behavior.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
1
Terminology
Introduction
applications. New applications should use alternative means of obtaining equivalent
functionality.
33
34
may
35
36
37
38
39
Describes a feature or behavior that is optional for an implementation that conforms to
IEEE Std 1003.1-2001. An application should not rely on the existence of the feature or
behavior. An application that relies on such a feature or behavior cannot be assured to be
portable across conforming implementations.
To avoid ambiguity, the opposite of may is expressed as need not, instead of may not.
40
shall
For an implementation that conforms to IEEE Std 1003.1-2001, describes a feature or
behavior that is mandatory. An application can rely on the existence of the feature or
behavior.
41
42
43
44
For an application or user, describes a behavior that is mandatory.
45
46
47
48
49
50
should
For an implementation that conforms to IEEE Std 1003.1-2001, describes a feature or
behavior that is recommended but not mandatory. An application should not rely on the
existence of the feature or behavior. An application that relies on such a feature or behavior
cannot be assured to be portable across conforming implementations.
51
52
For an application, describes a feature or behavior that is recommended programming
practice for optimum portability.
53
54
55
undefined
Describes the nature of a value or behavior not defined by IEEE Std 1003.1-2001 which
results from use of an invalid program construct or invalid data input.
56
57
58
59
The value or behavior may vary among implementations that conform to
IEEE Std 1003.1-2001. An application should not rely on the existence or validity of the
value or behavior. An application that relies on any particular value or behavior cannot be
assured to be portable across conforming implementations.
60
61
62
unspecified
Describes the nature of a value or behavior not specified by IEEE Std 1003.1-2001 which
results from use of a valid program construct or valid data input.
63
64
65
66
The value or behavior may vary among implementations that conform to
IEEE Std 1003.1-2001. An application should not rely on the existence or validity of the
value or behavior. An application that relies on any particular value or behavior cannot be
assured to be portable across conforming implementations.
2
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Introduction
67
1.6
Definitions
Concepts and definitions are defined in the Base Definitions volume of IEEE Std 1003.1-2001.
68
69
Definitions
1.7
Relationship to Other Formal Standards
70
71
Great care has been taken to ensure that this volume of IEEE Std 1003.1-2001 is fully aligned with
the following standards:
72
73
ISO C (1999)
ISO/IEC 9899: 1999, Programming Languages — C.
74
75
76
77
78
79
Parts of the ISO/IEC 9899: 1999 standard (hereinafter referred to as the ISO C standard) are
referenced to describe requirements also mandated by this volume of IEEE Std 1003.1-2001.
Some functions and headers included within this volume of IEEE Std 1003.1-2001 have a version
in the ISO C standard; in this case CX markings are added as appropriate to show where the
ISO C standard has been extended (see Section 1.8.1). Any conflict between this volume of
IEEE Std 1003.1-2001 and the ISO C standard is unintentional.
80
81
This volume of IEEE Std 1003.1-2001 also allows, but does not require, mathematics functions to
support IEEE Std 754-1985 and IEEE Std 854-1987.
82
1.8
Portability
83
84
85
86
Some of the utilities in the Shell and Utilities volume of IEEE Std 1003.1-2001 and functions in
the System Interfaces volume of IEEE Std 1003.1-2001 describe functionality that might not be
fully portable to systems meeting the requirements for POSIX conformance (see the Base
Definitions volume of IEEE Std 1003.1-2001, Chapter 2, Conformance).
87
88
89
Where optional, enhanced, or reduced functionality is specified, the text is shaded and a code in
the margin identifies the nature of the option, extension, or warning (see Section 1.8.1). For
maximum portability, an application should avoid such functionality.
90
1.8.1
Margin codes and their meanings are listed in the Base Definitions volume
IEEE Std 1003.1-2001, but are repeated here for convenience:
91
92
93
94
95
ADV
AIO
Advisory Information
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Asynchronous Input and Output
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the AIO margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the AIO
margin legend.
102
103
104
105
106
of
Where applicable, functions are marked with the ADV margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the ADV
margin legend.
96
97
98
99
100
101
Codes
BAR
Barriers
The functionality described is optional. The functionality described is also an extension to the
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
3
Portability
Introduction
107
ISO C standard.
108
109
110
Where applicable, functions are marked with the BAR margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the BAR
margin legend.
111
112
BE
Where applicable, utilities are marked with the BE margin legend in the SYNOPSIS section.
Where additional semantics apply to a utility, the material is identified by use of the BE margin
legend.
113
114
115
116
117
CD
CPT
CS
Clock Selection
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the CS margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the CS
margin legend.
130
131
132
133
134
135
Process CPU-Time Clocks
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the CPT margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the CPT
margin legend.
124
125
126
127
128
129
C-Language Development Utilities
The functionality described is optional.
Where applicable, utilities are marked with the CD margin legend in the SYNOPSIS section.
Where additional semantics apply to a utility, the material is identified by use of the CD margin
legend.
118
119
120
121
122
123
Batch Environment Services and Utilities
The functionality described is optional.
CX
Extension to the ISO C standard
The functionality described is an extension to the ISO C standard. Application writers may make
use of an extension as it is supported on all IEEE Std 1003.1-2001-conforming systems.
136
137
138
139
140
With each function or header from the ISO C standard, a statement to the effect that ‘‘any
conflict is unintentional’’ is included. That is intended to refer to a direct conflict.
IEEE Std 1003.1-2001 acts in part as a profile of the ISO C standard, and it may choose to further
constrain behaviors allowed to vary by the ISO C standard. Such limitations are not considered
conflicts.
141
142
Where additional semantics apply to a function or header, the material is identified by use of the
CX margin legend.
143
144
FD
Where applicable, utilities are marked with the FD margin legend in the SYNOPSIS section.
Where additional semantics apply to a utility, the material is identified by use of the FD margin
legend.
145
146
147
148
FORTRAN Development Utilities
The functionality described is optional.
FR
149
4
FORTRAN Runtime Utilities
The functionality described is optional.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Introduction
Where applicable, utilities are marked with the FR margin legend in the SYNOPSIS section.
Where additional semantics apply to a utility, the material is identified by use of the FR margin
legend.
150
151
152
153
154
155
FSC
IP6
IPV6
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the IP6 margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the IP6
margin legend.
162
163
164
165
166
167
File Synchronization
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the FSC margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the FSC
margin legend.
156
157
158
159
160
161
Portability
MC1
Advisory Information and either Memory Mapped Files or Shared Memory Objects
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
168
This is a shorthand notation for combinations of multiple option codes.
169
170
171
Where applicable, functions are marked with the MC1 margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the MC1
margin legend.
172
173
Refer to the Base Definitions volume of IEEE Std 1003.1-2001, Section 1.5.2, Margin Code
Notation.
174
175
176
MC2
Memory Mapped Files, Shared Memory Objects, or Memory Protection
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
177
This is a shorthand notation for combinations of multiple option codes.
178
179
180
Where applicable, functions are marked with the MC2 margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the MC2
margin legend.
181
182
Refer to the Base Definitions volume of IEEE Std 1003.1-2001, Section 1.5.2, Margin Code
Notation.
183
184
185
MF
Where applicable, functions are marked with the MF margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the MF
margin legend.
186
187
188
189
190
191
192
193
Memory Mapped Files
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
ML
Process Memory Locking
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the ML margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the ML
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
5
Portability
margin legend.
194
195
196
197
MLR
MON
MPR
MSG
MX
OB
OF
Output Format Incompletely Specified
The functionality described is an XSI extension. The format of the output produced by the utility
is not fully specified. It is therefore not possible to post-process this output in a consistent
fashion. Typical problems include unknown length of strings and unspecified field delimiters.
Where applicable, the material is identified by use of the OF margin legend.
234
235
Obsolescent
The functionality described may be withdrawn in a future version of this volume of
IEEE Std 1003.1-2001. Strictly Conforming POSIX Applications and Strictly Conforming XSI
Applications shall not use obsolescent features.
Where applicable, the material is identified by use of the OB margin legend.
229
230
231
232
233
IEC 60559 Floating-Point Option
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the MX margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the MX
margin legend.
222
223
224
225
226
227
228
Message Passing
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the MSG margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the MSG
margin legend.
216
217
218
219
220
221
Memory Protection
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the MPR margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the MPR
margin legend.
210
211
212
213
214
215
Monotonic Clock
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the MON margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the MON
margin legend.
204
205
206
207
208
209
Range Memory Locking
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the MLR margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the MLR
margin legend.
198
199
200
201
202
203
Introduction
OH
236
237
6
Optional Header
In the SYNOPSIS section of some interfaces in the System Interfaces volume of
IEEE Std 1003.1-2001 an included header is marked as in the following example:
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Introduction
238
239
240
OH
PIO
PS
RS
RTS
SD
SEM
281
282
Semaphores
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the SEM margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the SEM
margin legend.
275
276
277
278
279
280
Software Development Utilities
The functionality described is optional.
Where applicable, utilities are marked with the SD margin legend in the SYNOPSIS section.
Where additional semantics apply to a utility, the material is identified by use of the SD margin
legend.
269
270
271
272
273
274
Realtime Signals Extension
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the RTS margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the RTS
margin legend.
264
265
266
267
268
Raw Sockets
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the RS margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the RS
margin legend.
258
259
260
261
262
263
Process Scheduling
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the PS margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the PS
margin legend.
252
253
254
255
256
257
Prioritized Input and Output
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the PIO margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the PIO
margin legend.
246
247
248
249
250
251
#include <sys/types.h>
#include <grp.h>
struct group *getgrnam(const char *name);
The OH margin legend indicates that the marked header is not required on XSI-conformant
systems.
241
242
243
244
245
Portability
SHM
Shared Memory Objects
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the SHM margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the SHM
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
7
Portability
margin legend.
283
284
285
286
SIO
SPI
SPN
SS
TCT
TEF
THR
Threads
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the THR margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the THR
margin legend.
323
324
325
326
327
Trace Event Filter
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TEF margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TEF
margin legend.
317
318
319
320
321
322
Thread CPU-Time Clocks
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TCT margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TCT
margin legend.
311
312
313
314
315
316
Process Sporadic Server
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the SS margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the SS
margin legend.
305
306
307
308
309
310
Spawn
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the SPN margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the SPN
margin legend.
299
300
301
302
303
304
Spin Locks
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the SPI margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the SPI
margin legend.
293
294
295
296
297
298
Synchronized Input and Output
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the SIO margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the SIO
margin legend.
287
288
289
290
291
292
Introduction
TMO
8
Timeouts
The functionality described is optional. The functionality described is also an extension to the
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Introduction
Portability
328
ISO C standard.
329
330
331
Where applicable, functions are marked with the TMO margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TMO
margin legend.
332
333
334
TMR
Where applicable, functions are marked with the TMR margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TMR
margin legend.
335
336
337
338
339
340
TPI
TPP
TPS
TRC
TRI
371
372
Trace Inherit
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TRI margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TRI
margin legend.
365
366
367
368
369
370
Trace
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TRC margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TRC
margin legend.
359
360
361
362
363
364
Thread Execution Scheduling
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TPS margin legend for the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TPS
margin legend.
353
354
355
356
357
358
Thread Priority Protection
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TPP margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TPP
margin legend.
347
348
349
350
351
352
Thread Priority Inheritance
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TPI margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TPI
margin legend.
341
342
343
344
345
346
Timers
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
TRL
Trace Log
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TRL margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TRL
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
9
Portability
margin legend.
373
374
375
376
TSA
TSF
TSH
TSP
TSS
TYM
UP
User Portability Utilities
The functionality described is optional.
Where applicable, utilities are marked with the UP margin legend in the SYNOPSIS section.
Where additional semantics apply to a utility, the material is identified by use of the UP margin
legend.
412
413
414
415
416
417
Typed Memory Objects
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TYM margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TYM
margin legend.
407
408
409
410
411
Thread Stack Address Size
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TSS margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TSS
margin legend.
401
402
403
404
405
406
Thread Sporadic Server
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TSP margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TSP
margin legend.
395
396
397
398
399
400
Thread Process-Shared Synchronization
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TSH margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TSH
margin legend.
389
390
391
392
393
394
Thread-Safe Functions
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TSF margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TSF
margin legend.
383
384
385
386
387
388
Thread Stack Address Attribute
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
Where applicable, functions are marked with the TSA margin legend for the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the TSA
margin legend.
377
378
379
380
381
382
Introduction
XSI
Extension
The functionality described is an XSI extension. Functionality marked XSI is also an extension to
the ISO C standard. Application writers may confidently make use of an extension on all
10
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Introduction
Portability
418
systems supporting the X/Open System Interfaces Extension.
419
420
421
If an entire SYNOPSIS section is shaded and marked XSI, all the functionality described in that
reference page is an extension. See the Base Definitions volume of IEEE Std 1003.1-2001, Section
3.439, XSI.
422
423
424
XSR
Where applicable, functions are marked with the XSR margin legend in the SYNOPSIS section.
Where additional semantics apply to a function, the material is identified by use of the XSR
margin legend.
425
426
427
428
XSI STREAMS
The functionality described is optional. The functionality described is also an extension to the
ISO C standard.
1.9
Format of Entries
429
430
The entries in Chapter 3 are based on a common format as follows. The only sections relating to
conformance are the SYNOPSIS, DESCRIPTION, RETURN VALUE, and ERRORS sections.
431
432
NAME
433
434
435
436
SYNOPSIS
This section summarizes the use of the entry being described. If it is necessary to
include a header to use this function, the names of such headers are shown, for
example:
437
This section gives the name or names of the entry and briefly states its purpose.
#include <stdio.h>
438
439
DESCRIPTION
This section describes the functionality of the function or header.
440
441
RETURN VALUE
This section indicates the possible return values, if any.
442
443
444
If the implementation can detect errors, ‘‘successful completion’’ means that no error
has been detected during execution of the function. If the implementation does detect
an error, the error is indicated.
445
446
447
448
For functions where no errors are defined, ‘‘successful completion’’ means that if the
implementation checks for errors, no error has been detected. If the implementation can
detect errors, and an error is detected, the indicated return value is returned and errno
may be set.
449
450
451
ERRORS
This section gives the symbolic names of the error values returned by a function or
stored into a variable accessed through the symbol errno if an error occurs.
452
453
‘‘No errors are defined’’ means that error values returned by a function or stored into a
variable accessed through the symbol errno, if any, depend on the implementation.
454
455
456
457
458
EXAMPLES
This section is informative.
This section gives examples of usage, where appropriate. In the event of conflict
between an example and a normative part of this volume of IEEE Std 1003.1-2001, the
normative material is to be taken as correct.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
11
Format of Entries
Introduction
APPLICATION USAGE
This section is informative.
459
460
This section gives warnings and advice to application writers about the entry. In the
event of conflict between warnings and advice and a normative part of this volume of
IEEE Std 1003.1-2001, the normative material is to be taken as correct.
461
462
463
RATIONALE
This section is informative.
464
465
This section contains historical information concerning the contents of this volume of
IEEE Std 1003.1-2001 and why features were included or discarded by the standard
developers.
466
467
468
FUTURE DIRECTIONS
This section is informative.
469
470
This section provides comments which should be used as a guide to current thinking;
there is not necessarily a commitment to adopt these future directions.
471
472
SEE ALSO
This section is informative.
473
474
This section gives references to related information.
475
CHANGE HISTORY
This section is informative.
476
477
This section shows the derivation of the entry and any significant changes that have
been made to it.
478
479
12
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Chapter 2
General Information
480
This chapter covers information that is relevant to all the functions specified in Chapter 3 and
the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers.
481
482
483
2.1
Use and Implementation of Functions
484
485
Each of the following statements shall apply unless explicitly stated otherwise in the detailed
descriptions that follow:
486
487
488
1. If an argument to a function has an invalid value (such as a value outside the domain of
the function, or a pointer outside the address space of the program, or a null pointer), the
behavior is undefined.
489
490
491
492
493
494
495
496
2. Any function declared in a header may also be implemented as a macro defined in the
header, so a function should not be declared explicitly if its header is included. Any macro
definition of a function can be suppressed locally by enclosing the name of the function in
parentheses, because the name is then not followed by the left parenthesis that indicates
expansion of a macro function name. For the same syntactic reason, it is permitted to take
the address of a function even if it is also defined as a macro. The use of the C-language
#undef construct to remove any such macro definition shall also ensure that an actual
function is referred to.
497
498
499
500
501
3. Any invocation of a function that is implemented as a macro shall expand to code that
evaluates each of its arguments exactly once, fully protected by parentheses where
necessary, so it is generally safe to use arbitrary expressions as arguments. Likewise, those
function-like macros described in the following sections may be invoked in an expression
anywhere a function with a compatible return type could be called.
502
503
504
4. Provided that a function can be declared without reference to any type defined in a header,
it is also permissible to declare the function explicitly and use it without including its
associated header.
505
506
5. If a function that accepts a variable number of arguments is not declared (explicitly or by
including its associated header), the behavior is undefined.
507
2.2
The Compilation Environment
508
2.2.1
POSIX.1 Symbols
509
510
511
512
513
514
Certain symbols in this volume of IEEE Std 1003.1-2001 are defined in headers (see the Base
Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers). Some of those headers could
also define symbols other than those defined by IEEE Std 1003.1-2001, potentially conflicting
with symbols used by the application. Also, IEEE Std 1003.1-2001 defines symbols that are not
permitted by other standards to appear in those headers without some control on the visibility
of those symbols.
515
516
517
Symbols called ‘‘feature test macros’’ are used to control the visibility of symbols that might be
included in a header. Implementations, future versions of IEEE Std 1003.1-2001, and other
standards may define additional feature test macros.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
13
The Compilation Environment
General Information
518
519
520
521
522
In the compilation of an application that #defines a feature test macro specified by
IEEE Std 1003.1-2001, no header defined by IEEE Std 1003.1-2001 shall be included prior to the
definition of the feature test macro. This restriction also applies to any implementationprovided header in which these feature test macros are used. If the definition of the macro does
not precede the #include, the result is undefined.
523
Feature test macros shall begin with the underscore character (’_’).
524
2.2.1.1
The _POSIX_C_SOURCE Feature Test Macro
525
526
A POSIX-conforming application should ensure that the feature test macro _POSIX_C_SOURCE
is defined before inclusion of any header.
527
528
When an application includes a header described by IEEE Std 1003.1-2001, and when this feature
test macro is defined to have the value 200112L:
529
530
1. All symbols required by IEEE Std 1003.1-2001 to appear when the header is included shall
be made visible.
531
532
2. Symbols that are explicitly permitted, but not required, by IEEE Std 1003.1-2001 to appear
in that header (including those in reserved name spaces) may be made visible.
533
534
3. Additional symbols not required or explicitly permitted by IEEE Std 1003.1-2001 to be in
that header shall not be made visible, except when enabled by another feature test macro.
535
536
537
Identifiers in IEEE Std 1003.1-2001 may only be undefined using the #undef directive as
described in Section 2.1 (on page 13) or Section 2.2.2. These #undef directives shall follow all
#include directives of any header in IEEE Std 1003.1-2001.
538
539
Note:
The POSIX.1-1990 standard specified a macro called _POSIX_SOURCE. This has been
superseded by _POSIX_C_SOURCE.
540
2.2.1.2
The _XOPEN_SOURCE Feature Test Macro
541
542
543
XSI
An XSI-conforming application should ensure that the feature test macro _XOPEN_SOURCE is
defined with the value 600 before inclusion of any header. This is needed to enable the
functionality described in Section 2.2.1.1 and in addition to enable the XSI extension.
Since this volume of IEEE Std 1003.1-2001 is aligned with the ISO C standard, and since all
functionality enabled by _POSIX_C_SOURCE set equal to 200112L is enabled by
_XOPEN_SOURCE set equal to 600, there should be no need to define _POSIX_C_SOURCE if
_XOPEN_SOURCE is so defined. Therefore, if _XOPEN_SOURCE is set equal to 600 and
_POSIX_C_SOURCE is set equal to 200112L, the behavior is the same as if only
_XOPEN_SOURCE is defined and set equal to 600. However, should _POSIX_C_SOURCE be set
to a value greater than 200112L, the behavior is unspecified.
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
2.2.2
XSI
14
The Name Space
All identifiers in this volume of IEEE Std 1003.1-2001, except environ, are defined in at least one
of the headers, as shown in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 13,
Headers. When _XOPEN_SOURCE or _POSIX_C_SOURCE is defined, each header defines or
declares some identifiers, potentially conflicting with identifiers used by the application. The set
of identifiers visible to the application consists of precisely those identifiers from the header
pages of the included headers, as well as additional identifiers reserved for the implementation.
In addition, some headers may make visible identifiers from other headers as indicated on the
relevant header pages.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
The Compilation Environment
560
561
562
563
Implementations may also add members to a structure or union without controlling the
visibility of those members with a feature test macro, as long as a user-defined macro with the
same name cannot interfere with the correct interpretation of the program. The identifiers
reserved for use by the implementation are described below:
564
565
1. Each identifier with external linkage described in the header section is reserved for use as
an identifier with external linkage if the header is included.
566
567
2. Each macro described in the header section is reserved for any use if the header is
included.
568
569
3. Each identifier with file scope described in the header section is reserved for use as an
identifier with file scope in the same name space if the header is included.
570
571
572
573
574
The prefixes posix_, POSIX_, and _POSIX_ are reserved for use by IEEE Std 1003.1-2001 and
other POSIX standards. Implementations may add symbols to the headers shown in the
following table, provided the identifiers for those symbols begin with the corresponding
reserved prefixes in the following table, and do not use the reserved prefixes posix_, POSIX_, or
_POSIX_.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
15
The Compilation Environment
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
AIO
MSG
XSI
IP6
XSI
PS
SEM
XSI
RTS
XSI
XSI
MF
XSI
XSI
XSI
XSI
XSI
16
General Information
_ ____________________________________________________________________________________
L
L
L
L
L
Complete
L
L
L
L
L
Header
Prefix
Suffix
Name
_L ____________________________________________________________________________________
L
L
L
L
<aio.h>
aio_, lio_, AIO_, LIO_
L
L
L
L
L
L
L
L
L in_, inet_
L <arpa/inet.h>
L
L
L
L to[a-z], is[a-z]
L <ctype.h>
L
L
L
L
L
<dirent.h>
d_
L
L
L
L
L
<errno.h>
E[0-9], E[A-Z]
L
L
L
L
L
<fcntl.h>
l_
L
L
L
L
L
L
L
L
L gl_
L <glob.h>
L
L
L
L gr_
L <grp.h>
L
L
L
L
L
<inttypes.h>
int[0-9a-z_]*_t,
L
L
L
L
L
uint[0-9a-z_]*_t
L
L
L
L
L
<limits.h>
_MAX, _MIN L
L
L
L
L
L
L
L
L LC_[A-Z]
L <locale.h>
L
L
L
L mq_, MQ_
L <mqueue.h>
L
L
L
L
L
<ndbm.h>
dbm_
L
L
L
L
L
<netdb.h>
h_, n_, p_, s_
L
L
L
L
L
<net/if.h>
if_
L
L
L
L
L
L
L
L
L in_, ip_, s_, sin_
L <netinet/in.h>
L
L
L
L in6_, s6_, sin6_
L
L
L
L
L
L
<poll.h>
pd_, ph_, ps_
L
L
L
L
L
<pthread.h>
pthread_, PTHREAD_
L
L
L
L
L
<pwd.h>
pw_
L
L
L
L
L
<regex.h>
re_, rm_
L
L
L
L
L
L
L
L
L sched_, SCHED_
L <sched.h>
L
L
L
L sem_, SEM_
L <semaphore.h>
L
L
L
L
L
<signal.h>
sa_, uc_, SIG[A-Z], SIG_[A-Z]
L
L
L
L
L
ss_, sv_
L
L
L
L
L
si_, SI_, sigev_, SIGEV_, sival_
L
L
L
L
L
L
L
L
L bi_, ic_, l_, sl_, str_
L <stropts.h>
L
L int[0-9a-z_]*_t,
L
L
L <stdint.h>
L
L
L
L
L
uint[0-9a-z_]*_t
L
L
L
L
L
<stdlib.h>
str[a-z]
L
L
L
L
L
<string.h>
str[a-z], mem[a-z], wcs[a-z]
L
L
L
L
L
L
L key, pad, seq
L
L ipc_
L <sys/ipc.h>
L
L
L
L shm_, MAP_, MCL_, MS_, PROT_
L <sys/mman.h>
L
L
L
L
L
<sys/msg.h>
msg
msg
L
L
L
L
L
<sys/resource.h>
rlim_, ru_
L
L
L
L
L
<sys/select.h>
fd_, fds_, FD_
L
L
L
L
L
L
L sem
L
L sem
L <sys/sem.h>
L
L
L
L shm
L <sys/shm.h>
L
L
L
L
<sys/socket.h>
ss_, sa_, if_, ifc_, ifru_, infu_, ifra_, L
L
L
L
L
L
msg_, cmsg_, l_
L
L
L
L
L
<sys/stat.h>
st_
L
L
L
L
L
<sys/statvfs.h>
f_
L
L
L
L
L
L
L
L
L fds_, it_, tv_, FD_
L <sys/time.h>
L
L
L
L tms_
L <sys/times.h>
L
L
L
L
L_ ____________________________________________________________________________________
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
XSI
XSI
TMR
TMR
XSI
XSI
XSI
The Compilation Environment
_ ____________________________________________________________________________________
L
L
L
L
L
Complete
L
L
L
L
L
Header
Prefix
Suffix
Name
_L ____________________________________________________________________________________
L
L
L
L
<sys/uio.h>
iov_
UIO_MAXIOV
L
L
L
L
L
L <sys/un.h>
L sun_
L
L
L
L <sys/utsname.h>
L uts_
L
L
L
L
L
L
L
L
<sys/wait.h>
si_, W[A-Z], P_
L
L
L
L
L
<termios.h>
c_
L
L
L
L
L
<time.h>
tm_
L
L
L
L
L
L
L clock_, timer_, it_, tv_,
L
L
L
L
L CLOCK_, TIMER_
L
L
L
L
L
L
L
L
<ucontext.h>
uc_, ss_
L
L
L
L
L
<ulimit.h>
UL_
L
L
L
L
L
<utime.h>
utim_
L
L
L
L
L
L <utmpx.h>
L ut_
L _LVL, _TIME,
L
L
L
L
L _PROCESS
L
L
L
L
L
L
L
<wchar.h>
wcs[a-z]
L
L
L
L
L
<wctype.h>
is[a-z], to[a-z]
L
L
L
L
L
<wordexp.h>
we_
L
L
L
L
L
ANY header
POSIX_, _POSIX_, posix_
_t
L
L
L
L
L_ ____________________________________________________________________________________
The notation [A−Z] indicates any uppercase letter in the portable character set. The notation
[a−z] indicates any lowercase letter in the portable character set. Commas and spaces in the
lists of prefixes and complete names in the above table are not part of any prefix or complete
name.
643
644
645
646
Note:
647
648
649
650
If any header in the following table is included, macros with the prefixes shown may be defined.
After the last inclusion of a given header, an application may use identifiers with the
corresponding prefixes for its own purpose, provided their use is preceded by a #undef of the
corresponding macro.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
17
The Compilation Environment
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
XSI
XSI
XSI
XSI
IP6
XSI
XSI
XSI
XSI
XSI
XSI
XSI
XSI
XSI
XSI
XSI
XSI
XSI
XSI
XSI
XSI
General Information
_____________________________________________________________________________________
L
L
L
Header
Prefix
_____________________________________________________________________________________
L
L
L
<dlfcn.h>
RTLD_
L
L
L
<fcntl.h>
F_, O_, S_
L
L
L
MM_
L
L
L <fmtmsg.h>
L
L <fnmatch.h>
L
FNM_
L
L
L
<ftw.h>
FTW
L
L
L
<glob.h>
GLOB_
L
L
L
<inttypes.h>
PRI[a-z], SCN[a-z]
L
L
L
DBM_
L
L <ndbm.h>
L
L
L
L <net/if.h>
IF_
L
L
L
<netinet/in.h>
IMPLINK_, IN_, INADDR_, IP_, IPPORT_, IPPROTO_, SOCK_
L
L
L
IPV6_, IN6_
L
L
L
<netinet/tcp.h> L TCP_
L
L
NL_
L
L <nl_types.h>
L
L <poll.h>
L
L
POLL
L
L
L
<regex.h>
REG_
L
L
L
<signal.h>
SA_, SIG_[0-9a-z_],
L
L
L
BUS_, CLD_, FPE_, ILL_, POLL_, SEGV_, SI_, SS_, SV_, TRAP_
L
L
L
INT[0-9A-Z_]_MIN, INT[0-9A-Z_]_MAX, INT[0-9A-Z_]_C
L
L
L <stdint.h>
L
L
L
UINT[0-9A-Z_]_MIN, UINT[0-9A-Z_]_MAX, UINT[0-9A-Z_]_C
L
L
L
<stropts.h>
FLUSH[A-Z], I_, M_, MUXID_R[A-Z], S_, SND[A-Z], STR
L
L
L
<syslog.h>
LOG_
L
L
L
<sys/ipc.h>
IPC_
L
L
L
<sys/mman.h>
PROT_, MAP_, MS_
L
L
L
MSG[A-Z]
L
L
L <sys/msg.h>
L
L
L <sys/resource.h>
PRIO_, RLIM_, RLIMIT_, RUSAGE_
L
L
L
<sys/sem.h>
SEM_
L
L
L
<sys/shm.h>
SHM[A-Z], SHM_[A-Z]
L
L
L
<sys/socket.h>
AF_, CMSG_, MSG_, PF_, SCM_, SHUT_, SO
L
L
L
S_
L
L
L <sys/stat.h>
L
L
L <sys/statvfs.h>
ST_
L
L
L
<sys/time.h>
FD_, ITIMER_
L
L
L
<sys/uio.h>
IOV_
L
L
L
<sys/wait.h>
BUS_, CLD_, FPE_, ILL_, POLL_, SEGV_, SI_, TRAP_
L
L
L
V, I, O, TC, B[0-9] (See below.)
L
L
L <termios.h>
L
L
L <wordexp.h>
WRDE_
L
L
L_____________________________________________________________________________________
The notation [0−9] indicates any digit. The notation [A−Z] indicates any uppercase letter in the
portable character set. The notation [0−9a−z_] indicates any digit, any lowercase letter in the
portable character set, or underscore.
688
689
690
Note:
691
The following reserved names are used as exact matches for <termios.h>:
692
693
694
695
696
697
XSI
18
CBAUD
DEFECHO
ECHOCTL
ECHOKE
ECHOPRT
EXTA
EXTB
FLUSHO
LOBLK
PENDIN
SWTCH
VDISCARD
VDSUSP
VLNEXT
VREPRINT
VSTATUS
VWERASE
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
698
The Compilation Environment
The following identifiers are reserved regardless of the inclusion of headers:
699
700
1. All identifiers that begin with an underscore and either an uppercase letter or another
underscore are always reserved for any use by the implementation.
701
702
2. All identifiers that begin with an underscore are always reserved for use as identifiers with
file scope in both the ordinary identifier and tag name spaces.
703
704
705
3. All identifiers in the table below are reserved for use as identifiers with external linkage.
Some of these identifiers do not appear in this volume of IEEE Std 1003.1-2001, but are
reserved for future use by the ISO C standard.
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
_Exit
abort
abs
acos
acosf
acosh
acoshf
acoshl
acosl
acosl
asctime
asin
asinf
asinh
asinhf
asinhl
asinl
asinl
atan
atan2
atan2f
atan2l
atanf
atanf
atanh
atanh
atanhf
atanhl
atanl
atanl
atexit
atof
atoi
atol
atoll
bsearch
cabs
cabsf
cabsl
cacos
cexmp1
cexmp1f
cexmp1l
cexp
cexp2
cexp2f
cexp2l
cexpf
cexpl
cimag
cimagf
cimagl
clearerr
clgamma
clgammaf
clgammal
clock
clog
clog10
clog10f
clog10l
clog1p
clog1pf
clog1pl
clog2
clog2f
clog2l
clogf
clogl
conj
conjf
conjl
copysign
copysignf
copysignl
cos
cosf
cosh
coshf
coshl
fabsf
fabsl
fclose
fdim
fdimf
fdiml
feclearexcept
fegetenv
fegetexceptflag
fegetround
feholdexcept
feof
feraiseexcept
ferror
fesetenv
fesetexceptflag
fesetround
fetestexcept
feupdateenv
fflush
fgetc
fgetpos
fgets
fgetwc
fgetws
floor
floorf
floorl
fma
fmaf
fmal
fmax
fmaxf
fmaxl
fmin
fminf
fminl
fmod
fmodf
fmodl
lgammal
llabs
llrint
llrintf
llrintl
llround
llroundf
llroundl
localeconv
localtime
log
log10
log10f
log10l
log1p
log1pf
log1pl
log2
log2f
log2l
logb
logbf
logbl
logf
logl
longjmp
lrint
lrintf
lrintl
lround
lroundf
lroundl
malloc
mblen
mbrlen
mbrtowc
mbsinit
mbsrtowcs
mbstowcs
mbtowc
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
scalbln
scalblnf
scalblnl
scalbn
scalbnf
scalbnl
scanf
setbuf
setjmp
setlocale
setvbuf
signal
sin
sinf
sinh
sinhf
sinhl
sinl
sprintf
sqrt
sqrtf
sqrtl
srand
sscanf
str[a-z]*
strtof
strtoimax
strtold
strtoll
strtoull
strtoumax
swprintf
swscanf
system
tan
tanf
tanh
tanhf
tanhl
tanl
19
The Compilation Environment
cacosf
cacosh
cacoshf
cacoshl
cacosl
calloc
carg
cargf
cargl
casin
casinf
casinh
casinhf
casinhl
casinl
catan
catanf
catanh
catanh
catanhf
catanhf
catanhl
catanhl
catanl
cbrt
cbrtf
cbrtl
ccos
ccosf
ccosh
ccoshf
ccoshl
ccosl
ceil
ceilf
ceilf
ceill
ceill
cerf
cerfc
cerfcf
cerfcl
cerff
cerfl
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
Note:
790
791
792
General Information
cosl
cpow
cpowf
cpowl
cproj
cprojf
cprojl
creal
crealf
creall
csin
csinf
csinh
csinhf
csinhl
csinl
csqrt
csqrtf
csqrtl
ctan
ctanf
ctanl
ctgamma
ctgammaf
ctgammal
ltime
difftime
div
erfcf
erfcl
erff
erfl
errno
exit
exp
exp2
exp2f
exp2l
expf
expl
expm1
expm1f
expm1l
fabs
fopen
fprintf
fputc
fputs
fputwc
fputws
fread
free
freopen
frexp
frexpf
frexpl
fscanf
fseek
fsetpos
ftell
fwide
fwprintf
fwrite
fwscanf
getc
getchar
getenv
gets
getwc
getwchar
gmtime
hypotf
hypotl
ilogb
ilogbf
ilogbl
imaxabs
imaxdiv
is[a-z]*
isblank
iswblank
labs
ldexp
ldexpf
ldexpl
ldiv
ldiv
lgammaf
mem[a-z]*
mktime
modf
modff
modfl
nan
nanf
nanl
nearbyint
nearbyintf
nearbyintl
nextafterf
nextafterl
nexttoward
nexttowardf
nexttowardl
perror
pow
powf
powl
printf
putc
putchar
puts
putwc
putwchar
qsort
raise
rand
realloc
remainderf
remainderl
remove
remquo
remquof
remquol
rename
rewind
rint
rintf
rintl
round
roundf
roundl
tgamma
tgammaf
tgammal
time
tmpfile
tmpnam
to[a-z]*
trunc
truncf
truncl
ungetc
ungetwc
va_end
vfprintf
vfscanf
vfwprintf
vfwscanf
vprintf
vscanf
vsprintf
vsscanf
vswprintf
vswscanf
vwprintf
vwscanf
wcrtomb
wcs[a-z]*
wcstof
wcstoimax
wcstold
wcstoll
wcstoull
wcstoumax
wctob
wctomb
wctrans
wctype
wcwidth
wmem[a-z]*
wprintf
wscanf
The notation [a−z] indicates any lowercase letter in the portable character set. The
notation ’*’ indicates any combination of digits, letters in the portable character set, or
underscore.
4. All functions and external identifiers defined in the Base Definitions volume of
IEEE Std 1003.1-2001, Chapter 13, Headers are reserved for use as identifiers with external
linkage.
793
794
795
20
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
The Compilation Environment
5. All the identifiers defined in this volume of IEEE Std 1003.1-2001 that have external linkage
are always reserved for use as identifiers with external linkage.
796
797
798
No other identifiers are reserved.
799
800
801
802
Applications shall not declare or define identifiers with the same name as an identifier reserved
in the same context. Since macro names are replaced whenever found, independent of scope and
name space, macro names matching any of the reserved identifier names shall not be defined by
an application if any associated header is included.
803
804
805
Except that the effect of each inclusion of <assert.h> depends on the definition of NDEBUG,
headers may be included in any order, and each may be included more than once in a given
scope, with no difference in effect from that of being included only once.
806
807
808
809
810
811
If used, the application shall ensure that a header is included outside of any external declaration
or definition, and it shall be first included before the first reference to any type or macro it
defines, or to any function or object it declares. However, if an identifier is declared or defined in
more than one header, the second and subsequent associated headers may be included after the
initial reference to the identifier. Prior to the inclusion of a header, the application shall not
define any macros with names lexically identical to symbols defined by that header.
812
2.3
Error Numbers
813
814
Most functions can provide an error number. The means by which each function provides its
error numbers is specified in its description.
815
816
817
818
819
Some functions provide the error number in a variable accessed through the symbol errno. The
symbol errno, defined by including the <errno.h> header, expands to a modifiable lvalue of type
int. It is unspecified whether errno is a macro or an identifier declared with external linkage. If a
macro definition is suppressed in order to access an actual object, or a program defines an
identifier with the name errno, the behavior is undefined.
820
821
822
823
The value of errno should only be examined when it is indicated to be valid by a function’s return
value. No function in this volume of IEEE Std 1003.1-2001 shall set errno to zero. For each thread
of a process, the value of errno shall not be affected by function calls or assignments to errno by
other threads.
824
825
Some functions return an error number directly as the function value. These functions return a
value of zero to indicate success.
826
827
If more than one error occurs in processing a function call, any one of the possible errors may be
returned, as the order of detection is undefined.
828
829
830
831
832
833
834
Implementations may support additional errors not included in this list, may generate errors
included in this list under circumstances other than those described here, or may contain
extensions or limitations that prevent some errors from occurring. The ERRORS section on each
reference page specifies whether an error shall be returned, or whether it may be returned.
Implementations shall not generate a different error number from the ones described here for
error conditions described in this volume of IEEE Std 1003.1-2001, but may generate additional
errors unless explicitly disallowed for a particular function.
835
836
837
Each implementation shall document, in the conformance document, situations in which each of
the optional conditions defined in IEEE Std 1003.1-2001 is detected. The conformance document
may also contain statements that one or more of the optional error conditions are not detected.
838
839
For functions under the Threads option for which [EINTR] is not listed as a possible error
condition in this volume of IEEE Std 1003.1-2001, an implementation shall not return an error
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
21
Error Numbers
General Information
840
code of [EINTR].
841
842
843
844
845
846
847
848
The following symbolic names identify the possible error numbers, in the context of the
functions specifically defined in this volume of IEEE Std 1003.1-2001; these general descriptions
are more precisely defined in the ERRORS sections of the functions that return them. Only these
symbolic names should be used in programs, since the actual value of the error number is
unspecified. All values listed in this section shall be unique integer constant expressions with
type int suitable for use in #if preprocessing directives, except as noted below. The values for all
these names shall be found in the <errno.h> header defined in the Base Definitions volume of
IEEE Std 1003.1-2001. The actual values are unspecified by this volume of IEEE Std 1003.1-2001.
849
850
851
852
[E2BIG]
Argument list too long. The sum of the number of bytes used by the new process image’s
argument list and environment list is greater than the system-imposed limit of {ARG_MAX}
bytes.
853
or:
854
Lack of space in an output buffer.
855
or:
856
Argument is greater than the system-imposed maximum.
857
858
859
[EACCES]
Permission denied. An attempt was made to access a file in a way forbidden by its file
access permissions.
860
861
[EADDRINUSE]
Address in use. The specified address is in use.
862
863
[EADDRNOTAVAIL]
Address not available. The specified address is not available from the local system.
864
865
866
867
[EAFNOSUPPORT]
Address family not supported. The implementation does not support the specified address
family, or the specified address is not a valid address for the address family of the specified
socket.
868
869
870
[EAGAIN]
Resource temporarily unavailable. This is a temporary condition and later calls to the same
routine may complete normally.
871
872
873
[EALREADY]
Connection already in progress. A connection request is already in progress for the specified
socket.
874
875
876
[EBADF]
Bad file descriptor. A file descriptor argument is out of range, refers to no open file, or a
read (write) request is made to a file that is only open for writing (reading).
877
878
879
880
XSR
[EBADMSG]
Bad message. During a read( ), getmsg( ), getpmsg( ), or ioctl ( ) I_RECVFD request to a
STREAMS device, a message arrived at the head of the STREAM that is inappropriate for
the function receiving the message.
881
read( )
882
883
getmsg( ) or getpmsg( )
A file descriptor was received instead of a control message.
22
Message waiting to be read on a STREAM is not a data message.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Error Numbers
884
885
ioctl ( )
Control or data information was received instead of a file descriptor when
I_RECVFD was specified.
886
or:
887
Bad Message. The implementation has detected a corrupted message.
888
889
890
891
[EBUSY]
Resource busy. An attempt was made to make use of a system resource that is not currently
available, as it is being used by another process in a manner that would have conflicted with
the request being made by this process.
892
893
894
[ECANCELED]
Operation canceled. The associated asynchronous operation was canceled before
completion.
895
896
897
[ECHILD]
No child process. A wait( ) or waitpid ( ) function was executed by a process that had no
existing or unwaited-for child process.
898
899
[ECONNABORTED]
Connection aborted. The connection has been aborted.
900
901
902
903
[ECONNREFUSED]
Connection refused. An attempt to connect to a socket was refused because there was no
process listening or because the queue of connection requests was full and the underlying
protocol does not support retransmissions.
904
905
[ECONNRESET]
Connection reset. The connection was forcibly closed by the peer.
906
907
908
[EDEADLK]
Resource deadlock would occur. An attempt was made to lock a system resource that
would have resulted in a deadlock situation.
909
910
[EDESTADDRREQ]
Destination address required. No bind address was established.
911
912
913
[EDOM]
Domain error. An input argument is outside the defined domain of the mathematical
function (defined in the ISO C standard).
914
915
[EDQUOT]
Reserved.
916
917
918
[EEXIST]
File exists. An existing file was mentioned in an inappropriate context; for example, as a
new link name in the link( ) function.
919
920
921
922
923
[EFAULT]
Bad address. The system detected an invalid address in attempting to use an argument of a
call. The reliable detection of this error cannot be guaranteed, and when not detected may
result in the generation of a signal, indicating an address violation, which is sent to the
process.
924
925
[EFBIG]
File too large. The size of a file would exceed the maximum file size of an implementation or
offset maximum established in the corresponding file description.
926
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
23
Error Numbers
General Information
927
928
929
[EHOSTUNREACH]
Host is unreachable. The destination host cannot be reached (probably because the host is
down or a remote router cannot reach it).
930
931
932
[EIDRM]
Identifier removed. Returned during XSI interprocess communication if an identifier has
been removed from the system.
933
934
935
936
[EILSEQ]
Illegal byte sequence. A wide-character code has been detected that does not correspond to
a valid character, or a byte sequence does not form a valid wide-character code (defined in
the ISO C standard).
937
938
939
[EINPROGRESS]
Operation in progress. This code is used to indicate that an asynchronous operation has not
yet completed.
940
or:
941
942
O_NONBLOCK is set for the socket file descriptor and the connection cannot be
immediately established.
943
944
945
946
947
[EINTR]
Interrupted function call. An asynchronous signal was caught by the process during the
execution of an interruptible function. If the signal handler performs a normal return, the
interrupted function call may return this condition (see the Base Definitions volume of
IEEE Std 1003.1-2001, <signal.h>).
948
949
950
[EINVAL]
Invalid argument. Some invalid argument was supplied; for example, specifying an
undefined signal in a signal( ) function or a kill ( ) function.
951
952
953
954
[EIO]
Input/output error. Some physical input or output error has occurred. This error may be
reported on a subsequent operation on the same file descriptor. Any other error-causing
operation on the same file descriptor may cause the [EIO] error indication to be lost.
955
956
[EISCONN]
Socket is connected. The specified socket is already connected.
957
958
[EISDIR]
Is a directory. An attempt was made to open a directory with write mode specified.
959
960
961
962
[ELOOP]
Symbolic link loop. A loop exists in symbolic links encountered during pathname
resolution. This error may also be returned if more than {SYMLOOP_MAX} symbolic links
are encountered during pathname resolution.
963
964
965
[EMFILE]
Too many open files. An attempt was made to open more than the maximum number of file
descriptors allowed in this process.
966
967
968
[EMLINK]
Too many links. An attempt was made to have the link count of a single file exceed
{LINK_MAX}.
969
[EMSGSIZE]
Message too large. A message sent on a transport provider was larger than an internal
message buffer or some other network limit.
970
971
24
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
972
or:
973
Inappropriate message buffer length.
Error Numbers
974
975
[EMULTIHOP]
Reserved.
976
977
978
979
980
[ENAMETOOLONG]
Filename too long. The length of a pathname exceeds {PATH_MAX}, or a pathname
component is longer than {NAME_MAX}. This error may also occur when pathname
substitution, as a result of encountering a symbolic link during pathname resolution, results
in a pathname string the size of which exceeds {PATH_MAX}.
981
982
[ENETDOWN]
Network is down. The local network interface used to reach the destination is down.
983
984
[ENETRESET]
The connection was aborted by the network.
985
986
[ENETUNREACH]
Network unreachable. No route to the network is present.
987
988
989
990
[ENFILE]
Too many files open in system. Too many files are currently open in the system. The system
has reached its predefined limit for simultaneously open files and temporarily cannot accept
requests to open another one.
991
992
993
[ENOBUFS]
No buffer space available. Insufficient buffer resources were available in the system to
perform the socket operation.
994
995
XSR
[ENODATA]
No message available. No message is available on the STREAM head read queue.
996
997
998
[ENODEV]
No such device. An attempt was made to apply an inappropriate function to a device; for
example, trying to read a write-only device such as a printer.
999
1000
1001
[ENOENT]
No such file or directory. A component of a specified pathname does not exist, or the
pathname is an empty string.
1002
1003
1004
1005
[ENOEXEC]
Executable file format error. A request is made to execute a file that, although it has the
appropriate permissions, is not in the format required by the implementation for executable
files.
1006
1007
1008
[ENOLCK]
No locks available. A system-imposed limit on the number of simultaneous file and record
locks has been reached and no more are currently available.
1009
1010
[ENOLINK]
Reserved.
1011
1012
1013
[ENOMEM]
Not enough space. The new process image requires more memory than is allowed by the
hardware or system-imposed memory management constraints.
1014
1015
[ENOMSG]
No message of the desired type. The message queue does not contain a message of the
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
25
Error Numbers
General Information
required type during XSI interprocess communication.
1016
1017
1018
1019
[ENOPROTOOPT]
Protocol not available. The protocol option specified to setsockopt ( ) is not supported by the
implementation.
1020
1021
1022
[ENOSPC]
No space left on a device. During the write( ) function on a regular file or when extending a
directory, there is no free space left on the device.
1023
1024
1025
1026
XSR
[ENOSR]
No STREAM resources. Insufficient STREAMS memory resources are available to perform a
STREAMS-related function. This is a temporary condition; it may be recovered from if other
processes release resources.
1027
1028
1029
XSR
[ENOSTR]
Not a STREAM. A STREAM function was attempted on a file descriptor that was not
associated with a STREAMS device.
1030
1031
1032
[ENOSYS]
Function not implemented. An attempt was made to use a function that is not available in
this implementation.
1033
1034
[ENOTCONN]
Socket not connected. The socket is not connected.
1035
1036
1037
[ENOTDIR]
Not a directory. A component of the specified pathname exists, but it is not a directory,
when a directory was expected.
1038
1039
1040
[ENOTEMPTY]
Directory not empty. A directory other than an empty directory was supplied when an
empty directory was expected.
1041
1042
[ENOTSOCK]
Not a socket. The file descriptor does not refer to a socket.
1043
1044
1045
[ENOTSUP]
Not supported. The implementation does not support this feature of the Realtime Option
Group.
1046
1047
1048
[ENOTTY]
Inappropriate I/O control operation. A control function has been attempted for a file or
special file for which the operation is inappropriate.
1049
1050
1051
1052
[ENXIO]
No such device or address. Input or output on a special file refers to a device that does not
exist, or makes a request beyond the capabilities of the device. It may also occur when, for
example, a tape drive is not on-line.
1053
1054
1055
[EOPNOTSUPP]
Operation not supported on socket. The type of socket (address family or protocol) does not
support the requested operation.
1056
1057
1058
[EOVERFLOW]
Value too large to be stored in data type. An operation was attempted which would
generate a value that is outside the range of values that can be represented in the relevant
data type or that are allowed for a given data item.
1059
26
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Error Numbers
1060
1061
1062
[EPERM]
Operation not permitted. An attempt was made to perform an operation limited to
processes with appropriate privileges or to the owner of a file or other resource.
1063
1064
1065
[EPIPE]
Broken pipe. A write was attempted on a socket, pipe, or FIFO for which there is no process
to read the data.
1066
1067
1068
[EPROTO]
Protocol error. Some protocol error occurred. This error is device-specific, but is generally
not related to a hardware failure.
1069
1070
1071
[EPROTONOSUPPORT]
Protocol not supported. The protocol is not supported by the address family, or the protocol
is not supported by the implementation.
1072
1073
[EPROTOTYPE]
Protocol wrong type for socket. The socket type is not supported by the protocol.
1074
1075
1076
[ERANGE]
Result too large or too small. The result of the function is too large (overflow) or too small
(underflow) to be represented in the available space (defined in the ISO C standard).
1077
1078
1079
[EROFS]
Read-only file system. An attempt was made to modify a file or directory on a file system
that is read-only.
1080
1081
[ESPIPE]
Invalid seek. An attempt was made to access the file offset associated with a pipe or FIFO.
1082
1083
1084
[ESRCH]
No such process. No process can be found corresponding to that specified by the given
process ID.
1085
1086
[ESTALE]
Reserved.
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
XSR
[ETIME]
STREAM ioctl ( ) timeout. The timer set for a STREAMS ioctl ( ) call has expired. The cause of
this error is device-specific and could indicate either a hardware or software failure, or a
timeout value that is too short for the specific operation. The status of the ioctl ( ) operation
is unspecified.
[ETIMEDOUT]
Connection timed out. The connection to a remote machine has timed out. If the connection
timed out during execution of the function that reported this error (as opposed to timing
out prior to the function being called), it is unspecified whether the function has completed
some or all of the documented behavior associated with a successful completion of the
function.
1098
or:
1099
1100
Operation timed out. The time limit associated with the operation was exceeded before the
operation completed.
1101
1102
[ETXTBSY]
Text file busy. An attempt was made to execute a pure-procedure program that is currently
open for writing, or an attempt has been made to open for writing a pure-procedure
program that is being executed.
1103
1104
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
27
Error Numbers
General Information
1105
1106
1107
1108
[EWOULDBLOCK]
Operation would block. An operation on a socket marked as non-blocking has encountered
a situation such as no data available that otherwise would have caused the function to
suspend execution.
1109
1110
A conforming implementation may assign the same values for [EWOULDBLOCK] and
[EAGAIN].
[EXDEV]
Improper link. A link to a file on another file system was attempted.
1111
1112
1113
2.3.1
Additional Error Numbers
Additional implementation-defined error numbers may be defined in <errno.h>.
1114
1115
2.4
Signal Concepts
1116
2.4.1
Signal Generation and Delivery
RTS
A signal is said to be ‘‘generated’’ for (or sent to) a process or thread when the event that causes
the signal first occurs. Examples of such events include detection of hardware faults, timer
expiration, signals generated via the sigevent structure and terminal activity, as well as
invocations of the kill ( ) and sigqueue( ) functions. In some circumstances, the same event
generates signals for multiple processes.
1117
1118
1119
1120
1121
RTS
1122
1123
1124
1125
1126
1127
At the time of generation, a determination shall be made whether the signal has been generated
for the process or for a specific thread within the process. Signals which are generated by some
action attributable to a particular thread, such as a hardware fault, shall be generated for the
thread that caused the signal to be generated. Signals that are generated in association with a
process ID or process group ID or an asynchronous event, such as terminal activity, shall be
generated for the process.
1128
1129
1130
1131
Each process has an action to be taken in response to each signal defined by the system (see
Section 2.4.3 (on page 31)). A signal is said to be ‘‘delivered’’ to a process when the appropriate
action for the process and signal is taken. A signal is said to be ‘‘accepted’’ by a process when the
signal is selected and returned by one of the sigwait ( ) functions.
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
During the time between the generation of a signal and its delivery or acceptance, the signal is
said to be ‘‘pending’’. Ordinarily, this interval cannot be detected by an application. However, a
signal can be ‘‘blocked’’ from delivery to a thread. If the action associated with a blocked signal
is anything other than to ignore the signal, and if that signal is generated for the thread, the
signal shall remain pending until it is unblocked, it is accepted when it is selected and returned
by a call to the sigwait ( ) function, or the action associated with it is set to ignore the signal.
Signals generated for the process shall be delivered to exactly one of those threads within the
process which is in a call to a sigwait ( ) function selecting that signal or has not blocked delivery
of the signal. If there are no threads in a call to a sigwait ( ) function selecting that signal, and if all
threads within the process block delivery of the signal, the signal shall remain pending on the
process until a thread calls a sigwait ( ) function selecting that signal, a thread unblocks delivery
of the signal, or the action associated with the signal is set to ignore the signal. If the action
associated with a blocked signal is to ignore the signal and if that signal is generated for the
process, it is unspecified whether the signal is discarded immediately upon generation or
remains pending.
28
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Signal Concepts
1147
1148
1149
1150
1151
Each thread has a ‘‘signal mask’’ that defines the set of signals currently blocked from delivery
to it. The signal mask for a thread shall be initialized from that of its parent or creating thread,
or from the corresponding thread in the parent process if the thread was created as the result of a
call to fork ( ). The pthread_sigmask( ), sigaction ( ), sigprocmask ( ), and sigsuspend( ) functions control
the manipulation of the signal mask.
1152
1153
1154
1155
1156
1157
1158
1159
The determination of which action is taken in response to a signal is made at the time the signal
is delivered, allowing for any changes since the time of generation. This determination is
independent of the means by which the signal was originally generated. If a subsequent
occurrence of a pending signal is generated, it is implementation-defined as to whether the
signal is delivered or accepted more than once in circumstances other than those in which
queuing is required under the Realtime Signals Extension option. The order in which multiple,
simultaneously pending signals outside the range SIGRTMIN to SIGRTMAX are delivered to or
accepted by a process is unspecified.
RTS
1160
1161
1162
1163
1164
1165
When any stop signal (SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU) is generated for a process, any
pending SIGCONT signals for that process shall be discarded. Conversely, when SIGCONT is
generated for a process, all pending stop signals for that process shall be discarded. When
SIGCONT is generated for a process that is stopped, the process shall be continued, even if the
SIGCONT signal is blocked or ignored. If SIGCONT is blocked and not ignored, it shall remain
pending until it is either unblocked or a stop signal is generated for the process.
1166
1167
An implementation shall document any condition not specified by this volume of
IEEE Std 1003.1-2001 under which the implementation generates signals.
1168
2.4.2
Realtime Signal Generation and Delivery
1169
1170
1171
RTS
This section describes extensions to support realtime signal generation and delivery. This
functionality is dependent on support of the Realtime Signals Extension option (and the rest of
this section is not further shaded for this option).
1179
1180
1181
1182
1183
Some signal-generating functions, such as high-resolution timer expiration, asynchronous I/O
completion, interprocess message arrival, and the sigqueue( ) function, support the specification
of an application-defined value, either explicitly as a parameter to the function or in a sigevent
structure parameter. The sigevent structure is defined in <signal.h> and contains at least the
following members:
_____________________________________________________________________
L
L
L
L
Member Type
Member Name
Description
_____________________________________________________________________
L
L
L
L
int
sigev_notify
Notification type.
L
L
L
L
int
sigev_signo
Signal number.
L
L
L
L
sigev_value
Signal value.
L union sigval
L
L
L
L void(*)(unsigned sigval)
L
sigev_notify_function L Notification function. L
L
L
(pthread_attr_t*)
sigev_notify_attributes LL Notification attributes. LL
L
L_____________________________________________________________________
1184
1185
1186
The sigev_notify member specifies the notification mechanism to use when an asynchronous
event occurs. This volume of IEEE Std 1003.1-2001 defines the following values for the
sigev_notify member:
1187
1188
SIGEV_NONE
No asynchronous notification shall be delivered when the event of
interest occurs.
1189
1190
1191
1192
SIGEV_SIGNAL
The signal specified in sigev_signo shall be generated for the process when
the event of interest occurs. If the implementation supports the Realtime
Signals Extension option and if the SA_SIGINFO flag is set for that signal
number, then the signal shall be queued to the process and the value
1172
1173
1174
1175
1176
1177
1178
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
29
Signal Concepts
General Information
specified in sigev_value shall be the si_value component of the generated
signal. If SA_SIGINFO is not set for that signal number, it is unspecified
whether the signal is queued and what value, if any, is sent.
1193
1194
1195
1196
SIGEV_THREAD
1197
An implementation may define additional notification mechanisms.
1198
1199
1200
The sigev_signo member specifies the signal to be generated. The sigev_value member is the
application-defined value to be passed to the signal-catching function at the time of the signal
delivery or to be returned at signal acceptance as the si_value member of the siginfo_t structure.
1201
1204
1205
The sigval union is defined in <signal.h> and contains at least the following members:
_ ___________________________________________________
L Member Type
L
L
Member Name L
Description
_ ___________________________________________________
L
L
L
L
int
sival_int
Integer signal value. L
L
L
L
void*
sival_ptr
Pointer signal value. L
L
L
L_ ___________________________________________________
1206
1207
The sival_int member shall be used when the application-defined value is of type int; the
sival_ptr member shall be used when the application-defined value is a pointer.
1208
1209
1210
1211
1212
1213
When a signal is generated by the sigqueue( ) function or any signal-generating function that
supports the specification of an application-defined value, the signal shall be marked pending
and, if the SA_SIGINFO flag is set for that signal, the signal shall be queued to the process along
with the application-specified signal value. Multiple occurrences of signals so generated are
queued in FIFO order. It is unspecified whether signals so generated are queued when the
SA_SIGINFO flag is not set for that signal.
1214
1215
1216
1217
Signals generated by the kill ( ) function or other events that cause signals to occur, such as
detection of hardware faults, alarm( ) timer expiration, or terminal activity, and for which the
implementation does not support queuing, shall have no effect on signals already queued for the
same signal number.
1218
1219
1220
When multiple unblocked signals, all in the range SIGRTMIN to SIGRTMAX, are pending, the
behavior shall be as if the implementation delivers the pending unblocked signal with the lowest
signal number within that range. No other ordering of signal delivery is specified.
1221
1222
If, when a pending signal is delivered, there are additional signals queued to that signal number,
the signal shall remain pending. Otherwise, the pending indication shall be reset.
1223
1224
1225
Multi-threaded programs can use an alternate event notification mechanism. When a
notification is processed, and the sigev_notify member of the sigevent structure has the value
SIGEV_THREAD, the function sigev_notify_function is called with parameter sigev_value .
1226
1227
1228
1229
1230
1231
The function shall be executed in an environment as if it were the start_routine for a newly
created thread with thread attributes specified by sigev_notify_attributes. If sigev_notify_attributes
is NULL, the behavior shall be as if the thread were created with the detachstate attribute set to
PTHREAD_CREATE_DETACHED. Supplying an attributes structure with a detachstate attribute
of PTHREAD_CREATE_JOINABLE results in undefined behavior. The signal mask of this
thread is implementation-defined.
1202
1203
30
A notification function shall be called to perform notification.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
1232
2.4.3
Signal Concepts
Signal Actions
1233
1234
1235
There are three types of action that can be associated with a signal: SIG_DFL, SIG_IGN, or a
pointer to a function. Initially, all signals shall be set to SIG_DFL or SIG_IGN prior to entry of
the main( ) routine (see the exec functions). The actions prescribed by these values are as follows:
1236
SIG_DFL
1237
1238
1239
1240
Signal-specific default action.
The default actions for the signals defined in this volume of IEEE Std 1003.1-2001
are specified under <signal.h>. If the Realtime Signals Extension option is
supported, the default actions for the realtime signals in the range SIGRTMIN to
SIGRTMAX shall be to terminate the process abnormally.
RTS
1241
1242
1243
1244
1245
1246
1247
1248
1249
If the default action is to stop the process, the execution of that process is
temporarily suspended. When a process stops, a SIGCHLD signal shall be
generated for its parent process, unless the parent process has set the
SA_NOCLDSTOP flag. While a process is stopped, any additional signals that are
sent to the process shall not be delivered until the process is continued, except
SIGKILL which always terminates the receiving process. A process that is a
member of an orphaned process group shall not be allowed to stop in response to
the SIGTSTP, SIGTTIN, or SIGTTOU signals. In cases where delivery of one of
these signals would stop such a process, the signal shall be discarded.
1250
1251
1252
Setting a signal action to SIG_DFL for a signal that is pending, and whose default
action is to ignore the signal (for example, SIGCHLD), shall cause the pending
signal to be discarded, whether or not it is blocked.
1253
1254
1255
1256
1257
1258
1259
When a stopped process is continued, a SIGCHLD signal may be generated for its
parent process, unless the parent process has set the SA_NOCLDSTOP flag.
XSI
SIG_IGN
1260
1261
1262
1263
The default action for SIGCONT is to resume execution at the point where the
process was stopped, after first handling any pending unblocked signals. If the
Realtime Signals Extension option is supported, any queued values pending shall
be discarded and the resources used to queue them shall be released and returned
to the system for other use.
RTS
RTS
RTS
Ignore signal.
Delivery of the signal shall have no effect on the process. The behavior of a process
is undefined after it ignores a SIGFPE, SIGILL, SIGSEGV, or SIGBUS signal that
was not generated by kill ( ),sigqueue( ),or raise( ).
1264
1265
The system shall not allow the action for the signals SIGKILL or SIGSTOP to be set
to SIG_IGN.
1266
1267
Setting a signal action to SIG_IGN for a signal that is pending shall cause the
pending signal to be discarded, whether or not it is blocked.
1268
1269
1270
1271
1272
1273
1274
1275
XSI
If a process sets the action for the SIGCHLD signal to SIG_IGN, the behavior is
unspecified, except as specified below.
If the action for the SIGCHLD signal is set to SIG_IGN, child processes of the
calling processes shall not be transformed into zombie processes when they
terminate. If the calling process subsequently waits for its children, and the process
has no unwaited-for children that were transformed into zombie processes, it shall
block until all of its children terminate, and wait( ), waitid ( ), and waitpid ( ) shall fail
and set errno to [ECHILD].
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
31
Signal Concepts
1276
1277
1278
RTS
General Information
If the Realtime Signals Extension option is supported, any queued values pending
shall be discarded and the resources used to queue them shall be released and
made available to queue other signals.
pointer to a function
Catch signal.
1279
1280
1281
1282
1283
1284
On delivery of the signal, the receiving process is to execute the signal-catching
function at the specified address. After returning from the signal-catching function,
the receiving process shall resume execution at the point at which it was
interrupted.
1285
1286
If the SA_SIGINFO flag for the signal is cleared, the signal-catching function shall
be entered as a C-language function call as follows:
1287
void func(int signo);
1288
1289
XSI|RTS
If the SA_SIGINFO flag for the signal is set, the signal-catching function shall be
entered as a C-language function call as follows:
1290
void func(int signo, siginfo_t *info, void *context);
1291
1292
1293
1296
1297
1298
where func is the specified signal-catching function, signo is the signal number of
the signal being delivered, and info is a pointer to a siginfo_t structure defined in
<signal.h> containing at least the following members:
____________________________________________________
L
Member Type L Member Name L
Description
_L ___________________________________________________
L
L
L
L
int
si_signo
Signal number.
L
L
L
L
int
si_code
Cause of the signal. L
L
L
L
union sigval LL si_value
Signal value.
LL
LL_
LL
___________________________________________________
1299
1300
1301
The si_signo member shall contain the signal number. This shall be the same as the
signo parameter. The si_code member shall contain a code identifying the cause of
the signal. The following values are defined for si_code:
1302
1303
1304
1305
SI_USER
The signal was sent by the kill ( ) function. The implementation
may set si_code to SI_USER if the signal was sent by the raise( ) or
abort( ) functions or any similar functions provided as
implementation extensions.
1294
1295
1306
RTS
SI_QUEUE
The signal was sent by the sigqueue( ) function.
1307
1308
RTS
SI_TIMER
The signal was generated by the expiration of a timer set by
timer_settime( ).
1309
1310
RTS
SI_ASYNCIO
The signal was generated by the completion of an asynchronous
I/O request.
1311
1312
RTS
SI_MESGQ
The signal was generated by the arrival of a message on an
empty message queue.
If the signal was not generated by one of the functions or events listed above, the
si_code shall be set to an implementation-defined value that is not equal to any of
the values defined above.
1313
1314
1315
1316
1317
1318
1319
RTS
If the Realtime Signals Extension is supported, and si_code is one of SI_QUEUE,
SI_TIMER, SI_ASYNCIO, or SI_MESGQ, then si_value shall contain the
application-specified signal value. Otherwise, the contents of si_value are
undefined.
32
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
1320
1321
1322
XSI
RTS
Signal Concepts
The behavior of a process is undefined after it returns normally from a signalcatching function for a SIGBUS, SIGFPE, SIGILL, or SIGSEGV signal that was not
generated by kill ( ),sigqueue( ),or raise( ).
1323
The system shall not allow a process to catch the signals SIGKILL and SIGSTOP.
1324
1325
1326
If a process establishes a signal-catching function for the SIGCHLD signal while it
has a terminated child process for which it has not waited, it is unspecified
whether a SIGCHLD signal is generated to indicate that child process.
1327
1328
1329
1330
When signal-catching functions are invoked asynchronously with process
execution, the behavior of some of the functions defined by this volume of
IEEE Std 1003.1-2001 is unspecified if they are called from a signal-catching
function.
1331
1332
1333
The following table defines a set of functions that shall be either reentrant or noninterruptible by signals and shall be async-signal-safe. Therefore applications may
invoke them, without restriction, from signal-catching functions:
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
_Exit( )
_exit( )
accept( )
access( )
aio_error ( )
aio_return( )
aio_suspend( )
alarm( )
bind( )
cfgetispeed( )
cfgetospeed( )
cfsetispeed( )
cfsetospeed( )
chdir( )
chmod( )
chown( )
clock_gettime ( )
close( )
connect( )
creat( )
dup( )
dup2( )
execle( )
execve( )
fchmod( )
fchown( )
fcntl( )
fdatasync ( )
fork ( )
1363
1364
1365
1366
1367
All functions not in the above table are considered to be unsafe with respect to
signals. In the presence of signals, all functions defined by this volume of
IEEE Std 1003.1-2001 shall behave as defined when called from or interrupted by a
signal-catching function, with a single exception: when a signal interrupts an
unsafe function and the signal-catching function calls an unsafe function, the
fpathconf ( )
fstat( )
fsync( )
ftruncate( )
getegid( )
geteuid( )
getgid( )
getgroups( )
getpeername( )
getpgrp( )
getpid( )
getppid( )
getsockname( )
getsockopt ( )
getuid( )
kill ( )
link ( )
listen( )
lseek( )
lstat( )
mkdir( )
mkfifo ( )
open( )
pathconf ( )
pause( )
pipe( )
poll ( )
posix_trace_event( )
pselect( )
raise( )
read( )
readlink ( )
recv( )
recvfrom( )
recvmsg( )
rename( )
rmdir( )
select( )
sem_post( )
send( )
sendmsg( )
sendto( )
setgid( )
setpgid( )
setsid( )
setsockopt ( )
setuid( )
shutdown( )
sigaction ( )
sigaddset( )
sigdelset( )
sigemptyset( )
sigfillset ( )
sigismember( )
sleep( )
signal( )
sigpause( )
sigpending( )
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
sigprocmask ( )
sigqueue( )
sigset( )
sigsuspend( )
socket( )
socketpair ( )
stat( )
symlink( )
sysconf( )
tcdrain( )
tcflow ( )
tcflush( )
tcgetattr( )
tcgetpgrp( )
tcsendbreak( )
tcsetattr( )
tcsetpgrp( )
time( )
timer_getoverrun( )
timer_gettime( )
timer_settime( )
times( )
umask( )
uname( )
unlink( )
utime( )
wait( )
waitpid ( )
write( )
33
Signal Concepts
behavior is undefined.
1368
When a signal is delivered to a thread, if the action of that signal specifies termination, stop, or
continue, the entire process shall be terminated, stopped, or continued, respectively.
1369
1370
1371
2.4.4
Signal Effects on Other Functions
Signals affect the behavior of certain functions defined by this volume of IEEE Std 1003.1-2001 if
delivered to a process while it is executing such a function. If the action of the signal is to
terminate the process, the process shall be terminated and the function shall not return. If the
action of the signal is to stop the process, the process shall stop until continued or terminated.
Generation of a SIGCONT signal for the process shall cause the process to be continued, and the
original function shall continue at the point the process was stopped. If the action of the signal is
to invoke a signal-catching function, the signal-catching function shall be invoked; in this case
the original function is said to be ‘‘interrupted’’ by the signal. If the signal-catching function
executes a return statement, the behavior of the interrupted function shall be as described
individually for that function, except as noted for unsafe functions. Signals that are ignored shall
not affect the behavior of any function; signals that are blocked shall not affect the behavior of
any function until they are unblocked and then delivered, except as specified for the sigpending( )
and sigwait ( ) functions.
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
General Information
2.5
Standard I/O Streams
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
A stream is associated with an external file (which may be a physical device) by ‘‘opening’’ a file,
which may involve ‘‘creating’’ a new file. Creating an existing file causes its former contents to
be discarded if necessary. If a file can support positioning requests (such as a disk file, as
opposed to a terminal), then a ‘‘file position indicator’’ associated with the stream is positioned
at the start (byte number 0) of the file, unless the file is opened with append mode, in which case
it is implementation-defined whether the file position indicator is initially positioned at the
beginning or end of the file. The file position indicator is maintained by subsequent reads,
writes, and positioning requests, to facilitate an orderly progression through the file. All input
takes place as if bytes were read by successive calls to fgetc( ); all output takes place as if bytes
were written by successive calls to fputc( ).
1396
1397
1398
1399
1400
1401
1402
1403
When a stream is ‘‘unbuffered’’, bytes are intended to appear from the source or at the
destination as soon as possible; otherwise, bytes may be accumulated and transmitted as a block.
When a stream is ‘‘fully buffered’’, bytes are intended to be transmitted as a block when a buffer
is filled. When a stream is ‘‘line buffered’’, bytes are intended to be transmitted as a block when a
newline byte is encountered. Furthermore, bytes are intended to be transmitted as a block when
a buffer is filled, when input is requested on an unbuffered stream, or when input is requested
on a line-buffered stream that requires the transmission of bytes. Support for these
characteristics is implementation-defined, and may be affected via setbuf( ) and setvbuf( ).
1404
1405
1406
1407
A file may be disassociated from a controlling stream by ‘‘closing’’ the file. Output streams are
flushed (any unwritten buffer contents are transmitted) before the stream is disassociated from
the file. The value of a pointer to a FILE object is unspecified after the associated file is closed
(including the standard streams).
1408
1409
1410
1411
1412
A file may be subsequently reopened, by the same or another program execution, and its
contents reclaimed or modified (if it can be repositioned at its start). If the main( ) function
returns to its original caller, or if the exit( ) function is called, all open files are closed (hence all
output streams are flushed) before program termination. Other paths to program termination,
such as calling abort( ), need not close all files properly.
34
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Standard I/O Streams
1413
1414
The address of the FILE object used to control a stream may be significant; a copy of a FILE
object need not necessarily serve in place of the original.
1415
1416
1417
1418
1419
At program start-up, three streams are predefined and need not be opened explicitly: standard
input (for reading conventional input), standard output (for writing conventional output), and
standard error (for writing diagnostic output). When opened, the standard error stream is not
fully buffered; the standard input and standard output streams are fully buffered if and only if
the stream can be determined not to refer to an interactive device.
1420
2.5.1
Interaction of File Descriptors and Standard I/O Streams
1421
1422
1423
CX
This section describes the interaction of file descriptors and standard I/O streams. This
functionality is an extension to the ISO C standard (and the rest of this section is not further CX
shaded).
1424
1425
1426
1427
An open file description may be accessed through a file descriptor, which is created using
functions such as open( ) or pipe( ), or through a stream, which is created using functions such as
fopen( ) or popen( ). Either a file descriptor or a stream is called a ‘‘handle’’ on the open file
description to which it refers; an open file description may have several handles.
1428
1429
1430
Handles can be created or destroyed by explicit user action, without affecting the underlying
open file description. Some of the ways to create them include fcntl( ), dup( ), fdopen( ), fileno ( ),
and fork ( ). They can be destroyed by at least fclose( ), close( ), and the exec functions.
1431
1432
1433
1434
1435
1436
A file descriptor that is never used in an operation that could affect the file offset (for example,
read( ), write( ), or lseek( )) is not considered a handle for this discussion, but could give rise to one
(for example, as a consequence of fdopen( ), dup( ), or fork ( )). This exception does not include the
file descriptor underlying a stream, whether created with fopen( ) or fdopen( ), so long as it is not
used directly by the application to affect the file offset. The read( ) and write( ) functions
implicitly affect the file offset; lseek( ) explicitly affects it.
1437
1438
1439
1440
The result of function calls involving any one handle (the ‘‘active handle’’) is defined elsewhere
in this volume of IEEE Std 1003.1-2001, but if two or more handles are used, and any one of them
is a stream, the application shall ensure that their actions are coordinated as described below. If
this is not done, the result is undefined.
1441
1442
1443
1444
1445
A handle which is a stream is considered to be closed when either an fclose( ) or freopen( ) is
executed on it (the result of freopen( ) is a new stream, which cannot be a handle on the same
open file description as its previous value), or when the process owning that stream terminates
with exit( ), abort( ), or due to a signal. A file descriptor is closed by close( ), _exit( ), or the exec
functions when FD_CLOEXEC is set on that file descriptor.
1446
1447
1448
1449
1450
1451
For a handle to become the active handle, the application shall ensure that the actions below are
performed between the last use of the handle (the current active handle) and the first use of the
second handle (the future active handle). The second handle then becomes the active handle. All
activity by the application affecting the file offset on the first handle shall be suspended until it
again becomes the active file handle. (If a stream function has as an underlying function one that
affects the file offset, the stream function shall be considered to affect the file offset.)
1452
The handles need not be in the same process for these rules to apply.
1453
1454
1455
1456
1457
Note that after a fork ( ), two handles exist where one existed before. The application shall ensure
that, if both handles can ever be accessed, they are both in a state where the other could become
the active handle first. The application shall prepare for a fork ( ) exactly as if it were a change of
active handle. (If the only action performed by one of the processes is one of the exec functions or
_exit( ) (not exit( )), the handle is never accessed in that process.)
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
35
Standard I/O Streams
General Information
For the first handle, the first applicable condition below applies. After the actions required
below are taken, if the handle is still open, the application can close it.
1458
1459
1460
•
If it is a file descriptor, no action is required.
1461
1462
•
If the only further action to be performed on any handle to this open file descriptor is to close
it, no action need be taken.
1463
•
If it is a stream which is unbuffered, no action need be taken.
1464
1465
•
If it is a stream which is line buffered, and the last byte written to the stream was a
<newline> (that is, as if a:
putc(’\n’)
1466
was the most recent operation on that stream), no action need be taken.
1467
1468
1469
•
If it is a stream which is open for writing or appending (but not also open for reading), the
application shall either perform an fflush( ), or the stream shall be closed.
1470
1471
•
If the stream is open for reading and it is at the end of the file (feof( ) is true), no action need
be taken.
1472
1473
1474
•
If the stream is open with a mode that allows reading and the underlying open file
description refers to a device that is capable of seeking, the application shall either perform
an fflush( ), or the stream shall be closed.
1475
Otherwise, the result is undefined.
1476
For the second handle:
•
1477
1478
1479
If any previous active handle has been used by a function that explicitly changed the file
offset, except as required above for the first handle, the application shall perform an lseek( ) or
fseek( ) (as appropriate to the type of handle) to an appropriate location.
1480
1481
1482
If the active handle ceases to be accessible before the requirements on the first handle, above,
have been met, the state of the open file description becomes undefined. This might occur during
functions such as a fork ( ) or _exit( ).
1483
1484
The exec functions make inaccessible all streams that are open at the time they are called,
independent of which streams or file descriptors may be available to the new process image.
1485
1486
1487
1488
1489
When these rules are followed, regardless of the sequence of handles used, implementations
shall ensure that an application, even one consisting of several processes, shall yield correct
results: no data shall be lost or duplicated when writing, and all data shall be written in order,
except as requested by seeks. It is implementation-defined whether, and under what conditions,
all input is seen exactly once.
1490
If the rules above are not followed, the result is unspecified.
1491
1492
1493
1494
Each function that operates on a stream is said to have zero or more ‘‘underlying functions’’.
This means that the stream function shares certain traits with the underlying functions, but does
not require that there be any relation between the implementations of the stream function and its
underlying functions.
36
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
1495
2.5.2
Standard I/O Streams
Stream Orientation and Encoding Rules
1496
1497
1498
1499
1500
1501
1502
For conformance to the ISO/IEC 9899: 1999 standard, the definition of a stream includes an
‘‘orientation’’. After a stream is associated with an external file, but before any operations are
performed on it, the stream is without orientation. Once a wide-character input/output function
has been applied to a stream without orientation, the stream shall become ‘‘wide-oriented’’.
Similarly, once a byte input/output function has been applied to a stream without orientation,
the stream shall become ‘‘byte-oriented’’. Only a call to the freopen( ) function or the fwide( )
function can otherwise alter the orientation of a stream.
1503
1504
A successful call to freopen( ) shall remove any orientation. The three predefined streams standard
input, standard output, and standard error shall be unoriented at program start-up.
1505
1506
1507
1508
Byte input/output functions cannot be applied to a wide-oriented stream, and wide-character
input/output functions cannot be applied to a byte-oriented stream. The remaining stream
operations shall not affect and shall not be affected by a stream’s orientation, except for the
following additional restriction:
•
1509
1510
1511
For wide-oriented streams, after a successful call to a file-positioning function that leaves the
file position indicator prior to the end-of-file, a wide-character output function can overwrite
a partial character; any file contents beyond the byte(s) written are henceforth undefined.
1512
1513
1514
1515
1516
Each wide-oriented stream has an associated mbstate_t object that stores the current parse state
of the stream. A successful call to fgetpos( ) shall store a representation of the value of this
mbstate_t object as part of the value of the fpos_t object. A later successful call to fsetpos( ) using
the same stored fpos_t value shall restore the value of the associated mbstate_t object as well as
the position within the controlled stream.
1517
1518
1519
1520
1521
1522
Implementations that support multiple encoding rules associate an encoding rule with the
stream. The encoding rule shall be determined by the setting of the LC_CTYPE category in the
current locale at the time when the stream becomes wide-oriented. As with the stream’s
orientation, the encoding rule associated with a stream cannot be changed once it has been set,
except by a successful call to freopen( ) which clears the encoding rule and resets the orientation
to unoriented.
1523
1524
1525
Although wide-oriented streams are conceptually sequences of wide characters, the external file
associated with a wide-oriented stream is a sequence of (possibly multi-byte) characters
generalized as follows:
1526
1527
•
Multi-byte encodings within files may contain embedded null bytes (unlike multi-byte
encodings valid for use internal to the program).
1528
•
A file need not begin nor end in the initial shift state.
1529
1530
Moreover, the encodings used for characters may differ among files. Both the nature and choice
of such encodings are implementation-defined.
1531
1532
1533
1534
1535
The wide-character input functions read characters from the stream and convert them to wide
characters as if they were read by successive calls to the fgetwc( ) function. Each conversion shall
occur as if by a call to the mbrtowc( ) function, with the conversion state described by the stream’s
own mbstate_t object, except the encoding rule associated with the stream is used instead of the
encoding rule implied by the LC_CTYPE category of the current locale.
CX
1536
1537
1538
1539
1540
CX
The wide-character output functions convert wide characters to (possibly multi-byte) characters
and write them to the stream as if they were written by successive calls to the fputwc( ) function.
Each conversion shall occur as if by a call to the wcrtomb( ) function, with the conversion state
described by the stream’s own mbstate_t object, except the encoding rule associated with the
stream is used instead of the encoding rule implied by the LC_CTYPE category of the current
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
37
Standard I/O Streams
General Information
1541
locale.
1542
1543
1544
1545
1546
An ‘‘encoding error’’ shall occur if the character sequence presented to the underlying mbrtowc( )
function does not form a valid (generalized) character, or if the code value passed to the
underlying wcrtomb( ) function does not correspond to a valid (generalized) character. The
wide-character input/output functions and the byte input/output functions store the value of
the macro [EILSEQ] in errno if and only if an encoding error occurs.
1547
1548
1549
1550
2.6
STREAMS
XSR
STREAMS functionality is provided on implementations supporting the XSI STREAMS Option
Group. This functionality is dependent on support of the XSI STREAMS option (and the rest of
this section is not further shaded for this option).
1551
1552
1553
1554
1555
STREAMS provides a uniform mechanism for implementing networking services and other
character-based I/O. The STREAMS function provides direct access to protocol modules.
STREAMS modules are unspecified objects. Access to STREAMS modules is provided by
interfaces in IEEE Std 1003.1-2001. Creation of STREAMS modules is outside the scope of
IEEE Std 1003.1-2001.
1556
1557
1558
1559
1560
1561
A STREAM is typically a full-duplex connection between a process and an open device or
pseudo-device. However, since pipes may be STREAMS-based, a STREAM can be a full-duplex
connection between two processes. The STREAM itself exists entirely within the implementation
and provides a general character I/O function for processes. It optionally includes one or more
intermediate processing modules that are interposed between the process end of the STREAM
(STREAM head) and a device driver at the end of the STREAM (STREAM end).
1562
STREAMS I/O is based on messages. There are three types of message:
1563
•
Data messages containing actual data for input or output
1564
1565
•
Control data containing instructions for the STREAMS modules and underlying
implementation
1566
•
Other messages, which include file descriptors
1567
1568
1569
1570
1571
1572
1573
The interface between the STREAM and the rest of the implementation is provided by a set of
functions at the STREAM head. When a process calls write( ), writev( ), putmsg( ), putpmsg( ), or
ioctl ( ), messages are sent down the STREAM, and read( ), readv( ), getmsg( ), or getpmsg( ) accepts
data from the STREAM and passes it to a process. Data intended for the device at the
downstream end of the STREAM is packaged into messages and sent downstream, while data
and signals from the device are composed into messages by the device driver and sent upstream
to the STREAM head.
1574
1575
1576
1577
1578
1579
When a STREAMS-based device is opened, a STREAM shall be created that contains the
STREAM head and the STREAM end (driver). If pipes are STREAMS-based in an
implementation, when a pipe is created, two STREAMS shall be created, each containing a
STREAM head. Other modules are added to the STREAM using ioctl ( ). New modules are
‘‘pushed’’ onto the STREAM one at a time in last-in, first-out (LIFO) style, as though the
STREAM was a push-down stack.
38
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
STREAMS
1580
Priority
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
Message types are classified according to their queuing priority and may be normal (nonpriority), priority , or high-priority messages. A message belongs to a particular priority band that
determines its ordering when placed on a queue. Normal messages have a priority band of 0 and
shall always be placed at the end of the queue following all other messages in the queue. Highpriority messages are always placed at the head of a queue, but shall be discarded if there is
already a high-priority message in the queue. Their priority band shall be ignored; they are
high-priority by virtue of their type. Priority messages have a priority band greater than 0.
Priority messages are always placed after any messages of the same or higher priority. Highpriority and priority messages are used to send control and data information outside the normal
flow of control. By convention, high-priority messages shall not be affected by flow control.
Normal and priority messages have separate flow controls.
1592
Message Parts
1593
1594
1595
1596
1597
1598
1599
A process may access STREAMS messages that contain a data part, control part, or both. The
data part is that information which is transmitted over the communication medium and the
control information is used by the local STREAMS modules. The other types of messages are
used between modules and are not accessible to processes. Messages containing only a data part
are accessible via putmsg( ), putpmsg( ), getmsg( ), getpmsg( ), read( ), readv( ), write( ), or writev( ).
Messages containing a control part with or without a data part are accessible via calls to
putmsg( ), putpmsg( ), getmsg( ), or getpmsg( ).
1600
2.6.1
Accessing STREAMS
1601
1602
1603
A process accesses STREAMS-based files using the standard functions close( ), ioctl ( ), getmsg( ),
getpmsg( ), open( ), pipe( ), poll ( ), putmsg( ), putpmsg( ), read( ), or write( ). Refer to the applicable
function definitions for general properties and errors.
1604
1605
1606
Calls to ioctl ( ) shall perform control functions on the STREAM associated with the file descriptor
fildes. The control functions may be performed by the STREAM head, a STREAMS module, or
the STREAMS driver for the STREAM.
1607
1608
1609
1610
1611
STREAMS modules and drivers can detect errors, sending an error message to the STREAM
head, thus causing subsequent functions to fail and set errno to the value specified in the
message. In addition, STREAMS modules and drivers can elect to fail a particular ioctl ( ) request
alone by sending a negative acknowledgement message to the STREAM head. This shall cause
just the pending ioctl ( ) request to fail and set errno to the value specified in the message.
1612
1613
1614
1615
1616
1617
1618
2.7
XSI Interprocess Communication
XSI
This section describes extensions to support interprocess communication. This functionality is
dependent on support of the XSI extension (and the rest of this section is not further shaded for
this option).
The following message passing, semaphore, and shared memory services form an XSI
interprocess communication facility. Certain aspects of their operation are common, and are
defined as follows.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
39
XSI Interprocess Communication
________________________________
L
IPC Functions
________________________________
L
L
msgctl( )
semctl( )
shmctl( ) L
L
msgget( )
semget( )
shmdt( ) L
L
semop( )
shmget( ) L
L msgrcv( )
L msgsnd( )
L
shmat(
)
________________________________
L
L
1619
1620
L
1621
1622
1623
1624
Another interprocess communication facility is provided by functions in the Realtime Option
Group; see Section 2.8 (on page 41).
1625
1626
1627
General Information
2.7.1
IPC General Description
1628
1629
1630
1631
Each individual shared memory segment, message queue, and semaphore set shall be identified
by a unique positive integer, called, respectively, a shared memory identifier, shmid, a
semaphore identifier, semid, and a message queue identifier, msqid. The identifiers shall be
returned by calls to shmget( ), semget( ), and msgget( ), respectively.
1632
1633
1634
Associated with each identifier is a data structure which contains data related to the operations
which may be or may have been performed; see the Base Definitions volume of
IEEE Std 1003.1-2001, <sys/shm.h>, <sys/sem.h>, and <sys/msg.h> for their descriptions.
1635
1636
1637
1638
1639
Each of the data structures contains both ownership information and an ipc_perm structure (see
the Base Definitions volume of IEEE Std 1003.1-2001, <sys/ipc.h>) which are used in conjunction
to determine whether or not read/write (read/alter for semaphores) permissions should be
granted to processes using the IPC facilities. The mode member of the ipc_perm structure acts as
a bit field which determines the permissions.
1640
1643
1644
1645
1646
1647
1648
The values of the bits are given below in octal notation.
_______________________
L
L
Bit L
Meaning
_______________________
L
L
L
0400 L Read by user.
L
L
0200 L Write by user. L
L
Read by group. L
L 0040
L
L
L 0020
Write by group. L
L
L
0004
Read by others. L
L
L
L
0002 L Write by others. L
L_______________________
1649
1650
1651
The name of the ipc_perm structure is shm_perm, sem_perm, or msg_perm, depending on which
service is being used. In each case, read and write/alter permissions shall be granted to a process
if one or more of the following are true ("xxx" is replaced by shm, sem, or msg, as appropriate):
1641
1642
1652
•
The process has appropriate privileges.
1653
1654
1655
•
The effective user ID of the process matches xxx_perm.cuid or xxx_perm.uid in the data
structure associated with the IPC identifier, and the appropriate bit of the user field in
xxx_perm.mode is set.
1656
1657
1658
1659
•
The effective user ID of the process does not match xxx_perm.cuid or xxx_perm.uid but the
effective group ID of the process matches xxx_perm.cgid or xxx_perm.gid in the data structure
associated with the IPC identifier, and the appropriate bit of the group field in xxx_perm.mode
is set.
1660
1661
1662
1663
•
The effective user ID of the process does not match xxx_perm.cuid or xxx_perm.uid and the
effective group ID of the process does not match xxx_perm.cgid or xxx_perm.gid in the data
structure associated with the IPC identifier, but the appropriate bit of the other field in
xxx_perm.mode is set.
40
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Otherwise, the permission shall be denied.
1664
1665
XSI Interprocess Communication
2.8
Realtime
1666
1667
1668
This section defines functions to support the source portability of applications with realtime
requirements. The presence of many of these functions is dependent on support for
implementation options described in the text.
1669
1670
1671
The specific functional areas included in this section and their scope include the following. Full
definitions of these terms can be found in the Base Definitions volume of IEEE Std 1003.1-2001,
Chapter 3, Definitions.
1672
•
Semaphores
1673
•
Process Memory Locking
1674
•
Memory Mapped Files and Shared Memory Objects
1675
•
Priority Scheduling
1676
•
Realtime Signal Extension
1677
•
Timers
1678
•
Interprocess Communication
1679
•
Synchronized Input and Output
1680
•
Asynchronous Input and Output
All the realtime functions defined in this volume of IEEE Std 1003.1-2001 are portable, although
some of the numeric parameters used by an implementation may have hardware dependencies.
1681
1682
1683
2.8.1
Realtime Signals
1684
1685
RTS
Realtime signal generation and delivery is dependent on support for the Realtime Signals
Extension option.
See Section 2.4.2 (on page 29).
1686
1687
2.8.2
Asynchronous I/O
1688
1689
AIO
The functionality described in this section is dependent on support of the Asynchronous Input
and Output option (and the rest of this section is not further shaded for this option).
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
An asynchronous I/O control block structure aiocb is used in many asynchronous I/O
functions. It is defined in the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h> and has
at least the following members:
___________________________________________________________
L
L
Member Type L Member Name L
Description
___________________________________________________________
L
L
L
L
int
aio_fildes
File descriptor.
L
L
L
L
off_t
aio_offset
File offset.
L
L
L
L
aio_buf
Location of buffer.
L volatile void*
L
L
L
L size_t
L
L
L
aio_nbytes
Length of transfer.
L
L
L
L
int
aio_reqprio
Request priority offset.
L
L
L
L
struct sigevent L aio_sigevent
Signal number and value. L
L
L
int
aio_lio_opcode
Operation to be performed. L
L
___________________________________________________________
L
L
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
41
Realtime
General Information
1701
The aio_fildes element is the file descriptor on which the asynchronous operation is performed.
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
If O_APPEND is not set for the file descriptor aio_fildes and if aio_fildes is associated with a
device that is capable of seeking, then the requested operation takes place at the absolute
position in the file as given by aio_offset , as if lseek( ) were called immediately prior to the
operation with an offset argument equal to aio_offset and a whence argument equal to SEEK_SET.
If O_APPEND is set for the file descriptor, or if aio_fildes is associated with a device that is
incapable of seeking, write operations append to the file in the same order as the calls were
made, with the following exception: under implementation-defined circumstances, such as
operation on a multi-processor or when requests of differing priorities are submitted at the same
time, the ordering restriction may be relaxed. Since there is no way for a strictly conforming
application to determine whether this relaxation applies, all strictly conforming applications
which rely on ordering of output shall be written in such a way that they will operate correctly if
the relaxation applies. After a successful call to enqueue an asynchronous I/O operation, the
value of the file offset for the file is unspecified. The aio_nbytes and aio_buf elements are the same
as the nbyte and buf arguments defined by read( ) and write( ), respectively.
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
If _POSIX_PRIORITIZED_IO and _POSIX_PRIORITY_SCHEDULING are defined, then
asynchronous I/O is queued in priority order, with the priority of each asynchronous operation
based on the current scheduling priority of the calling process. The aio_reqprio member can be
used to lower (but not raise) the asynchronous I/O operation priority and is within the range
zero through {AIO_PRIO_DELTA_MAX}, inclusive. Unless both _POSIX_PRIORITIZED_IO and
_POSIX_PRIORITY_SCHEDULING are defined, the order of processing asynchronous I/O
requests
is
unspecified.
When
both
_POSIX_PRIORITIZED_IO
and
_POSIX_PRIORITY_SCHEDULING are defined, the order of processing of requests submitted
by processes whose schedulers are not SCHED_FIFO, SCHED_RR, or SCHED_SPORADIC is
unspecified. The priority of an asynchronous request is computed as (process scheduling
priority) minus aio_reqprio . The priority assigned to each asynchronous I/O request is an
indication of the desired order of execution of the request relative to other asynchronous I/O
requests for this file. If _POSIX_PRIORITIZED_IO is defined, requests issued with the same
priority to a character special file are processed by the underlying device in FIFO order; the order
of processing of requests of the same priority issued to files that are not character special files is
unspecified. Numerically higher priority values indicate requests of higher priority. The value of
aio_reqprio has no effect on process scheduling priority. When prioritized asynchronous I/O
requests to the same file are blocked waiting for a resource required for that I/O operation, the
higher-priority I/O requests shall be granted the resource before lower-priority I/O requests are
granted the resource. The relative priority of asynchronous I/O and synchronous I/O is
implementation-defined. If _POSIX_PRIORITIZED_IO is defined, the implementation shall
define for which files I/O prioritization is supported.
1738
1739
1740
1741
The aio_sigevent determines how the calling process shall be notified upon I/O completion, as
specified in Section 2.4.1 (on page 28). If aio_sigevent.sigev_notify is SIGEV_NONE, then no signal
shall be posted upon I/O completion, but the error status for the operation and the return status
for the operation shall be set appropriately.
1742
1743
1744
1745
The aio_lio_opcode field is used only by the lio_listio ( ) call. The lio_listio ( ) call allows multiple
asynchronous I/O operations to be submitted at a single time. The function takes as an
argument an array of pointers to aiocb structures. Each aiocb structure indicates the operation to
be performed (read or write) via the aio_lio_opcode field.
1746
1747
The address of the aiocb structure is used as a handle for retrieving the error status and return
status of the asynchronous operation while it is in progress.
1748
1749
The aiocb structure and the data buffers associated with the asynchronous I/O operation are
being used by the system for asynchronous I/O while, and only while, the error status of the
42
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Realtime
1750
1751
asynchronous operation is equal to [EINPROGRESS]. Applications shall not modify the aiocb
structure while the structure is being used by the system for asynchronous I/O.
1752
1753
1754
1755
1756
The return status of the asynchronous operation is the number of bytes transferred by the I/O
operation. If the error status is set to indicate an error completion, then the return status is set to
the return value that the corresponding read( ), write( ), or fsync( ) call would have returned.
When the error status is not equal to [EINPROGRESS], the return status shall reflect the return
status of the corresponding synchronous operation.
1757
2.8.3
Memory Management
1758
2.8.3.1
Memory Locking
1759
1760
ML
The functionality described in this section is dependent on support of the Process Memory
Locking option (and the rest of this section is not further shaded for this option).
1761
1762
1763
1764
Range memory locking operations are defined in terms of pages. Implementations may restrict
the size and alignment of range lockings to be on page-size boundaries. The page size, in bytes,
is the value of the configurable system variable {PAGESIZE}. If an implementation has no
restrictions on size or alignment, it may specify a 1-byte page size.
1765
1766
1767
1768
1769
1770
Memory locking guarantees the residence of portions of the address space. It is
implementation-defined whether locking memory guarantees fixed translation between virtual
addresses (as seen by the process) and physical addresses. Per-process memory locks are not
inherited across a fork ( ), and all memory locks owned by a process are unlocked upon exec or
process termination. Unmapping of an address range removes any memory locks established on
that address range by this process.
1771
2.8.3.2
Memory Mapped Files
1772
1773
MF
The functionality described in this section is dependent on support of the Memory Mapped Files
option (and the rest of this section is not further shaded for this option).
1774
1775
1776
1777
Range memory mapping operations are defined in terms of pages. Implementations may
restrict the size and alignment of range mappings to be on page-size boundaries. The page size,
in bytes, is the value of the configurable system variable {PAGESIZE}. If an implementation has
no restrictions on size or alignment, it may specify a 1-byte page size.
1778
1779
1780
1781
1782
1783
Memory mapped files provide a mechanism that allows a process to access files by directly
incorporating file data into its address space. Once a file is mapped into a process address space,
the data can be manipulated as memory. If more than one process maps a file, its contents are
shared among them. If the mappings allow shared write access, then data written into the
memory object through the address space of one process appears in the address spaces of all
processes that similarly map the same portion of the memory object.
1784
1785
1786
SHM
Shared memory objects are named regions of storage that may be independent of the file system
and can be mapped into the address space of one or more processes to allow them to share the
associated memory.
1787
1788
1789
1790
1791
SHM
An unlink( ) of a file or shm_unlink( ) of a shared memory object, while causing the removal of the
name, does not unmap any mappings established for the object. Once the name has been
removed, the contents of the memory object are preserved as long as it is referenced. The
memory object remains referenced as long as a process has the memory object open or has some
area of the memory object mapped.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
43
Realtime
General Information
1792
2.8.3.3
Memory Protection
1793
1794
1795
MPR MF
The functionality described in this section is dependent on support of the Memory Protection
and Memory Mapped Files option (and the rest of this section is not further shaded for these
options).
When an object is mapped, various application accesses to the mapped region may result in
signals. In this context, SIGBUS is used to indicate an error using the mapped object, and
SIGSEGV is used to indicate a protection violation or misuse of an address:
1796
1797
1798
1799
•
A mapping may be restricted to disallow some types of access.
1800
1801
•
Write attempts to memory that was mapped without write access, or any access to memory
mapped PROT_NONE, shall result in a SIGSEGV signal.
1802
•
References to unmapped addresses shall result in a SIGSEGV signal.
1803
1804
•
Reference to whole pages within the mapping, but beyond the current length of the object,
shall result in a SIGBUS signal.
1805
1806
•
The size of the object is unaffected by access beyond the end of the object (even if a SIGBUS is
not generated).
1807
2.8.3.4
Typed Memory Objects
1808
1809
TYM
The functionality described in this section is dependent on support of the Typed Memory
Objects option (and the rest of this section is not further shaded for this option).
Implementations may support the Typed Memory Objects option without supporting the
Memory Mapped Files option or the Shared Memory Objects option. Typed memory objects are
implementation-configurable named storage pools accessible from one or more processors in a
system, each via one or more ports, such as backplane buses, LANs, I/O channels, and so on.
Each valid combination of a storage pool and a port is identified through a name that is defined
at system configuration time, in an implementation-defined manner; the name may be
independent of the file system. Using this name, a typed memory object can be opened and
mapped into process address space. For a given storage pool and port, it is necessary to support
both dynamic allocation from the pool as well as mapping at an application-supplied offset
within the pool; when dynamic allocation has been performed, subsequent deallocation must be
supported. Lastly, accessing typed memory objects from different ports requires a method for
obtaining the offset and length of contiguous storage of a region of typed memory (dynamically
allocated or not); this allows typed memory to be shared among processes and/or processors
while being accessed from the desired port.
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
2.8.4
Process Scheduling
1825
1826
PS
The functionality described in this section is dependent on support of the Process Scheduling
option (and the rest of this section is not further shaded for this option).
1827
Scheduling Policies
1828
1829
1830
1831
1832
1833
1834
The scheduling semantics described in this volume of IEEE Std 1003.1-2001 are defined in terms
of a conceptual model that contains a set of thread lists. No implementation structures are
necessarily implied by the use of this conceptual model. It is assumed that no time elapses
during operations described using this model, and therefore no simultaneous operations are
possible. This model discusses only processor scheduling for runnable threads, but it should be
noted that greatly enhanced predictability of realtime applications results if the sequencing of
other resources takes processor scheduling policy into account.
44
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Realtime
1835
1836
1837
1838
1839
There is, conceptually, one thread list for each priority. A runnable thread will be on the thread
list for that thread’s priority. Multiple scheduling policies shall be provided. Each non-empty
thread list is ordered, contains a head as one end of its order, and a tail as the other. The purpose
of a scheduling policy is to define the allowable operations on this set of lists (for example,
moving threads between and within lists).
1840
1841
1842
Each process shall be controlled by an associated scheduling policy and priority. These
parameters may be specified by explicit application execution of the sched_setscheduler( ) or
sched_setparam( ) functions.
1843
1844
1845
Each thread shall be controlled by an associated scheduling policy and priority. These
parameters may be specified by explicit application execution of the pthread_setschedparam( )
function.
1846
1847
1848
Associated with each policy is a priority range. Each policy definition shall specify the minimum
priority range for that policy. The priority ranges for each policy may but need not overlap the
priority ranges of other policies.
1849
1850
1851
A conforming implementation shall select the thread that is defined as being at the head of the
highest priority non-empty thread list to become a running thread, regardless of its associated
policy. This thread is then removed from its thread list.
1852
1853
1854
Four scheduling policies are specifically required. Other implementation-defined scheduling
policies may be defined. The following symbols are defined in the Base Definitions volume of
IEEE Std 1003.1-2001, <sched.h>:
1855
SCHED_FIFO
First in, first out (FIFO) scheduling policy.
1856
SCHED_RR
Round robin scheduling policy.
1857
SS
SCHED_SPORADIC Sporadic server scheduling policy.
1858
SCHED_OTHER
Another scheduling policy.
1859
The values of these symbols shall be distinct.
1860
SCHED_FIFO
1861
1862
Conforming implementations shall include a scheduling policy called the FIFO scheduling
policy.
1863
1864
1865
1866
Threads scheduled under this policy are chosen from a thread list that is ordered by the time its
threads have been on the list without being executed; generally, the head of the list is the thread
that has been on the list the longest time, and the tail is the thread that has been on the list the
shortest time.
1867
Under the SCHED_FIFO policy, the modification of the definitional thread lists is as follows:
1868
1869
1. When a running thread becomes a preempted thread, it becomes the head of the thread list
for its priority.
1870
1871
2. When a blocked thread becomes a runnable thread, it becomes the tail of the thread list for
its priority.
1872
1873
1874
3. When a running thread calls the sched_setscheduler( ) function, the process specified in the
function call is modified to the specified policy and the priority specified by the param
argument.
1875
1876
4. When a running thread calls the sched_setparam( ) function, the priority of the process
specified in the function call is modified to the priority specified by the param argument.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
45
Realtime
General Information
1877
1878
1879
5. When a running thread calls the pthread_setschedparam( ) function, the thread specified in
the function call is modified to the specified policy and the priority specified by the param
argument.
1880
1881
6. When a running thread calls the pthread_setschedprio( ) function, the thread specified in the
function call is modified to the priority specified by the prio argument.
1882
1883
1884
7. If a thread whose policy or priority has been modified other than by pthread_setschedprio( )
is a running thread or is runnable, it then becomes the tail of the thread list for its new
priority.
1885
1886
1887
8. If a thread whose policy or priority has been modified by pthread_setschedprio( ) is a
running thread or is runnable, the effect on its position in the thread list depends on the
direction of the modification, as follows:
1888
a. If the priority is raised, the thread becomes the tail of the thread list.
1889
b. If the priority is unchanged, the thread does not change position in the thread list.
1890
c. If the priority is lowered, the thread becomes the head of the thread list.
1891
1892
9. When a running thread issues the sched_yield( ) function, the thread becomes the tail of the
thread list for its priority.
1893
1894
10. At no other time is the position of a thread with this scheduling policy within the thread
lists affected.
1895
1896
1897
1898
For this policy, valid priorities shall be within the range returned by the sched_get_priority_max( )
and sched_get_priority_min( ) functions when SCHED_FIFO is provided as the parameter.
Conforming implementations shall provide a priority range of at least 32 priorities for this
policy.
1899
SCHED_RR
1900
1901
1902
1903
1904
1905
Conforming implementations shall include a scheduling policy called the ‘‘round robin’’
scheduling policy. This policy shall be identical to the SCHED_FIFO policy with the additional
condition that when the implementation detects that a running thread has been executing as a
running thread for a time period of the length returned by the sched_rr_get_interval( ) function or
longer, the thread shall become the tail of its thread list and the head of that thread list shall be
removed and made a running thread.
1906
1907
1908
1909
1910
The effect of this policy is to ensure that if there are multiple SCHED_RR threads at the same
priority, one of them does not monopolize the processor. An application should not rely only on
the use of SCHED_RR to ensure application progress among multiple threads if the application
includes threads using the SCHED_FIFO policy at the same or higher priority levels or
SCHED_RR threads at a higher priority level.
1911
1912
A thread under this policy that is preempted and subsequently resumes execution as a running
thread completes the unexpired portion of its round robin interval time period.
1913
1914
1915
1916
For this policy, valid priorities shall be within the range returned by the sched_get_priority_max( )
and sched_get_priority_min( ) functions when SCHED_RR is provided as the parameter.
Conforming implementations shall provide a priority range of at least 32 priorities for this
policy.
46
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
SCHED_SPORADIC
1917
1918
1919
1920
Realtime
SS|TSP
The functionality described in this section is dependent on support of the Process Sporadic
Server or Thread Sporadic Server options (and the rest of this section is not further shaded for
these options).
1921
1922
If _POSIX_SPORADIC_SERVER or _POSIX_THREAD_SPORADIC_SERVER is defined, the
implementation shall include a scheduling policy identified by the value SCHED_SPORADIC.
1923
1924
1925
1926
1927
1928
1929
The sporadic server policy is based primarily on two parameters: the replenishment period and
the available execution capacity. The replenishment period is given by the sched_ss_repl_period
member of the sched_param structure. The available execution capacity is initialized to the
value given by the sched_ss_init_budget member of the same parameter. The sporadic server
policy is identical to the SCHED_FIFO policy with some additional conditions that cause the
thread’s assigned priority to be switched between the values specified by the sched_priority and
sched_ss_low_priority members of the sched_param structure.
1930
1931
1932
1933
1934
1935
1936
1937
1938
The priority assigned to a thread using the sporadic server scheduling policy is determined in
the following manner: if the available execution capacity is greater than zero and the number of
pending replenishment operations is strictly less than sched_ss_max_repl, the thread is assigned
the priority specified by sched_priority; otherwise, the assigned priority shall be
sched_ss_low_priority. If the value of sched_priority is less than or equal to the value of
sched_ss_low_priority, the results are undefined. When active, the thread shall belong to the
thread list corresponding to its assigned priority level, according to the mentioned priority
assignment. The modification of the available execution capacity and, consequently of the
assigned priority, is done as follows:
1939
1940
1941
1942
1. When the thread at the head of the sched_priority list becomes a running thread, its
execution time shall be limited to at most its available execution capacity, plus the
resolution of the execution time clock used for this scheduling policy. This resolution shall
be implementation-defined.
1943
1944
1945
1946
2. Each time the thread is inserted at the tail of the list associated with sched_priority—
because as a blocked thread it became runnable with priority sched_priority or because a
replenishment operation was performed—the time at which this operation is done is
posted as the activation_time.
1947
1948
1949
1950
3. When the running thread with assigned priority equal to sched_priority becomes a
preempted thread, it becomes the head of the thread list for its priority, and the execution
time consumed is subtracted from the available execution capacity. If the available
execution capacity would become negative by this operation, it shall be set to zero.
1951
1952
1953
1954
4. When the running thread with assigned priority equal to sched_priority becomes a blocked
thread, the execution time consumed is subtracted from the available execution capacity,
and a replenishment operation is scheduled, as described in 6 and 7. If the available
execution capacity would become negative by this operation, it shall be set to zero.
1955
1956
1957
1958
1959
5. When the running thread with assigned priority equal to sched_priority reaches the limit
imposed on its execution time, it becomes the tail of the thread list for
sched_ss_low_priority, the execution time consumed is subtracted from the available
execution capacity (which becomes zero), and a replenishment operation is scheduled, as
described in 6 and 7.
1960
1961
6. Each time a replenishment operation is scheduled, the amount of execution capacity to be
replenished, replenish_amount, is set equal to the execution time consumed by the thread
since the activation_time. The replenishment is scheduled to occur at activation_time plus
sched_ss_repl_period. If the scheduled time obtained is before the current time, the
1962
1963
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
47
Realtime
General Information
1964
1965
1966
1967
1968
replenishment operation is carried out immediately. Several replenishment operations may
be pending at the same time, each of which will be serviced at its respective scheduled
time. With the above rules, the number of replenishment operations simultaneously
pending for a given thread that is scheduled under the sporadic server policy shall not be
greater than sched_ss_max_repl.
1969
1970
1971
1972
1973
1974
7. A replenishment operation consists of adding the corresponding replenish_amount to the
available execution capacity at the scheduled time. If, as a consequence of this operation,
the execution capacity would become larger than sched_ss_initial_budget, it shall be
rounded down to a value equal to sched_ss_initial_budget. Additionally, if the thread was
runnable or running, and had assigned priority equal to sched_ss_low_priority, then it
becomes the tail of the thread list for sched_priority.
1975
Execution time is defined in Section 2.2.2 (on page 14).
1976
1977
For this policy, changing the value of a CPU-time clock via clock_settime( ) shall have no effect on
its behavior.
1978
1979
1980
1981
For this policy, valid priorities shall be within the range returned by the sched_get_priority_min( )
and sched_get_priority_max( ) functions when SCHED_SPORADIC is provided as the parameter.
Conforming implementations shall provide a priority range of at least 32 distinct priorities for
this policy.
1982
SCHED_OTHER
1983
1984
1985
1986
1987
Conforming implementations shall include one scheduling policy identified as SCHED_OTHER
(which may execute identically with either the FIFO or round robin scheduling policy). The
effect of scheduling threads with the SCHED_OTHER policy in a system in which other threads
are executing under SCHED_FIFO, SCHED_RR, or SCHED_SPORADIC is implementationdefined.
SS
1988
1989
This policy is defined to allow strictly conforming applications to be able to indicate in a
portable manner that they no longer need a realtime scheduling policy.
1990
1991
1992
For threads executing under this policy, the implementation shall use only priorities within the
range returned by the sched_get_priority_max( ) and sched_get_priority_min( ) functions when
SCHED_OTHER is provided as the parameter.
1993
2.8.5
Clocks and Timers
1994
1995
TMR
The functionality described in this section is dependent on support of the Timers option (and the
rest of this section is not further shaded for this option).
1996
The <time.h> header defines the types and manifest constants used by the timing facility.
1997
Time Value Specification Structures
1998
1999
2002
2003
Many of the timing facility functions accept or return time value specifications. A time value
structure timespec specifies a single time value and includes at least the following members:
_______________________________________________
L Member Type
L
Member Name L Description L
_______________________________________________
L
L
L
L
time_t
tv_sec
Seconds.
L
L
L
L
long
tv_nsec
Nanoseconds. L
L_______________________________________________
L
L
2004
2005
2006
The tv_nsec member is only valid if greater than or equal to zero, and less than the number of
nanoseconds in a second (1 000 million). The time interval described by this structure is (tv_sec *
9
10 + tv_nsec) nanoseconds.
2000
2001
48
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Realtime
2011
2012
A time value structure itimerspec specifies an initial timer value and a repetition interval for use
by the per-process timer functions. This structure includes at least the following members:
___________________________________________________
L
Member Type L Member Name L
Description
_L __________________________________________________
L
L
L
L
struct timespec L it_interval
Timer period.
L
L
L
struct timespec L it_value
Timer expiration. L
__________________________________________________
L
L_
2013
2014
2015
If the value described by it_value is non-zero, it indicates the time to or time of the next timer
expiration (for relative and absolute timer values, respectively). If the value described by it_value
is zero, the timer shall be disarmed.
2016
2017
2018
2019
If the value described by it_interval is non-zero, it specifies an interval which shall be used in
reloading the timer when it expires; that is, a periodic timer is specified. If the value described by
it_interval is zero, the timer is disarmed after its next expiration; that is, a one-shot timer is
specified.
2020
Timer Event Notification Control Block
2007
2008
2009
2010
2021
2022
2023
2024
2025
RTS
Per-process timers may be created that notify the process of timer expirations by queuing a
realtime extended signal. The sigevent structure, defined in the Base Definitions volume of
IEEE Std 1003.1-2001, <signal.h>, is used in creating such a timer. The sigevent structure
contains the signal number and an application-specific data value which shall be used when
notifying the calling process of timer expiration events.
2026
Manifest Constants
2027
2028
The following constants are defined in the Base Definitions volume of IEEE Std 1003.1-2001,
<time.h>:
2029
CLOCK_REALTIME
The identifier for the system-wide realtime clock.
2030
2031
TIMER_ABSTIME
Flag indicating time is absolute with respect to the clock associated
with a timer.
The identifier for the system-wide monotonic clock, which is defined
as a clock whose value cannot be set via clock_settime( ) and which
cannot have backward clock jumps. The maximum possible clock
jump is implementation-defined.
2032
2033
2034
2035
MON
CLOCK_MONOTONIC
2036
2037
2038
2039
2040
2041
2042
MON
The maximum allowable resolution for CLOCK_REALTIME and CLOCK_MONOTONIC clocks
and all time services based on these clocks is represented by {_POSIX_CLOCKRES_MIN} and
shall be defined as 20 ms (1/50 of a second). Implementations may support smaller values of
resolution for these clocks to provide finer granularity time bases. The actual resolution
supported by an implementation for a specific clock is obtained using the clock_getres( ) function.
If the actual resolution supported for a time service based on one of these clocks differs from the
resolution supported for that clock, the implementation shall document this difference.
2043
2044
2045
2046
2047
MON
The minimum allowable maximum value for CLOCK_REALTIME and CLOCK_MONOTONIC
clocks and all absolute time services based on them is the same as that defined by the ISO C
standard for the time_t type. If the maximum value supported by a time service based on one of
these clocks differs from the maximum value supported by that clock, the implementation shall
document this difference.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
49
Realtime
General Information
Execution Time Monitoring
2048
2049
2050
CPT
If _POSIX_CPUTIME is defined, process CPU-time clocks shall be supported in addition to the
clocks described in Manifest Constants (on page 49).
2051
TCT
If _POSIX_THREAD_CPUTIME is defined, thread CPU-time clocks shall be supported.
2052
2053
2054
2055
CPT|TCT
CPU-time clocks measure execution or CPU time, which is defined in the Base Definitions
volume of IEEE Std 1003.1-2001, Section 3.117, CPU Time (Execution Time). The mechanism
used to measure execution time is described in the Base Definitions volume of
IEEE Std 1003.1-2001, Section 4.9, Measurement of Execution Time.
2056
2057
CPT
If _POSIX_CPUTIME is defined, the following constant of the type clockid_t is defined in
<time.h>:
CLOCK_PROCESS_CPUTIME_ID
When this value of the type clockid_t is used in a clock ( ) or timer*( ) function call, it is
interpreted as the identifier of the CPU-time clock associated with the process making the
function call.
2058
2059
2060
2061
2062
2063
2064
TCT
CLOCK_THREAD_CPUTIME_ID
When this value of the type clockid_t is used in a clock ( ) or timer*( ) function call, it is
interpreted as the identifier of the CPU-time clock associated with the thread making the
function call.
2065
2066
2067
2068
2069
2070
2071
If _POSIX_THREAD_CPUTIME is defined, the following constant of the type clockid_t is
defined in <time.h>:
2.9
Threads
THR
The functionality described in this section is dependent on support of the Threads option (and
the rest of this section is not further shaded for this option).
2072
2073
2074
This section defines functionality to support multiple flows of control, called ‘‘threads’’, within a
process. For the definition of threads, see the Base Definitions volume of IEEE Std 1003.1-2001,
Section 3.393, Thread.
2075
The specific functional areas covered by threads and their scope include:
2076
2077
•
Thread management: the creation, control, and termination of multiple flows of control in the
same process under the assumption of a common shared address space
2078
2079
•
Synchronization primitives optimized for tightly coupled operation of multiple control flows
in a common, shared address space
2080
2.9.1
All functions defined by this volume of IEEE Std 1003.1-2001 shall be thread-safe, except that the
following functions1 need not be thread-safe.
2081
2082
2083
2084
Thread-Safety
__________________
1. The functions in the table are not shaded to denote applicable options. Individual reference pages should be consulted.
50
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Threads
getutxline( )
gmtime( )
hcreate( )
hdestroy( )
hsearch( )
inet_ntoa ( )
l64a ( )
lgamma( )
lgammaf ( )
lgammal ( )
localeconv ( )
localtime ( )
lrand48( )
mrand48( )
nftw( )
nl_langinfo ( )
ptsname( )
putc_unlocked ( )
putchar_unlocked( )
putenv( )
pututxline( )
rand( )
readdir( )
setenv( )
setgrent( )
setkey( )
setpwent( )
setutxent( )
strerror( )
strtok( )
ttyname( )
unsetenv( )
wcstombs( )
wctomb( )
asctime( )
basename( )
catgets( )
crypt( )
ctime( )
dbm_clearerr( )
dbm_close( )
dbm_delete( )
dbm_error( )
dbm_fetch( )
dbm_firstkey( )
dbm_nextkey( )
dbm_open( )
dbm_store( )
dirname( )
dlerror( )
drand48( )
2102
2103
The ctermid( ) and tmpnam( ) functions need not be thread-safe if passed a NULL argument. The
wcrtomb( ) and wcsrtombs( ) functions need not be thread-safe if passed a NULL ps argument.
2104
2105
Implementations shall provide internal synchronization as necessary in order to satisfy this
requirement.
2106
2.9.2
Thread IDs
Although implementations may have thread IDs that are unique in a system, applications
should only assume that thread IDs are usable and unique within a single process. The effect of
calling any of the functions defined in this volume of IEEE Std 1003.1-2001 and passing as an
argument the thread ID of a thread from another process is unspecified. A conforming
implementation is free to reuse a thread ID after the thread terminates if it was created with the
detachstate attribute set to PTHREAD_CREATE_DETACHED or if pthread_detach( ) or
pthread_join ( ) has been called for that thread. If a thread is detached, its thread ID is invalid for
use as an argument in a call to pthread_detach( ) or pthread_join ( ).
2107
2108
2109
2110
2111
2112
2113
2114
2115
ecvt( )
encrypt( )
endgrent( )
endpwent( )
endutxent( )
fcvt( )
ftw( )
gcvt( )
getc_unlocked ( )
getchar_unlocked( )
getdate( )
getenv( )
getgrent( )
getgrgid( )
getgrnam( )
gethostbyaddr( )
gethostbyname( )
gethostent( )
getlogin ( )
getnetbyaddr( )
getnetbyname( )
getnetent( )
getopt( )
getprotobyname( )
getprotobynumber( )
getprotoent( )
getpwent( )
getpwnam( )
getpwuid( )
getservbyname( )
getservbyport( )
getservent( )
getutxent( )
getutxid( )
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2.9.3
Thread Mutexes
2116
2117
2118
A thread that has blocked shall not prevent any unblocked thread that is eligible to use the same
processing resources from eventually making forward progress in its execution. Eligibility for
processing resources is determined by the scheduling policy.
2119
A thread shall become the owner of a mutex, m, when one of the following occurs:
2120
•
It returns successfully from pthread_mutex_lock( ) with m as the mutex argument.
2121
•
It returns successfully from pthread_mutex_trylock( ) with m as the mutex argument.
•
It returns successfully from pthread_mutex_timedlock( ) with m as the mutex argument.
2123
2124
•
It returns (successfully or not) from pthread_cond_wait( ) with m as the mutex argument
(except as explicitly indicated otherwise for certain errors).
2125
2126
•
It returns (successfully or not) from pthread_cond_timedwait( ) with m as the mutex argument
(except as explicitly indicated otherwise for certain errors).
2122
2127
TMO
The thread shall remain the owner of m until one of the following occurs:
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
51
Threads
General Information
2128
•
It executes pthread_mutex_unlock( ) with m as the mutex argument
2129
•
It blocks in a call to pthread_cond_wait( ) with m as the mutex argument.
2130
•
It blocks in a call to pthread_cond_timedwait( ) with m as the mutex argument.
2131
The implementation shall behave as if at all times there is at most one owner of any mutex.
2132
2133
2134
A thread that becomes the owner of a mutex is said to have ‘‘acquired’’ the mutex and the mutex
is said to have become ‘‘locked’’; when a thread gives up ownership of a mutex it is said to have
‘‘released’’ the mutex and the mutex is said to have become ‘‘unlocked’’.
2135
2.9.4
Thread Scheduling
2136
2137
TPS
The functionality described in this section is dependent on support of the Thread Execution
Scheduling option (and the rest of this section is not further shaded for this option).
2138
Thread Scheduling Attributes
2139
2140
In support of the scheduling function, threads have attributes which are accessed through the
pthread_attr_t thread creation attributes object.
2141
2142
The contentionscope attribute defines the scheduling contention scope of the thread to be either
PTHREAD_SCOPE_PROCESS or PTHREAD_SCOPE_SYSTEM.
2143
2144
2145
The inheritsched attribute specifies whether a newly created thread is to inherit the scheduling
attributes of the creating thread or to have its scheduling values set according to the other
scheduling attributes in the pthread_attr_t object.
2146
2147
2148
The schedpolicy attribute defines the scheduling policy for the thread. The schedparam attribute
defines the scheduling parameters for the thread. The interaction of threads having different
policies within a process is described as part of the definition of those policies.
2149
2150
2151
2152
2153
2154
If the Thread Execution Scheduling option is defined, and the schedpolicy attribute specifies one
of the priority-based policies defined under this option, the schedparam attribute contains the
scheduling priority of the thread. A conforming implementation ensures that the priority value
in schedparam is in the range associated with the scheduling policy when the thread attributes
object is used to create a thread, or when the scheduling attributes of a thread are dynamically
modified. The meaning of the priority value in schedparam is the same as that of priority .
2155
2156
2157
2158
2159
TSP
If _POSIX_THREAD_SPORADIC_SERVER is defined, the schedparam attribute supports four
new members that are used for the sporadic server scheduling policy. These members are
sched_ss_low_priority, sched_ss_repl_period, sched_ss_init_budget, and sched_ss_max_repl. The
meaning of these attributes is the same as in the definitions that appear under Section 2.8.4 (on
page 44).
When a process is created, its single thread has a scheduling policy and associated attributes
equal to the process’ policy and attributes. The default scheduling contention scope value is
implementation-defined. The default values of other scheduling attributes are implementationdefined.
2160
2161
2162
2163
52
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Threads
2164
Thread Scheduling Contention Scope
2165
2166
2167
2168
2169
The scheduling contention scope of a thread defines the set of threads with which the thread
competes for use of the processing resources. The scheduling operation selects at most one
thread to execute on each processor at any point in time and the thread’s scheduling attributes
(for example, priority ), whether under process scheduling contention scope or system scheduling
contention scope, are the parameters used to determine the scheduling decision.
2170
2171
The scheduling contention scope, in the context of scheduling a mixed scope environment,
affects threads as follows:
2172
2173
2174
2175
2176
2177
2178
2179
•
A thread created with PTHREAD_SCOPE_SYSTEM scheduling contention scope contends
for resources with all other threads in the same scheduling allocation domain relative to their
system scheduling attributes. The system scheduling attributes of a thread created with
PTHREAD_SCOPE_SYSTEM scheduling contention scope are the scheduling attributes with
which the thread was created. The system scheduling attributes of a thread created with
PTHREAD_SCOPE_PROCESS scheduling contention scope are the implementation-defined
mapping into system attribute space of the scheduling attributes with which the thread was
created.
2180
2181
2182
2183
2184
2185
•
Threads created with PTHREAD_SCOPE_PROCESS scheduling contention scope contend
directly with other threads within their process that were created with
PTHREAD_SCOPE_PROCESS scheduling contention scope. The contention is resolved
based on the threads’ scheduling attributes and policies. It is unspecified how such threads
are scheduled relative to threads in other processes or threads with
PTHREAD_SCOPE_SYSTEM scheduling contention scope.
2186
2187
•
Conforming implementations shall support the PTHREAD_SCOPE_PROCESS scheduling
contention scope, the PTHREAD_SCOPE_SYSTEM scheduling contention scope, or both.
2188
Scheduling Allocation Domain
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
Implementations shall support scheduling allocation domains containing one or more
processors. It should be noted that the presence of multiple processors does not automatically
indicate a scheduling allocation domain size greater than one. Conforming implementations on
multi-processors may map all or any subset of the CPUs to one or multiple scheduling allocation
domains, and could define these scheduling allocation domains on a per-thread, per-process, or
per-system basis, depending on the types of applications intended to be supported by the
implementation. The scheduling allocation domain is independent of scheduling contention
scope, as the scheduling contention scope merely defines the set of threads with which a thread
contends for processor resources, while scheduling allocation domain defines the set of
processors for which it contends. The semantics of how this contention is resolved among
threads for processors is determined by the scheduling policies of the threads.
2200
2201
2202
2203
The choice of scheduling allocation domain size and the level of application control over
scheduling allocation domains is implementation-defined. Conforming implementations may
change the size of scheduling allocation domains and the binding of threads to scheduling
allocation domains at any time.
2204
2205
2206
2207
2208
For application threads with scheduling allocation domains of size equal to one, the scheduling
rules defined for SCHED_FIFO and SCHED_RR shall be used; see Scheduling Policies (on page
44). All threads with system scheduling contention scope, regardless of the processes in which
they reside, compete for the processor according to their priorities. Threads with process
scheduling contention scope compete only with other threads with process scheduling
contention scope within their process.
2209
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
53
Threads
2210
2211
2212
2213
2214
2215
2216
2217
2218
TSP
TSP
2226
For application threads with scheduling allocation domains of size greater than one, the rules
defined for SCHED_FIFO, SCHED_RR, and SCHED_SPORADIC shall be used in an
implementation-defined manner. Each thread with system scheduling contention scope
competes for the processors in its scheduling allocation domain in an implementation-defined
manner according to its priority. Threads with process scheduling contention scope are
scheduled relative to other threads within the same scheduling contention scope in the process.
If _POSIX_THREAD_SPORADIC_SERVER is defined, the rules defined for SCHED_SPORADIC
in Scheduling Policies (on page 44) shall be used in an implementation-defined manner for
application threads whose scheduling allocation domain size is greater than one.
Scheduling Documentation
2219
2220
2221
2222
2223
2224
2225
General Information
TSP
2.9.5
If _POSIX_PRIORITY_SCHEDULING is defined, then any scheduling policies beyond
SCHED_OTHER, SCHED_FIFO, SCHED_RR, and SCHED_SPORADIC, as well as the effects of
the scheduling policies indicated by these other values, and the attributes required in order to
support such a policy, are implementation-defined. Furthermore, the implementation shall
document the effect of all processor scheduling allocation domain values supported for these
policies.
Thread Cancelation
2227
2228
2229
2230
The thread cancelation mechanism allows a thread to terminate the execution of any other
thread in the process in a controlled manner. The target thread (that is, the one that is being
canceled) is allowed to hold cancelation requests pending in a number of ways and to perform
application-specific cleanup processing when the notice of cancelation is acted upon.
2231
2232
2233
Cancelation is controlled by the cancelation control functions. Each thread maintains its own
cancelability state. Cancelation may only occur at cancelation points or when the thread is
asynchronously cancelable.
2234
2235
2236
2237
2238
The thread cancelation mechanism described in this section depends upon programs having set
deferred cancelability state, which is specified as the default. Applications shall also carefully
follow static lexical scoping rules in their execution behavior. For example, use of setjmp( ),
return, goto, and so on, to leave user-defined cancelation scopes without doing the necessary
scope pop operation results in undefined behavior.
2239
2240
2241
Use of asynchronous cancelability while holding resources which potentially need to be released
may result in resource loss. Similarly, cancelation scopes may only be safely manipulated
(pushed and popped) when the thread is in the deferred or disabled cancelability states.
2242
2.9.5.1
Cancelability States
2243
2244
The cancelability state of a thread determines the action taken upon receipt of a cancelation
request. The thread may control cancelation in a number of ways.
2245
Each thread maintains its own cancelability state, which may be encoded in two bits:
2246
2247
2248
2249
1. Cancelability-Enable: When cancelability is PTHREAD_CANCEL_DISABLE (as defined in
the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>), cancelation requests
against the target thread are held pending. By default, cancelability is set to
PTHREAD_CANCEL_ENABLE (as defined in <pthread.h>).
2250
2251
2252
2253
2. Cancelability Type: When cancelability is enabled and the cancelability type is
PTHREAD_CANCEL_ASYNCHRONOUS (as defined in <pthread.h>), new or pending
cancelation requests may be acted upon at any time. When cancelability is enabled and the
cancelability type is PTHREAD_CANCEL_DEFERRED (as defined in <pthread.h>),
54
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
cancelation requests are held pending until a cancelation point (see below) is reached. If
cancelability is disabled, the setting of the cancelability type has no immediate effect as all
cancelation requests are held pending; however, once cancelability is enabled again the
new type is in effect. The cancelability type is PTHREAD_CANCEL_DEFERRED in all
newly created threads including the thread in which main( ) was first invoked.
2254
2255
2256
2257
2258
2259
Threads
2.9.5.2
Cancelation Points
2260
Cancelation points shall occur when a thread is executing the following functions:
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
accept( )
aio_suspend( )
clock_nanosleep( )
close( )
connect( )
creat( )
fcntl( )2
fsync( )
getmsg( )
getpmsg( )
lockf ( )
mq_receive( )
mq_send( )
mq_timedreceive( )
2275
2276
mq_timedsend( )
msgrcv( )
msgsnd( )
msync( )
nanosleep( )
open( )
pause( )
poll ( )
pread( )
pthread_cond_timedwait( )
pthread_cond_wait( )
pthread_join ( )
pthread_testcancel( )
putmsg( )
putpmsg( )
pwrite( )
read( )
readv( )
recv( )
recvfrom( )
recvmsg( )
select( )
sem_timedwait( )
sem_wait( )
send( )
sendmsg( )
sendto( )
sigpause( )
sigsuspend( )
sigtimedwait ( )
sigwait ( )
sigwaitinfo ( )
sleep( )
system( )
tcdrain( )
usleep( )
wait( )
waitid ( )
waitpid ( )
write( )
writev( )
__________________
2. When the cmd argument is F_SETLKW.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
55
Threads
General Information
2277
A cancelation point may also occur when a thread is executing the following functions:
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
catclose ( )
catgets( )
catopen( )
closedir( )
closelog ( )
ctermid( )
dbm_close( )
dbm_delete( )
dbm_fetch( )
dbm_nextkey( )
dbm_open( )
dbm_store( )
dlclose( )
dlopen( )
endgrent( )
endhostent( )
endnetent( )
endprotoent( )
endpwent( )
endservent( )
endutxent( )
fclose( )
fcntl( )3
fflush( )
fgetc( )
fgetpos( )
fgets( )
fgetwc( )
fgetws( )
fopen( )
fprintf( )
fputc( )
fputs( )
fputwc( )
fputws( )
fread( )
freopen( )
fscanf( )
fseek( )
fseeko( )
fsetpos( )
2319
2320
An implementation shall not introduce cancelation points into any other functions specified in
this volume of IEEE Std 1003.1-2001.
2321
2322
ftell( )
ftello ( )
ftw( )
fwprintf( )
fwrite( )
fwscanf( )
getc( )
getc_unlocked ( )
getchar( )
getchar_unlocked( )
getcwd( )
getdate( )
getgrent( )
getgrgid( )
getgrgid_r( )
getgrnam( )
getgrnam_r( )
gethostbyaddr ( )
gethostbyname( )
gethostent( )
gethostname( )
getlogin ( )
getlogin_r ( )
getnetbyaddr( )
getnetbyname( )
getnetent( )
getprotobyname( )
getprotobynumber( )
getprotoent( )
getpwent( )
getpwnam( )
getpwnam_r( )
getpwuid( )
getpwuid_r( )
gets( )
getservbyname( )
getservbyport( )
getservent( )
getutxent( )
getutxid( )
getutxline( )
getwc( )
getwchar( )
getwd( )
glob( )
iconv_close ( )
iconv_open ( )
ioctl ( )
lseek( )
mkstemp( )
nftw( )
opendir( )
openlog ( )
pclose( )
perror( )
popen( )
posix_fadvise ( )
posix_fallocate( )
posix_madvise ( )
posix_spawn ( )
posix_spawnp ( )
posix_trace_clear( )
posix_trace_close( )
posix_trace_create( )
posix_trace_create_withlog( )
posix_trace_eventtypelist_getnext_id( )
posix_trace_eventtypelist_rewind( )
posix_trace_flush( )
posix_trace_get_attr( )
posix_trace_get_filter( )
posix_trace_get_status( )
posix_trace_getnext_event( )
posix_trace_open( )
posix_trace_rewind( )
posix_trace_set_filter( )
posix_trace_shutdown( )
posix_trace_timedgetnext_event( )
posix_typed_mem_open( )
printf( )
pthread_rwlock_rdlock( )
pthread_rwlock_timedrdlock( )
pthread_rwlock_timedwrlock( )
pthread_rwlock_wrlock( )
putc( )
putc_unlocked ( )
putchar( )
putchar_unlocked( )
puts( )
pututxline( )
putwc( )
putwchar( )
readdir( )
readdir_r( )
remove( )
rename( )
rewind( )
rewinddir( )
scanf( )
seekdir( )
semop( )
setgrent( )
sethostent( )
setnetent( )
setprotoent( )
setpwent( )
setservent( )
setutxent( )
strerror( )
syslog( )
tmpfile( )
tmpnam( )
ttyname( )
ttyname_r( )
ungetc( )
ungetwc( )
unlink( )
vfprintf ( )
vfwprintf ( )
vprintf( )
vwprintf( )
wprintf( )
wscanf( )
__________________
3. For any value of the cmd argument.
56
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Threads
2323
2324
2325
2326
The side effects of acting upon a cancelation request while suspended during a call of a function
are the same as the side effects that may be seen in a single-threaded program when a call to a
function is interrupted by a signal and the given function returns [EINTR]. Any such side effects
occur before any cancelation cleanup handlers are called.
2327
2328
2329
2330
2331
2332
2333
2334
2335
Whenever a thread has cancelability enabled and a cancelation request has been made with that
thread as the target, and the thread then calls any function that is a cancelation point (such as
pthread_testcancel( ) or read( )), the cancelation request shall be acted upon before the function
returns. If a thread has cancelability enabled and a cancelation request is made with the thread
as a target while the thread is suspended at a cancelation point, the thread shall be awakened
and the cancelation request shall be acted upon. However, if the thread is suspended at a
cancelation point and the event for which it is waiting occurs before the cancelation request is
acted upon, it is unspecified whether the cancelation request is acted upon or whether the
cancelation request remains pending and the thread resumes normal execution.
2336
2.9.5.3
Thread Cancelation Cleanup Handlers
2337
2338
2339
Each thread maintains a list of cancelation cleanup handlers. The programmer uses the
pthread_cleanup_push( ) and pthread_cleanup_pop( ) functions to place routines on and remove
routines from this list.
2340
2341
2342
2343
2344
2345
2346
2347
2348
When a cancelation request is acted upon, the routines in the list are invoked one by one in LIFO
sequence; that is, the last routine pushed onto the list (Last In) is the first to be invoked (First
Out). The thread invokes the cancelation cleanup handler with cancelation disabled until the last
cancelation cleanup handler returns. When the cancelation cleanup handler for a scope is
invoked, the storage for that scope remains valid. If the last cancelation cleanup handler returns,
thread execution is terminated and a status of PTHREAD_CANCELED is made available to any
threads joining with the target. The symbolic constant PTHREAD_CANCELED expands to a
constant expression of type (void *) whose value matches no pointer to an object in memory nor
the value NULL.
2349
The cancelation cleanup handlers are also invoked when the thread calls pthread_exit ( ).
2350
2351
2352
2353
A side effect of acting upon a cancelation request while in a condition variable wait is that the
mutex is re-acquired before calling the first cancelation cleanup handler. In addition, the thread
is no longer considered to be waiting for the condition and the thread shall not have consumed
any pending condition signals on the condition.
2354
A cancelation cleanup handler cannot exit via longjmp( ) or siglongjmp ( ).
2355
2.9.5.4
Async-Cancel Safety
2356
2357
The pthread_cancel( ), pthread_setcancelstate( ), and pthread_setcanceltype( ) functions are defined to
be async-cancel safe.
2358
No other functions in this volume of IEEE Std 1003.1-2001 are required to be async-cancel-safe.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
57
Threads
2359
2.9.6
General Information
Thread Read-Write Locks
2360
2361
2362
2363
Multiple readers, single writer (read-write) locks allow many threads to have simultaneous
read-only access to data while allowing only one thread to have exclusive write access at any
given time. They are typically used to protect data that is read more frequently than it is
changed.
2364
2365
2366
2367
One or more readers acquire read access to the resource by performing a read lock operation on
the associated read-write lock. A writer acquires exclusive write access by performing a write
lock operation. Basically, all readers exclude any writers and a writer excludes all readers and
any other writers.
2368
2369
2370
2371
A thread that has blocked on a read-write lock (for example, has not yet returned from a
pthread_rwlock_rdlock( ) or pthread_rwlock_wrlock( ) call) shall not prevent any unblocked thread
that is eligible to use the same processing resources from eventually making forward progress in
its execution. Eligibility for processing resources shall be determined by the scheduling policy.
2372
2373
2374
Read-write locks can be used to synchronize threads in the current process and other processes if
they are allocated in memory that is writable and shared among the cooperating processes and
have been initialized for this behavior.
2375
2.9.7
All of the functions chmod( ), close( ), fchmod( ), fcntl( ), fstat( ), ftruncate( ), lseek( ), open( ), read( ),
readlink ( ), stat( ), symlink( ), and write( ) shall be atomic with respect to each other in the effects
specified in IEEE Std 1003.1-2001 when they operate on regular files. If two threads each call one
of these functions, each call shall either see all of the specified effects of the other call, or none of
them.
2376
2377
2378
2379
2380
2381
2.10
Sockets
A socket is an endpoint for communication using the facilities described in this section. A socket
is created with a specific socket type, described in Section 2.10.6 (on page 59), and is associated
with a specific protocol, detailed in Section 2.10.3 (on page 59). A socket is accessed via a file
descriptor obtained when the socket is created.
2382
2383
2384
2385
2386
Thread Interactions with Regular File Operations
2.10.1
Address Families
2387
2388
2389
2390
2391
2392
2393
All network protocols are associated with a specific address family. An address family provides
basic services to the protocol implementation to allow it to function within a specific network
environment. These services may include packet fragmentation and reassembly, routing,
addressing, and basic transport. An address family is normally comprised of a number of
protocols, one per socket type. Each protocol is characterized by an abstract socket type. It is not
required that an address family support all socket types. An address family may contain
multiple protocols supporting the same socket abstraction.
2394
2395
2396
Section 2.10.17 (on page 66), Section 2.10.19 (on page 67), and Section 2.10.20 (on page 67),
respectively, describe the use of sockets for local UNIX connections, for Internet protocols based
on IPv4, and for Internet protocols based on IPv6.
58
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
2397
2.10.2
2.10.3
2.10.4
2.10.5
2418
2419
2420
2421
Interfaces
Each network interface in a system corresponds to a path through which messages can be sent
and received. A network interface usually has a hardware device associated with it, though
certain interfaces such as the loopback interface, do not.
2414
2415
2416
2417
Routing
Sockets provides packet routing facilities. A routing information database is maintained, which
is used in selecting the appropriate network interface when transmitting packets.
2411
2412
2413
Protocols
A protocol supports one of the socket abstractions detailed in Section 2.10.6. Selecting a protocol
involves specifying the address family, socket type, and protocol number to the socket( )
function. Certain semantics of the basic socket abstractions are protocol-specific. All protocols
are expected to support the basic model for their particular socket type, but may, in addition,
provide non-standard facilities or extensions to a mechanism.
2405
2406
2407
2408
2409
2410
Addressing
An address family defines the format of a socket address. All network addresses are described
using a general structure, called a sockaddr, as defined in the Base Definitions volume of
IEEE Std 1003.1-2001, <sys/socket.h>. However, each address family imposes finer and more
specific structure, generally defining a structure with fields specific to the address family. The
field sa_family in the sockaddr structure contains the address family identifier, specifying the
format of the sa_data area. The size of the sa_data area is unspecified.
2398
2399
2400
2401
2402
2403
2404
Sockets
2.10.6
RS
Socket Types
A socket is created with a specific type, which defines the communication semantics and which
allows the selection of an appropriate communication protocol. Four types are defined:
SOCK_RAW, SOCK_STREAM, SOCK_SEQPACKET, and SOCK_DGRAM. Implementations
may specify additional socket types.
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
The SOCK_STREAM socket type provides reliable, sequenced, full-duplex octet streams
between the socket and a peer to which the socket is connected. A socket of type
SOCK_STREAM must be in a connected state before any data may be sent or received. Record
boundaries are not maintained; data sent on a stream socket using output operations of one size
may be received using input operations of smaller or larger sizes without loss of data. Data may
be buffered; successful return from an output function does not imply that the data has been
delivered to the peer or even transmitted from the local system. If data cannot be successfully
transmitted within a given time then the connection is considered broken, and subsequent
operations shall fail. A SIGPIPE signal is raised if a thread sends on a broken stream (one that is
no longer connected). Support for an out-of-band data transmission facility is protocol-specific.
2432
2433
2434
2435
2436
2437
2438
The SOCK_SEQPACKET socket type is similar to the SOCK_STREAM type, and is also
connection-oriented. The only difference between these types is that record boundaries are
maintained using the SOCK_SEQPACKET type. A record can be sent using one or more output
operations and received using one or more input operations, but a single operation never
transfers parts of more than one record. Record boundaries are visible to the receiver via the
MSG_EOR flag in the received message flags returned by the recvmsg( ) function. It is protocolspecific whether a maximum record size is imposed.
2439
2440
The SOCK_DGRAM socket type supports connectionless data transfer which is not necessarily
acknowledged or reliable. Datagrams may be sent to the address specified (possibly multicast or
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
59
Sockets
General Information
broadcast) in each output operation, and incoming datagrams may be received from multiple
sources. The source address of each datagram is available when receiving the datagram. An
application may also pre-specify a peer address, in which case calls to output functions shall
send to the pre-specified peer. If a peer has been specified, only datagrams from that peer shall
be received. A datagram must be sent in a single output operation, and must be received in a
single input operation. The maximum size of a datagram is protocol-specific; with some
protocols, the limit is implementation-defined. Output datagrams may be buffered within the
system; thus, a successful return from an output function does not guarantee that a datagram is
actually sent or received. However, implementations should attempt to detect any errors
possible before the return of an output function, reporting any error by an unsuccessful return
value.
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
RS
The SOCK_RAW socket type is similar to the SOCK_DGRAM type. It differs in that it is
normally used with communication providers that underlie those used for the other socket
types. For this reason, the creation of a socket with type SOCK_RAW shall require appropriate
privilege. The format of datagrams sent and received with this socket type generally include
specific protocol headers, and the formats are protocol-specific and implementation-defined.
2457
2.10.7
Socket I/O Mode
2458
2459
2460
The I/O mode of a socket is described by the O_NONBLOCK file status flag which pertains to
the open file description for the socket. This flag is initially off when a socket is created, but may
be set and cleared by the use of the F_SETFL command of the fcntl( ) function.
2461
2462
2463
2464
2465
2466
2467
2468
When the O_NONBLOCK flag is set, functions that would normally block until they are
complete shall either return immediately with an error, or shall complete asynchronously to the
execution of the calling process. Data transfer operations (the read( ), write( ), send( ), and recv( )
functions) shall complete immediately, transfer only as much as is available, and then return
without blocking, or return an error indicating that no transfer could be made without blocking.
The connect( ) function initiates a connection and shall return without blocking when
O_NONBLOCK is set; it shall return the error [EINPROGRESS] to indicate that the connection
was initiated successfully, but that it has not yet completed.
2469
2.10.8
The owner of a socket is unset when a socket is created. The owner may be set to a process ID or
process group ID using the F_SETOWN command of the fcntl( ) function.
2470
2471
2472
2.10.9
Socket Queue Limits
The transmit and receive queue sizes for a socket are set when the socket is created. The default
sizes used are both protocol-specific and implementation-defined. The sizes may be changed
using the setsockopt ( ) function.
2473
2474
2475
2476
Socket Owner
2.10.10 Pending Error
Errors may occur asynchronously, and be reported to the socket in response to input from the
network protocol. The socket stores the pending error to be reported to a user of the socket at the
next opportunity. The error is returned in response to a subsequent send( ), recv( ), or getsockopt ( )
operation on the socket, and the pending error is then cleared.
2477
2478
2479
2480
60
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
2481
Sockets
2.10.11 Socket Receive Queue
2482
2483
2484
2485
2486
2487
2488
A socket has a receive queue that buffers data when it is received by the system until it is
removed by a receive call. Depending on the type of the socket and the communication provider,
the receive queue may also contain ancillary data such as the addressing and other protocol data
associated with the normal data in the queue, and may contain out-of-band or expedited data.
The limit on the queue size includes any normal, out-of-band data, datagram source addresses,
and ancillary data in the queue. The description in this section applies to all sockets, even though
some elements cannot be present in some instances.
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
The contents of a receive buffer are logically structured as a series of data segments with
associated ancillary data and other information. A data segment may contain normal data or
out-of-band data, but never both. A data segment may complete a record if the protocol
supports records (always true for types SOCK_SEQPACKET and SOCK_DGRAM). A record
may be stored as more than one segment; the complete record might never be present in the
receive buffer at one time, as a portion might already have been returned to the application, and
another portion might not yet have been received from the communications provider. A data
segment may contain ancillary protocol data, which is logically associated with the segment.
Ancillary data is received as if it were queued along with the first normal data octet in the
segment (if any). A segment may contain ancillary data only, with no normal or out-of-band
data. For the purposes of this section, a datagram is considered to be a data segment that
terminates a record, and that includes a source address as a special type of ancillary data. Data
segments are placed into the queue as data is delivered to the socket by the protocol. Normal
data segments are placed at the end of the queue as they are delivered. If a new segment
contains the same type of data as the preceding segment and includes no ancillary data, and if
the preceding segment does not terminate a record, the segments are logically merged into a
single segment.
2506
2507
2508
2509
2510
The receive queue is logically terminated if an end-of-file indication has been received or a
connection has been terminated. A segment shall be considered to be terminated if another
segment follows it in the queue, if the segment completes a record, or if an end-of-file or other
connection termination has been reported. The last segment in the receive queue shall also be
considered to be terminated while the socket has a pending error to be reported.
2511
A receive operation shall never return data or ancillary data from more than one segment.
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2.10.12 Socket Out-of-Band Data State
The handling of received out-of-band data is protocol-specific. Out-of-band data may be placed
in the socket receive queue, either at the end of the queue or before all normal data in the queue.
In this case, out-of-band data is returned to an application program by a normal receive call.
Out-of-band data may also be queued separately rather than being placed in the socket receive
queue, in which case it shall be returned only in response to a receive call that requests out-ofband data. It is protocol-specific whether an out-of-band data mark is placed in the receive
queue to demarcate data preceding the out-of-band data and following the out-of-band data. An
out-of-band data mark is logically an empty data segment that cannot be merged with other
segments in the queue. An out-of-band data mark is never returned in response to an input
operation. The sockatmark ( ) function can be used to test whether an out-of-band data mark is the
first element in the queue. If an out-of-band data mark is the first element in the queue when an
input function is called without the MSG_PEEK option, the mark is removed from the queue and
the following data (if any) is processed as if the mark had not been present.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
61
Sockets
2526
2.10.13 Connection Indication Queue
Sockets that are used to accept incoming connections maintain a queue of outstanding
connection indications. This queue is a list of connections that are awaiting acceptance by the
application; see listen( ).
2527
2528
2529
2530
General Information
2.10.14 Signals
2531
2532
2533
2534
One category of event at the socket interface is the generation of signals. These signals report
protocol events or process errors relating to the state of the socket. The generation or delivery of
a signal does not change the state of the socket, although the generation of the signal may have
been caused by a state change.
2535
2536
The SIGPIPE signal shall be sent to a thread that attempts to send data on a socket that is no
longer able to send. In addition, the send operation fails with the error [EPIPE].
2537
2538
2539
2540
2541
If a socket has an owner, the SIGURG signal is sent to the owner of the socket when it is notified
of expedited or out-of-band data. The socket state at this time is protocol-dependent, and the
status of the socket is specified in Section 2.10.17 (on page 66), Section 2.10.19 (on page 67), and
Section 2.10.20 (on page 67). Depending on the protocol, the expedited data may or may not
have arrived at the time of signal generation.
2542
2.10.15 Asynchronous Errors
2543
2544
If any of the following conditions occur asynchronously for a socket, the corresponding value
listed below shall become the pending error for the socket:
2545
2546
[ECONNABORTED]
The connection was aborted locally.
2547
2548
2549
2550
[ECONNREFUSED]
For a connection-mode socket attempting a non-blocking connection, the attempt to connect
was forcefully rejected. For a connectionless-mode socket, an attempt to deliver a datagram
was forcefully rejected.
2551
2552
[ECONNRESET]
The peer has aborted the connection.
2553
2554
[EHOSTDOWN]
The destination host has been determined to be down or disconnected.
2555
2556
[EHOSTUNREACH]
The destination host is not reachable.
2557
2558
2559
[EMSGSIZE]
For a connectionless-mode socket, the size of a previously sent datagram prevented
delivery.
2560
2561
[ENETDOWN]
The local network connection is not operational.
2562
2563
[ENETRESET]
The connection was aborted by the network.
2564
2565
[ENETUNREACH]
The destination network is not reachable.
62
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
2566
Sockets
2.10.16 Use of Options
2567
2568
2569
There are a number of socket options which either specialize the behavior of a socket or provide
useful information. These options may be set at different protocol levels and are always present
at the uppermost ‘‘socket’’ level.
2570
2571
2572
Socket options are manipulated by two functions, getsockopt ( ) and setsockopt ( ). These functions
allow an application program to customize the behavior and characteristics of a socket to
provide the desired effect.
2573
2574
2575
2576
All of the options have default values. The type and meaning of these values is defined by the
protocol level to which they apply. Instead of using the default values, an application program
may choose to customize one or more of the options. However, in the bulk of cases, the default
values are sufficient for the application.
2577
2578
2579
2580
Some of the options are used to enable or disable certain behavior within the protocol modules
(for example, turn on debugging) while others may be used to set protocol-specific information
(for example, IP time-to-live on all the application’s outgoing packets). As each of the options is
introduced, its effect on the underlying protocol modules is described.
2581
Table 2-1 shows the value for the socket level.
2584
Table 2-1 Value of Level for Socket Options
_______________________________________________________
L
L
Name
Description
_L ______________________________________________________
L
L
L
SOL_SOCKET L Options are intended for the sockets level. L
______________________________________________________
L_
2585
2586
2587
2588
2589
Table 2-2 (on page 64) lists those options present at the socket level; that is, when the level
parameter of the getsockopt ( ) or setsockopt ( ) function is SOL_SOCKET, the types of the option
value parameters associated with each option, and a brief synopsis of the meaning of the option
value parameter. Unless otherwise noted, each may be examined with getsockopt ( ) and set with
setsockopt ( ) on all types of socket.
2582
2583
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
63
Sockets
General Information
Table 2-2 Socket-Level Options
__________________________________________________________________________________
L
L
L
Option
Parameter Type LL
Parameter Meaning
_________________________________________________________________________________
L
L
L_
L SO_BROADCAST
L
L
L
int
Non-zero requests permission to transmit
L
L
L
L
broadcast datagrams (SOCK_DGRAM sockets
L
L
L
L
only).
L
L
L
L
int
Non-zero requests debugging in underlying
L SO_DEBUG
L
L
L
L
L
L
L
protocol modules.
L
L
L
L
SO_DONTROUTE L int
Non-zero requests bypass of normal routing;
L
L
L
route based on destination address only.
L
L
L
L
L SO_ERROR
L
L
L
int
Requests and clears pending error information
L
L
L
L
on the socket (getsockopt ( ) only).
L
L
L
L
SO_KEEPALIVE
int
Non-zero requests periodic transmission of
L
L
L
L
keepalive messages (protocol-specific).
L
L
L
L
L
L
L
L
SO_LINGER
struct linger
Specify actions to be taken for queued, unsent
L
L
L
data on close( ): linger on/off and linger time in L
L
L
L
L
seconds.
L
L
L
L
L SO_OOBINLINE
L
L
L
int
Non-zero requests that out-of-band data be
L
L
L
placed into normal data input queue as received. L
L
L
L
L
SO_RCVBUF
int
Size of receive buffer (in bytes).
L
L
L
L
int
Minimum amount of data to return to
L SO_RCVLOWAT
L
L
L
L
L
L
L
application for input operations (in bytes).
L
L
L
L
SO_RCVTIMEO
struct timeval
Timeout value for a socket receive operation.
L
L
L
L
int
Non-zero requests reuse of local addresses in
L SO_REUSEADDR
L
L
L
L
L
L
L
bind( ) (protocol-specific).
L
L
L
L
SO_SNDBUF
int
Size of send buffer (in bytes).
L
L
L
L
int
Minimum amount of data to send for output
L SO_SNDLOWAT
L
L
L
L
L
L
L
operations (in bytes).
L
L
L
L
SO_SNDTIMEO
struct timeval
Timeout value for a socket send operation.
L
L
L
L
int
Identify socket type (getsockopt ( ) only).
L SO_TYPE
L
L
L
_________________________________________________________________________________
L
L
L
L_
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
The SO_BROADCAST option requests permission to send broadcast datagrams on the socket.
Support for SO_BROADCAST is protocol-specific. The default for SO_BROADCAST is that the
ability to send broadcast datagrams on a socket is disabled.
2623
2624
2625
2626
The SO_DEBUG option enables debugging in the underlying protocol modules. This can be
useful for tracing the behavior of the underlying protocol modules during normal system
operation. The semantics of the debug reports are implementation-defined. The default value for
SO_DEBUG is for debugging to be turned off.
2627
2628
2629
2630
2631
The SO_DONTROUTE option requests that outgoing messages bypass the standard routing
facilities. The destination must be on a directly-connected network, and messages are directed to
the appropriate network interface according to the destination address. It is protocol-specific
whether this option has any effect and how the outgoing network interface is chosen. Support
for this option with each protocol is implementation-defined.
2632
2633
2634
2635
2636
The SO_ERROR option is used only on getsockopt ( ). When this option is specified, getsockopt ( )
shall return any pending error on the socket and clear the error status. It shall return a value of 0
if there is no pending error. SO_ERROR may be used to check for asynchronous errors on
connected connectionless-mode sockets or for other types of asynchronous errors. SO_ERROR
has no default value.
64
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Sockets
2637
2638
2639
The SO_KEEPALIVE option enables the periodic transmission of messages on a connected
socket. The behavior of this option is protocol-specific. The default value for SO_KEEPALIVE is
zero, specifying that this capability is turned off.
2640
2641
2642
2643
The SO_LINGER option controls the action of the interface when unsent messages are queued
on a socket and a close( ) is performed. The details of this option are protocol-specific. The
default value for SO_LINGER is zero, or off, for the l_onoff element of the option value and zero
seconds for the linger time specified by the l_linger element.
2644
2645
2646
2647
2648
The SO_OOBINLINE option is valid only on protocols that support out-of-band data. The
SO_OOBINLINE option requests that out-of-band data be placed in the normal data input queue
as received; it is then accessible using the read( ) or recv( ) functions without the MSG_OOB flag
set. The default for SO_OOBINLINE is off; that is, for out-of-band data not to be placed in the
normal data input queue.
2649
2650
2651
2652
2653
The SO_RCVBUF option requests that the buffer space allocated for receive operations on this
socket be set to the value, in bytes, of the option value. Applications may wish to increase buffer
size for high volume connections, or may decrease buffer size to limit the possible backlog of
incoming data. The default value for the SO_RCVBUF option value is implementation-defined,
and may vary by protocol.
2654
2655
The maximum value for the option for a socket may be obtained by the use of the fpathconf ( )
function, using the value _PC_SOCK_MAXBUF.
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
The SO_RCVLOWAT option sets the minimum number of bytes to process for socket input
operations. In general, receive calls block until any (non-zero) amount of data is received, then
return the smaller of the amount available or the amount requested. The default value for
SO_RCVLOWAT is 1, and does not affect the general case. If SO_RCVLOWAT is set to a larger
value, blocking receive calls normally wait until they have received the smaller of the low water
mark value or the requested amount. Receive calls may still return less than the low water mark
if an error occurs, a signal is caught, or the type of data next in the receive queue is different
from that returned (for example, out-of-band data). As mentioned previously, the default value
for SO_RCVLOWAT is 1 byte. It is implementation-defined whether the SO_RCVLOWAT option
can be set.
2666
2667
2668
2669
2670
2671
2672
The SO_RCVTIMEO option is an option to set a timeout value for input operations. It accepts a
timeval structure with the number of seconds and microseconds specifying the limit on how
long to wait for an input operation to complete. If a receive operation has blocked for this much
time without receiving additional data, it shall return with a partial count or errno shall be set to
[EWOULDBLOCK] if no data were received. The default for this option is the value zero, which
indicates that a receive operation will not time out. It is implementation-defined whether the
SO_RCVTIMEO option can be set.
2673
2674
2675
The SO_REUSEADDR option indicates that the rules used in validating addresses supplied in a
bind( ) should allow reuse of local addresses. Operation of this option is protocol-specific. The
default value for SO_REUSEADDR is off; that is, reuse of local addresses is not permitted.
2676
2677
2678
2679
2680
The SO_SNDBUF option requests that the buffer space allocated for send operations on this
socket be set to the value, in bytes, of the option value. The default value for the SO_SNDBUF
option value is implementation-defined, and may vary by protocol. The maximum value for the
option for a socket may be obtained by the use of the fpathconf ( ) function, using the value
_PC_SOCK_MAXBUF.
2681
The SO_SNDLOWAT option sets the minimum number of bytes to process for socket output
operations. Most output operations process all of the data supplied by the call, delivering data to
the protocol for transmission and blocking as necessary for flow control. Non-blocking output
operations process as much data as permitted subject to flow control without blocking, but
2682
2683
2684
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
65
Sockets
General Information
2685
2686
2687
2688
2689
process no data if flow control does not allow the smaller of the send low water mark value or
the entire request to be processed. A select( ) operation testing the ability to write to a socket shall
return true only if the send low water mark could be processed. The default value for
SO_SNDLOWAT is implementation-defined and protocol-specific. It is implementation-defined
whether the SO_SNDLOWAT option can be set.
2690
2691
2692
2693
2694
2695
2696
2697
The SO_SNDTIMEO option is an option to set a timeout value for the amount of time that an
output function shall block because flow control prevents data from being sent. As noted in
Table 2-2 (on page 64), the option value is a timeval structure with the number of seconds and
microseconds specifying the limit on how long to wait for an output operation to complete. If a
send operation has blocked for this much time, it shall return with a partial count or errno set to
[EWOULDBLOCK] if no data were sent. The default for this option is the value zero, which
indicates that a send operation will not time out. It is implementation-defined whether the
SO_SNDTIMEO option can be set.
2698
2699
2700
The SO_TYPE option is used only on getsockopt ( ). When this option is specified, getsockopt ( )
shall return the type of the socket (for example, SOCK_STREAM). This option is useful to
servers that inherit sockets on start-up. SO_TYPE has no default value.
2701
2.10.17 Use of Sockets for Local UNIX Connections
2702
Support for UNIX domain sockets is mandatory.
2703
UNIX domain sockets provide process-to-process communication in a single system.
2704
2.10.17.1 Headers
2705
2706
2707
2708
The symbolic constant AF_UNIX defined in the <sys/socket.h> header is used to identify the
UNIX domain address family. The <sys/un.h> header contains other definitions used in
connection with UNIX domain sockets. See the Base Definitions volume of IEEE Std 1003.1-2001,
Chapter 13, Headers.
2709
2710
2711
2712
2713
2714
2715
The sockaddr_storage structure defined in <sys/socket.h> shall be large enough to
accommodate a sockaddr_un structure (see the <sys/un.h> header defined in the Base
Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers) and shall be aligned at an
appropriate boundary so that pointers to it can be cast as pointers to sockaddr_un structures
and used to access the fields of those structures without alignment problems. When a
sockaddr_storage structure is cast as a sockaddr_un structure, the ss_family field maps onto the
sun_family field.
2716
2.10.18 Use of Sockets over Internet Protocols
2717
2718
When a socket is created in the Internet family with a protocol value of zero, the implementation
shall use the protocol listed below for the type of socket created.
2719
SOCK_STREAM
IPPROTO_TCP.
2720
SOCK_DGRAM
IPPROTO_UDP.
SOCK_RAW
IPPROTO_RAW.
2721
RS
SOCK_SEQPACKET Unspecified.
2722
2723
2724
2725
2726
2727
RS
66
A raw interface to IP is available by creating an Internet socket of type SOCK_RAW. The default
protocol for type SOCK_RAW shall be identified in the IP header with the value
IPPROTO_RAW. Applications should not use the default protocol when creating a socket with
type SOCK_RAW, but should identify a specific protocol by value. The ICMP control protocol is
accessible from a raw socket by specifying a value of IPPROTO_ICMP for protocol.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
2728
2.10.19 Use of Sockets over Internet Protocols Based on IPv4
Support for sockets over Internet protocols based on IPv4 is mandatory.
2729
2730
Sockets
2.10.19.1 Headers
2731
2732
2733
2734
The symbolic constant AF_INET defined in the <sys/socket.h> header is used to identify the
IPv4 Internet address family. The <netinet/in.h> header contains other definitions used in
connection with IPv4 Internet sockets. See the Base Definitions volume of IEEE Std 1003.1-2001,
Chapter 13, Headers.
2735
2736
2737
2738
2739
2740
2741
The sockaddr_storage structure defined in <sys/socket.h> shall be large enough to
accommodate a sockaddr_in structure (see the <netinet/in.h> header defined in the Base
Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers) and shall be aligned at an
appropriate boundary so that pointers to it can be cast as pointers to sockaddr_in structures and
used to access the fields of those structures without alignment problems. When a
sockaddr_storage structure is cast as a sockaddr_in structure, the ss_family field maps onto the
sin_family field.
2742
2.10.20 Use of Sockets over Internet Protocols Based on IPv6
2743
2744
2745
IP6
2746
2747
2748
This section describes extensions to support sockets over Internet protocols based on IPv6. This
functionality is dependent on support of the IPV6 option (and the rest of this section is not
further shaded for this option).
To enable smooth transition from IPv4 to IPv6, the features defined in this section may, in certain
circumstances, also be used in connection with IPv4; see Section 2.10.20.2 (on page 68).
2.10.20.1 Addressing
2749
2750
IPv6 overcomes the addressing limitations of previous versions by using 128-bit addresses
instead of 32-bit addresses. The IPv6 address architecture is described in RFC 2373.
2751
There are three kinds of IPv6 address:
2752
2753
Unicast
Identifies a single interface.
2754
2755
2756
A unicast address can be global, link-local (designed for use on a single link), or site-local
(designed for systems not connected to the Internet). Link-local and site-local addresses
need not be globally unique.
2757
2758
2759
Anycast
Identifies a set of interfaces such that a packet sent to the address can be delivered to any
member of the set.
2760
2761
An anycast address is similar to a unicast address; the nodes to which an anycast address is
assigned must be explicitly configured to know that it is an anycast address.
2762
2763
2764
Multicast
Identifies a set of interfaces such that a packet sent to the address should be delivered to
every member of the set.
2765
2766
2767
2768
2769
2770
An application can send multicast datagrams by simply specifying an IPv6 multicast
address in the address argument of sendto( ). To receive multicast datagrams, an application
must join the multicast group (using setsockopt ( ) with IPV6_JOIN_GROUP) and must bind
to the socket the UDP port on which datagrams will be received. Some applications should
also bind the multicast group address to the socket, to prevent other datagrams destined to
that port from being delivered to the socket.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
67
Sockets
General Information
A multicast address can be global, node-local, link-local, site-local, or organization-local.
2771
2772
The following special IPv6 addresses are defined:
2773
2774
2775
Unspecified
An address that is not assigned to any interface and is used to indicate the absence of an
address.
2776
2777
2778
Loopback
A unicast address that is not assigned to any interface and can be used by a node to send
packets to itself.
2779
Two sets of IPv6 addresses are defined to correspond to IPv4 addresses:
2780
2781
2782
IPv4-compatible addresses
These are assigned to nodes that support IPv6 and can be used when traffic is ‘‘tunneled’’
through IPv4.
2783
2784
IPv4-mapped addresses
These are used to represent IPv4 addresses in IPv6 address format; see Section 2.10.20.2.
2785
2786
Note that the unspecified address and the loopback address must not be treated as IPv4compatible addresses.
2787
2.10.20.2 Compatibility with IPv4
2788
2789
2790
The API provides the ability for IPv6 applications to interoperate with applications using IPv4,
by using IPv4-mapped IPv6 addresses. These addresses can be generated automatically by the
getaddrinfo ( ) function when the specified host has only IPv4 addresses.
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
Applications can use AF_INET6 sockets to open TCP connections to IPv4 nodes, or send UDP
packets to IPv4 nodes, by simply encoding the destination’s IPv4 address as an IPv4-mapped
IPv6 address, and passing that address, within a sockaddr_in6 structure, in the connect( ),
sendto( ), or sendmsg( ) function. When applications use AF_INET6 sockets to accept TCP
connections from IPv4 nodes, or receive UDP packets from IPv4 nodes, the system shall return
the peer’s address to the application in the accept( ), recvfrom( ), recvmsg( ), or getpeername( )
function using a sockaddr_in6 structure encoded this way. If a node has an IPv4 address, then
the implementation shall allow applications to communicate using that address via an
AF_INET6 socket. In such a case, the address will be represented at the API by the
corresponding IPv4-mapped IPv6 address. Also, the implementation may allow an AF_INET6
socket bound to in6addr_any to receive inbound connections and packets destined to one of the
node’s IPv4 addresses.
2803
2804
2805
2806
An application can use AF_INET6 sockets to bind to a node’s IPv4 address by specifying the
address as an IPv4-mapped IPv6 address in a sockaddr_in6 structure in the bind( ) function. For
an AF_INET6 socket bound to a node’s IPv4 address, the system shall return the address in the
getsockname( ) function as an IPv4-mapped IPv6 address in a sockaddr_in6 structure.
2807
2.10.20.3 Interface Identification
Each local interface is assigned a unique positive integer as a numeric index. Indexes start at 1;
zero is not used. There may be gaps so that there is no current interface for a particular positive
index. Each interface also has a unique implementation-defined name.
2808
2809
2810
68
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
2811
Sockets
2.10.20.4 Options
2812
The following options apply at the IPPROTO_IPV6 level:
2813
2814
2815
2816
2817
2818
IPV6_JOIN_GROUP
When set via setsockopt ( ), it joins the application to a multicast group on an interface
(identified by its index) and addressed by a given multicast address, enabling packets sent
to that address to be read via the socket. If the interface index is specified as zero, the
system selects the interface (for example, by looking up the address in a routing table and
using the resulting interface).
2819
An attempt to read this option using getsockopt ( ) shall result in an [EOPNOTSUPP] error.
2820
The parameter type of this option is a pointer to an ipv6_mreq structure.
2821
2822
2823
IPV6_LEAVE_GROUP
When set via setsockopt ( ), it removes the application from the multicast group on an
interface (identified by its index) and addressed by a given multicast address.
2824
An attempt to read this option using getsockopt ( ) shall result in an [EOPNOTSUPP] error.
2825
The parameter type of this option is a pointer to an ipv6_mreq structure.
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
IPV6_MULTICAST_HOPS
The value of this option is the hop limit for outgoing multicast IPv6 packets sent via the
socket. Its possible values are the same as those of IPV6_UNICAST_HOPS. If the
IPV6_MULTICAST_HOPS option is not set, a value of 1 is assumed. This option can be set
via setsockopt ( ) and read via getsockopt ( ).
The parameter type of this option is a pointer to an int. (Default value: 1)
IPV6_MULTICAST_IF
The index of the interface to be used for outgoing multicast packets. It can be set via
setsockopt ( ) and read via getsockopt ( ). If the interface index is specified as zero, the system
selects the interface (for example, by looking up the address in a routing table and using the
resulting interface).
The parameter type of this option is a pointer to an unsigned int. (Default value: 0)
2838
2839
2840
2841
2842
IPV6_MULTICAST_LOOP
This option controls whether outgoing multicast packets should be delivered back to the
local application when the sending interface is itself a member of the destination multicast
group. If it is set to 1 they are delivered. If it is set to 0 they are not. Other values result in an
[EINVAL] error. This option can be set via setsockopt ( ) and read via getsockopt ( ).
2843
2844
The parameter type of this option is a pointer to an unsigned int which is used as a Boolean
value. (Default value: 1)
2845
2846
2847
2848
2849
IPV6_UNICAST_HOPS
The value of this option is the hop limit for outgoing unicast IPv6 packets sent via the
socket. If the option is not set, or is set to −1, the system selects a default value. Attempts to
set a value less than −1 or greater than 255 shall result in an [EINVAL] error. This option can
be set via setsockopt ( ) and read via getsockopt ( ).
2850
2851
2852
2853
2854
The parameter type of this option is a pointer to an int. (Default value: Unspecified)
IPV6_V6ONLY
This socket option restricts AF_INET6 sockets to IPv6 communications only. AF_INET6
sockets may be used for both IPv4 and IPv6 communications. Some applications may want
to restrict their use of an AF_INET6 socket to IPv6 communications only. For these
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
69
Sockets
General Information
2855
2856
2857
applications, the IPv6_V6ONLY socket option is defined. When this option is turned on, the
socket can be used to send and receive IPv6 packets only. This is an IPPROTO_IPV6-level
option.
2858
2859
The parameter type of this option is a pointer to an int which is used as a Boolean value.
(Default value: 0)
2860
2861
An [EOPNOTSUPP] error shall result if IPV6_JOIN_GROUP or IPV6_LEAVE_GROUP is used
with getsockopt ( ).
2862
2.10.20.5 Headers
2863
2864
2865
The symbolic constant AF_INET6 is defined in the <sys/socket.h> header to identify the IPv6
Internet address family. See the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 13,
Headers.
2866
2867
2868
2869
2870
2871
2872
The sockaddr_storage structure defined in <sys/socket.h> shall be large enough to
accommodate a sockaddr_in6 structure (see the <netinet/in.h> header defined in the Base
Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers) and shall be aligned at an
appropriate boundary so that pointers to it can be cast as pointers to sockaddr_in6 structures
and used to access the fields of those structures without alignment problems. When a
sockaddr_storage structure is cast as a sockaddr_in6 structure, the ss_family field maps onto the
sin6_family field.
2873
2874
2875
The <netinet/in.h>, <arpa/inet.h>, and <netdb.h> headers contain other definitions used in
connection with IPv6 Internet sockets; see the Base Definitions volume of IEEE Std 1003.1-2001,
Chapter 13, Headers.
2876
2877
2878
2879
2.11
Tracing
TRC
This section describes extensions to support tracing of user applications. This functionality is
dependent on support of the Trace option (and the rest of this section is not further shaded for
this option).
2880
2881
2882
The tracing facilities defined in IEEE Std 1003.1-2001 allow a process to select a set of trace event
types, to activate a trace stream of the selected trace events as they occur in the flow of
execution, and to retrieve the recorded trace events.
2883
2884
2885
2886
2887
The tracing operation relies on three logically different components: the traced process, the
controller process, and the analyzer process. During the execution of the traced process, when a
trace point is reached, a trace event is recorded into the trace streams created for that process in
which the associated trace event type identifier is not being filtered out. The controller process
controls the operation of recording the trace events into the trace stream. It shall be able to:
2888
•
Initialize the attributes of a trace stream
2889
•
Create the trace stream (for a specified traced process) using those attributes
2890
•
Start and stop tracing for the trace stream
2891
•
Filter the type of trace events to be recorded, if the Trace Event Filter option is supported
2892
•
Shut a trace stream down
These operations can be done for an active trace stream. The analyzer process retrieves the
traced events either at runtime, when the trace stream has not yet been shut down, but is still
recording trace events; or after opening a trace log that had been previously recorded and shut
down. These three logically different operations can be performed by the same process, or can be
2893
2894
2895
2896
70
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Tracing
2897
distributed into different processes.
2898
2899
2900
2901
A trace stream identifier can be created by a call to posix_trace_create( ),
posix_trace_create_withlog( ),
or
posix_trace_open( ).
The
posix_trace_create( )
and
posix_trace_create_withlog( ) functions should be used by a controller process. The
posix_trace_open( ) should be used by an analyzer process.
2902
2903
2904
2905
2906
The tracing functions can serve different purposes. One purpose is debugging the possibly preinstrumented code, while another is post-mortem fault analysis. These two potential uses differ
in that the first requires pre-filtering capabilities to avoid overwhelming the trace stream and
permits focusing on expected information; while the second needs comprehensive trace
capabilities in order to be able to record all types of information.
2907
The events to be traced belong to two classes:
2908
1. User trace events (generated by the application instrumentation)
2909
2. System trace events (generated by the operating system)
2910
2911
2912
2913
2914
The trace interface defines several system trace event types associated with control of and
operation of the trace stream. This small set of system trace events includes the minimum
required to interpret correctly the trace event information present in the stream. Other desirable
system trace events for some particular application profile may be implemented and are
encouraged; for example, process and thread scheduling, signal occurrence, and so on.
2915
2916
2917
2918
2919
2920
2921
2922
Each traced process shall have a mapping of the trace event names to trace event type identifiers
that have been defined for that process. Each active trace stream shall have a mapping that
incorporates all the trace event type identifiers predefined by the trace system plus all the
mappings of trace event names to trace event type identifiers of the processes that are being
traced into that trace stream. These mappings are defined from the instrumented application by
calling the posix_trace_eventid_open( ) function and from the controller process by calling the
posix_trace_trid_eventid_open( ) function. For a pre-recorded trace stream, the list of trace event
types is obtained from the pre-recorded trace log.
2923
2924
The st_ctime and st_mtime fields of a file associated with an active trace stream shall be marked
for update every time any of the tracing operations modifies that file.
2925
2926
The st_atime field of a file associated with a trace stream shall be marked for update every time
any of the tracing operations causes data to be read from that file.
2927
2928
2929
Results are undefined if the application performs any operation on a file descriptor associated
with an active or pre-recorded trace stream until posix_trace_shutdown( ) or posix_trace_close( ) is
called for that trace stream.
2930
2931
2932
The main purpose of this option is to define a complete set of functions and concepts that allow
a conforming application to be traced from creation to termination, whatever its realtime
constraints and properties.
2933
2.11.1
2934
2.11.1.1 Structures
2935
2936
Tracing Data Definitions
The <trace.h> header shall define the posix_trace_status_info and posix_trace_event_info structures
described below. Implementations may add extensions to these structures.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
71
Tracing
General Information
2937
posix_trace_status_info Structure
2938
2939
2940
To facilitate control of a trace stream, information about the current state of an active trace
stream can be obtained dynamically. This structure is returned by a call to the
posix_trace_get_status( ) function.
2941
2942
The posix_trace_status_info structure defined in <trace.h> shall contain at least the following
members:
________________________________________________________________________________
L Member Type
L
L
L
Member Name
Description
________________________________________________________________________________
L
L
L
L
int
posix_stream_status
The operating mode of the trace stream. L
L
L
L
int
posix_stream_full_status
The full status of the trace stream.
L
L
L
L
posix_stream_overrun_status L Indicates whether trace events were
L int
L
L
L
L
L
L
lost
in
the
trace
stream.
_______________________________________________________________________________
L
L
L
L_
2943
2944
2945
2946
2947
2948
2958
If the Trace Log option is supported in addition to the Trace option, the posix_trace_status_info
structure defined in <trace.h> shall contain at least the following additional members:
_____________________________________________________________________________
L
L
L
L Member Type
Member Name
Description
_____________________________________________________________________________
L
L
L
L
int
posix_stream_flush_status L Indicates whether a flush is in progress. L
L
L
int
posix_stream_flush_error L Indicates whether any error occurred
L
L
L
during the last flush operation.
L
L
L
L
L
L
L
int
posix_log_overrun_status L Indicates whether trace events were
L
L
L
L
lost
in
the
trace
log.
L
L
L
L
int
posix_log_full_status
The full status of the trace log.
LL
L_____________________________________________________________________________
LL
LL
L
2959
2960
The posix_stream_status member indicates the operating mode of the trace stream and shall have
one of the following values defined by manifest constants in the <trace.h> header:
2961
2962
POSIX_TRACE_RUNNING
Tracing is in progress; that is, the trace stream is accepting trace events.
2963
2964
2965
2966
POSIX_TRACE_SUSPENDED
The trace stream is not accepting trace events. The tracing operation has not yet started or
has stopped, either following a posix_trace_stop( ) function call or because the trace resources
are exhausted.
2967
2968
The posix_stream_full_status member indicates the full status of the trace stream, and it shall have
one of the following values defined by manifest constants in the <trace.h> header:
2969
2970
POSIX_TRACE_FULL
The space in the trace stream for trace events is exhausted.
2971
2972
POSIX_TRACE_NOT_FULL
There is still space available in the trace stream.
2973
2974
The combination of the posix_stream_status and posix_stream_full_status members also indicates
the actual status of the stream. The status shall be interpreted as follows:
2975
2976
2977
POSIX_TRACE_RUNNING and POSIX_TRACE_NOT_FULL
This status combination indicates that tracing is in progress, and there is space available for
recording more trace events.
2978
2979
2980
POSIX_TRACE_RUNNING and POSIX_TRACE_FULL
This status combination indicates that tracing is in progress and that the trace stream is full
of trace events. This status combination cannot occur unless the stream-full-policy is set to
2949
2950
2951
2952
2953
2954
2955
2956
2957
72
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Tracing
2981
2982
2983
POSIX_TRACE_LOOP. The trace stream contains trace events recorded during a moving
time window of prior trace events, and some older trace events may have been overwritten
and thus lost.
2984
2985
2986
POSIX_TRACE_SUSPENDED and POSIX_TRACE_NOT_FULL
This status combination indicates that tracing has not yet been started, has been stopped by
the posix_trace_stop( ) function, or has been cleared by the posix_trace_clear( ) function.
2987
2988
2989
2990
2991
POSIX_TRACE_SUSPENDED and POSIX_TRACE_FULL
This status combination indicates that tracing has been stopped by the implementation
because the stream-full-policy attribute was POSIX_TRACE_UNTIL_FULL and trace
resources were exhausted, or that the trace stream was stopped by the function
posix_trace_stop( ) at a time when trace resources were exhausted.
2992
2993
2994
The posix_stream_overrun_status member indicates whether trace events were lost in the trace
stream, and shall have one of the following values defined by manifest constants in the
<trace.h> header:
2995
2996
POSIX_TRACE_OVERRUN
At least one trace event was lost and thus was not recorded in the trace stream.
2997
2998
POSIX_TRACE_NO_OVERRUN
No trace events were lost.
2999
3000
When the corresponding trace stream is created, the posix_stream_overrun_status member shall be
set to POSIX_TRACE_NO_OVERRUN.
3001
3002
Whenever an overrun occurs, the posix_stream_overrun_status member shall be set to
POSIX_TRACE_OVERRUN.
3003
An overrun occurs when:
3004
•
The policy is POSIX_TRACE_LOOP and a recorded trace event is overwritten.
3005
3006
•
The policy is POSIX_TRACE_UNTIL_FULL and the trace stream is full when a trace event is
generated.
3007
3008
•
If the Trace Log option is supported, the policy is POSIX_TRACE_FLUSH and at least one
trace event is lost while flushing the trace stream to the trace log.
3009
The posix_stream_overrun_status member is reset to zero after its value is read.
3010
3011
3012
If the Trace Log option is supported in addition to the Trace option, the posix_stream_flush_status,
posix_stream_flush_error, posix_log_overrun_status, and posix_log_full_status members are defined
as follows; otherwise, they are undefined.
3013
3014
3015
The posix_stream_flush_status member indicates whether a flush operation is being performed
and shall have one of the following values defined by manifest constants in the header
<trace.h>:
3016
3017
POSIX_TRACE_FLUSHING
The trace stream is currently being flushed to the trace log.
3018
3019
POSIX_TRACE_NOT_FLUSHING
No flush operation is in progress.
3020
3021
The posix_stream_flush_status member shall be set to POSIX_TRACE_FLUSHING if a flush
operation is in progress either due to a call to the posix_trace_flush( ) function (explicit or caused
by a trace stream shutdown operation) or because the trace stream has become full with the
stream-full-policy attribute set to POSIX_TRACE_FLUSH. The posix_stream_flush_status member
shall be set to POSIX_TRACE_NOT_FLUSHING if no flush operation is in progress.
3022
3023
3024
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
73
Tracing
General Information
3025
3026
3027
3028
3029
The posix_stream_flush_error member shall be set to zero if no error occurred during flushing. If
an error occurred during a previous flushing operation, the posix_stream_flush_error member
shall be set to the value of the first error that occurred. If more than one error occurs while
flushing, error values after the first shall be discarded. The posix_stream_flush_error member is
reset to zero after its value is read.
3030
3031
3032
The posix_log_overrun_status member indicates whether trace events were lost in the trace log,
and shall have one of the following values defined by manifest constants in the <trace.h>
header:
3033
3034
POSIX_TRACE_OVERRUN
At least one trace event was lost.
3035
3036
POSIX_TRACE_NO_OVERRUN
No trace events were lost.
3037
3038
3039
3040
When the corresponding trace stream is created, the posix_log_overrun_status member shall be set
to POSIX_TRACE_NO_OVERRUN. Whenever an overrun occurs, this status shall be set to
POSIX_TRACE_OVERRUN. The posix_log_overrun_status member is reset to zero after its value
is read.
3041
3042
The posix_log_full_status member indicates the full status of the trace log, and it shall have one of
the following values defined by manifest constants in the <trace.h> header:
3043
3044
POSIX_TRACE_FULL
The space in the trace log is exhausted.
3045
3046
POSIX_TRACE_NOT_FULL
There is still space available in the trace log.
3047
3048
The posix_log_full_status member is only meaningful if the log-full-policy attribute is either
POSIX_TRACE_UNTIL_FULL or POSIX_TRACE_LOOP.
3049
3050
3051
For an active trace stream without log, that is created by the posix_trace_create( ) function, the
posix_log_overrun_status member shall be set to POSIX_TRACE_NO_OVERRUN and the
posix_log_full_status member shall be set to POSIX_TRACE_NOT_FULL.
3052
posix_trace_event_info Structure
3053
3054
3055
The trace event structure posix_trace_event_info contains the information for one recorded
trace event. This structure is returned by the set of functions posix_trace_getnext_event( ),
posix_trace_timedgetnext_event( ), and posix_trace_trygetnext_event( ).
3056
3057
3065
The posix_trace_event_info structure defined in <trace.h> shall contain at least the following
members:
_ __________________________________________________________________________________
L
L
L
Member Type L
Member Name
Description
_ __________________________________________________________________________________
L
L
L
L
trace_event_id_t L posix_event_id
Trace event type identification.
L
L
L
pid_t
posix_pid
Process ID of the process that generated the
L
L
L
L
trace event.
L
L
L
L
L
L
L
void *
posix_prog_address
Address at which the trace point was invoked. L
L
L
L
L
int
posix_truncation_status L Status about the truncation of the data
L
L
L
associated with this trace event.
L
L
L
L
L struct timespec
L
L
posix_timestamp
Time at which the trace event was generated. LL
L_ __________________________________________________________________________________
L
L
3066
3067
3068
In addition, if the Trace option and the Threads option are both supported, the
posix_trace_event_info structure defined in <trace.h> shall contain the following additional
member:
3058
3059
3060
3061
3062
3063
3064
74
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Tracing
_______________________________________________________
L Member Type
L
L
Member Name L
Description
_______________________________________________________
L
L
L
L
pthread_t
posix_thread_id L Thread ID of the thread L
L
L
that generated the trace L
L
L
L
event.
L
L
L
L
_______________________________________________________
L
L
L
L
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
The posix_event_id member represents the identification of the trace event type and its value is
not directly defined by the user. This identification is returned by a call to one of the following
functions:
posix_trace_trid_eventid_open( ),
posix_trace_eventtypelist_getnext_id( ),
or
posix_trace_eventid_open( ). The name of the trace event type can be obtained by calling
posix_trace_eventid_get_name( ).
3079
3080
3081
The posix_pid is the process identifier of the traced process which generated the trace event. If
the posix_event_id member is one of the implementation-defined system trace events and that
trace event is not associated with any process, the posix_pid member shall be set to zero.
3082
3083
3084
3085
3086
For a user trace event, the posix_prog_address member is the process mapped address of the point
at which the associated call to the posix_trace_event( ) function was made. For a system trace
event, if the trace event is caused by a system service explicitly called by the application, the
posix_prog_address member shall be the address of the process at the point where the call to that
system service was made.
3087
3088
3089
3090
3091
The posix_truncation_status member defines whether the data associated with a trace event has
been truncated at the time the trace event was generated, or at the time the trace event was read
from the trace stream, or (if the Trace Log option is supported) from the trace log (see the event
argument from the posix_trace_getnext_event( ) function). The posix_truncation_status member
shall have one of the following values defined by manifest constants in the <trace.h> header:
3092
3093
POSIX_TRACE_NOT_TRUNCATED
All the traced data is available.
3094
3095
POSIX_TRACE_TRUNCATED_RECORD
Data was truncated at the time the trace event was generated.
3096
3097
3098
3099
POSIX_TRACE_TRUNCATED_READ
Data was truncated at the time the trace event was read from a trace stream or a trace log
because the reader’s buffer was too small. This truncation status overrides the
POSIX_TRACE_TRUNCATED_RECORD status.
3100
3101
3102
The posix_timestamp member shall be the time at which the trace event was generated. The clock
used is implementation-defined, but the resolution of this clock can be retrieved by a call to the
posix_trace_attr_getclockres( ) function.
3103
If the Threads option is supported in addition to the Trace option:
3104
3105
3106
3107
3108
3109
3110
3111
•
The posix_thread_id member is the identifier of the thread that generated the trace event. If
the posix_event_id member is one of the implementation-defined system trace events and that
trace event is not associated with any thread, the posix_thread_id member shall be set to zero.
Otherwise, this member is undefined.
2.11.1.2 Trace Stream Attributes
Trace streams have attributes that compose the posix_trace_attr_t trace stream attributes object.
This object shall contain at least the following attributes:
•
The generation-version attribute identifies the origin and version of the trace system.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
75
Tracing
General Information
3112
3113
•
The trace-name attribute is a character string defined by the trace controller, and that
identifies the trace stream.
3114
•
The creation-time attribute represents the time of the creation of the trace stream.
3115
3116
•
The clock-resolution attribute defines the clock resolution of the clock used to generate
timestamps.
3117
3118
•
The stream-min-size attribute defines the minimum size in bytes of the trace stream strictly
reserved for the trace events.
3119
3120
•
The stream-full-policy attribute defines the policy followed when the trace stream is full; its
value is POSIX_TRACE_LOOP, POSIX_TRACE_UNTIL_FULL, or POSIX_TRACE_FLUSH.
3121
•
The max-data-size attribute defines the maximum record size in bytes of a trace event.
In addition, if the Trace option and the Trace Inherit option are both supported, the
posix_trace_attr_t trace stream creation attributes object shall contain at least the following
attributes:
3122
3123
3124
•
3125
3126
3127
The inheritance attribute specifies whether a newly created trace stream will inherit tracing in
its parent’s process trace stream. It is either POSIX_TRACE_INHERITED or
POSIX_TRACE_CLOSE_FOR_CHILD.
In addition, if the Trace option and the Trace Log option are both supported, the
posix_trace_attr_t trace stream creation attributes object shall contain at least the following
attribute:
3128
3129
3130
3131
3132
3133
3134
•
If the file type corresponding to the trace log supports the POSIX_TRACE_LOOP or the
POSIX_TRACE_UNTIL_FULL policies, the log-max-size attribute defines the maximum size
in bytes of the trace log associated with an active trace stream. Other stream data—for
example, trace attribute values—shall not be included in this size.
3135
3136
3137
•
The log-full-policy attribute defines the policy of a trace log associated with an active trace
stream
to
be
POSIX_TRACE_LOOP,
POSIX_TRACE_UNTIL_FULL,
or
POSIX_TRACE_APPEND.
3138
2.11.2
Trace Event Type Definitions
3139
2.11.2.1 System Trace Event Type Definitions
The following system trace event types, defined in the <trace.h> header, track the invocation of
the trace operations:
3140
3141
3142
•
POSIX_TRACE_START shall be associated with a trace start operation.
3143
•
POSIX_TRACE_STOP shall be associated with a trace stop operation.
3144
3145
•
If the Trace Event Filter option is supported, POSIX_TRACE_FILTER shall be associated with
a trace event type filter change operation.
The following system trace event types, defined in the <trace.h> header, report operational trace
events:
3146
3147
3148
•
POSIX_TRACE_OVERFLOW shall mark the beginning of a trace overflow condition.
3149
•
POSIX_TRACE_RESUME shall mark the end of a trace overflow condition.
3150
3151
•
If the Trace Log option is supported, POSIX_TRACE_FLUSH_START shall mark the
beginning of a flush operation.
76
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Tracing
3152
3153
•
If the Trace Log option is supported, POSIX_TRACE_FLUSH_STOP shall mark the end of a
flush operation.
3154
3155
•
If an implementation-defined trace error condition is reported, it shall be marked
POSIX_TRACE_ERROR.
3156
3157
3158
The interpretation of a trace stream or a trace log by a trace analyzer process relies on the
information recorded for each trace event, and also on system trace events that indicate the
invocation of trace control operations and trace system operational trace events.
3159
3160
The POSIX_TRACE_START and POSIX_TRACE_STOP trace events specify the time windows
during which the trace stream is running.
3161
3162
•
The POSIX_TRACE_STOP trace event with an associated data that is equal to zero indicates
a call of the function posix_trace_stop( ).
3163
3164
•
The POSIX_TRACE_STOP trace event with an associated data that is different from zero
indicates an automatic stop of the trace stream (see posix_trace_attr_getstreamfullpolicy( )).
3165
3166
The POSIX_TRACE_FILTER trace event indicates that a trace event type filter value changed
while the trace stream was running.
3167
3168
The POSIX_TRACE_ERROR serves to inform the analyzer process that an implementationdefined internal error of the trace system occurred.
3169
3170
3171
The POSIX_TRACE_OVERFLOW trace event shall be reported with a timestamp equal to the
timestamp of the first trace event overwritten. This is an indication that some generated trace
events have been lost.
3172
3173
3174
3175
The POSIX_TRACE_RESUME trace event shall be reported with a timestamp equal to the
timestamp of the first valid trace event reported after the overflow condition ends and shall be
reported before this first valid trace event. This is an indication that the trace system is reliably
recording trace events after an overflow condition.
3176
3177
Each of these trace event types shall be defined by a constant trace event name and a
trace_event_id_t constant; trace event data is associated with some of these trace events.
3178
3179
If the Trace option is supported and the Trace Event Filter option and the Trace Log option are
not supported, the following predefined system trace events in Table 2-3 shall be defined:
3180
3189
Table 2-3 Trace Option: System Trace Events
____________________________________________________________________
L
L
L
Event Name
Constant
Associated Data L
_ ________________
L
L
L
L
Data Type
_L ___________________________________________________________________
L
L
L
L posix_trace_error
L
POSIX_TRACE_ERROR
L
error
L
_ ________________
L
L
L
L
int
_L ___________________________________________________________________
L
L
L
posix_trace_start
POSIX_TRACE_START
None.
L_
L
L
L
___________________________________________________________________
L
L
L
posix_trace_stop
POSIX_TRACE_STOP
auto
_ ________________L
L
L
L
L
int
_L ___________________________________________________________________
L
L
L
L posix_trace_overflow
L
L
POSIX_TRACE_OVERFLOW L None.
____________________________________________________________________
L
L
L
L
posix_trace_resume L POSIX_TRACE_RESUME
None.
___________________________________________________________________
L
L
L_
3190
3191
3192
If the Trace option and the Trace Event Filter option are both supported, and if the Trace Log
option is not supported, the following predefined system trace events in Table 2-4 (on page 78)
shall be defined:
3181
3182
3183
3184
3185
3186
3187
3188
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
77
Tracing
General Information
3206
Table 2-4 Trace and Trace Event Filter Options: System Trace Events
_____________________________________________________________________
L
L
L
Event Name
Constant
Associated Data L
__________________
L
L
L
L
Data Type
____________________________________________________________________
L_
L
L
L
POSIX_TRACE_ERROR
error
L posix_trace_error
L
L
L
__________________
L
L
L
L
int
_L ____________________________________________________________________
L
L
L
POSIX_TRACE_START
event_filter
L posix_trace_start
L
L __________________
L
L
L
trace_event_set_t L
_L ____________________________________________________________________
L
L
L
L
posix_trace_stop
POSIX_TRACE_STOP
auto
L
L
L __________________L
L
L
L
int
_L ____________________________________________________________________
L
L
L
posix_trace_filter
POSIX_TRACE_FILTER
old_event_filter L
L
L
L
L
new_event_filter
L
L
L __________________L
L
L
trace_event_set_t L
_L ____________________________________________________________________
L
L
L
L
posix_trace_overflow
POSIX_TRACE_OVERFLOW
None.
_L ____________________________________________________________________
L
L
L
posix_trace_resume L POSIX_TRACE_RESUME
None.
____________________________________________________________________
L
L
L_
3207
3208
3209
If the Trace option and the Trace Log option are both supported, and if the Trace Event Filter
option is not supported, the following predefined system trace events in Table 2-5 shall be
defined:
3210
3221
Table 2-5 Trace and Trace Log Options: System Trace Events
________________________________________________________________________
L
L
L
Event Name
Constant
Associated Data L
_ ________________
L
L
L
L
Data Type
_L _______________________________________________________________________
L
L
L
L posix_trace_error
POSIX_TRACE_ERROR
error
L
L
_ ________________L
L
L
L
L
int
________________________________________________________________________
L
L
L
L
posix_trace_start
POSIX_TRACE_START
None.
L_
L
L
L
_______________________________________________________________________
L
L
L
L
posix_trace_stop
POSIX_TRACE_STOP
auto
_ ________________
L
L
L
L
int
_______________________________________________________________________
L_
L
L
L
L posix_trace_overflow
L
L
L
POSIX_TRACE_OVERFLOW
None.
________________________________________________________________________
L
L
L
L
posix_trace_resume
POSIX_TRACE_RESUME
None.
_L _______________________________________________________________________
L
L
L
posix_trace_flush_start L POSIX_TRACE_FLUSH_START L None.
L_
L
_______________________________________________________________________
L
L
L
L
posix_trace_flush_stop
POSIX_TRACE_FLUSH_STOP
None.
_______________________________________________________________________
L
L
L
L_
3222
3223
If the Trace option, the Trace Event Filter option, and the Trace Log option are all supported, the
following predefined system trace events in Table 2-6 (on page 79) shall be defined:
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
78
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
Table 2-6 Trace, Trace Log, and Trace Event Filter Options: System Trace Events
_________________________________________________________________________
L
L
L
Event Name
Constant
Associated Data L
__________________
L
L
L
L
Data Type
________________________________________________________________________
L_
L
L
L
L posix_trace_error
L
L
L
POSIX_TRACE_ERROR
error
__________________
L
L
L
L
int
_________________________________________________________________________
L
L
L
L
POSIX_TRACE_START
event_filter
L posix_trace_start
L
L __________________
L
L
L
L
trace_event_set_t L
_________________________________________________________________________
L
L
L
L
posix_trace_stop
POSIX_TRACE_STOP
auto
L
L
L __________________L
L
L
L
L
int
_________________________________________________________________________
L
L
L
posix_trace_filter
POSIX_TRACE_FILTER
old_event_filter L
L
L
L
L
new_event_filter
L
L
L __________________L
L
L
L
trace_event_set_t L
_________________________________________________________________________
L
L
L
L
posix_trace_overflow
POSIX_TRACE_OVERFLOW
None.
_L ________________________________________________________________________
L
L
L
posix_trace_resume
POSIX_TRACE_RESUME
None.
L_
L
L
L
________________________________________________________________________
L
L
L
posix_trace_flush_start
POSIX_TRACE_FLUSH_START
None.
_________________________________________________________________________L
L
L
L
L
posix_trace_flush_stop L POSIX_TRACE_FLUSH_STOP L None.
________________________________________________________________________
L
L_
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
Tracing
2.11.2.2 User Trace Event Type Definitions
3241
3242
3243
3244
3245
The user trace event POSIX_TRACE_UNNAMED_USEREVENT is defined in the <trace.h>
header. If the limit of per-process user trace event names represented by
{TRACE_USER_EVENT_MAX} has already been reached, this predefined user event shall be
returned when the application tries to register more events than allowed. The data associated
with this trace event is application-defined.
3246
The following predefined user trace event in Table 2-7 shall be defined:
Table 2-7 Trace Option: User Trace Event
_________________________________________________________________________
L
L
L
Event Name
Constant
_________________________________________________________________________
L
L
L
posix_trace_unnamed_userevent L POSIX_TRACE_UNNAMED_USEREVENT L
________________________________________________________________________
L_
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
2.11.3
Trace Functions
The trace interface is built and structured to improve portability through use of trace data of
opaque type. The object-oriented approach for the manipulation of trace attributes and trace
event type identifiers requires definition of many constructor and selector functions which
operate on these opaque types. Also, the trace interface must support several different tracing
roles. To facilitate reading the trace interface, the trace functions are grouped into small
functional sets supporting the three different roles:
•
A trace controller process requires functions to set up and customize all the resources needed
to run a trace stream, including:
3259
— Attribute initialization and destruction (posix_trace_attr_init( ))
3260
— Identification information manipulation (posix_trace_attr_getgenversion( ))
3261
— Trace system behavior modification (posix_trace_attr_getinherited( ))
3262
— Trace stream and trace log size set (posix_trace_attr_getmaxusereventsize( ))
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
79
Tracing
General Information
3263
— Trace stream creation, flush, and shutdown (posix_trace_create( ))
3264
— Trace stream and trace log clear (posix_trace_clear( ))
3265
— Trace event type identifier manipulation (posix_trace_trid_eventid_open( ))
3266
— Trace event type identifier list exploration (posix_trace_eventtypelist_getnext_id( ))
3267
— Trace event type set manipulation (posix_trace_eventset_empty( ))
3268
— Trace event type filter set (posix_trace_set_filter( ))
3269
— Trace stream start and stop (posix_trace_start( ))
3270
— Trace stream information and status read (posix_trace_get_attr( ))
•
3271
A traced process requires functions to instrument trace points:
— Trace event type identifiers definition and trace points insertion (posix_trace_event( ))
3272
•
3273
3274
A trace analyzer process requires functions to retrieve information from a trace stream and
trace log:
3275
— Identification information read (posix_trace_attr_getgenversion( ))
3276
— Trace system behavior information read (posix_trace_attr_getinherited( ))
3277
— Trace stream and trace log size get (posix_trace_attr_getmaxusereventsize( ))
3278
— Trace event type identifier manipulation (posix_trace_trid_eventid_open( ))
3279
— Trace event type identifier list exploration (posix_trace_eventtypelist_getnext_id( ))
3280
— Trace log open, rewind, and close (posix_trace_open( ))
3281
— Trace stream information and status read (posix_trace_get_attr( ))
3282
— Trace event read (posix_trace_getnext_event( ))
3283
2.12
Data Types
All of the data types used by various functions are defined by the implementation. The
following table describes some of these types. Other types referenced in the description of a
function, not mentioned here, can be found in the appropriate header for that function.
___________________________________________________________________________________
L
L
L
Defined Type
Description
__________________________________________________________________________________
L
L
L_
L cc_t
L
L
Type used for terminal special characters.
L
L
clock_t
Integer or real-floating type used for processor times, as defined in L
L
L
L
the ISO C standard.
L
L
L
Used for clock ID type in some timer functions.
L clockid_t
L
L
L dev_t
L
L
Arithmetic type used for device numbers.
L
L
L
DIR
Type representing a directory stream.
L
L
L
div_t
Structure
type
returned
by
the
div(
)
function.
L
L
L
FILE
Structure containing information about a file.
L
L
L
Structure type used in pathname pattern matching.
L glob_t
L
L
L fpos_t
L
Type containing all information needed to specify uniquely every LL
L_
__________________________________________________________________________________
L
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
80
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
General Information
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
Data Types
___________________________________________________________________________________
L
L
Defined Type
Description
__________________________________________________________________________________
L
L
L_
L
L
L
position within a file.
L
L
L
gid_t
Integer type used for group IDs.
L
L
L
iconv_t
Type used for conversion descriptors.
L
L
L
id_t
Integer type used as a general identifier; can be used to contain
L
L
L
at least the largest of a pid_t, uid_t, or gid_t.
L
L
L
L
L
L ino_t
Unsigned integer type used for file serial numbers.
L
L
L
key_t
Arithmetic type used for XSI interprocess communication.
L
L
L
ldiv_t
Structure type returned by the ldiv ( ) function.
L
L
L
mode_t
Integer type used for file attributes.
L
L
L
Used for message queue descriptors.
L
L
L mqd_t
L
L
L nfds_t
Integer type used for the number of file descriptors.
L
L
L
nlink_t
Integer type used for link counts.
L
L
L
off_t
Signed integer type used for file sizes.
L
L
L
pid_t
Signed integer type used for process and process group IDs.
L
L
L
Used to identify a thread attribute object.
L
L
L pthread_attr_t
L
L
L pthread_cond_t
Used for condition variables.
L
L
L
pthread_condattr_t
Used to identify a condition attribute object.
L
L
L
pthread_key_t
Used for thread-specific data keys.
L
L
L
pthread_mutex_t
Used for mutexes.
L
L
L
Used to identify a mutex attribute object.
L
L
L pthread_mutexattr_t
L
L
L pthread_once_t
Used for dynamic package initialization.
L
L
L pthread_rwlock_t
Used for read-write locks.
L
L
L
pthread_rwlockattr_t
Used for read-write lock attributes.
L
L
L
pthread_t
Used to identify a thread.
L
L
L
ptrdiff_t
Signed integer type of the result of subtracting two pointers.
L
L
L
Structure type used in regular expression matching.
L
L
L regex_t
L
L
L regmatch_t
Structure type used in regular expression matching.
L
L
L
rlim_t
Unsigned integer type used for limit values, to which objects of
L
L
L
type int and off_t can be cast without loss of value.
L
L
L
sem_t
Type used in performing semaphore operations.
L
L
L
Integer type of an object that can be accessed as an atomic
L
L
L sig_atomic_t
L
L
L
entity, even in the presence of asynchronous interrupts.
L
L
L
sigset_t
Integer or structure type of an object used to represent sets
L
L
L
of signals.
L
L
L
size_t
Unsigned integer type used for size of objects.
L
L
L
Type used for terminal baud rates.
L
L
L speed_t
L
L
L ssize_t
Signed integer type used for a count of bytes or an error
L
L
L
indication.
L
L
L
suseconds_t
Signed integer type used for time in microseconds.
L
L
L
Type used for terminal modes.
L
L
L tcflag_t
L
L time_t
Integer or real-floating type used for time in seconds, as defined in L
L
L
L
the ISO C standard.
L
L
L
timer_t
Used for timer ID returned by the timer_create( ) function.
L
L
L
uid_t
Integer type used for user IDs.
L
L
L
Unsigned integer type used for time in microseconds.
L
L
L useconds_t
L
L
L va_list
Type used for traversing variable argument lists.
L
L
wchar_t
Integer type whose range of values can represent distinct codes for LL
L
L_
__________________________________________________________________________________
L
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
81
Data Types
General Information
___________________________________________________________________________________
L
L
Defined Type
Description
__________________________________________________________________________________
L
L
L_
L
L
all members of the largest extended character set specified by the L
L
L
L
supported locales.
L
L
L
wctype_t
Scalar type which represents a character class descriptor.
L
L
L
wint_t
Integer type capable of storing any valid value of wchar_t or
L
L
L
WEOF.
L
L
L
L wordexp_t
L
L
Structure type used in word expansion.
__________________________________________________________________________________
L
L
L_
3348
3349
L
3350
3351
3352
3353
3354
3355
82
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Chapter 3
3356
3357
3358
System Interfaces
This chapter describes the functions, macros, and external variables to support applications
portability at the C-language source level.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
83
FD_CLR( )
System Interfaces
3359
3360
NAME
3361
3362
SYNOPSIS
#include <sys/time.h>
FD_CLR — macros for synchronous I/O multiplexing
FD_CLR(int fd, fd_set *fdset);
FD_ISSET(int fd, fd_set *fdset);
FD_SET(int fd, fd_set *fdset);
FD_ZERO(fd_set *fdset);
3363
3364
3365
3366
3367
3368
DESCRIPTION
Refer to pselect( ).
84
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
3369
3370
NAME
3371
3372
SYNOPSIS
#include <unistd.h>
3373
3374
3375
3376
_Exit( )
_Exit, _exit — terminate a process
void _Exit(int status);
void _exit(int status);
DESCRIPTION
Refer to exit( ).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
85
_longjmp( )
System Interfaces
3377
3378
NAME
3379
3380
SYNOPSIS
XSI
#include <setjmp.h>
_longjmp, _setjmp — non-local goto
void _longjmp(jmp_buf env, int val);
int _setjmp(jmp_buf env);
3381
3382
3383
3384
3385
3386
3387
DESCRIPTION
The _longjmp ( ) and _setjmp( ) functions shall be equivalent to longjmp( ) and setjmp( ),
respectively, with the additional restriction that _longjmp ( ) and _setjmp( ) shall not manipulate
the signal mask.
3388
3389
If _longjmp ( ) is called even though env was never initialized by a call to _setjmp( ), or when the
last such call was in a function that has since returned, the results are undefined.
3390
3391
RETURN VALUE
Refer to longjmp( ) and setjmp( ).
3392
3393
ERRORS
No errors are defined.
3394
3395
EXAMPLES
None.
3396
3397
3398
3399
3400
3401
3402
3403
APPLICATION USAGE
If _longjmp ( ) is executed and the environment in which _setjmp( ) was executed no longer exists,
errors can occur. The conditions under which the environment of the _setjmp( ) no longer exists
include exiting the function that contains the _setjmp( ) call, and exiting an inner block with
temporary storage. This condition might not be detectable, in which case the _longjmp ( ) occurs
and, if the environment no longer exists, the contents of the temporary storage of an inner block
are unpredictable. This condition might also cause unexpected process termination. If the
function has returned, the results are undefined.
3404
3405
3406
3407
Passing longjmp( ) a pointer to a buffer not created by setjmp( ), passing _longjmp ( ) a pointer to a
buffer not created by _setjmp( ), passing siglongjmp ( ) a pointer to a buffer not created by
sigsetjmp( ), or passing any of these three functions a buffer that has been modified by the user
can cause all the problems listed above, and more.
3408
3409
The _longjmp ( ) and _setjmp( ) functions are included to support programs written to historical
system interfaces. New applications should use siglongjmp ( ) and sigsetjmp( ) respectively.
3410
3411
RATIONALE
None.
3412
3413
FUTURE DIRECTIONS
The _longjmp ( ) and _setjmp( ) functions may be marked LEGACY in a future version.
3414
3415
3416
SEE ALSO
longjmp( ), setjmp( ), siglongjmp ( ),
IEEE Std 1003.1-2001, <setjmp.h>
3417
3418
CHANGE HISTORY
First released in Issue 4, Version 2.
86
sigsetjmp( ),
the
Base
Definitions
volume
of
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
3419
3420
_longjmp( )
Issue 5
Moved from X/OPEN UNIX extension to BASE.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
87
_tolower( )
System Interfaces
3421
3422
NAME
3423
3424
SYNOPSIS
XSI
#include <ctype.h>
_tolower — transliterate uppercase characters to lowercase
int _tolower(int c);
3425
3426
3427
3428
3429
DESCRIPTION
The _tolower ( ) macro shall be equivalent to tolower(c) except that the application shall ensure
that the argument c is an uppercase letter.
3430
3431
3432
RETURN VALUE
Upon successful completion, _tolower ( ) shall return the lowercase letter corresponding to the
argument passed.
3433
3434
ERRORS
No errors are defined.
3435
3436
EXAMPLES
None.
3437
3438
APPLICATION USAGE
None.
3439
3440
RATIONALE
None.
3441
3442
FUTURE DIRECTIONS
None.
3443
3444
3445
SEE ALSO
tolower( ), isupper( ), the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale,
<ctype.h>
3446
3447
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
3448
3449
Issue 6
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
88
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
3450
3451
NAME
3452
3453
SYNOPSIS
XSI
#include <ctype.h>
_toupper( )
_toupper — transliterate lowercase characters to uppercase
int _toupper(int c);
3454
3455
3456
3457
3458
DESCRIPTION
The _toupper( ) macro shall be equivalent to toupper( ) except that the application shall ensure
that the argument c is a lowercase letter.
3459
3460
3461
RETURN VALUE
Upon successful completion, _toupper( ) shall return the uppercase letter corresponding to the
argument passed.
3462
3463
ERRORS
No errors are defined.
3464
3465
EXAMPLES
None.
3466
3467
APPLICATION USAGE
None.
3468
3469
RATIONALE
None.
3470
3471
FUTURE DIRECTIONS
None.
3472
3473
3474
SEE ALSO
islower( ), toupper( ), the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale,
<ctype.h>
3475
3476
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
3477
3478
Issue 6
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
89
a64l( )
System Interfaces
3479
3480
NAME
3481
3482
SYNOPSIS
XSI
#include <stdlib.h>
a64l, l64a — convert between a 32-bit integer and a radix-64 ASCII string
long a64l(const char *s);
char *l64a(long value);
3483
3484
3485
3486
3487
3488
3489
3490
DESCRIPTION
These functions maintain numbers stored in radix-64 ASCII characters. This is a notation by
which 32-bit integers can be represented by up to six characters; each character represents a digit
in radix-64 notation. If the type long contains more than 32 bits, only the low-order 32 bits shall
be used for these operations.
3491
3492
The characters used to represent digits are ’.’ (dot) for 0, ’/’ for 1, ’0’ through ’9’ for [2,11],
’A’ through ’Z’ for [12,37], and ’a’ through ’z’ for [38,63].
3493
3494
3495
3496
3497
3498
3499
3500
The a64l ( ) function shall take a pointer to a radix-64 representation, in which the first digit is the
least significant, and return the corresponding long value. If the string pointed to by s contains
more than six characters, a64l ( ) shall use the first six. If the first six characters of the string
contain a null terminator, a64l ( ) shall use only characters preceding the null terminator. The
a64l ( ) function shall scan the character string from left to right with the least significant digit on
the left, decoding each character as a 6-bit radix-64 number. If the type long contains more than
32 bits, the resulting value is sign-extended. The behavior of a64l ( ) is unspecified if s is a null
pointer or the string pointed to by s was not generated by a previous call to l64a ( ).
3501
3502
The l64a ( ) function shall take a long argument and return a pointer to the corresponding radix64 representation. The behavior of l64a ( ) is unspecified if value is negative.
3503
3504
The value returned by l64a ( ) may be a pointer into a static buffer. Subsequent calls to l64a ( ) may
overwrite the buffer.
3505
3506
The l64a ( ) function need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
3507
3508
3509
RETURN VALUE
Upon successful completion, a64l ( ) shall return the long value resulting from conversion of the
input string. If a string pointed to by s is an empty string, a64l ( ) shall return 0L.
3510
3511
The l64a ( ) function shall return a pointer to the radix-64 representation. If value is 0L, l64a ( ) shall
return a pointer to an empty string.
3512
3513
ERRORS
No errors are defined.
3514
3515
EXAMPLES
None.
3516
3517
APPLICATION USAGE
If the type long contains more than 32 bits, the result of a64l(l64a(x)) is x in the low-order 32 bits.
3518
3519
RATIONALE
This is not the same encoding as used by either encoding variant of the uuencode utility.
90
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
a64l( )
3520
3521
FUTURE DIRECTIONS
None.
3522
3523
3524
SEE ALSO
strtoul( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>, the Shell and Utilities
volume of IEEE Std 1003.1-2001, uuencode
3525
3526
CHANGE HISTORY
First released in Issue 4, Version 2.
3527
3528
Issue 5
Moved from X/OPEN UNIX extension to BASE.
3529
3530
Normative text previously in the APPLICATION USAGE section is moved to the
DESCRIPTION.
3531
A note indicating that these functions need not be reentrant is added to the DESCRIPTION.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
91
abort( )
System Interfaces
3532
3533
NAME
3534
3535
SYNOPSIS
#include <stdlib.h>
abort — generate an abnormal process abort
void abort(void);
3536
3537
3538
3539
3540
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
3541
3542
The abort( ) function shall cause abnormal process termination to occur, unless the signal
SIGABRT is being caught and the signal handler does not return.
3543
3544
CX
The abnormal termination processing shall include at least the effect of fclose( ) on all open
streams and the default actions defined for SIGABRT.
3545
3546
XSI
On XSI-conformant systems, in addition the abnormal termination processing shall include the
effect of fclose( ) on message catalog descriptors.
The SIGABRT signal shall be sent to the calling process as if by means of raise( ) with the
argument SIGABRT.
3547
3548
The status made available to wait( ) or waitpid ( ) by abort( ) shall be that of a process terminated
by the SIGABRT signal. The abort( ) function shall override blocking or ignoring the SIGABRT
signal.
3549
3550
3551
CX
3552
3553
RETURN VALUE
The abort( ) function shall not return.
3554
3555
ERRORS
No errors are defined.
3556
3557
EXAMPLES
None.
3558
3559
3560
APPLICATION USAGE
Catching the signal is intended to provide the application writer with a portable means to abort
processing, free from possible interference from any implementation-defined functions.
3561
3562
RATIONALE
None.
3563
3564
FUTURE DIRECTIONS
None.
3565
3566
3567
SEE ALSO
exit( ), kill ( ), raise( ), signal( ),
IEEE Std 1003.1-2001, <stdlib.h>
3568
3569
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
3570
3571
Issue 6
wait( ),
waitpid ( ),
the
Base
Definitions
volume
of
Extensions beyond the ISO C standard are marked.
92
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
3572
3573
NAME
3574
3575
SYNOPSIS
#include <stdlib.h>
abs( )
abs — return an integer absolute value
int abs(int i);
3576
3577
3578
3579
3580
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
3581
3582
The abs( ) function shall compute the absolute value of its integer operand, i. If the result cannot
be represented, the behavior is undefined.
3583
3584
RETURN VALUE
The abs( ) function shall return the absolute value of its integer operand.
3585
3586
ERRORS
No errors are defined.
3587
3588
EXAMPLES
None.
3589
3590
3591
APPLICATION USAGE
In two’s-complement representation, the absolute value of the negative integer with largest
magnitude {INT_MIN} might not be representable.
3592
3593
RATIONALE
None.
3594
3595
FUTURE DIRECTIONS
None.
3596
3597
SEE ALSO
fabs( ), labs( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>
3598
3599
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
3600
3601
Issue 6
Extensions beyond the ISO C standard are marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
93
accept( )
System Interfaces
3602
3603
NAME
3604
3605
SYNOPSIS
#include <sys/socket.h>
accept — accept a new connection on a socket
int accept(int socket, struct sockaddr *restrict address,
socklen_t *restrict address_len);
3606
3607
3608
3609
3610
3611
DESCRIPTION
The accept( ) function shall extract the first connection on the queue of pending connections,
create a new socket with the same socket type protocol and address family as the specified
socket, and allocate a new file descriptor for that socket.
3612
The accept( ) function takes the following arguments:
3613
3614
socket
Specifies a socket that was created with socket( ), has been bound to an address
with bind( ), and has issued a successful call to listen( ).
3615
3616
address
Either a null pointer, or a pointer to a sockaddr structure where the address of
the connecting socket shall be returned.
3617
3618
3619
address_len
Points to a socklen_t structure which on input specifies the length of the
supplied sockaddr structure, and on output specifies the length of the stored
address.
3620
3621
3622
If address is not a null pointer, the address of the peer for the accepted connection shall be stored
in the sockaddr structure pointed to by address, and the length of this address shall be stored in
the object pointed to by address_len.
3623
3624
If the actual length of the address is greater than the length of the supplied sockaddr structure,
the stored address shall be truncated.
3625
3626
If the protocol permits connections by unbound clients, and the peer is not bound, then the value
stored in the object pointed to by address is unspecified.
3627
3628
3629
3630
If the listen queue is empty of connection requests and O_NONBLOCK is not set on the file
descriptor for the socket, accept( ) shall block until a connection is present. If the listen( ) queue is
empty of connection requests and O_NONBLOCK is set on the file descriptor for the socket,
accept( ) shall fail and set errno to [EAGAIN] or [EWOULDBLOCK].
3631
3632
The accepted socket cannot itself accept more connections. The original socket remains open and
can accept more connections.
3633
3634
3635
RETURN VALUE
Upon successful completion, accept( ) shall return the non-negative file descriptor of the accepted
socket. Otherwise, −1 shall be returned and errno set to indicate the error.
3636
3637
ERRORS
The accept( ) function shall fail if:
3638
3639
3640
[EAGAIN] or [EWOULDBLOCK]
O_NONBLOCK is set for the socket file descriptor and no connections are
present to be accepted.
3641
[EBADF]
3642
[ECONNABORTED]
A connection has been aborted.
3643
94
The socket argument is not a valid file descriptor.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
accept( )
System Interfaces
3644
3645
[EINTR]
The accept( ) function was interrupted by a signal that was caught before a
valid connection arrived.
3646
[EINVAL]
The socket is not accepting connections.
3647
[EMFILE]
{OPEN_MAX} file descriptors are currently open in the calling process.
3648
[ENFILE]
The maximum number of file descriptors in the system are already open.
3649
[ENOTSOCK]
The socket argument does not refer to a socket.
3650
3651
[EOPNOTSUPP] The socket type of the specified socket does not support accepting
connections.
3652
The accept( ) function may fail if:
3653
[ENOBUFS]
No buffer space is available.
3654
[ENOMEM]
There was insufficient memory available to complete the operation.
[EPROTO]
A protocol error has occurred; for example, the STREAMS protocol stack has
not been initialized.
3655
3656
XSR
3657
3658
EXAMPLES
None.
3659
3660
3661
APPLICATION USAGE
When a connection is available, select( ) indicates that the file descriptor for the socket is ready
for reading.
3662
3663
RATIONALE
None.
3664
3665
FUTURE DIRECTIONS
None.
3666
3667
3668
SEE ALSO
bind( ), connect( ), listen( ), socket( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<sys/socket.h>
3669
3670
CHANGE HISTORY
First released in Issue 6. Derived from the XNS, Issue 5.2 specification.
3671
3672
The restrict keyword is added to the accept( ) prototype for alignment with the
ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
95
access( )
System Interfaces
3673
3674
NAME
3675
3676
SYNOPSIS
#include <unistd.h>
access — determine accessibility of a file
int access(const char *path, int amode);
3677
3678
3679
3680
3681
DESCRIPTION
The access( ) function shall check the file named by the pathname pointed to by the path
argument for accessibility according to the bit pattern contained in amode, using the real user ID
in place of the effective user ID and the real group ID in place of the effective group ID.
3682
3683
The value of amode is either the bitwise-inclusive OR of the access permissions to be checked
(R_OK, W_OK, X_OK) or the existence test (F_OK).
3684
3685
3686
3687
If any access permissions are checked, each shall be checked individually, as described in the
Base Definitions volume of IEEE Std 1003.1-2001, Chapter 3, Definitions. If the process has
appropriate privileges, an implementation may indicate success for X_OK even if none of the
execute file permission bits are set.
3688
3689
3690
RETURN VALUE
If the requested access is permitted, access( ) succeeds and shall return 0; otherwise, −1 shall be
returned and errno shall be set to indicate the error.
3691
3692
ERRORS
The access( ) function shall fail if:
3693
3694
[EACCES]
Permission bits of the file mode do not permit the requested access, or search
permission is denied on a component of the path prefix.
3695
3696
[ELOOP]
A loop exists in symbolic links encountered during resolution of the path
argument.
3697
3698
3699
[ENAMETOOLONG]
The length of the path argument exceeds {PATH_MAX} or a pathname
component is longer than {NAME_MAX}.
3700
[ENOENT]
A component of path does not name an existing file or path is an empty string.
3701
[ENOTDIR]
A component of the path prefix is not a directory.
3702
[EROFS]
Write access is requested for a file on a read-only file system.
3703
The access( ) function may fail if:
3704
[EINVAL]
The value of the amode argument is invalid.
3705
3706
[ELOOP]
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path argument.
3707
3708
3709
[ENAMETOOLONG]
As a result of encountering a symbolic link in resolution of the path argument,
the length of the substituted pathname string exceeded {PATH_MAX}.
3710
3711
[ETXTBSY]
96
Write access is requested for a pure procedure (shared text) file that is being
executed.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
3712
access( )
EXAMPLES
3713
Testing for the Existence of a File
3714
The following example tests whether a file named myfile exists in the /tmp directory.
3715
3716
3717
3718
#include <unistd.h>
...
int result;
const char *filename = "/tmp/myfile";
3719
result = access (filename, F_OK);
3720
3721
3722
APPLICATION USAGE
Additional values of amode other than the set defined in the description may be valid; for
example, if a system has extended access controls.
3723
3724
3725
RATIONALE
In early proposals, some inadequacies in the access( ) function led to the creation of an eaccess( )
function because:
3726
3727
3728
1. Historical implementations of access( ) do not test file access correctly when the process’
real user ID is superuser. In particular, they always return zero when testing execute
permissions without regard to whether the file is executable.
3729
3730
3731
2. The superuser has complete access to all files on a system. As a consequence, programs
started by the superuser and switched to the effective user ID with lesser privileges cannot
use access( ) to test their file access permissions.
3732
3733
3734
3735
3736
3737
However, the historical model of eaccess( ) does not resolve problem (1), so this volume of
IEEE Std 1003.1-2001 now allows access( ) to behave in the desired way because several
implementations have corrected the problem. It was also argued that problem (2) is more easily
solved by using open( ), chdir( ), or one of the exec functions as appropriate and responding to the
error, rather than creating a new function that would not be as reliable. Therefore, eaccess( ) is not
included in this volume of IEEE Std 1003.1-2001.
3738
3739
3740
The sentence concerning appropriate privileges and execute permission bits reflects the two
possibilities implemented by historical implementations when checking superuser access for
X_OK.
3741
3742
New implementations are discouraged from returning X_OK unless at least one execution
permission bit is set.
3743
3744
FUTURE DIRECTIONS
None.
3745
3746
SEE ALSO
chmod( ), stat( ), the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>
3747
3748
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
3749
3750
3751
Issue 6
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
3752
•
The [ELOOP] mandatory error condition is added.
3753
•
A second [ENAMETOOLONG] is added as an optional error condition.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
97
access( )
•
3754
System Interfaces
The [ETXTBSY] optional error condition is added.
The following changes were made to align with the IEEE P1003.1a draft standard:
3755
•
3756
98
The [ELOOP] optional error condition is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
acos( )
System Interfaces
3757
3758
NAME
3759
3760
SYNOPSIS
#include <math.h>
acos, acosf, acosl — arc cosine functions
double acos(double x);
float acosf(float x);
long double acosl(long double x);
3761
3762
3763
3764
3765
3766
3767
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
3768
3769
These functions shall compute the principal value of the arc cosine of their argument x. The
value of x should be in the range [−1,1].
3770
3771
3772
3773
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
3774
3775
3776
RETURN VALUE
Upon successful completion, these functions shall return the arc cosine of x, in the range [0,π]
radians.
3777
3778
MX
For finite values of x not in the range [−1,1], a domain error shall occur, and either a NaN (if
supported), or an implementation-defined value shall be returned.
3779
MX
If x is NaN, a NaN shall be returned.
3780
If x is +1, +0 shall be returned.
3781
3782
If x is ±Inf, a domain error shall occur, and either a NaN (if supported), or an implementationdefined value shall be returned.
3783
3784
ERRORS
These functions shall fail if:
3785
MX
Domain Error
The x argument is finite and is not in the range [−1,1], or is ±Inf.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [EDOM]. If the integer expression (math_errhandling
& MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception
shall be raised.
3786
3787
3788
3789
3790
3791
EXAMPLES
None.
3792
3793
3794
APPLICATION USAGE
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
3795
3796
RATIONALE
None.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
99
acos( )
System Interfaces
3797
3798
FUTURE DIRECTIONS
None.
3799
3800
3801
SEE ALSO
cos( ), feclearexcept( ), fetestexcept( ), isnan( ), the Base Definitions volume of IEEE Std 1003.1-2001,
Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
3802
3803
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
3804
3805
3806
Issue 5
3807
3808
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The acosf ( ) and acosl ( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
3809
3810
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
3811
3812
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
100
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
acosh( )
System Interfaces
3813
3814
NAME
3815
3816
SYNOPSIS
#include <math.h>
acosh, acoshf, acoshl, — inverse hyperbolic cosine functions
double acosh(double x);
float acoshf(float x);
long double acoshl(long double x);
3817
3818
3819
3820
3821
3822
3823
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
3824
These functions shall compute the inverse hyperbolic cosine of their argument x.
3825
3826
3827
3828
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
3829
3830
3831
RETURN VALUE
Upon successful completion, these functions shall return the inverse hyperbolic cosine of their
argument.
3832
3833
MX
For finite values of x < 1, a domain error shall occur, and either a NaN (if supported), or an
implementation-defined value shall be returned.
3834
MX
If x is NaN, a NaN shall be returned.
3835
If x is +1, +0 shall be returned.
3836
If x is +Inf, +Inf shall be returned.
3837
3838
If x is −Inf, a domain error shall occur, and either a NaN (if supported), or an implementationdefined value shall be returned.
3839
3840
ERRORS
These functions shall fail if:
3841
MX
Domain Error
The x argument is finite and less than +1.0, or is −Inf.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [EDOM]. If the integer expression (math_errhandling
& MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception
shall be raised.
3842
3843
3844
3845
3846
3847
EXAMPLES
None.
3848
3849
3850
APPLICATION USAGE
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
3851
3852
RATIONALE
None.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
101
acosh( )
System Interfaces
3853
3854
FUTURE DIRECTIONS
None.
3855
3856
3857
SEE ALSO
cosh( ), feclearexcept( ), fetestexcept( ), the Base Definitions volume of IEEE Std 1003.1-2001, Section
4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
3858
3859
CHANGE HISTORY
First released in Issue 4, Version 2.
3860
3861
Issue 5
3862
3863
Issue 6
Moved from X/OPEN UNIX extension to BASE.
The acosh( ) function is no longer marked as an extension.
3864
3865
The acoshf ( ), and acoshl ( ) functions are added for alignment with the ISO/IEC 9899: 1999
standard.
3866
3867
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
3868
3869
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
102
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
3870
3871
NAME
3872
3873
SYNOPSIS
#include <math.h>
3874
3875
3876
acosl( )
acosl — arc cosine functions
long double acosl(long double x);
DESCRIPTION
Refer to acos( ).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
103
aio_cancel( )
System Interfaces
3877
3878
NAME
3879
3880
SYNOPSIS
AIO
#include <aio.h>
aio_cancel — cancel an asynchronous I/O request (REALTIME)
int aio_cancel(int fildes, struct aiocb *aiocbp);
3881
3882
3883
3884
3885
3886
3887
DESCRIPTION
The aio_cancel ( ) function shall attempt to cancel one or more asynchronous I/O requests
currently outstanding against file descriptor fildes. The aiocbp argument points to the
asynchronous I/O control block for a particular request to be canceled. If aiocbp is NULL, then
all outstanding cancelable asynchronous I/O requests against fildes shall be canceled.
3888
3889
3890
Normal asynchronous notification shall occur for asynchronous I/O operations that are
successfully canceled. If there are requests that cannot be canceled, then the normal
asynchronous completion process shall take place for those requests when they are completed.
3891
3892
3893
For requested operations that are successfully canceled, the associated error status shall be set to
[ECANCELED] and the return status shall be −1. For requested operations that are not
successfully canceled, the aiocbp shall not be modified by aio_cancel ( ).
3894
3895
If aiocbp is not NULL, then if fildes does not have the same value as the file descriptor with which
the asynchronous operation was initiated, unspecified results occur.
3896
Which operations are cancelable is implementation-defined.
3897
3898
3899
3900
3901
3902
3903
3904
3905
RETURN VALUE
The aio_cancel ( ) function shall return the value AIO_CANCELED to the calling process if the
requested operation(s) were canceled. The value AIO_NOTCANCELED shall be returned if at
least one of the requested operation(s) cannot be canceled because it is in progress. In this case,
the state of the other operations, if any, referenced in the call to aio_cancel ( ) is not indicated by
the return value of aio_cancel ( ). The application may determine the state of affairs for these
operations by using aio_error ( ). The value AIO_ALLDONE is returned if all of the operations
have already completed. Otherwise, the function shall return −1 and set errno to indicate the
error.
3906
3907
ERRORS
The aio_cancel ( ) function shall fail if:
[EBADF]
3908
The fildes argument is not a valid file descriptor.
3909
3910
EXAMPLES
None.
3911
3912
3913
APPLICATION USAGE
The aio_cancel ( ) function is part of the Asynchronous Input and Output option and need not be
available on all implementations.
3914
3915
RATIONALE
None.
3916
3917
FUTURE DIRECTIONS
None.
104
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
aio_cancel( )
3918
3919
SEE ALSO
aio_read ( ), aio_write ( ), the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>
3920
3921
CHANGE HISTORY
First released in Issue 5. Included for alignment with the POSIX Realtime Extension.
3922
3923
3924
Issue 6
3925
The [ENOSYS] error condition has been removed as stubs need not be provided if an
implementation does not support the Asynchronous Input and Output option.
The APPLICATION USAGE section is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
105
aio_error( )
System Interfaces
3926
3927
NAME
3928
3929
SYNOPSIS
AIO
#include <aio.h>
aio_error — retrieve errors status for an asynchronous I/O operation (REALTIME)
int aio_error(const struct aiocb *aiocbp);
3930
3931
3932
3933
3934
3935
3936
3937
DESCRIPTION
The aio_error ( ) function shall return the error status associated with the aiocb structure
referenced by the aiocbp argument. The error status for an asynchronous I/O operation is the
SIO
errno value that would be set by the corresponding read( ), write( ), fdatasync ( ), or fsync( )
operation. If the operation has not yet completed, then the error status shall be equal to
[EINPROGRESS].
3938
3939
3940
3941
3942
RETURN VALUE
If the asynchronous I/O operation has completed successfully, then 0 shall be returned. If the
asynchronous operation has completed unsuccessfully, then the error status, as described for
SIO
read( ), write( ), fdatasync ( ), and fsync( ), shall be returned. If the asynchronous I/O operation has
not yet completed, then [EINPROGRESS] shall be returned.
3943
3944
ERRORS
The aio_error ( ) function may fail if:
[EINVAL]
3945
3946
The aiocbp argument does not refer to an asynchronous operation whose
return status has not yet been retrieved.
3947
3948
EXAMPLES
None.
3949
3950
3951
APPLICATION USAGE
The aio_error ( ) function is part of the Asynchronous Input and Output option and need not be
available on all implementations.
3952
3953
RATIONALE
None.
3954
3955
FUTURE DIRECTIONS
None.
3956
3957
3958
SEE ALSO
aio_cancel ( ), aio_fsync ( ), aio_read ( ), aio_return( ), aio_write ( ), close( ), exec, exit( ), fork ( ), lio_listio ( ),
lseek( ), read( ), the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>
3959
3960
CHANGE HISTORY
First released in Issue 5. Included for alignment with the POSIX Realtime Extension.
3961
3962
3963
Issue 6
The [ENOSYS] error condition has been removed as stubs need not be provided if an
implementation does not support the Asynchronous Input and Output option.
The APPLICATION USAGE section is added.
3964
106
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
aio_fsync( )
System Interfaces
3965
3966
NAME
3967
3968
SYNOPSIS
AIO
#include <aio.h>
3969
3970
aio_fsync — asynchronous file synchronization (REALTIME)
int aio_fsync(int op, struct aiocb *aiocbp);
3971
3972
3973
3974
3975
3976
DESCRIPTION
The aio_fsync ( ) function shall asynchronously force all I/O operations associated with the file
indicated by the file descriptor aio_fildes member of the aiocb structure referenced by the aiocbp
argument and queued at the time of the call to aio_fsync ( ) to the synchronized I/O completion
state. The function call shall return when the synchronization request has been initiated or
queued to the file or device (even when the data cannot be synchronized immediately).
3977
3978
3979
3980
3981
3982
If op is O_DSYNC, all currently queued I/O operations shall be completed as if by a call to
fdatasync ( ); that is, as defined for synchronized I/O data integrity completion. If op is O_SYNC,
all currently queued I/O operations shall be completed as if by a call to fsync( ); that is, as
defined for synchronized I/O file integrity completion. If the aio_fsync ( ) function fails, or if the
operation queued by aio_fsync ( ) fails, then, as for fsync( ) and fdatasync ( ), outstanding I/O
operations are not guaranteed to have been completed.
3983
3984
3985
3986
If aio_fsync ( ) succeeds, then it is only the I/O that was queued at the time of the call to
aio_fsync ( ) that is guaranteed to be forced to the relevant completion state. The completion of
subsequent I/O on the file descriptor is not guaranteed to be completed in a synchronized
fashion.
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
The aiocbp argument refers to an asynchronous I/O control block. The aiocbp value may be used
as an argument to aio_error ( ) and aio_return( ) in order to determine the error status and return
status, respectively, of the asynchronous operation while it is proceeding. When the request is
queued, the error status for the operation is [EINPROGRESS]. When all data has been
successfully transferred, the error status shall be reset to reflect the success or failure of the
operation. If the operation does not complete successfully, the error status for the operation shall
be set to indicate the error. The aio_sigevent member determines the asynchronous notification to
occur as specified in Section 2.4.1 (on page 28) when all operations have achieved synchronized
I/O completion. All other members of the structure referenced by aiocbp are ignored. If the
control block referenced by aiocbp becomes an illegal address prior to asynchronous I/O
completion, then the behavior is undefined.
3998
3999
If the aio_fsync ( ) function fails or aiocbp indicates an error condition, data is not guaranteed to
have been successfully transferred.
4000
4001
4002
4003
RETURN VALUE
The aio_fsync ( ) function shall return the value 0 to the calling process if the I/O operation is
successfully queued; otherwise, the function shall return the value −1 and set errno to indicate
the error.
4004
4005
ERRORS
The aio_fsync ( ) function shall fail if:
4006
4007
[EAGAIN]
The requested asynchronous operation was not queued due to temporary
resource limitations.
4008
[EBADF]
The aio_fildes member of the aiocb structure referenced by the aiocbp argument
is not a valid file descriptor open for writing.
4009
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
107
aio_fsync( )
System Interfaces
4010
[EINVAL]
This implementation does not support synchronized I/O for this file.
4011
[EINVAL]
A value of op other than O_DSYNC or O_SYNC was specified.
4012
4013
4014
In the event that any of the queued I/O operations fail, aio_fsync ( ) shall return the error
condition defined for read( ) and write( ). The error is returned in the error status for the
asynchronous fsync( ) operation, which can be retrieved using aio_error ( ).
4015
4016
EXAMPLES
None.
4017
4018
4019
APPLICATION USAGE
The aio_fsync ( ) function is part of the Asynchronous Input and Output option and need not be
available on all implementations.
4020
4021
RATIONALE
None.
4022
4023
FUTURE DIRECTIONS
None.
4024
4025
4026
SEE ALSO
fcntl( ), fdatasync ( ), fsync( ), open( ), read( ), write( ), the Base Definitions volume of
IEEE Std 1003.1-2001, <aio.h>
4027
4028
CHANGE HISTORY
First released in Issue 5. Included for alignment with the POSIX Realtime Extension.
4029
4030
4031
Issue 6
The [ENOSYS] error condition has been removed as stubs need not be provided if an
implementation does not support the Asynchronous Input and Output option.
The APPLICATION USAGE section is added.
4032
108
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
aio_read( )
System Interfaces
4033
4034
NAME
4035
4036
SYNOPSIS
AIO
#include <aio.h>
aio_read — asynchronous read from a file (REALTIME)
int aio_read(struct aiocb *aiocbp);
4037
4038
4039
4040
4041
4042
4043
DESCRIPTION
The aio_read ( ) function shall read aiocbp->aio_nbytes from the file associated with
aiocbp->aio_fildes into the buffer pointed to by aiocbp->aio_buf. The function call shall return when
the read request has been initiated or queued to the file or device (even when the data cannot be
delivered immediately).
4044
4045
PIO
If prioritized I/O is supported for this file, then the asynchronous operation shall be submitted
at a priority equal to the scheduling priority of the process minus aiocbp->aio_reqprio.
4046
4047
4048
4049
4050
4051
4052
4053
The aiocbp value may be used as an argument to aio_error ( ) and aio_return( ) in order to
determine the error status and return status, respectively, of the asynchronous operation while it
is proceeding. If an error condition is encountered during queuing, the function call shall return
without having initiated or queued the request. The requested operation takes place at the
absolute position in the file as given by aio_offset , as if lseek( ) were called immediately prior to
the operation with an offset equal to aio_offset and a whence equal to SEEK_SET. After a
successful call to enqueue an asynchronous I/O operation, the value of the file offset for the file
is unspecified.
4054
The aiocbp->aio_lio_opcode field shall be ignored by aio_read ( ).
4055
4056
4057
The aiocbp argument points to an aiocb structure. If the buffer pointed to by aiocbp->aio_buf or
the control block pointed to by aiocbp becomes an illegal address prior to asynchronous I/O
completion, then the behavior is undefined.
4058
Simultaneous asynchronous operations using the same aiocbp produce undefined results.
4059
4060
4061
SIO
If synchronized I/O is enabled on the file associated with aiocbp->aio_fildes, the behavior of this
function shall be according to the definitions of synchronized I/O data integrity completion and
synchronized I/O file integrity completion.
4062
4063
For any system action that changes the process memory space while an asynchronous I/O is
outstanding to the address range being changed, the result of that action is undefined.
4064
4065
For regular files, no data transfer shall occur past the offset maximum established in the open
file description associated with aiocbp->aio_fildes.
4066
4067
4068
4069
RETURN VALUE
The aio_read ( ) function shall return the value zero to the calling process if the I/O operation is
successfully queued; otherwise, the function shall return the value −1 and set errno to indicate
the error.
4070
4071
ERRORS
The aio_read ( ) function shall fail if:
4072
4073
[EAGAIN]
4074
Each of the following conditions may be detected synchronously at the time of the call to
aio_read ( ), or asynchronously. If any of the conditions below are detected synchronously, the
aio_read ( ) function shall return −1 and set errno to the corresponding value. If any of the
conditions below are detected asynchronously, the return status of the asynchronous operation
4075
4076
4077
The requested asynchronous I/O operation was not queued due to system
resource limitations.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
109
aio_read( )
System Interfaces
4078
is set to −1, and the error status of the asynchronous operation is set to the corresponding value.
4079
[EBADF]
The aiocbp->aio_fildes argument is not a valid file descriptor open for reading.
4080
4081
4082
[EINVAL]
The file offset value implied by aiocbp->aio_offset would be invalid,
aiocbp->aio_reqprio is not a valid value, or aiocbp->aio_nbytes is an invalid
value.
4083
4084
4085
4086
4087
In the case that the aio_read ( ) successfully queues the I/O operation but the operation is
subsequently canceled or encounters an error, the return status of the asynchronous operation is
one of the values normally returned by the read( ) function call. In addition, the error status of
the asynchronous operation is set to one of the error statuses normally set by the read( ) function
call, or one of the following values:
4088
[EBADF]
The aiocbp->aio_fildes argument is not a valid file descriptor open for reading.
4089
4090
[ECANCELED]
The requested I/O was canceled before the I/O completed due to an explicit
aio_cancel ( ) request.
4091
[EINVAL]
The file offset value implied by aiocbp->aio_offset would be invalid.
4092
The following condition may be detected synchronously or asynchronously:
4093
4094
4095
[EOVERFLOW]
The file is a regular file, aiobcp->aio_nbytes is greater than 0, and the starting
offset in aiobcp->aio_offset is before the end-of-file and is at or beyond the offset
maximum in the open file description associated with aiocbp->aio_fildes.
4096
4097
EXAMPLES
None.
4098
4099
4100
APPLICATION USAGE
The aio_read ( ) function is part of the Asynchronous Input and Output option and need not be
available on all implementations.
4101
4102
RATIONALE
None.
4103
4104
FUTURE DIRECTIONS
None.
4105
4106
4107
SEE ALSO
aio_cancel ( ), aio_error ( ), lio_listio ( ), aio_return( ), aio_write ( ), close( ), exec, exit( ), fork ( ), lseek( ),
read( ), the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>
4108
4109
CHANGE HISTORY
First released in Issue 5. Included for alignment with the POSIX Realtime Extension.
Large File Summit extensions are added.
4110
4111
4112
4113
Issue 6
The [ENOSYS] error condition has been removed as stubs need not be provided if an
implementation does not support the Asynchronous Input and Output option.
The APPLICATION USAGE section is added.
4114
110
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
4115
4116
aio_read( )
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
4117
4118
•
In the DESCRIPTION, text is added to indicate setting of the offset maximum in the open file
description. This change is to support large files.
4119
4120
•
In the ERRORS section, the [EOVERFLOW] condition is added. This change is to support
large files.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
111
aio_return( )
System Interfaces
4121
4122
NAME
4123
4124
SYNOPSIS
AIO
#include <aio.h>
aio_return — retrieve return status of an asynchronous I/O operation (REALTIME)
ssize_t aio_return(struct aiocb *aiocbp);
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
DESCRIPTION
The aio_return( ) function shall return the return status associated with the aiocb structure
referenced by the aiocbp argument. The return status for an asynchronous I/O operation is the
value that would be returned by the corresponding read( ), write( ), or fsync( ) function call. If the
error status for the operation is equal to [EINPROGRESS], then the return status for the
operation is undefined. The aio_return( ) function may be called exactly once to retrieve the
return status of a given asynchronous operation; thereafter, if the same aiocb structure is used in
a call to aio_return( ) or aio_error ( ), an error may be returned. When the aiocb structure referred
to by aiocbp is used to submit another asynchronous operation, then aio_return( ) may be
successfully used to retrieve the return status of that operation.
4137
4138
4139
4140
RETURN VALUE
If the asynchronous I/O operation has completed, then the return status, as described for read( ),
write( ), and fsync( ), shall be returned. If the asynchronous I/O operation has not yet completed,
the results of aio_return( ) are undefined.
4141
4142
ERRORS
The aio_return( ) function may fail if:
[EINVAL]
4143
4144
The aiocbp argument does not refer to an asynchronous operation whose
return status has not yet been retrieved.
4145
4146
EXAMPLES
None.
4147
4148
4149
APPLICATION USAGE
The aio_return( ) function is part of the Asynchronous Input and Output option and need not be
available on all implementations.
4150
4151
RATIONALE
None.
4152
4153
FUTURE DIRECTIONS
None.
4154
4155
4156
SEE ALSO
aio_cancel ( ), aio_error ( ), aio_fsync ( ), aio_read ( ), aio_write ( ), close( ), exec, exit( ), fork ( ), lio_listio ( ),
lseek( ), read( ), the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>
4157
4158
CHANGE HISTORY
First released in Issue 5. Included for alignment with the POSIX Realtime Extension.
4159
4160
4161
Issue 6
The [ENOSYS] error condition has been removed as stubs need not be provided if an
implementation does not support the Asynchronous Input and Output option.
4162
The APPLICATION USAGE section is added.
4163
4164
The [EINVAL] error condition is updated as a ‘‘may fail’’. This is for consistency with the
DESCRIPTION.
112
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
aio_suspend( )
System Interfaces
4165
4166
NAME
4167
4168
SYNOPSIS
AIO
#include <aio.h>
aio_suspend — wait for an asynchronous I/O request (REALTIME)
int aio_suspend(const struct aiocb * const list[], int nent,
const struct timespec *timeout);
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
DESCRIPTION
The aio_suspend( ) function shall suspend the calling thread until at least one of the asynchronous
I/O operations referenced by the list argument has completed, until a signal interrupts the
function, or, if timeout is not NULL, until the time interval specified by timeout has passed. If any
of the aiocb structures in the list correspond to completed asynchronous I/O operations (that is,
the error status for the operation is not equal to [EINPROGRESS]) at the time of the call, the
function shall return without suspending the calling thread. The list argument is an array of
pointers to asynchronous I/O control blocks. The nent argument indicates the number of
elements in the array. Each aiocb structure pointed to has been used in initiating an
asynchronous I/O request via aio_read ( ), aio_write ( ), or lio_listio ( ). This array may contain
NULL pointers, which are ignored. If this array contains pointers that refer to aiocb structures
that have not been used in submitting asynchronous I/O, the effect is undefined.
4184
4185
4186
4187
If the time interval indicated in the timespec structure pointed to by timeout passes before any of
the I/O operations referenced by list are completed, then aio_suspend( ) shall return with an
error. If the Monotonic Clock option is supported, the clock that shall be used to measure this
time interval shall be the CLOCK_MONOTONIC clock.
MON
4188
4189
4190
4191
RETURN VALUE
If the aio_suspend( ) function returns after one or more asynchronous I/O operations have
completed, the function shall return zero. Otherwise, the function shall return a value of −1 and
set errno to indicate the error.
4192
4193
The application may determine which asynchronous I/O completed by scanning the associated
error and return status using aio_error ( ) and aio_return( ), respectively.
4194
4195
ERRORS
The aio_suspend( ) function shall fail if:
4196
4197
[EAGAIN]
No asynchronous I/O indicated in the list referenced by list completed in the
time interval indicated by timeout.
4198
4199
4200
4201
[EINTR]
A signal interrupted the aio_suspend( ) function. Note that, since each
asynchronous I/O operation may possibly provoke a signal when it
completes, this error return may be caused by the completion of one (or more)
of the very I/O operations being awaited.
4202
4203
EXAMPLES
None.
4204
4205
4206
APPLICATION USAGE
The aio_suspend( ) function is part of the Asynchronous Input and Output option and need not
be available on all implementations.
4207
4208
RATIONALE
None.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
113
aio_suspend( )
System Interfaces
4209
4210
FUTURE DIRECTIONS
None.
4211
4212
SEE ALSO
aio_read ( ), aio_write ( ), lio_listio ( ), the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>
4213
4214
CHANGE HISTORY
First released in Issue 5. Included for alignment with the POSIX Realtime Extension.
4215
4216
4217
Issue 6
The [ENOSYS] error condition has been removed as stubs need not be provided if an
implementation does not support the Asynchronous Input and Output option.
4218
The APPLICATION USAGE section is added.
4219
4220
The DESCRIPTION is updated for alignment with IEEE Std 1003.1j-2000 by specifying that the
CLOCK_MONOTONIC clock, if supported, is used.
114
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
aio_write( )
System Interfaces
4221
4222
NAME
4223
4224
SYNOPSIS
AIO
#include <aio.h>
aio_write — asynchronous write to a file (REALTIME)
int aio_write(struct aiocb *aiocbp);
4225
4226
4227
4228
4229
4230
DESCRIPTION
The aio_write ( ) function shall write aiocbp->aio_nbytes to the file associated with aiocbp->aio_fildes
from the buffer pointed to by aiocbp->aio_buf. The function shall return when the write request
has been initiated or, at a minimum, queued to the file or device.
4231
4232
PIO
If prioritized I/O is supported for this file, then the asynchronous operation shall be submitted
at a priority equal to the scheduling priority of the process minus aiocbp->aio_reqprio.
4233
4234
4235
The aiocbp argument may be used as an argument to aio_error ( ) and aio_return( ) in order to
determine the error status and return status, respectively, of the asynchronous operation while it
is proceeding.
4236
4237
4238
The aiocbp argument points to an aiocb structure. If the buffer pointed to by aiocbp->aio_buf or
the control block pointed to by aiocbp becomes an illegal address prior to asynchronous I/O
completion, then the behavior is undefined.
4239
4240
4241
4242
4243
4244
If O_APPEND is not set for the file descriptor aio_fildes , then the requested operation shall take
place at the absolute position in the file as given by aio_offset , as if lseek( ) were called
immediately prior to the operation with an offset equal to aio_offset and a whence equal to
SEEK_SET. If O_APPEND is set for the file descriptor, write operations append to the file in the
same order as the calls were made. After a successful call to enqueue an asynchronous I/O
operation, the value of the file offset for the file is unspecified.
4245
The aiocbp->aio_lio_opcode field shall be ignored by aio_write ( ).
4246
Simultaneous asynchronous operations using the same aiocbp produce undefined results.
4247
4248
4249
SIO
If synchronized I/O is enabled on the file associated with aiocbp->aio_fildes, the behavior of this
function shall be according to the definitions of synchronized I/O data integrity completion, and
synchronized I/O file integrity completion.
4250
4251
For any system action that changes the process memory space while an asynchronous I/O is
outstanding to the address range being changed, the result of that action is undefined.
4252
4253
For regular files, no data transfer shall occur past the offset maximum established in the open
file description associated with aiocbp->aio_fildes.
4254
4255
4256
4257
RETURN VALUE
The aio_write ( ) function shall return the value zero to the calling process if the I/O operation is
successfully queued; otherwise, the function shall return the value −1 and set errno to indicate
the error.
4258
4259
ERRORS
The aio_write ( ) function shall fail if:
4260
4261
[EAGAIN]
4262
Each of the following conditions may be detected synchronously at the time of the call to
aio_write ( ), or asynchronously. If any of the conditions below are detected synchronously, the
aio_write ( ) function shall return −1 and set errno to the corresponding value. If any of the
4263
4264
The requested asynchronous I/O operation was not queued due to system
resource limitations.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
115
aio_write( )
System Interfaces
4265
4266
4267
conditions below are detected asynchronously, the return status of the asynchronous operation
shall be set to −1, and the error status of the asynchronous operation is set to the corresponding
value.
4268
[EBADF]
The aiocbp->aio_fildes argument is not a valid file descriptor open for writing.
4269
4270
4271
[EINVAL]
The file offset value implied by aiocbp->aio_offset would be invalid,
aiocbp->aio_reqprio is not a valid value, or aiocbp->aio_nbytes is an invalid
value.
4272
4273
4274
4275
4276
In the case that the aio_write ( ) successfully queues the I/O operation, the return status of the
asynchronous operation shall be one of the values normally returned by the write( ) function call.
If the operation is successfully queued but is subsequently canceled or encounters an error, the
error status for the asynchronous operation contains one of the values normally set by the
write( ) function call, or one of the following:
4277
[EBADF]
The aiocbp->aio_fildes argument is not a valid file descriptor open for writing.
4278
[EINVAL]
The file offset value implied by aiocbp->aio_offset would be invalid.
4279
4280
[ECANCELED]
The requested I/O was canceled before the I/O completed due to an explicit
aio_cancel ( ) request.
4281
The following condition may be detected synchronously or asynchronously:
4282
4283
4284
[EFBIG]
The file is a regular file, aiobcp->aio_nbytes is greater than 0, and the starting
offset in aiobcp->aio_offset is at or beyond the offset maximum in the open file
description associated with aiocbp->aio_fildes.
4285
4286
EXAMPLES
None.
4287
4288
4289
APPLICATION USAGE
The aio_write ( ) function is part of the Asynchronous Input and Output option and need not be
available on all implementations.
4290
4291
RATIONALE
None.
4292
4293
FUTURE DIRECTIONS
None.
4294
4295
4296
SEE ALSO
aio_cancel ( ), aio_error ( ), aio_read ( ), aio_return( ), close( ), exec, exit( ), fork ( ), lio_listio ( ), lseek( ),
write( ), the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>
4297
4298
CHANGE HISTORY
First released in Issue 5. Included for alignment with the POSIX Realtime Extension.
Large File Summit extensions are added.
4299
4300
4301
4302
Issue 6
The [ENOSYS] error condition has been removed as stubs need not be provided if an
implementation does not support the Asynchronous Input and Output option.
4303
The APPLICATION USAGE section is added.
4304
4305
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
•
4306
4307
116
In the DESCRIPTION, text is added to indicate that for regular files no data transfer occurs
past the offset maximum established in the open file description associated with
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
aiocbp->aio_fildes.
4308
4309
aio_write( )
•
The [EFBIG] error is added as part of the large file support extensions.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
117
alarm( )
System Interfaces
4310
4311
NAME
4312
4313
SYNOPSIS
#include <unistd.h>
alarm — schedule an alarm signal
unsigned alarm(unsigned seconds);
4314
4315
4316
4317
4318
DESCRIPTION
The alarm( ) function shall cause the system to generate a SIGALRM signal for the process after
the number of realtime seconds specified by seconds have elapsed. Processor scheduling delays
may prevent the process from handling the signal as soon as it is generated.
4319
If seconds is 0, a pending alarm request, if any, is canceled.
4320
4321
4322
Alarm requests are not stacked; only one SIGALRM generation can be scheduled in this manner.
If the SIGALRM signal has not yet been generated, the call shall result in rescheduling the time
at which the SIGALRM signal is generated.
Interactions between alarm( ) and any of setitimer( ), ualarm( ), or usleep( ) are unspecified.
4323
XSI
4324
4325
4326
4327
RETURN VALUE
If there is a previous alarm( ) request with time remaining, alarm( ) shall return a non-zero value
that is the number of seconds until the previous request would have generated a SIGALRM
signal. Otherwise, alarm( ) shall return 0.
4328
4329
ERRORS
The alarm( ) function is always successful, and no return value is reserved to indicate an error.
4330
4331
EXAMPLES
None.
4332
4333
4334
APPLICATION USAGE
The fork ( ) function clears pending alarms in the child process. A new process image created by
one of the exec functions inherits the time left to an alarm signal in the old process’ image.
4335
4336
4337
4338
4339
4340
Application writers should note that the type of the argument seconds and the return value of
alarm( ) is unsigned. That means that a Strictly Conforming POSIX System Interfaces
Application cannot pass a value greater than the minimum guaranteed value for {UINT_MAX},
which the ISO C standard sets as 65 535, and any application passing a larger value is restricting
its portability. A different type was considered, but historical implementations, including those
with a 16-bit int type, consistently use either unsigned or int.
4341
4342
Application writers should be aware of possible interactions when the same process uses both
the alarm( ) and sleep( ) functions.
4343
4344
4345
4346
4347
4348
4349
RATIONALE
Many historical implementations (including Version 7 and System V) allow an alarm to occur up
to a second early. Other implementations allow alarms up to half a second or one clock tick
early or do not allow them to occur early at all. The latter is considered most appropriate, since it
gives the most predictable behavior, especially since the signal can always be delayed for an
indefinite amount of time due to scheduling. Applications can thus choose the seconds argument
as the minimum amount of time they wish to have elapse before the signal.
4350
4351
4352
The term ‘‘realtime’’ here and elsewhere (sleep( ), times( )) is intended to mean ‘‘wall clock’’ time
as common English usage, and has nothing to do with ‘‘realtime operating systems’’. It is in
contrast to virtual time, which could be misinterpreted if just time were used.
4353
4354
In some implementations, including 4.3 BSD, very large values of the seconds argument are
silently rounded down to an implementation-defined maximum value. This maximum is large
118
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
alarm( )
4355
enough (to the order of several months) that the effect is not noticeable.
4356
4357
4358
4359
There were two possible choices for alarm generation in multi-threaded applications: generation
for the calling thread or generation for the process. The first option would not have been
particularly useful since the alarm state is maintained on a per-process basis and the alarm that
is established by the last invocation of alarm( ) is the only one that would be active.
4360
4361
4362
Furthermore, allowing generation of an asynchronous signal for a thread would have introduced
an exception to the overall signal model. This requires a compelling reason in order to be
justified.
4363
4364
FUTURE DIRECTIONS
None.
4365
4366
4367
SEE ALSO
alarm( ), exec, fork ( ), getitimer( ), pause( ), sigaction ( ), sleep( ), ualarm( ), usleep( ), the Base
Definitions volume of IEEE Std 1003.1-2001, <signal.h>, <unistd.h>
4368
4369
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
4370
4371
4372
Issue 6
4373
4374
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
•
The DESCRIPTION is updated to indicate that interactions with the setitimer( ), ualarm( ), and
usleep( ) functions are unspecified.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
119
asctime( )
System Interfaces
4375
4376
NAME
4377
4378
SYNOPSIS
#include <time.h>
4379
4380
4381
TSF
4382
4383
4384
4385
DESCRIPTION
CX
For asctime( ): The functionality described on this reference page is aligned with the ISO C
standard. Any conflict between the requirements described here and the ISO C standard is
unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4386
4387
The asctime( ) function shall convert the broken-down time in the structure pointed to by timeptr
into a string in the form:
4388
Sun Sep 16 01:03:52 1973\n\0
4389
using the equivalent of the following algorithm:
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
char *asctime(const struct tm *timeptr)
{
static char wday_name[7][3] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static char mon_name[12][3] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char result[26];
4400
4401
4402
4403
4404
4405
4406
4407
sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
wday_name[timeptr->tm_wday],
mon_name[timeptr->tm_mon],
timeptr->tm_mday, timeptr->tm_hour,
timeptr->tm_min, timeptr->tm_sec,
1900 + timeptr->tm_year);
return result;
}
4408
The tm structure is defined in the <time.h> header.
4409
4410
4411
4412
asctime, asctime_r — convert date and time to a string
CX
The asctime( ), ctime( ), gmtime( ), and localtime ( ) functions shall return values in one of two static
objects: a broken-down time structure and an array of type char. Execution of any of the
functions may overwrite the information returned in either of these objects by any of the other
functions.
The asctime( ) function need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
4413
4414
4415
4416
4417
char *asctime(const struct tm *timeptr);
char *asctime_r(const struct tm *restrict tm, char *restrict buf);
TSF
120
The asctime_r( ) function shall convert the broken-down time in the structure pointed to by tm
into a string (of the same form as that returned by asctime( )) that is placed in the user-supplied
buffer pointed to by buf (which shall contain at least 26 bytes) and then return buf.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
asctime( )
4418
4419
RETURN VALUE
Upon successful completion, asctime( ) shall return a pointer to the string.
4420
4421
4422
TSF
4423
4424
ERRORS
No errors are defined.
4425
4426
EXAMPLES
None.
4427
4428
4429
4430
4431
APPLICATION USAGE
Values for the broken-down time structure can be obtained by calling gmtime( ) or localtime ( ).
This function is included for compatibility with older implementations, and does not support
localized date and time formats. Applications should use strftime( ) to achieve maximum
portability.
4432
4433
The asctime_r( ) function is thread-safe and shall return values in a user-supplied buffer instead
of possibly using a static data area that may be overwritten by each call.
Upon successful completion, asctime_r( ) shall return a pointer to a character string containing
the date and time. This string is pointed to by the argument buf. If the function is unsuccessful,
it shall return NULL.
4434
4435
RATIONALE
None.
4436
4437
FUTURE DIRECTIONS
None.
4438
4439
4440
SEE ALSO
clock ( ), ctime( ), difftime ( ), gmtime( ), localtime ( ), mktime( ), strftime( ), strptime( ), time( ), utime( ),
the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>
4441
4442
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
4443
4444
4445
Issue 5
Normative text previously in the APPLICATION USAGE section is moved to the
DESCRIPTION.
4446
The asctime_r( ) function is included for alignment with the POSIX Threads Extension.
4447
4448
A note indicating that the asctime( ) function need not be reentrant is added to the
DESCRIPTION.
4449
4450
Issue 6
The asctime_r( ) function is marked as part of the Thread-Safe Functions option.
4451
Extensions beyond the ISO C standard are marked.
4452
4453
The APPLICATION USAGE section is updated to include a note on the thread-safe function and
its avoidance of possibly using a static data area.
4454
The DESCRIPTION of asctime_r( ) is updated to describe the format of the string returned.
4455
4456
The restrict keyword is added to the asctime_r( ) prototype for alignment with the
ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
121
asin( )
System Interfaces
4457
4458
NAME
4459
4460
SYNOPSIS
#include <math.h>
asin, asinf, asinl — arc sine function
double asin(double x);
float asinf(float x);
long double asinl(long double x);
4461
4462
4463
4464
4465
4466
4467
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4468
4469
These functions shall compute the principal value of the arc sine of their argument x. The value
of x should be in the range [−1,1].
4470
4471
4472
4473
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
4474
4475
4476
RETURN VALUE
Upon successful completion, these functions shall return the arc sine of x, in the range
[−π/2,π/2] radians.
4477
4478
MX
For finite values of x not in the range [−1,1], a domain error shall occur, and either a NaN (if
supported), or an implementation-defined value shall be returned.
4479
MX
If x is NaN, a NaN shall be returned.
4480
If x is ±0, x shall be returned.
4481
4482
If x is ±Inf, a domain error shall occur, and either a NaN (if supported), or an implementationdefined value shall be returned.
4483
If x is subnormal, a range error may occur and x should be returned.
4484
4485
ERRORS
These functions shall fail if:
4486
MX
Domain Error
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [EDOM]. If the integer expression (math_errhandling
& MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception
shall be raised.
4487
4488
4489
4490
These functions may fail if:
4491
4492
The x argument is finite and is not in the range [−1,1], or is ±Inf.
MX
Range Error
The value of x is subnormal.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
4493
4494
4495
4496
122
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
asin( )
4497
4498
EXAMPLES
None.
4499
4500
4501
APPLICATION USAGE
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
4502
4503
RATIONALE
None.
4504
4505
FUTURE DIRECTIONS
None.
4506
4507
4508
SEE ALSO
feclearexcept( ), fetestexcept( ), isnan( ), sin( ), the Base Definitions volume of IEEE Std 1003.1-2001,
Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
4509
4510
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
4511
4512
4513
Issue 5
4514
4515
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The asinf( ) and asinl( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
4516
4517
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
4518
4519
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
123
asinh( )
System Interfaces
4520
4521
NAME
4522
4523
SYNOPSIS
#include <math.h>
asinh, asinhf, asinhl — inverse hyperbolic sine functions
double asinh(double x);
float asinhf(float x);
long double asinhl(long double x);
4524
4525
4526
4527
4528
4529
4530
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4531
These functions shall compute the inverse hyperbolic sine of their argument x.
4532
4533
4534
4535
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
4536
4537
4538
RETURN VALUE
Upon successful completion, these functions shall return the inverse hyperbolic sine of their
argument.
4539
MX
If x is NaN, a NaN shall be returned.
4540
If x is ±0, or ±Inf, x shall be returned.
4541
If x is subnormal, a range error may occur and x should be returned.
4542
4543
ERRORS
These functions may fail if:
4544
MX
Range Error
The value of x is subnormal.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
4545
4546
4547
4548
4549
4550
EXAMPLES
None.
4551
4552
4553
APPLICATION USAGE
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
4554
4555
RATIONALE
None.
4556
4557
FUTURE DIRECTIONS
None.
4558
4559
4560
SEE ALSO
feclearexcept( ), fetestexcept( ), sinh( ), the Base Definitions volume of IEEE Std 1003.1-2001, Section
4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
124
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
4561
4562
CHANGE HISTORY
First released in Issue 4, Version 2.
4563
4564
Issue 5
4565
4566
Issue 6
asinh( )
Moved from X/OPEN UNIX extension to BASE.
The asinh( ) function is no longer marked as an extension.
4567
4568
The asinhf( ) and asinhl( ) functions are added for alignment with the ISO/IEC 9899: 1999
standard.
4569
4570
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
4571
4572
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
125
asinl( )
System Interfaces
4573
4574
NAME
4575
4576
SYNOPSIS
#include <math.h>
asinl — arc sine function
long double asinl(long double x);
4577
4578
4579
DESCRIPTION
Refer to asin( ).
126
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
4580
4581
NAME
4582
4583
SYNOPSIS
#include <assert.h>
assert( )
assert — insert program diagnostics
void assert(scalar expression);
4584
4585
4586
4587
4588
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4589
4590
4591
4592
The assert( ) macro shall insert diagnostics into programs; it shall expand to a void expression.
When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal
to 0), assert( ) shall write information about the particular call that failed on stderr and shall call
abort( ).
4593
4594
4595
4596
The information written about the call that failed shall include the text of the argument, the
name of the source file, the source file line number, and the name of the enclosing function; the
latter are, respectively, the values of the preprocessing macros _ _FILE_ _ and _ _LINE_ _ and of
the identifier _ _func_ _.
4597
4598
4599
Forcing a definition of the name NDEBUG, either from the compiler command line or with the
preprocessor control statement #define NDEBUG ahead of the #include <assert.h> statement,
shall stop assertions from being compiled into the program.
4600
4601
RETURN VALUE
The assert( ) macro shall not return a value.
4602
4603
ERRORS
No errors are defined.
4604
4605
EXAMPLES
None.
4606
4607
APPLICATION USAGE
None.
4608
4609
RATIONALE
None.
4610
4611
FUTURE DIRECTIONS
None.
4612
4613
SEE ALSO
abort( ), stderr, the Base Definitions volume of IEEE Std 1003.1-2001, <assert.h>
4614
4615
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
4616
4617
4618
Issue 6
4619
The prototype for the expression argument to assert( ) is changed from int to scalar for alignment
with the ISO/IEC 9899: 1999 standard.
The DESCRIPTION of assert( ) is updated for alignment with the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
127
atan( )
System Interfaces
4620
4621
NAME
4622
4623
SYNOPSIS
#include <math.h>
atan, atanf, atanl — arc tangent function
double atan(double x);
float atanf(float x);
long double atanl(long double x);
4624
4625
4626
4627
4628
4629
4630
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4631
These functions shall compute the principal value of the arc tangent of their argument x.
4632
4633
4634
4635
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
4636
4637
4638
RETURN VALUE
Upon successful completion, these functions shall return the arc tangent of x in the range
[−π/2,π/2] radians.
4639
MX
If x is NaN, a NaN shall be returned.
4640
If x is ±0, x shall be returned.
4641
If x is ±Inf, ±π/2 shall be returned.
4642
If x is subnormal, a range error may occur and x should be returned.
4643
4644
ERRORS
These functions may fail if:
4645
MX
Range Error
The value of x is subnormal.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
4646
4647
4648
4649
4650
4651
EXAMPLES
None.
4652
4653
4654
APPLICATION USAGE
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
4655
4656
RATIONALE
None.
4657
4658
FUTURE DIRECTIONS
None.
4659
4660
SEE ALSO
atan2( ), feclearexcept( ), fetestexcept( ), isnan( ), tan( ), the Base Definitions volume of
IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions,
<math.h>
4661
4662
128
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
4663
4664
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
4665
4666
4667
Issue 5
4668
4669
Issue 6
atan( )
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The atanf ( ) and atanl ( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
4670
4671
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
4672
4673
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
129
atan2( )
System Interfaces
4674
4675
NAME
4676
4677
SYNOPSIS
#include <math.h>
atan2, atan2f, atan2l — arc tangent functions
double atan2(double y, double x);
float atan2f(float y, float x);
long double atan2l(long double y, long double x);
4678
4679
4680
4681
4682
4683
4684
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4685
4686
These functions shall compute the principal value of the arc tangent of y/x, using the signs of
both arguments to determine the quadrant of the return value.
4687
4688
4689
4690
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
4691
4692
4693
RETURN VALUE
Upon successful completion, these functions shall return the arc tangent of y/x in the range
[−π,π] radians.
4694
If y is ±0 and x is < 0, ±π shall be returned.
4695
If y is ±0 and x is > 0, ±0 shall be returned.
4696
If y is < 0 and x is ±0, −π/2 shall be returned.
4697
If y is > 0 and x is ±0, π/2 shall be returned.
4698
If x is 0, a pole error shall not occur.
4699
MX
If either x or y is NaN, a NaN shall be returned.
4700
If the result underflows, a range error may occur and y/x should be returned.
4701
If y is ±0 and x is −0, ±π shall be returned.
4702
If y is ±0 and x is +0, ±0 shall be returned.
4703
For finite values of ±y > 0, if x is −Inf, ±π shall be returned.
4704
For finite values of ±y > 0, if x is +Inf, ±0 shall be returned.
4705
For finite values of x, if y is ±Inf, ±π/2 shall be returned.
4706
If y is ±Inf and x is −Inf, ±3π/4 shall be returned.
4707
If y is ±Inf and x is +Inf, ±π/4 shall be returned.
4708
If both arguments are 0, a domain error shall not occur.
4709
4710
ERRORS
These functions may fail if:
4711
MX
Range Error
The result underflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
4712
4713
130
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
atan2( )
System Interfaces
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
4714
4715
4716
4717
EXAMPLES
None.
4718
4719
4720
APPLICATION USAGE
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
4721
4722
RATIONALE
None.
4723
4724
FUTURE DIRECTIONS
None.
4725
4726
4727
4728
SEE ALSO
atan( ), feclearexcept( ), fetestexcept( ), isnan( ), tan( ), the Base Definitions volume of
IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions,
<math.h>
4729
4730
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
4731
4732
4733
Issue 5
4734
4735
4736
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The atan2f ( ) and atan2l ( ) functions are added for alignment with the ISO/IEC 9899: 1999
standard.
4737
4738
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
4739
4740
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
131
atanf( )
System Interfaces
4741
4742
NAME
4743
4744
SYNOPSIS
#include <math.h>
atanf — arc tangent function
float atanf(float x);
4745
4746
4747
DESCRIPTION
Refer to atan( ).
132
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
atanh( )
System Interfaces
4748
4749
NAME
4750
4751
SYNOPSIS
#include <math.h>
atanh, atanhf, atanhl — inverse hyperbolic tangent functions
double atanh(double x);
float atanhf(float x);
long double atanhl(long double x);
4752
4753
4754
4755
4756
4757
4758
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4759
These functions shall compute the inverse hyperbolic tangent of their argument x.
4760
4761
4762
4763
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
4764
4765
4766
RETURN VALUE
Upon successful completion, these functions shall return the inverse hyperbolic tangent of their
argument.
4767
4768
4769
If x is ±1, a pole error shall occur, and atanh( ), atanhf ( ), and atanhl ( ) shall return the value of the
macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively, with the same sign as the
correct value of the function.
4770
4771
MX
For finite |x|>1, a domain error shall occur, and either a NaN (if supported), or an
implementation-defined value shall be returned.
4772
MX
If x is NaN, a NaN shall be returned.
4773
If x is ±0, x shall be returned.
4774
4775
If x is ±Inf, a domain error shall occur, and either a NaN (if supported), or an implementationdefined value shall be returned.
4776
If x is subnormal, a range error may occur and x should be returned.
4777
4778
ERRORS
These functions shall fail if:
4779
MX
Domain Error
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [EDOM]. If the integer expression (math_errhandling
& MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception
shall be raised.
4780
4781
4782
4783
4784
4785
4786
4787
4788
The x argument is finite and not in the range [−1,1], or is ±Inf.
Pole Error
The x argument is ±1.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-byzero floating-point exception shall be raised.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
133
atanh( )
These functions may fail if:
4789
4790
System Interfaces
MX
Range Error
The value of x is subnormal.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
4791
4792
4793
4794
4795
4796
EXAMPLES
None.
4797
4798
4799
APPLICATION USAGE
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
4800
4801
RATIONALE
None.
4802
4803
FUTURE DIRECTIONS
None.
4804
4805
4806
SEE ALSO
feclearexcept( ), fetestexcept( ), tanh( ), the Base Definitions volume of IEEE Std 1003.1-2001, Section
4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
4807
4808
CHANGE HISTORY
First released in Issue 4, Version 2.
4809
4810
Issue 5
4811
4812
Issue 6
Moved from X/OPEN UNIX extension to BASE.
The atanh( ) function is no longer marked as an extension.
4813
4814
The atanhf ( ) and atanhl ( ) functions are added for alignment with the ISO/IEC 9899: 1999
standard.
4815
4816
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
4817
4818
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
134
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
4819
4820
NAME
4821
4822
SYNOPSIS
#include <math.h>
4823
4824
4825
atanl( )
atanl — arc tangent function
long double atanl(long double x);
DESCRIPTION
Refer to atan( ).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
135
atexit( )
System Interfaces
4826
4827
NAME
4828
4829
SYNOPSIS
#include <stdlib.h>
atexit — register a function to run at process termination
int atexit(void (*func)(void));
4830
4831
4832
4833
4834
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4835
4836
4837
4838
4839
4840
The atexit( ) function shall register the function pointed to by func, to be called without
arguments at normal program termination. At normal program termination, all functions
registered by the atexit( ) function shall be called, in the reverse order of their registration, except
that a function is called after any previously registered functions that had already been called at
the time it was registered. Normal termination occurs either by a call to exit( ) or a return from
main( ).
4841
At least 32 functions can be registered with atexit( ).
After a successful call to any of the exec functions, any functions previously registered by atexit( )
shall no longer be registered.
4842
4843
CX
4844
4845
RETURN VALUE
Upon successful completion, atexit( ) shall return 0; otherwise, it shall return a non-zero value.
4846
4847
ERRORS
No errors are defined.
4848
4849
EXAMPLES
None.
4850
4851
4852
APPLICATION USAGE
The functions registered by a call to atexit( ) must return to ensure that all registered functions
are called.
4853
4854
4855
The application should call sysconf( ) to obtain the value of {ATEXIT_MAX}, the number of
functions that can be registered. There is no way for an application to tell how many functions
have already been registered with atexit( ).
4856
4857
RATIONALE
None.
4858
4859
FUTURE DIRECTIONS
None.
4860
4861
SEE ALSO
exit( ), sysconf( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>
4862
4863
CHANGE HISTORY
First released in Issue 4. Derived from the ANSI C standard.
4864
4865
Issue 6
Extensions beyond the ISO C standard are marked.
The DESCRIPTION is updated for alignment with the ISO/IEC 9899: 1999 standard.
4866
136
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
4867
4868
NAME
4869
4870
SYNOPSIS
#include <stdlib.h>
4871
4872
4873
4874
4875
atof( )
atof — convert a string to a double-precision number
double atof(const char *str);
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4876
The call atof (str) shall be equivalent to:
4877
strtod(str,(char **)NULL),
4878
4879
except that the handling of errors may differ. If the value cannot be represented, the behavior is
undefined.
4880
4881
RETURN VALUE
The atof ( ) function shall return the converted value if the value can be represented.
4882
4883
ERRORS
No errors are defined.
4884
4885
EXAMPLES
None.
4886
4887
4888
4889
APPLICATION USAGE
The atof ( ) function is subsumed by strtod( ) but is retained because it is used extensively in
existing code. If the number is not known to be in range, strtod( ) should be used because atof ( ) is
not required to perform any error checking.
4890
4891
RATIONALE
None.
4892
4893
FUTURE DIRECTIONS
None.
4894
4895
SEE ALSO
strtod( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>
4896
4897
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
137
atoi( )
System Interfaces
4898
4899
NAME
4900
4901
SYNOPSIS
#include <stdlib.h>
atoi — convert a string to an integer
int atoi(const char *str);
4902
4903
4904
4905
4906
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4907
The call atoi (str) shall be equivalent to:
4908
(int) strtol(str, (char **)NULL, 10)
4909
4910
except that the handling of errors may differ. If the value cannot be represented, the behavior is
undefined.
4911
4912
RETURN VALUE
The atoi ( ) function shall return the converted value if the value can be represented.
4913
4914
ERRORS
No errors are defined.
4915
EXAMPLES
4916
Converting an Argument
4917
4918
4919
The following example checks for proper usage of the program. If there is an argument and the
decimal conversion of this argument (obtained using atoi ( )) is greater than 0, then the program
has a valid number of minutes to wait for an event.
4920
4921
4922
4923
4924
4925
4926
4927
4928
#include <stdlib.h>
#include <stdio.h>
...
int minutes_to_event;
...
if (argc < 2 || ((minutes_to_event = atoi (argv[1]))) <= 0) {
fprintf(stderr, "Usage: %s minutes\n", argv[0]); exit(1);
}
...
4929
4930
4931
4932
APPLICATION USAGE
The atoi ( ) function is subsumed by strtol( ) but is retained because it is used extensively in
existing code. If the number is not known to be in range, strtol( ) should be used because atoi ( ) is
not required to perform any error checking.
4933
4934
RATIONALE
None.
4935
4936
FUTURE DIRECTIONS
None.
4937
4938
SEE ALSO
strtol( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>
138
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
4939
4940
atoi( )
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
139
atol( )
System Interfaces
4941
4942
NAME
4943
4944
SYNOPSIS
#include <stdlib.h>
atol, atoll — convert a string to a long integer
long atol(const char *str);
long long atoll(const char *nptr);
4945
4946
4947
4948
4949
4950
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
4951
The call atol (str) shall be equivalent to:
4952
strtol(str, (char **)NULL, 10)
4953
The call atoll (str) shall be equivalent to:
4954
strtoll(nptr, (char **)NULL, 10)
4955
4956
except that the handling of errors may differ. If the value cannot be represented, the behavior is
undefined.
4957
4958
RETURN VALUE
These functions shall return the converted value if the value can be represented.
4959
4960
ERRORS
No errors are defined.
4961
4962
EXAMPLES
None.
4963
4964
4965
4966
APPLICATION USAGE
The atol ( ) function is subsumed by strtol( ) but is retained because it is used extensively in
existing code. If the number is not known to be in range, strtol( ) should be used because atol ( ) is
not required to perform any error checking.
4967
4968
RATIONALE
None.
4969
4970
FUTURE DIRECTIONS
None.
4971
4972
SEE ALSO
strtol( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>
4973
4974
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
4975
4976
Issue 6
The atoll ( ) function is added for alignment with the ISO/IEC 9899: 1999 standard.
140
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
4977
4978
NAME
4979
4980
SYNOPSIS
XSI
#include <libgen.h>
4981
4982
basename( )
basename — return the last component of a pathname
char *basename(char *path);
4983
4984
4985
DESCRIPTION
The basename( ) function shall take the pathname pointed to by path and return a pointer to the
final component of the pathname, deleting any trailing ’/’ characters.
4986
4987
4988
If the string consists entirely of the ’/’ character, basename( ) shall return a pointer to the string
"/". If the string is exactly "//", it is implementation-defined whether ’/’ or "//" is
returned.
4989
4990
If path is a null pointer or points to an empty string, basename( ) shall return a pointer to the
string ".".
4991
4992
The basename( ) function may modify the string pointed to by path, and may return a pointer to
static storage that may then be overwritten by a subsequent call to basename( ).
4993
4994
The basename( ) function need not be reentrant. A function that is not required to be reentrant is
not required to be thread-safe.
4995
4996
RETURN VALUE
The basename( ) function shall return a pointer to the final component of path.
4997
4998
ERRORS
No errors are defined.
4999
EXAMPLES
5000
Using basename( )
5001
5002
The following program fragment returns a pointer to the value lib, which is the base name of
/usr/lib.
5003
5004
5005
5006
#include <libgen.h>
...
char *name = "/usr/lib";
char *base;
5007
5008
base = basename(name);
...
5009
Sample Input and Output Strings for basename( )
5010
5011
In the following table, the input string is the value pointed to by path, and the output string is
the return value of the basename( ) function.
___________________________________
L
L
Input String
Output String L
___________________________________
L
L
L
"/usr/lib"
"lib"
L
L
L
"/usr/"
"usr"
L
L
L
"/"
L "/"
L
L
L "///"
L
L
"/"
L
L
L
"//usr//lib//" L "lib"
L_
__________________________________
L
5012
5013
5014
5015
5016
5017
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
141
basename( )
System Interfaces
5018
5019
APPLICATION USAGE
None.
5020
5021
RATIONALE
None.
5022
5023
FUTURE DIRECTIONS
None.
5024
5025
5026
SEE ALSO
dirname( ), the Base Definitions volume of IEEE Std 1003.1-2001, <libgen.h>, the Shell and
Utilities volume of IEEE Std 1003.1-2001, basename
5027
5028
CHANGE HISTORY
First released in Issue 4, Version 2.
5029
5030
Issue 5
Moved from X/OPEN UNIX extension to BASE.
5031
5032
Normative text previously in the APPLICATION USAGE section is moved to the
DESCRIPTION.
5033
A note indicating that this function need not be reentrant is added to the DESCRIPTION.
5034
5035
Issue 6
In the DESCRIPTION, the note about reentrancy is expanded to cover thread-safety.
142
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5036
5037
NAME
5038
5039
SYNOPSIS
XSI
#include <strings.h>
bcmp( )
bcmp — memory operations (LEGACY)
int bcmp(const void *s1, const void *s2, size_t n);
5040
5041
5042
5043
5044
DESCRIPTION
The bcmp( ) function shall compare the first n bytes of the area pointed to by s1 with the area
pointed to by s2.
5045
5046
5047
RETURN VALUE
The bcmp( ) function shall return 0 if s1 and s2 are identical; otherwise, it shall return non-zero.
Both areas are assumed to be n bytes long. If the value of n is 0, bcmp( ) shall return 0.
5048
5049
ERRORS
No errors are defined.
5050
5051
EXAMPLES
None.
5052
5053
APPLICATION USAGE
The memcmp( ) function is preferred over this function.
5054
For maximum portability, it is recommended to replace the function call to bcmp( ) as follows:
5055
#define bcmp(b1,b2,len) memcmp((b1), (b2), (size_t)(len))
5056
5057
RATIONALE
None.
5058
5059
FUTURE DIRECTIONS
This function may be withdrawn in a future version.
5060
5061
SEE ALSO
memcmp( ), the Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>
5062
5063
CHANGE HISTORY
First released in Issue 4, Version 2.
5064
5065
Issue 5
5066
5067
Issue 6
Moved from X/OPEN UNIX extension to BASE.
This function is marked LEGACY.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
143
bcopy( )
System Interfaces
5068
5069
NAME
5070
5071
SYNOPSIS
XSI
#include <strings.h>
bcopy — memory operations (LEGACY)
void bcopy(const void *s1, void *s2, size_t n);
5072
5073
5074
5075
5076
DESCRIPTION
The bcopy( ) function shall copy n bytes from the area pointed to by s1 to the area pointed to by
s2.
5077
5078
The bytes are copied correctly even if the area pointed to by s1 overlaps the area pointed to by
s2.
5079
5080
RETURN VALUE
The bcopy( ) function shall not return a value.
5081
5082
ERRORS
No errors are defined.
5083
5084
EXAMPLES
None.
5085
5086
APPLICATION USAGE
The memmove( ) function is preferred over this function.
5087
The following are approximately equivalent (note the order of the arguments):
5088
bcopy(s1,s2,n) ˜= memmove(s2,s1,n)
5089
For maximum portability, it is recommended to replace the function call to bcopy( ) as follows:
5090
#define bcopy(b1,b2,len) (memmove((b2), (b1), (len)), (void) 0)
5091
5092
RATIONALE
None.
5093
5094
FUTURE DIRECTIONS
This function may be withdrawn in a future version.
5095
5096
SEE ALSO
memmove( ), the Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>
5097
5098
CHANGE HISTORY
First released in Issue 4, Version 2.
5099
5100
Issue 5
5101
5102
Issue 6
Moved from X/OPEN UNIX extension to BASE.
This function is marked LEGACY.
144
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
bind( )
System Interfaces
5103
5104
NAME
5105
5106
SYNOPSIS
#include <sys/socket.h>
5107
5108
5109
5110
5111
5112
bind — bind a name to a socket
int bind(int socket, const struct sockaddr *address,
socklen_t address_len);
DESCRIPTION
The bind( ) function shall assign a local socket address address to a socket identified by descriptor
socket that has no local socket address assigned. Sockets created with the socket( ) function are
initially unnamed; they are identified only by their address family.
5113
The bind( ) function takes the following arguments:
5114
socket
Specifies the file descriptor of the socket to be bound.
5115
5116
5117
address
Points to a sockaddr structure containing the address to be bound to the
socket. The length and format of the address depend on the address family of
the socket.
5118
5119
address_len
Specifies the length of the sockaddr structure pointed to by the address
argument.
5120
5121
The socket specified by socket may require the process to have appropriate privileges to use the
bind( ) function.
5122
5123
5124
RETURN VALUE
Upon successful completion, bind( ) shall return 0; otherwise, −1 shall be returned and errno set
to indicate the error.
5125
5126
ERRORS
The bind( ) function shall fail if:
5127
[EADDRINUSE] The specified address is already in use.
5128
5129
[EADDRNOTAVAIL]
The specified address is not available from the local machine.
5130
5131
5132
[EAFNOSUPPORT]
The specified address is not a valid address for the address family of the
specified socket.
5133
[EBADF]
The socket argument is not a valid file descriptor.
5134
5135
[EINVAL]
The socket is already bound to an address, and the protocol does not support
binding to a new address; or the socket has been shut down.
5136
[ENOTSOCK]
The socket argument does not refer to a socket.
5137
5138
[EOPNOTSUPP] The socket type of the specified socket does not support binding to an
address.
5139
If the address family of the socket is AF_UNIX, then bind( ) shall fail if:
5140
5141
5142
[EACCES]
5143
5144
[EDESTADDRREQ] or [EISDIR]
The address argument is a null pointer.
A component of the path prefix denies search permission, or the requested
name requires writing in a directory with a mode that denies write
permission.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
145
bind( )
System Interfaces
5145
[EIO]
An I/O error occurred.
5146
5147
[ELOOP]
A loop exists in symbolic links encountered during resolution of the pathname
in address.
5148
5149
5150
[ENAMETOOLONG]
A component of a pathname exceeded {NAME_MAX} characters, or an entire
pathname exceeded {PATH_MAX} characters.
5151
5152
[ENOENT]
A component of the pathname does not name an existing file or the pathname
is an empty string.
5153
[ENOTDIR]
A component of the path prefix of the pathname in address is not a directory.
5154
[EROFS]
The name would reside on a read-only file system.
5155
The bind( ) function may fail if:
5156
5157
[EACCES]
The specified address is protected and the current user does not have
permission to bind to it.
5158
[EINVAL]
The address_len argument is not a valid length for the address family.
5159
[EISCONN]
The socket is already connected.
5160
5161
[ELOOP]
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the pathname in address.
5162
5163
5164
[ENAMETOOLONG]
Pathname resolution of a symbolic link produced an intermediate result
whose length exceeds {PATH_MAX}.
5165
[ENOBUFS]
Insufficient resources were available to complete the call.
5166
5167
EXAMPLES
None.
5168
5169
APPLICATION USAGE
An application program can retrieve the assigned socket name with the getsockname( ) function.
5170
5171
RATIONALE
None.
5172
5173
FUTURE DIRECTIONS
None.
5174
5175
5176
SEE ALSO
connect( ), getsockname( ), listen( ), socket( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<sys/socket.h>
5177
5178
CHANGE HISTORY
First released in Issue 6. Derived from the XNS, Issue 5.2 specification.
146
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5179
5180
NAME
5181
5182
SYNOPSIS
OB XSI
#include <signal.h>
5183
5184
5185
5186
5187
bsd_signal( )
bsd_signal — simplified signal facilities
void (*bsd_signal(int sig, void (*func)(int)))(int);
DESCRIPTION
The bsd_signal( ) function provides a partially compatible interface for programs written to
historical system interfaces (see APPLICATION USAGE).
5188
The function call bsd_signal(sig, func) shall be equivalent to the following:
5189
5190
5191
void (*bsd_signal(int sig, void (*func)(int)))(int)
{
struct sigaction act, oact;
act.sa_handler = func;
act.sa_flags = SA_RESTART;
sigemptyset(&act.sa_mask);
sigaddset(&act.sa_mask, sig);
if (sigaction(sig, &act, &oact) == -1)
return(SIG_ERR);
return(oact.sa_handler);
5192
5193
5194
5195
5196
5197
5198
5199
}
5200
The handler function should be declared:
5201
void handler(int sig);
5202
5203
where sig is the signal number. The behavior is undefined if func is a function that takes more
than one argument, or an argument of a different type.
5204
5205
5206
RETURN VALUE
Upon successful completion, bsd_signal( ) shall return the previous action for sig. Otherwise,
SIG_ERR shall be returned and errno shall be set to indicate the error.
5207
5208
ERRORS
Refer to sigaction ( ).
5209
5210
EXAMPLES
None.
5211
5212
5213
5214
5215
5216
5217
APPLICATION USAGE
This function is a direct replacement for the BSD signal( ) function for simple applications that
are installing a single-argument signal handler function. If a BSD signal handler function is being
installed that expects more than one argument, the application has to be modified to use
sigaction ( ). The bsd_signal( ) function differs from signal( ) in that the SA_RESTART flag is set
and the SA_RESETHAND is clear when bsd_signal( ) is used. The state of these flags is not
specified for signal( ).
5218
5219
5220
It is recommended that new applications use the sigaction ( ) function.
RATIONALE
None.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
147
bsd_signal( )
System Interfaces
5221
5222
FUTURE DIRECTIONS
None.
5223
5224
5225
SEE ALSO
sigaction ( ), sigaddset( ), sigemptyset( ),
IEEE Std 1003.1-2001, <signal.h>
5226
5227
CHANGE HISTORY
First released in Issue 4, Version 2.
5228
5229
Issue 5
5230
5231
Issue 6
signal( ),
the
Base
Definitions
volume
of
Moved from X/OPEN UNIX extension to BASE.
This function is marked obsolescent.
148
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
bsearch( )
System Interfaces
5232
5233
NAME
5234
5235
SYNOPSIS
#include <stdlib.h>
5236
5237
bsearch — binary search a sorted table
void *bsearch(const void *key, const void *base, size_t nel,
size_t width, int (*compar)(const void *, const void *));
5238
5239
5240
5241
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5242
5243
5244
The bsearch( ) function shall search an array of nel objects, the initial element of which is pointed
to by base, for an element that matches the object pointed to by key. The size of each element in
the array is specified by width.
5245
5246
The comparison function pointed to by compar shall be called with two arguments that point to
the key object and to an array element, in that order.
5247
5248
5249
5250
5251
The application shall ensure that the function returns an integer less than, equal to, or greater
than 0 if the key object is considered, respectively, to be less than, to match, or to be greater than
the array element. The application shall ensure that the array consists of all the elements that
compare less than, all the elements that compare equal to, and all the elements that compare
greater than the key object, in that order.
5252
5253
5254
5255
RETURN VALUE
The bsearch( ) function shall return a pointer to a matching member of the array, or a null pointer
if no match is found. If two or more members compare equal, which member is returned is
unspecified.
5256
5257
ERRORS
No errors are defined.
5258
5259
5260
EXAMPLES
The example below searches a table containing pointers to nodes consisting of a string and its
length. The table is ordered alphabetically on the string in the node pointed to by each entry.
5261
5262
The code fragment below reads in strings and either finds the corresponding node and prints out
the string and its length, or prints an error message.
5263
5264
5265
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
5266
#define TABSIZE
5267
5268
5269
5270
5271
5272
5273
5274
struct node {
/* These are stored in the table. */
char *string;
int length;
};
struct node table[TABSIZE];
/* Table to be searched. */
.
.
.
{
struct node *node_ptr, node;
/* Routine to compare 2 nodes. */
5275
5276
5277
1000
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
149
bsearch( )
System Interfaces
int node_compare(const void *, const void *);
char str_space[20];
/* Space to read string into. */
.
.
.
node.string = str_space;
while (scanf("%s", node.string) != EOF) {
node_ptr = (struct node *)bsearch((void *)(&node),
(void *)table, TABSIZE,
sizeof(struct node), node_compare);
if (node_ptr != NULL) {
(void)printf("string = %20s, length = %d\n",
node_ptr->string, node_ptr->length);
} else {
(void)printf("not found: %s\n", node.string);
}
}
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
}
/*
This routine compares two nodes based on an
alphabetical ordering of the string field.
*/
int
node_compare(const void *node1, const void *node2)
{
return strcoll(((const struct node *)node1)->string,
((const struct node *)node2)->string);
}
5306
5307
5308
APPLICATION USAGE
The pointers to the key and the element at the base of the table should be of type pointer-toelement.
5309
5310
The comparison function need not compare every byte, so arbitrary data may be contained in
the elements in addition to the values being compared.
5311
In practice, the array is usually sorted according to the comparison function.
5312
5313
RATIONALE
None.
5314
5315
FUTURE DIRECTIONS
None.
5316
5317
5318
SEE ALSO
hcreate( ), lsearch( ), qsort( ), tsearch( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<stdlib.h>
5319
5320
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
5321
5322
Issue 6
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
150
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5323
5324
NAME
5325
5326
5327
SYNOPSIS
#include <stdio.h>
#include <wchar.h>
5328
btowc( )
btowc — single byte to wide character conversion
wint_t btowc(int c);
5329
5330
5331
5332
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5333
5334
The btowc( ) function shall determine whether c constitutes a valid (one-byte) character in the
initial shift state.
5335
The behavior of this function shall be affected by the LC_CTYPE category of the current locale.
5336
5337
5338
5339
RETURN VALUE
The btowc( ) function shall return WEOF if c has the value EOF or if (unsigned char) c does not
constitute a valid (one-byte) character in the initial shift state. Otherwise, it shall return the
wide-character representation of that character.
5340
5341
ERRORS
No errors are defined.
5342
5343
EXAMPLES
None.
5344
5345
APPLICATION USAGE
None.
5346
5347
RATIONALE
None.
5348
5349
FUTURE DIRECTIONS
None.
5350
5351
SEE ALSO
wctob( ), the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>
5352
5353
5354
CHANGE HISTORY
First released in Issue 5. Included for alignment with ISO/IEC 9899: 1990/Amendment 1: 1995
(E).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
151
bzero( )
System Interfaces
5355
5356
NAME
5357
5358
SYNOPSIS
XSI
#include <strings.h>
bzero — memory operations (LEGACY)
void bzero(void *s, size_t n);
5359
5360
5361
5362
DESCRIPTION
The bzero( ) function shall place n zero-valued bytes in the area pointed to by s.
5363
5364
RETURN VALUE
The bzero( ) function shall not return a value.
5365
5366
ERRORS
No errors are defined.
5367
5368
EXAMPLES
None.
5369
5370
APPLICATION USAGE
The memset( ) function is preferred over this function.
5371
For maximum portability, it is recommended to replace the function call to bzero( ) as follows:
5372
#define bzero(b,len) (memset((b), ’\0’, (len)), (void) 0)
5373
5374
RATIONALE
None.
5375
5376
FUTURE DIRECTIONS
This function may be withdrawn in a future version.
5377
5378
SEE ALSO
memset( ), the Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>
5379
5380
CHANGE HISTORY
First released in Issue 4, Version 2.
5381
5382
Issue 5
5383
5384
Issue 6
Moved from X/OPEN UNIX extension to BASE.
This function is marked LEGACY.
152
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5385
5386
NAME
5387
5388
SYNOPSIS
#include <complex.h>
5389
5390
5391
cabs( )
cabs, cabsf, cabsl — return a complex absolute value
double cabs(double complex z);
float cabsf(float complex z);
long double cabsl(long double complex z);
5392
5393
5394
5395
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5396
5397
These functions shall compute the complex absolute value (also called norm, modulus, or
magnitude) of z.
5398
5399
RETURN VALUE
These functions shall return the complex absolute value.
5400
5401
ERRORS
No errors are defined.
5402
5403
EXAMPLES
None.
5404
5405
APPLICATION USAGE
None.
5406
5407
RATIONALE
None.
5408
5409
FUTURE DIRECTIONS
None.
5410
5411
SEE ALSO
The Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
5412
5413
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
153
cacos( )
System Interfaces
5414
5415
NAME
5416
5417
SYNOPSIS
#include <complex.h>
cacos, cacosf, cacosl — complex arc cosine functions
double complex cacos(double complex z);
float complex cacosf(float complex z);
long double complex cacosl(long double complex z);
5418
5419
5420
5421
5422
5423
5424
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5425
5426
These functions shall compute the complex arc cosine of z, with branch cuts outside the interval
[−1, +1] along the real axis.
5427
5428
5429
RETURN VALUE
These functions shall return the complex arc cosine value, in the range of a strip mathematically
unbounded along the imaginary axis and in the interval [0, π] along the real axis.
5430
5431
ERRORS
No errors are defined.
5432
5433
EXAMPLES
None.
5434
5435
APPLICATION USAGE
None.
5436
5437
RATIONALE
None.
5438
5439
FUTURE DIRECTIONS
None.
5440
5441
SEE ALSO
ccos( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
5442
5443
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
154
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5444
5445
NAME
5446
5447
SYNOPSIS
#include <complex.h>
5448
5449
5450
cacosh( )
cacosh, cacoshf, cacoshl — complex arc hyperbolic cosine functions
double complex cacosh(double complex z);
float complex cacoshf(float complex z);
long double complex cacoshl(long double complex z);
5451
5452
5453
5454
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5455
5456
These functions shall compute the complex arc hyperbolic cosine of z, with a branch cut at
values less than 1 along the real axis.
5457
5458
5459
RETURN VALUE
These functions shall return the complex arc hyperbolic cosine value, in the range of a half-strip
of non-negative values along the real axis and in the interval [−iπ, +iπ] along the imaginary axis.
5460
5461
ERRORS
No errors are defined.
5462
5463
EXAMPLES
None.
5464
5465
APPLICATION USAGE
None.
5466
5467
RATIONALE
None.
5468
5469
FUTURE DIRECTIONS
None.
5470
5471
SEE ALSO
ccosh( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
5472
5473
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
155
cacosl( )
System Interfaces
5474
5475
NAME
5476
5477
SYNOPSIS
#include <complex.h>
cacosl — complex arc cosine functions
long double complex cacosl(long double complex z);
5478
5479
5480
DESCRIPTION
Refer to cacos( ).
156
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
calloc( )
System Interfaces
5481
5482
NAME
5483
5484
SYNOPSIS
#include <stdlib.h>
calloc — a memory allocator
void *calloc(size_t nelem, size_t elsize);
5485
5486
5487
5488
5489
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5490
5491
The calloc ( ) function shall allocate unused space for an array of nelem elements each of whose
size in bytes is elsize. The space shall be initialized to all bits 0.
5492
5493
5494
5495
5496
5497
5498
5499
The order and contiguity of storage allocated by successive calls to calloc ( ) is unspecified. The
pointer returned if the allocation succeeds shall be suitably aligned so that it may be assigned to
a pointer to any type of object and then used to access such an object or an array of such objects
in the space allocated (until the space is explicitly freed or reallocated). Each such allocation
shall yield a pointer to an object disjoint from any other object. The pointer returned shall point
to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null
pointer shall be returned. If the size of the space requested is 0, the behavior is implementationdefined: the value returned shall be either a null pointer or a unique pointer.
5500
5501
5502
5503
5504
RETURN VALUE
Upon successful completion with both nelem and elsize non-zero, calloc ( ) shall return a pointer to
the allocated space. If either nelem or elsize is 0, then either a null pointer or a unique pointer
value that can be successfully passed to free( ) shall be returned. Otherwise, it shall return a null
CX
pointer and set errno to indicate the error.
5505
5506
ERRORS
The calloc ( ) function shall fail if:
5507
CX
5508
5509
EXAMPLES
None.
5510
5511
APPLICATION USAGE
There is now no requirement for the implementation to support the inclusion of <malloc.h>.
5512
5513
RATIONALE
None.
5514
5515
FUTURE DIRECTIONS
None.
5516
5517
SEE ALSO
free( ), malloc ( ), realloc ( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>
5518
5519
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
5520
5521
Issue 6
[ENOMEM]
Insufficient memory is available.
Extensions beyond the ISO C standard are marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
157
calloc( )
System Interfaces
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
5522
5523
•
5524
5525
158
The setting of errno and the [ENOMEM] error condition are mandatory if an insufficient
memory condition occurs.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5526
5527
NAME
5528
5529
SYNOPSIS
#include <complex.h>
5530
5531
5532
carg( )
carg, cargf, cargl — complex argument functions
double carg(double complex z);
float cargf(float complex z);
long double cargl(long double complex z);
5533
5534
5535
5536
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5537
5538
These functions shall compute the argument (also called phase angle) of z, with a branch cut
along the negative real axis.
5539
5540
RETURN VALUE
These functions shall return the value of the argument in the interval [−π, +π].
5541
5542
ERRORS
No errors are defined.
5543
5544
EXAMPLES
None.
5545
5546
APPLICATION USAGE
None.
5547
5548
RATIONALE
None.
5549
5550
FUTURE DIRECTIONS
None.
5551
5552
SEE ALSO
cimag( ), conj( ), cproj( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
5553
5554
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
159
casin( )
System Interfaces
5555
5556
NAME
5557
5558
SYNOPSIS
#include <complex.h>
casin, casinf, casinl — complex arc sine functions
double complex casin(double complex z);
float complex casinf(float complex z);
long double complex casinl(long double complex z);
5559
5560
5561
5562
5563
5564
5565
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5566
5567
These functions shall compute the complex arc sine of z, with branch cuts outside the interval
[−1, +1] along the real axis.
5568
5569
5570
RETURN VALUE
These functions shall return the complex arc sine value, in the range of a strip mathematically
unbounded along the imaginary axis and in the interval [−π/2, +π/2] along the real axis.
5571
5572
ERRORS
No errors are defined.
5573
5574
EXAMPLES
None.
5575
5576
APPLICATION USAGE
None.
5577
5578
RATIONALE
None.
5579
5580
FUTURE DIRECTIONS
None.
5581
5582
SEE ALSO
csin( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
5583
5584
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
160
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5585
5586
NAME
5587
5588
SYNOPSIS
#include <complex.h>
5589
5590
5591
casinh( )
casinh, casinhf, casinhl — complex arc hyperbolic sine functions
double complex casinh(double complex z);
float complex casinhf(float complex z);
long double complex casinhl(long double complex z);
5592
5593
5594
5595
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5596
5597
These functions shall compute the complex arc hyperbolic sine of z, with branch cuts outside the
interval [−i, +i] along the imaginary axis.
5598
5599
5600
5601
RETURN VALUE
These functions shall return the complex arc hyperbolic sine value, in the range of a strip
mathematically unbounded along the real axis and in the interval [−iπ/2, +iπ/2] along the
imaginary axis.
5602
5603
ERRORS
No errors are defined.
5604
5605
EXAMPLES
None.
5606
5607
APPLICATION USAGE
None.
5608
5609
RATIONALE
None.
5610
5611
FUTURE DIRECTIONS
None.
5612
5613
SEE ALSO
csinh( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
5614
5615
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
161
casinl( )
System Interfaces
5616
5617
NAME
5618
5619
SYNOPSIS
#include <complex.h>
casinl — complex arc sine functions
long double complex casinl(long double complex z);
5620
5621
5622
DESCRIPTION
Refer to casin( ).
162
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5623
5624
NAME
5625
5626
SYNOPSIS
#include <complex.h>
5627
5628
5629
catan( )
catan, catanf, catanl — complex arc tangent functions
double complex catan(double complex z);
float complex catanf(float complex z);
long double complex catanl(long double complex z);
5630
5631
5632
5633
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5634
5635
These functions shall compute the complex arc tangent of z, with branch cuts outside the
interval [−i, +i] along the imaginary axis.
5636
5637
5638
5639
RETURN VALUE
These functions shall return the complex arc tangent value, in the range of a strip
mathematically unbounded along the imaginary axis and in the interval [−π/2, +π/2] along the
real axis.
5640
5641
ERRORS
No errors are defined.
5642
5643
EXAMPLES
None.
5644
5645
APPLICATION USAGE
None.
5646
5647
RATIONALE
None.
5648
5649
FUTURE DIRECTIONS
None.
5650
5651
SEE ALSO
ctan( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
5652
5653
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
163
catanh( )
System Interfaces
5654
5655
NAME
5656
5657
SYNOPSIS
#include <complex.h>
catanh, catanhf, catanhl — complex arc hyperbolic tangent functions
double complex catanh(double complex z);
float complex catanhf(float complex z);
long double complex catanhl(long double complex z);
5658
5659
5660
5661
5662
5663
5664
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5665
5666
These functions shall compute the complex arc hyperbolic tangent of z, with branch cuts outside
the interval [−1, +1] along the real axis.
5667
5668
5669
5670
RETURN VALUE
These functions shall return the complex arc hyperbolic tangent value, in the range of a strip
mathematically unbounded along the real axis and in the interval [−iπ/2, +iπ/2] along the
imaginary axis.
5671
5672
ERRORS
No errors are defined.
5673
5674
EXAMPLES
None.
5675
5676
APPLICATION USAGE
None.
5677
5678
RATIONALE
None.
5679
5680
FUTURE DIRECTIONS
None.
5681
5682
SEE ALSO
ctanh( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
5683
5684
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
164
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5685
5686
NAME
5687
5688
SYNOPSIS
#include <complex.h>
5689
5690
5691
catanl( )
catanl — complex arc tangent functions
long double complex catanl(long double complex z);
DESCRIPTION
Refer to catan( ).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
165
catclose( )
System Interfaces
5692
5693
NAME
5694
5695
SYNOPSIS
XSI
#include <nl_types.h>
catclose — close a message catalog descriptor
int catclose(nl_catd catd);
5696
5697
5698
5699
5700
DESCRIPTION
The catclose ( ) function shall close the message catalog identified by catd. If a file descriptor is
used to implement the type nl_catd, that file descriptor shall be closed.
5701
5702
5703
RETURN VALUE
Upon successful completion, catclose ( ) shall return 0; otherwise, −1 shall be returned, and errno
set to indicate the error.
5704
5705
ERRORS
The catclose ( ) function may fail if:
5706
[EBADF]
The catalog descriptor is not valid.
5707
[EINTR]
The catclose ( ) function was interrupted by a signal.
5708
5709
EXAMPLES
None.
5710
5711
APPLICATION USAGE
None.
5712
5713
RATIONALE
None.
5714
5715
FUTURE DIRECTIONS
None.
5716
5717
SEE ALSO
catgets( ), catopen( ), the Base Definitions volume of IEEE Std 1003.1-2001, <nl_types.h>
5718
5719
CHANGE HISTORY
First released in Issue 2.
166
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
catgets( )
System Interfaces
5720
5721
NAME
5722
5723
SYNOPSIS
XSI
#include <nl_types.h>
catgets — read a program message
char *catgets(nl_catd catd, int set_id, int msg_id, const char *s);
5724
5725
5726
5727
5728
5729
5730
DESCRIPTION
The catgets( ) function shall attempt to read message msg_id, in set set_id, from the message
catalog identified by catd. The catd argument is a message catalog descriptor returned from an
earlier call to catopen( ). The s argument points to a default message string which shall be
returned by catgets( ) if it cannot retrieve the identified message.
5731
5732
The catgets( ) function need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
5733
5734
5735
5736
RETURN VALUE
If the identified message is retrieved successfully, catgets( ) shall return a pointer to an internal
buffer area containing the null-terminated message string. If the call is unsuccessful for any
reason, s shall be returned and errno may be set to indicate the error.
5737
5738
ERRORS
The catgets( ) function may fail if:
5739
[EBADF]
The catd argument is not a valid message catalog descriptor open for reading.
5740
5741
[EBADMSG]
The message identified by set_id and msg_id in the specified message catalog
did not satisfy implementation-defined security criteria.
5742
5743
[EINTR]
The read operation was terminated due to the receipt of a signal, and no data
was transferred.
5744
[EINVAL]
The message catalog identified by catd is corrupted.
5745
[ENOMSG]
The message identified by set_id and msg_id is not in the message catalog.
5746
5747
EXAMPLES
None.
5748
5749
APPLICATION USAGE
None.
5750
5751
RATIONALE
None.
5752
5753
FUTURE DIRECTIONS
None.
5754
5755
SEE ALSO
catclose ( ), catopen( ), the Base Definitions volume of IEEE Std 1003.1-2001, <nl_types.h>
5756
5757
CHANGE HISTORY
First released in Issue 2.
5758
5759
Issue 5
A note indicating that this function need not be reentrant is added to the DESCRIPTION.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
167
catgets( )
5760
5761
System Interfaces
Issue 6
In the DESCRIPTION, the note about reentrancy is expanded to cover thread-safety.
168
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
catopen( )
System Interfaces
5762
5763
NAME
5764
5765
SYNOPSIS
XSI
#include <nl_types.h>
5766
5767
catopen — open a message catalog
nl_catd catopen(const char *name, int oflag);
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
DESCRIPTION
The catopen( ) function shall open a message catalog and return a message catalog descriptor.
The name argument specifies the name of the message catalog to be opened. If name contains a
’/’, then name specifies a complete name for the message catalog. Otherwise, the environment
variable NLSPATH is used with name substituted for the %N conversion specification (see the
Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables). If
NLSPATH exists in the environment when the process starts, then if the process has appropriate
privileges, the behavior of catopen( ) is undefined. If NLSPATH does not exist in the environment,
or if a message catalog cannot be found in any of the components specified by NLSPATH, then
an implementation-defined default path shall be used. This default may be affected by the
setting of LC_MESSAGES if the value of oflag is NL_CAT_LOCALE, or the LANG environment
variable if oflag is 0.
5780
5781
5782
A message catalog descriptor shall remain valid in a process until that process closes it, or a
successful call to one of the exec functions. A change in the setting of the LC_MESSAGES
category may invalidate existing open catalogs.
5783
5784
If a file descriptor is used to implement message catalog descriptors, the FD_CLOEXEC flag
shall be set; see <fcntl.h>.
5785
5786
5787
5788
If the value of the oflag argument is 0, the LANG environment variable is used to locate the
catalog without regard to the LC_MESSAGES category. If the oflag argument is
NL_CAT_LOCALE, the LC_MESSAGES category is used to locate the message catalog (see the
Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables).
5789
5790
5791
5792
RETURN VALUE
Upon successful completion, catopen( ) shall return a message catalog descriptor for use on
subsequent calls to catgets( ) and catclose ( ). Otherwise, catopen( ) shall return (nl_catd) −1 and set
errno to indicate the error.
5793
5794
ERRORS
The catopen( ) function may fail if:
5795
5796
[EACCES]
Search permission is denied for the component of the path prefix of the
message catalog or read permission is denied for the message catalog.
5797
[EMFILE]
{OPEN_MAX} file descriptors are currently open in the calling process.
5798
5799
5800
[ENAMETOOLONG]
The length of a pathname of the message catalog exceeds {PATH_MAX} or a
pathname component is longer than {NAME_MAX}.
5801
5802
5803
[ENAMETOOLONG]
Pathname resolution of a symbolic link produced an intermediate result
whose length exceeds {PATH_MAX}.
5804
[ENFILE]
Too many files are currently open in the system.
5805
5806
[ENOENT]
The message catalog does not exist or the name argument points to an empty
string.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
169
catopen( )
System Interfaces
5807
[ENOMEM]
Insufficient storage space is available.
5808
[ENOTDIR]
A component of the path prefix of the message catalog is not a directory.
5809
5810
EXAMPLES
None.
5811
5812
5813
5814
APPLICATION USAGE
Some implementations of catopen( ) use malloc ( ) to allocate space for internal buffer areas. The
catopen( ) function may fail if there is insufficient storage space available to accommodate these
buffers.
5815
5816
Conforming applications must assume that message catalog descriptors are not valid after a call
to one of the exec functions.
5817
5818
5819
Application writers should be aware that guidelines for the location of message catalogs have
not yet been developed. Therefore they should take care to avoid conflicting with catalogs used
by other applications and the standard utilities.
5820
5821
RATIONALE
None.
5822
5823
FUTURE DIRECTIONS
None.
5824
5825
5826
SEE ALSO
catclose ( ), catgets( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<nl_types.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001
5827
5828
CHANGE HISTORY
First released in Issue 2.
170
<fcntl.h>,
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5829
5830
NAME
5831
5832
SYNOPSIS
#include <math.h>
cbrt, cbrtf, cbrtl — cube root functions
double cbrt(double x);
float cbrtf(float x);
long double cbrtl(long double x);
5833
5834
5835
5836
5837
5838
5839
cbrt( )
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the real cube root of their argument x.
5840
5841
5842
RETURN VALUE
Upon successful completion, these functions shall return the cube root of x.
5843
MX
If x is NaN, a NaN shall be returned.
If x is ±0 or ±Inf, x shall be returned.
5844
5845
5846
ERRORS
No errors are defined.
5847
5848
EXAMPLES
None.
5849
5850
APPLICATION USAGE
None.
5851
5852
5853
RATIONALE
For some applications, a true cube root function, which returns negative results for negative
arguments, is more appropriate than pow(x, 1.0/3.0), which returns a NaN for x less than 0.
5854
5855
FUTURE DIRECTIONS
None.
5856
5857
SEE ALSO
The Base Definitions volume of IEEE Std 1003.1-2001, <math.h>
5858
5859
CHANGE HISTORY
First released in Issue 4, Version 2.
5860
5861
Issue 5
5862
5863
Issue 6
Moved from X/OPEN UNIX extension to BASE.
The cbrt( ) function is no longer marked as an extension.
5864
The cbrtf( ) and cbrtl( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
5865
5866
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
5867
5868
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
171
ccos( )
System Interfaces
5869
5870
NAME
5871
5872
SYNOPSIS
#include <complex.h>
ccos, ccosf, ccosl — complex cosine functions
double complex ccos(double complex z);
float complex ccosf(float complex z);
long double complex ccosl(long double complex z);
5873
5874
5875
5876
5877
5878
5879
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the complex cosine of z.
5880
5881
5882
RETURN VALUE
These functions shall return the complex cosine value.
5883
5884
ERRORS
No errors are defined.
5885
5886
EXAMPLES
None.
5887
5888
APPLICATION USAGE
None.
5889
5890
RATIONALE
None.
5891
5892
FUTURE DIRECTIONS
None.
5893
5894
SEE ALSO
cacos( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
5895
5896
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
172
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5897
5898
NAME
5899
5900
SYNOPSIS
#include <complex.h>
5901
5902
5903
5904
5905
5906
5907
5908
ccosh( )
ccosh, ccoshf, ccoshl — complex hyperbolic cosine functions
double complex ccosh(double complex z);
float complex ccoshf(float complex z);
long double complex ccoshl(long double complex z);
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the complex hyperbolic cosine of z.
5909
5910
RETURN VALUE
These functions shall return the complex hyperbolic cosine value.
5911
5912
ERRORS
No errors are defined.
5913
5914
EXAMPLES
None.
5915
5916
APPLICATION USAGE
None.
5917
5918
RATIONALE
None.
5919
5920
FUTURE DIRECTIONS
None.
5921
5922
SEE ALSO
cacosh( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
5923
5924
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
173
ccosl( )
System Interfaces
5925
5926
NAME
5927
5928
SYNOPSIS
#include <complex.h>
ccosl — complex cosine functions
long double complex ccosl(long double complex z);
5929
5930
5931
DESCRIPTION
Refer to ccos( ).
174
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
ceil( )
System Interfaces
5932
5933
NAME
5934
5935
SYNOPSIS
#include <math.h>
ceil, ceilf, ceill — ceiling value function
double ceil(double x);
float ceilf(float x);
long double ceill(long double x);
5936
5937
5938
5939
5940
5941
5942
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
5943
These functions shall compute the smallest integral value not less than x.
5944
5945
5946
5947
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
5948
5949
5950
RETURN VALUE
Upon successful completion, ceil( ), ceilf( ), and ceill( ) shall return the smallest integral value not
less than x, expressed as a type double, float, or long double, respectively.
5951
MX
If x is NaN, a NaN shall be returned.
If x is ±0 or ±Inf, x shall be returned.
5952
If the correct value would cause overflow, a range error shall occur and ceil( ), ceilf( ), and ceill( )
shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively.
5953
5954
XSI
5955
5956
ERRORS
These functions shall fail if:
5957
XSI
Range Error
The result overflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow
floating-point exception shall be raised.
5958
5959
5960
5961
5962
5963
EXAMPLES
None.
5964
5965
5966
5967
APPLICATION USAGE
The integral value returned by these functions need not be expressible as an int or long. The
return value should be tested before assigning it to an integer type to avoid the undefined results
of an integer overflow.
5968
5969
The ceil( ) function can only overflow when the floating-point representation has
DBL_MANT_DIG > DBL_MAX_EXP.
5970
5971
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
175
ceil( )
System Interfaces
5972
5973
RATIONALE
None.
5974
5975
FUTURE DIRECTIONS
None.
5976
5977
5978
SEE ALSO
feclearexcept( ), fetestexcept( ), floor ( ), isnan( ), the Base Definitions volume of IEEE Std 1003.1-2001,
Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
5979
5980
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
5981
5982
5983
Issue 5
5984
5985
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The ceilf( ) and ceill( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
5986
5987
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
5988
5989
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
176
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
5990
5991
NAME
5992
5993
SYNOPSIS
#include <complex.h>
5994
5995
5996
5997
5998
5999
6000
6001
cexp( )
cexp, cexpf, cexpl — complex exponential functions
double complex cexp(double complex z);
float complex cexpf(float complex z);
long double complex cexpl(long double complex z);
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the complex exponent of z, defined as ez.
6002
6003
RETURN VALUE
These functions shall return the complex exponential value of z.
6004
6005
ERRORS
No errors are defined.
6006
6007
EXAMPLES
None.
6008
6009
APPLICATION USAGE
None.
6010
6011
RATIONALE
None.
6012
6013
FUTURE DIRECTIONS
None.
6014
6015
SEE ALSO
clog( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
6016
6017
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
177
cfgetispeed( )
System Interfaces
6018
6019
NAME
6020
6021
SYNOPSIS
#include <termios.h>
cfgetispeed — get input baud rate
speed_t cfgetispeed(const struct termios *termios_p);
6022
6023
6024
6025
DESCRIPTION
The cfgetispeed( ) function shall extract the input baud rate from the termios structure to which
the termios_p argument points.
This function shall return exactly the value in the termios data structure, without interpretation.
6026
6027
6028
6029
RETURN VALUE
Upon successful completion, cfgetispeed( ) shall return a value of type speed_t representing the
input baud rate.
6030
6031
ERRORS
No errors are defined.
6032
6033
EXAMPLES
None.
6034
6035
APPLICATION USAGE
None.
6036
6037
6038
6039
RATIONALE
The term ‘‘baud’’ is used historically here, but is not technically correct. This is properly ‘‘bits
per second’’, which may not be the same as baud. However, the term is used because of the
historical usage and understanding.
6040
6041
The cfgetospeed( ), cfgetispeed( ), cfsetospeed( ), and cfsetispeed( ) functions do not take arguments as
numbers, but rather as symbolic names. There are two reasons for this:
6042
6043
1. Historically, numbers were not used because of the way the rate was stored in the data
structure. This is retained even though a function is now used.
6044
6045
2. More importantly, only a limited set of possible rates is at all portable, and this constrains
the application to that set.
6046
6047
6048
There is nothing to prevent an implementation accepting as an extension a number (such as 126),
and since the encoding of the Bxxx symbols is not specified, this can be done to avoid
introducing ambiguity.
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
Setting the input baud rate to zero was a mechanism to allow for split baud rates. Clarifications
in this volume of IEEE Std 1003.1-2001 have made it possible to determine whether split rates are
supported and to support them without having to treat zero as a special case. Since this
functionality is also confusing, it has been declared obsolescent. The 0 argument referred to is
the literal constant 0, not the symbolic constant B0. This volume of IEEE Std 1003.1-2001 does not
preclude B0 from being defined as the value 0; in fact, implementations would likely benefit
from the two being equivalent. This volume of IEEE Std 1003.1-2001 does not fully specify
whether the previous cfsetispeed( ) value is retained after a tcgetattr( ) as the actual value or as
zero. Therefore, conforming applications should always set both the input speed and output
speed when setting either.
6059
In historical implementations, the baud rate information is traditionally kept in c_cflag.
Applications should be written to presume that this might be the case (and thus not blindly copy
c_cflag), but not to rely on it in case it is in some other field of the structure. Setting the c_cflag
field absolutely after setting a baud rate is a non-portable action because of this. In general, the
6060
6061
6062
178
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
6063
6064
cfgetispeed( )
unused parts of the flag fields might be used by the implementation and should not be blindly
copied from the descriptions of one terminal device to another.
6065
6066
FUTURE DIRECTIONS
None.
6067
6068
6069
SEE ALSO
cfgetospeed( ), cfsetispeed( ), cfsetospeed( ), tcgetattr( ), the Base Definitions
IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>
6070
6071
CHANGE HISTORY
First released in Issue 3. Included for alignment with the POSIX.1-1988 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
volume
of
179
cfgetospeed( )
System Interfaces
6072
6073
NAME
6074
6075
SYNOPSIS
#include <termios.h>
cfgetospeed — get output baud rate
speed_t cfgetospeed(const struct termios *termios_p);
6076
6077
6078
6079
DESCRIPTION
The cfgetospeed( ) function shall extract the output baud rate from the termios structure to which
the termios_p argument points.
This function shall return exactly the value in the termios data structure, without interpretation.
6080
6081
6082
6083
RETURN VALUE
Upon successful completion, cfgetospeed( ) shall return a value of type speed_t representing the
output baud rate.
6084
6085
ERRORS
No errors are defined.
6086
6087
EXAMPLES
None.
6088
6089
APPLICATION USAGE
None.
6090
6091
RATIONALE
Refer to cfgetispeed( ).
6092
6093
FUTURE DIRECTIONS
None.
6094
6095
6096
SEE ALSO
cfgetispeed( ), cfsetispeed( ), cfsetospeed( ), tcgetattr( ), the Base Definitions
IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>
6097
6098
CHANGE HISTORY
First released in Issue 3. Included for alignment with the POSIX.1-1988 standard.
180
volume
of
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
cfsetispeed( )
System Interfaces
6099
6100
NAME
6101
6102
SYNOPSIS
#include <termios.h>
cfsetispeed — set input baud rate
int cfsetispeed(struct termios *termios_p, speed_t speed);
6103
6104
6105
6106
DESCRIPTION
The cfsetispeed( ) function shall set the input baud rate stored in the structure pointed to by
termios_p to speed.
6107
6108
6109
6110
There shall be no effect on the baud rates set in the hardware until a subsequent successful call
to tcsetattr( ) with the same termios structure. Similarly, errors resulting from attempts to set
baud rates not supported by the terminal device need not be detected until the tcsetattr( )
function is called.
6111
6112
6113
RETURN VALUE
Upon successful completion, cfsetispeed( ) shall return 0; otherwise, −1 shall be returned, and
errno may be set to indicate the error.
6114
6115
ERRORS
The cfsetispeed( ) function may fail if:
6116
[EINVAL]
The speed value is not a valid baud rate.
6117
6118
[EINVAL]
The value of speed is outside the range of possible speed values as specified in
<termios.h>.
6119
6120
EXAMPLES
None.
6121
6122
APPLICATION USAGE
None.
6123
6124
RATIONALE
Refer to cfgetispeed( ).
6125
6126
FUTURE DIRECTIONS
None.
6127
6128
6129
SEE ALSO
cfgetispeed( ), cfgetospeed( ), cfsetospeed( ), tcsetattr( ), the Base Definitions
IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>
6130
6131
CHANGE HISTORY
First released in Issue 3. Included for alignment with the POSIX.1-1988 standard.
6132
6133
6134
Issue 6
6135
volume
of
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
•
The optional setting of errno and the [EINVAL] error conditions are added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
181
cfsetospeed( )
System Interfaces
6136
6137
NAME
6138
6139
SYNOPSIS
#include <termios.h>
cfsetospeed — set output baud rate
int cfsetospeed(struct termios *termios_p, speed_t speed);
6140
6141
6142
6143
DESCRIPTION
The cfsetospeed( ) function shall set the output baud rate stored in the structure pointed to by
termios_p to speed.
6144
6145
6146
6147
There shall be no effect on the baud rates set in the hardware until a subsequent successful call
to tcsetattr( ) with the same termios structure. Similarly, errors resulting from attempts to set
baud rates not supported by the terminal device need not be detected until the tcsetattr( )
function is called.
6148
6149
6150
RETURN VALUE
Upon successful completion, cfsetospeed( ) shall return 0; otherwise, it shall return −1 and errno
may be set to indicate the error.
6151
6152
ERRORS
The cfsetospeed( ) function may fail if:
6153
[EINVAL]
The speed value is not a valid baud rate.
6154
6155
[EINVAL]
The value of speed is outside the range of possible speed values as specified in
<termios.h>.
6156
6157
EXAMPLES
None.
6158
6159
APPLICATION USAGE
None.
6160
6161
RATIONALE
Refer to cfgetispeed( ).
6162
6163
FUTURE DIRECTIONS
None.
6164
6165
6166
SEE ALSO
cfgetispeed( ), cfgetospeed( ), cfsetispeed( ), tcsetattr( ), the Base Definitions
IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>
6167
6168
CHANGE HISTORY
First released in Issue 3. Included for alignment with the POSIX.1-1988 standard.
6169
6170
6171
Issue 6
volume
of
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
•
6172
182
The optional setting of errno and the [EINVAL] error conditions are added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
chdir( )
System Interfaces
6173
6174
NAME
6175
6176
SYNOPSIS
#include <unistd.h>
6177
chdir — change working directory
int chdir(const char *path);
6178
6179
6180
6181
DESCRIPTION
The chdir( ) function shall cause the directory named by the pathname pointed to by the path
argument to become the current working directory; that is, the starting point for path searches
for pathnames not beginning with ’/’.
6182
6183
6184
RETURN VALUE
Upon successful completion, 0 shall be returned. Otherwise, −1 shall be returned, the current
working directory shall remain unchanged, and errno shall be set to indicate the error.
6185
6186
ERRORS
The chdir( ) function shall fail if:
6187
[EACCES]
Search permission is denied for any component of the pathname.
6188
6189
[ELOOP]
A loop exists in symbolic links encountered during resolution of the path
argument.
6190
6191
6192
[ENAMETOOLONG]
The length of the path argument exceeds {PATH_MAX} or a pathname
component is longer than {NAME_MAX}.
6193
6194
[ENOENT]
A component of path does not name an existing directory or path is an empty
string.
6195
[ENOTDIR]
A component of the pathname is not a directory.
6196
The chdir( ) function may fail if:
6197
6198
[ELOOP]
6199
6200
6201
[ENAMETOOLONG]
As a result of encountering a symbolic link in resolution of the path argument,
the length of the substituted pathname string exceeded {PATH_MAX}.
6202
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path argument.
EXAMPLES
6203
Changing the Current Working Directory
6204
6205
The following example makes the value pointed to by directory, /tmp, the current working
directory.
6206
6207
6208
6209
#include <unistd.h>
...
char *directory = "/tmp";
int ret;
6210
ret = chdir (directory);
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
183
chdir( )
System Interfaces
6211
6212
APPLICATION USAGE
None.
6213
6214
RATIONALE
The chdir( ) function only affects the working directory of the current process.
6215
6216
FUTURE DIRECTIONS
None.
6217
6218
SEE ALSO
getcwd( ), the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>
6219
6220
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
6221
6222
Issue 6
The APPLICATION USAGE section is added.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
6223
6224
6225
•
The [ELOOP] mandatory error condition is added.
6226
•
A second [ENAMETOOLONG] is added as an optional error condition.
The following changes were made to align with the IEEE P1003.1a draft standard:
6227
•
6228
184
The [ELOOP] optional error condition is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
chmod( )
System Interfaces
6229
6230
NAME
6231
6232
SYNOPSIS
#include <sys/stat.h>
chmod — change mode of a file
int chmod(const char *path, mode_t mode);
6233
6234
6235
6236
6237
6238
DESCRIPTION
XSI
The chmod( ) function shall change S_ISUID, S_ISGID, S_ISVTX, and the file permission bits of
the file named by the pathname pointed to by the path argument to the corresponding bits in the
mode argument. The application shall ensure that the effective user ID of the process matches the
owner of the file or the process has appropriate privileges in order to do this.
6239
XSI
S_ISUID, S_ISGID, S_ISVTX,and the file permission bits are described in <sys/stat.h>.
6240
6241
6242
6243
If the calling process does not have appropriate privileges, and if the group ID of the file does
not match the effective group ID or one of the supplementary group IDs and if the file is a
regular file, bit S_ISGID (set-group-ID on execution) in the file’s mode shall be cleared upon
successful return from chmod( ).
6244
6245
Additional implementation-defined restrictions may cause the S_ISUID and S_ISGID bits in
mode to be ignored.
6246
6247
The effect on file descriptors for files open at the time of a call to chmod( ) is implementationdefined.
6248
Upon successful completion, chmod( ) shall mark for update the st_ctime field of the file.
6249
6250
6251
RETURN VALUE
Upon successful completion, 0 shall be returned; otherwise, −1 shall be returned and errno set to
indicate the error. If −1 is returned, no change to the file mode occurs.
6252
6253
ERRORS
The chmod( ) function shall fail if:
6254
[EACCES]
Search permission is denied on a component of the path prefix.
6255
6256
[ELOOP]
A loop exists in symbolic links encountered during resolution of the path
argument.
6257
6258
6259
[ENAMETOOLONG]
The length of the path argument exceeds {PATH_MAX} or a pathname
component is longer than {NAME_MAX}.
6260
[ENOTDIR]
A component of the path prefix is not a directory.
6261
[ENOENT]
A component of path does not name an existing file or path is an empty string.
6262
6263
[EPERM]
The effective user ID does not match the owner of the file and the process
does not have appropriate privileges.
6264
[EROFS]
The named file resides on a read-only file system.
6265
The chmod( ) function may fail if:
6266
[EINTR]
A signal was caught during execution of the function.
6267
[EINVAL]
The value of the mode argument is invalid.
6268
6269
[ELOOP]
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path argument.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
185
chmod( )
[ENAMETOOLONG]
As a result of encountering a symbolic link in resolution of the path argument,
the length of the substituted pathname strings exceeded {PATH_MAX}.
6270
6271
6272
6273
System Interfaces
EXAMPLES
6274
Setting Read Permissions for User, Group, and Others
6275
The following example sets read permissions for the owner, group, and others.
6276
#include <sys/stat.h>
6277
6278
6279
const char *path;
...
chmod(path, S_IRUSR|S_IRGRP|S_IROTH);
6280
Setting Read, Write, and Execute Permissions for the Owner Only
6281
6282
The following example sets read, write, and execute permissions for the owner, and no
permissions for group and others.
6283
#include <sys/stat.h>
6284
6285
6286
const char *path;
...
chmod(path, S_IRWXU);
6287
Setting Different Permissions for Owner, Group, and Other
6288
6289
The following example sets owner permissions for CHANGEFILE to read, write, and execute,
group permissions to read and execute, and other permissions to read.
6290
#include <sys/stat.h>
6291
6292
6293
#define CHANGEFILE "/etc/myfile"
...
chmod(CHANGEFILE, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH);
6294
Setting and Checking File Permissions
6295
6296
The following example sets the file permission bits for a file named /home/cnd/mod1, then calls
the stat( ) function to verify the permissions.
6297
6298
#include <sys/types.h>
#include <sys/stat.h>
6299
6300
6301
6302
6303
int status;
struct stat buffer
...
chmod("home/cnd/mod1", S_IRWXU|S_IRWXG|S_IROTH|S_IWOTH);
status = stat("home/cnd/mod1", &buffer;);
6304
6305
6306
APPLICATION USAGE
In order to ensure that the S_ISUID and S_ISGID bits are set, an application requiring this should
use stat( ) after a successful chmod( ) to verify this.
6307
6308
Any file descriptors currently open by any process on the file could possibly become invalid if
the mode of the file is changed to a value which would deny access to that process. One
186
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
chmod( )
6309
6310
situation where this could occur is on a stateless file system. This behavior will not occur in a
conforming environment.
6311
6312
6313
6314
6315
6316
6317
RATIONALE
This volume of IEEE Std 1003.1-2001 specifies that the S_ISGID bit is cleared by chmod( ) on a
regular file under certain conditions. This is specified on the assumption that regular files may
be executed, and the system should prevent users from making executable setgid( ) files perform
with privileges that the caller does not have. On implementations that support execution of
other file types, the S_ISGID bit should be cleared for those file types under the same
circumstances.
6318
6319
6320
6321
Implementations that use the S_ISUID bit to indicate some other function (for example,
mandatory record locking) on non-executable files need not clear this bit on writing. They
should clear the bit for executable files and any other cases where the bit grants special powers
to processes that change the file contents. Similar comments apply to the S_ISGID bit.
6322
6323
FUTURE DIRECTIONS
None.
6324
6325
6326
SEE ALSO
chown( ), mkdir( ), mkfifo ( ), open( ), stat( ), statvfs( ), the Base Definitions volume of
IEEE Std 1003.1-2001, <sys/stat.h>, <sys/types.h>
6327
6328
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
6329
6330
6331
Issue 6
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
6332
6333
6334
•
The requirement to include <sys/types.h> has been removed. Although <sys/types.h> was
required for conforming implementations of previous POSIX specifications, it was not
required for UNIX applications.
6335
•
The [EINVAL] and [EINTR] optional error conditions are added.
6336
•
A second [ENAMETOOLONG] is added as an optional error condition.
6337
6338
6339
The following changes were made to align with the IEEE P1003.1a draft standard:
•
The [ELOOP] optional error condition is added.
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
187
chown( )
System Interfaces
6340
6341
NAME
6342
6343
SYNOPSIS
#include <unistd.h>
chown — change owner and group of a file
6344
int chown(const char *path, uid_t owner, gid_t group);
6345
6346
DESCRIPTION
The chown( ) function shall change the user and group ownership of a file.
6347
6348
The path argument points to a pathname naming a file. The user ID and group ID of the named
file shall be set to the numeric values contained in owner and group, respectively.
6349
6350
6351
Only processes with an effective user ID equal to the user ID of the file or with appropriate
privileges may change the ownership of a file. If _POSIX_CHOWN_RESTRICTED is in effect for
path:
6352
•
Changing the user ID is restricted to processes with appropriate privileges.
6353
6354
6355
6356
•
Changing the group ID is permitted to a process with an effective user ID equal to the user
ID of the file, but without appropriate privileges, if and only if owner is equal to the file’s user
ID or (uid_t)−1 and group is equal either to the calling process’ effective group ID or to one of
its supplementary group IDs.
6357
6358
6359
6360
6361
6362
6363
6364
6365
If the specified file is a regular file, one or more of the S_IXUSR, S_IXGRP, or S_IXOTH bits of
the file mode are set, and the process does not have appropriate privileges, the set-user-ID
(S_ISUID) and set-group-ID (S_ISGID) bits of the file mode shall be cleared upon successful
return from chown( ). If the specified file is a regular file, one or more of the S_IXUSR, S_IXGRP,
or S_IXOTH bits of the file mode are set, and the process has appropriate privileges, it is
implementation-defined whether the set-user-ID and set-group-ID bits are altered. If the chown( )
function is successfully invoked on a file that is not a regular file and one or more of the
S_IXUSR, S_IXGRP, or S_IXOTH bits of the file mode are set, the set-user-ID and set-group-ID
bits may be cleared.
6366
6367
If owner or group is specified as (uid_t)−1 or (gid_t)−1, respectively, the corresponding ID of the
file shall not be changed. If both owner and group are −1, the times need not be updated.
6368
Upon successful completion, chown( ) shall mark for update the st_ctime field of the file.
6369
6370
6371
RETURN VALUE
Upon successful completion, 0 shall be returned; otherwise, −1 shall be returned and errno set to
indicate the error. If −1 is returned, no changes are made in the user ID and group ID of the file.
6372
6373
ERRORS
The chown( ) function shall fail if:
6374
[EACCES]
Search permission is denied on a component of the path prefix.
6375
6376
[ELOOP]
A loop exists in symbolic links encountered during resolution of the path
argument.
6377
6378
6379
[ENAMETOOLONG]
The length of the path argument exceeds {PATH_MAX} or a pathname
component is longer than {NAME_MAX}.
6380
[ENOTDIR]
A component of the path prefix is not a directory.
6381
[ENOENT]
A component of path does not name an existing file or path is an empty string.
188
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
chown( )
System Interfaces
6382
6383
6384
[EPERM]
The effective user ID does not match the owner of the file, or the calling
process
does
not
have
appropriate
privileges
and
_POSIX_CHOWN_RESTRICTED indicates that such privilege is required.
6385
[EROFS]
The named file resides on a read-only file system.
6386
The chown( ) function may fail if:
6387
[EIO]
An I/O error occurred while reading or writing to the file system.
6388
[EINTR]
The chown( ) function was interrupted by a signal which was caught.
6389
6390
[EINVAL]
The owner or group ID supplied is not a value supported by the
implementation.
6391
6392
[ELOOP]
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path argument.
6393
6394
6395
[ENAMETOOLONG]
As a result of encountering a symbolic link in resolution of the path argument,
the length of the substituted pathname string exceeded {PATH_MAX}.
6396
6397
EXAMPLES
None.
6398
6399
6400
6401
APPLICATION USAGE
Although chown( ) can be used on some implementations by the file owner to change the owner
and group to any desired values, the only portable use of this function is to change the group of
a file to the effective GID of the calling process or to a member of its group set.
6402
6403
6404
6405
6406
6407
6408
RATIONALE
System III and System V allow a user to give away files; that is, the owner of a file may change
its user ID to anything. This is a serious problem for implementations that are intended to meet
government security regulations. Version 7 and 4.3 BSD permit only the superuser to change the
user ID of a file. Some government agencies (usually not ones concerned directly with security)
find this limitation too confining. This volume of IEEE Std 1003.1-2001 uses may to permit secure
implementations while not disallowing System V.
6409
6410
6411
6412
System III and System V allow the owner of a file to change the group ID to anything. Version 7
permits only the superuser to change the group ID of a file. 4.3 BSD permits the owner to
change the group ID of a file to its effective group ID or to any of the groups in the list of
supplementary group IDs, but to no others.
6413
6414
6415
6416
6417
6418
6419
The POSIX.1-1990 standard requires that the chown( ) function invoked by a non-appropriate
privileged process clear the S_ISGID and the S_ISUID bits for regular files, and permits them to
be cleared for other types of files. This is so that changes in accessibility do not accidentally
cause files to become security holes. Unfortunately, requiring these bits to be cleared on nonexecutable data files also clears the mandatory file locking bit (shared with S_ISGID), which is
an extension on many implementations (it first appeared in System V). These bits should only be
required to be cleared on regular files that have one or more of their execute bits set.
6420
6421
FUTURE DIRECTIONS
None.
6422
6423
6424
SEE ALSO
chmod( ), pathconf ( ), the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>,
<unistd.h>
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
189
chown( )
System Interfaces
6425
6426
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
6427
6428
Issue 6
The following changes are made for alignment with the ISO POSIX-1: 1996 standard:
6429
6430
•
The wording describing the optional dependency on _POSIX_CHOWN_RESTRICTED is
restored.
6431
6432
6433
6434
•
The [EPERM] error is restored as an error dependent on _POSIX_CHOWN_RESTRICTED.
This is since its operand is a pathname and applications should be aware that the error may
not occur for that pathname if the file system
does not support
_POSIX_CHOWN_RESTRICTED.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
6435
6436
6437
6438
6439
•
The requirement to include <sys/types.h> has been removed. Although <sys/types.h> was
required for conforming implementations of previous POSIX specifications, it was not
required for UNIX applications.
6440
6441
•
The value for owner of (uid_t)−1 allows the use of −1 by the owner of a file to change the
group ID only. A corresponding change is made for group.
6442
•
The [ELOOP] mandatory error condition is added.
6443
•
The [EIO] and [EINTR] optional error conditions are added.
6444
•
A second [ENAMETOOLONG] is added as an optional error condition.
The following changes were made to align with the IEEE P1003.1a draft standard:
6445
6446
6447
•
Clarification is added that the S_ISUID and S_ISGID bits do not need to be cleared when the
process has appropriate privileges.
6448
•
The [ELOOP] optional error condition is added.
190
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
6449
6450
NAME
6451
6452
SYNOPSIS
#include <complex.h>
6453
6454
6455
6456
6457
6458
6459
cimag, cimagf, cimagl — complex imaginary functions
double cimag(double complex z);
float cimagf(float complex z);
long double cimagl(long double complex z);
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
6460
These functions shall compute the imaginary part of z.
6461
6462
RETURN VALUE
These functions shall return the imaginary part value (as a real).
6463
6464
ERRORS
No errors are defined.
6465
6466
EXAMPLES
None.
6467
6468
APPLICATION USAGE
For a variable z of complex type:
6469
cimag( )
z == creal(z) + cimag(z)*I
6470
6471
RATIONALE
None.
6472
6473
FUTURE DIRECTIONS
None.
6474
6475
SEE ALSO
carg( ), conj( ), cproj( ), creal( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
6476
6477
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
191
clearerr( )
System Interfaces
6478
6479
NAME
6480
6481
SYNOPSIS
#include <stdio.h>
clearerr — clear indicators on a stream
void clearerr(FILE *stream);
6482
6483
6484
6485
6486
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
6487
6488
The clearerr( ) function shall clear the end-of-file and error indicators for the stream to which
stream points.
6489
6490
RETURN VALUE
The clearerr( ) function shall not return a value.
6491
6492
ERRORS
No errors are defined.
6493
6494
EXAMPLES
None.
6495
6496
APPLICATION USAGE
None.
6497
6498
RATIONALE
None.
6499
6500
FUTURE DIRECTIONS
None.
6501
6502
SEE ALSO
The Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
6503
6504
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
192
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
6505
6506
NAME
6507
6508
SYNOPSIS
#include <time.h>
6509
clock( )
clock — report CPU time used
clock_t clock(void);
6510
6511
6512
6513
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
6514
6515
6516
The clock ( ) function shall return the implementation’s best approximation to the processor time
used by the process since the beginning of an implementation-defined era related only to the
process invocation.
6517
6518
6519
6520
6521
RETURN VALUE
To determine the time in seconds, the value returned by clock ( ) should be divided by the value
XSI
of the macro CLOCKS_PER_SEC. CLOCKS_PER_SEC is defined to be one million in <time.h>.
If the processor time used is not available or its value cannot be represented, the function shall
return the value (clock_t)−1.
6522
6523
ERRORS
No errors are defined.
6524
6525
EXAMPLES
None.
6526
6527
6528
6529
6530
APPLICATION USAGE
In order to measure the time spent in a program, clock ( ) should be called at the start of the
program and its return value subtracted from the value returned by subsequent calls. The value
returned by clock ( ) is defined for compatibility across systems that have clocks with different
resolutions. The resolution on any particular system need not be to microsecond accuracy.
6531
6532
The value returned by clock ( ) may wrap around on some implementations. For example, on a
machine with 32-bit values for clock_t, it wraps after 2 147 seconds or 36 minutes.
6533
6534
RATIONALE
None.
6535
6536
FUTURE DIRECTIONS
None.
6537
6538
6539
SEE ALSO
asctime( ), ctime( ), difftime ( ), gmtime( ), localtime ( ), mktime( ), strftime( ), strptime( ), time( ), utime( ),
the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>
6540
6541
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
193
clock_getcpuclockid( )
6542
6543
NAME
6544
6545
SYNOPSIS
CPT
#include <time.h>
System Interfaces
clock_getcpuclockid — access a process CPU-time clock (ADVANCED REALTIME)
int clock_getcpuclockid(pid_t pid, clockid_t *clock_id);
6546
6547
6548
6549
6550
6551
DESCRIPTION
The clock_getcpuclockid( ) function shall return the clock ID of the CPU-time clock of the process
specified by pid. If the process described by pid exists and the calling process has permission,
the clock ID of this clock shall be returned in clock_id .
6552
6553
If pid is zero, the clock_getcpuclockid( ) function shall return the clock ID of the CPU-time clock of
the process making the call, in clock_id .
6554
6555
The conditions under which one process has permission to obtain the CPU-time clock ID of
other processes are implementation-defined.
6556
6557
6558
RETURN VALUE
Upon successful completion, clock_getcpuclockid( ) shall return zero; otherwise, an error number
shall be returned to indicate the error.
6559
6560
ERRORS
The clock_getcpuclockid( ) function shall fail if:
6561
6562
[EPERM]
The requesting process does not have permission to access the CPU-time
clock for the process.
6563
The clock_getcpuclockid( ) function may fail if:
6564
[ESRCH]
No process can be found corresponding to the process specified by pid.
6565
6566
EXAMPLES
None.
6567
6568
6569
APPLICATION USAGE
The clock_getcpuclockid( ) function is part of the Process CPU-Time Clocks option and need not
be provided on all implementations.
6570
6571
RATIONALE
None.
6572
6573
FUTURE DIRECTIONS
None.
6574
6575
SEE ALSO
clock_getres( ), timer_create( ), the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>
6576
6577
CHANGE HISTORY
First released in Issue 6. Derived from IEEE Std 1003.1d-1999.
In the SYNOPSIS, the inclusion of <sys/types.h> is no longer required.
6578
194
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
6579
6580
NAME
6581
6582
SYNOPSIS
TMR
#include <time.h>
clock_getres( )
clock_getres, clock_gettime, clock_settime — clock and timer functions (REALTIME)
6583
6584
6585
6586
int clock_getres(clockid_t clock_id, struct timespec *res);
int clock_gettime(clockid_t clock_id, struct timespec *tp);
int clock_settime(clockid_t clock_id, const struct timespec *tp);
6587
6588
6589
6590
6591
6592
DESCRIPTION
The clock_getres( ) function shall return the resolution of any clock. Clock resolutions are
implementation-defined and cannot be set by a process. If the argument res is not NULL, the
resolution of the specified clock shall be stored in the location pointed to by res. If res is NULL,
the clock resolution is not returned. If the time argument of clock_settime( ) is not a multiple of res,
then the value is truncated to a multiple of res.
6593
The clock_gettime( ) function shall return the current value tp for the specified clock, clock_id .
6594
6595
6596
The clock_settime( ) function shall set the specified clock, clock_id , to the value specified by tp.
Time values that are between two consecutive non-negative integer multiples of the resolution
of the specified clock shall be truncated down to the smaller multiple of the resolution.
6597
6598
6599
6600
6601
6602
6603
A clock may be system-wide (that is, visible to all processes) or per-process (measuring time that
is meaningful only within a process). All implementations shall support a clock_id of
CLOCK_REALTIME as defined in <time.h>. This clock represents the realtime clock for the
system. For this clock, the values returned by clock_gettime( ) and specified by clock_settime( )
represent the amount of time (in seconds and nanoseconds) since the Epoch. An implementation
may also support additional clocks. The interpretation of time values for these clocks is
unspecified.
6604
6605
6606
6607
6608
6609
If the value of the CLOCK_REALTIME clock is set via clock_settime( ), the new value of the clock
shall be used to determine the time of expiration for absolute time services based upon the
CLOCK_REALTIME clock. This applies to the time at which armed absolute timers expire. If the
absolute time requested at the invocation of such a time service is before the new value of the
clock, the time service shall expire immediately as if the clock had reached the requested time
normally.
6610
6611
6612
6613
6614
Setting the value of the CLOCK_REALTIME clock via clock_settime( ) shall have no effect on
threads that are blocked waiting for a relative time service based upon this clock, including the
nanosleep( ) function; nor on the expiration of relative timers based upon this clock.
Consequently, these time services shall expire when the requested relative interval elapses,
independently of the new or old value of the clock.
6615
6616
6617
6618
6619
6620
6621
MON
The effect of setting a clock via clock_settime( ) on armed per-process timers associated with a
clock other than CLOCK_REALTIME is implementation-defined.
6622
6623
6624
6625
If the Monotonic Clock option is supported, all implementations shall support a clock_id of
CLOCK_MONOTONIC defined in <time.h>. This clock represents the monotonic clock for the
system. For this clock, the value returned by clock_gettime( ) represents the amount of time (in
seconds and nanoseconds) since an unspecified point in the past (for example, system start-up
time, or the Epoch). This point does not change after system start-up time. The value of the
CLOCK_MONOTONIC clock cannot be set via clock_settime( ). This function shall fail if it is
invoked with a clock_id argument of CLOCK_MONOTONIC.
CS
If the value of the CLOCK_REALTIME clock is set via clock_settime( ), the new value of the clock
shall be used to determine the time at which the system shall awaken a thread blocked on an
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
195
clock_getres( )
System Interfaces
6626
6627
6628
absolute clock_nanosleep( ) call based upon the CLOCK_REALTIME clock. If the absolute time
requested at the invocation of such a time service is before the new value of the clock, the call
shall return immediately as if the clock had reached the requested time normally.
6629
6630
6631
Setting the value of the CLOCK_REALTIME clock via clock_settime( ) shall have no effect on any
thread that is blocked on a relative clock_nanosleep( ) call. Consequently, the call shall return
when the requested relative interval elapses, independently of the new or old value of the clock.
6632
The appropriate privilege to set a particular clock is implementation-defined.
6633
6634
6635
6636
6637
6638
6639
6640
6641
CPT
If _POSIX_CPUTIME is defined, implementations shall support clock ID values obtained by
invoking clock_getcpuclockid( ), which represent the CPU-time clock of a given process.
Implementations
shall
also
support
the
special
clockid_t
value
CLOCK_PROCESS_CPUTIME_ID, which represents the CPU-time clock of the calling process
when invoking one of the clock_* ( ) or timer_*( ) functions. For these clock IDs, the values
returned by clock_gettime( ) and specified by clock_settime( ) represent the amount of execution
time of the process associated with the clock. Changing the value of a CPU-time clock via
clock_settime ( ) shall have no effect on the behavior of the sporadic server scheduling policy (see
Scheduling Policies (on page 44)).
6642
6643
6644
6645
6646
6647
6648
6649
6650
TCT
If _POSIX_THREAD_CPUTIME is defined, implementations shall support clock ID values
obtained by invoking pthread_getcpuclockid( ), which represent the CPU-time clock of a given
thread.
Implementations
shall
also
support
the
special
clockid_t
value
CLOCK_THREAD_CPUTIME_ID, which represents the CPU-time clock of the calling thread
when invoking one of the clock_* ( ) or timer_*( ) functions. For these clock IDs, the values
returned by clock_gettime( ) and specified by clock_settime( ) shall represent the amount of
execution time of the thread associated with the clock. Changing the value of a CPU-time clock
via clock_settime( ) shall have no effect on the behavior of the sporadic server scheduling policy
(see Scheduling Policies (on page 44)).
6651
6652
6653
RETURN VALUE
A return value of 0 shall indicate that the call succeeded. A return value of −1 shall indicate that
an error occurred, and errno shall be set to indicate the error.
6654
6655
ERRORS
The clock_getres( ), clock_gettime( ), and clock_settime( ) functions shall fail if:
6656
[EINVAL]
6657
The clock_settime( ) function shall fail if:
6658
[EINVAL]
The tp argument to clock_settime( ) is outside the range for the given clock ID.
6659
6660
[EINVAL]
The tp argument specified a nanosecond value less than zero or greater than
or equal to 1 000 million.
[EINVAL]
The value of the clock_id argument is CLOCK_MONOTONIC.
6661
MON
The clock_id argument does not specify a known clock.
6662
The clock_settime( ) function may fail if:
6663
6664
[EPERM]
196
The requesting process does not have the appropriate privilege to set the
specified clock.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
clock_getres( )
6665
6666
EXAMPLES
None.
6667
6668
APPLICATION USAGE
These functions are part of the Timers option and need not be available on all implementations.
Note that the absolute value of the monotonic clock is meaningless (because its origin is
arbitrary), and thus there is no need to set it. Furthermore, realtime applications can rely on the
fact that the value of this clock is never set and, therefore, that time intervals measured with this
clock will not be affected by calls to clock_settime( ).
6669
6670
6671
6672
6673
6674
RATIONALE
None.
6675
6676
FUTURE DIRECTIONS
None.
6677
6678
6679
6680
SEE ALSO
clock_getcpuclockid( ), clock_nanosleep( ), ctime( ), mq_timedreceive( ), mq_timedsend( ), nanosleep( ),
pthread_mutex_timedlock( ), sem_timedwait( ), time( ), timer_create( ), timer_getoverrun( ), the Base
Definitions volume of IEEE Std 1003.1-2001, <time.h>
6681
6682
CHANGE HISTORY
First released in Issue 5. Included for alignment with the POSIX Realtime Extension.
6683
6684
6685
Issue 6
The [ENOSYS] error condition has been removed as stubs need not be provided if an
implementation does not support the Timers option.
6686
The APPLICATION USAGE section is added.
6687
The following changes were made to align with the IEEE P1003.1a draft standard:
6688
•
Clarification is added of the effect of resetting the clock resolution.
6689
6690
CPU-time clocks and the clock_getcpuclockid( ) function are added for alignment with
IEEE Std 1003.1d-1999.
6691
The following changes are added for alignment with IEEE Std 1003.1j-2000:
6692
•
The DESCRIPTION is updated as follows:
6693
— The value returned by clock_gettime( ) for CLOCK_MONOTONIC is specified.
6694
— The clock_settime( ) function failing for CLOCK_MONOTONIC is specified.
6695
6696
— The effects of clock_settime( ) on the clock_nanosleep( ) function with respect to
CLOCK_REALTIME is specified.
6697
6698
•
An [EINVAL] error is added to the ERRORS section, indicating that clock_settime( ) fails for
CLOCK_MONOTONIC.
6699
6700
6701
•
The APPLICATION USAGE section notes that the CLOCK_MONOTONIC clock need not
and shall not be set by clock_settime( ) since the absolute value of the CLOCK_MONOTONIC
clock is meaningless.
6702
6703
6704
•
The clock_nanosleep( ), mq_timedreceive( ), mq_timedsend( ), pthread_mutex_timedlock( ),
sem_timedwait( ), timer_create( ), and timer_settime( ) functions are added to the SEE ALSO
section.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
197
clock_nanosleep( )
System Interfaces
6705
6706
NAME
6707
6708
SYNOPSIS
CS
#include <time.h>
clock_nanosleep — high resolution sleep with specifiable clock (ADVANCED REALTIME)
int clock_nanosleep(clockid_t clock_id, int flags,
const struct timespec *rqtp, struct timespec *rmtp);
6709
6710
6711
6712
6713
6714
6715
6716
6717
DESCRIPTION
If the flag TIMER_ABSTIME is not set in the flags argument, the clock_nanosleep( ) function shall
cause the current thread to be suspended from execution until either the time interval specified
by the rqtp argument has elapsed, or a signal is delivered to the calling thread and its action is to
invoke a signal-catching function, or the process is terminated. The clock used to measure the
time shall be the clock specified by clock_id .
6718
6719
6720
6721
6722
6723
6724
If the flag TIMER_ABSTIME is set in the flags argument, the clock_nanosleep( ) function shall
cause the current thread to be suspended from execution until either the time value of the clock
specified by clock_id reaches the absolute time specified by the rqtp argument, or a signal is
delivered to the calling thread and its action is to invoke a signal-catching function, or the
process is terminated. If, at the time of the call, the time value specified by rqtp is less than or
equal to the time value of the specified clock, then clock_nanosleep( ) shall return immediately
and the calling process shall not be suspended.
6725
6726
6727
6728
6729
6730
6731
6732
6733
The suspension time caused by this function may be longer than requested because the
argument value is rounded up to an integer multiple of the sleep resolution, or because of the
scheduling of other activity by the system. But, except for the case of being interrupted by a
signal, the suspension time for the relative clock_nanosleep( ) function (that is, with the
TIMER_ABSTIME flag not set) shall not be less than the time interval specified by rqtp, as
measured by the corresponding clock. The suspension for the absolute clock_nanosleep( ) function
(that is, with the TIMER_ABSTIME flag set) shall be in effect at least until the value of the
corresponding clock reaches the absolute time specified by rqtp, except for the case of being
interrupted by a signal.
6734
6735
The use of the clock_nanosleep( ) function shall have no effect on the action or blockage of any
signal.
6736
6737
6738
The clock_nanosleep( ) function shall fail if the clock_id argument refers to the CPU-time clock of
the calling thread. It is unspecified whether clock_id values of other CPU-time clocks are
allowed.
6739
6740
6741
RETURN VALUE
If the clock_nanosleep( ) function returns because the requested time has elapsed, its return value
shall be zero.
6742
6743
6744
6745
6746
6747
If the clock_nanosleep( ) function returns because it has been interrupted by a signal, it shall return
the corresponding error value. For the relative clock_nanosleep( ) function, if the rmtp argument is
non-NULL, the timespec structure referenced by it shall be updated to contain the amount of
time remaining in the interval (the requested time minus the time actually slept). If the rmtp
argument is NULL, the remaining time is not returned. The absolute clock_nanosleep( ) function
has no effect on the structure referenced by rmtp.
6748
If clock_nanosleep( ) fails, it shall return the corresponding error value.
198
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
clock_nanosleep( )
System Interfaces
6749
6750
ERRORS
The clock_nanosleep( ) function shall fail if:
6751
[EINTR]
The clock_nanosleep( ) function was interrupted by a signal.
6752
6753
6754
6755
6756
[EINVAL]
The rqtp argument specified a nanosecond value less than zero or greater than
or equal to 1 000 million; or the TIMER_ABSTIME flag was specified in flags
and the rqtp argument is outside the range for the clock specified by clock_id;
or the clock_id argument does not specify a known clock, or specifies the
CPU-time clock of the calling thread.
6757
6758
[ENOTSUP]
The clock_id argument specifies a clock for which clock_nanosleep( ) is not
supported, such as a CPU-time clock.
6759
6760
EXAMPLES
None.
6761
6762
6763
6764
APPLICATION USAGE
Calling clock_nanosleep( ) with the value TIMER_ABSTIME not set in the flags argument and with
a clock_id of CLOCK_REALTIME is equivalent to calling nanosleep( ) with the same rqtp and rmtp
arguments.
6765
6766
6767
6768
6769
RATIONALE
The nanosleep( ) function specifies that the system-wide clock CLOCK_REALTIME is used to
measure the elapsed time for this time service. However, with the introduction of the monotonic
clock CLOCK_MONOTONIC a new relative sleep function is needed to allow an application to
take advantage of the special characteristics of this clock.
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
There are many applications in which a process needs to be suspended and then activated
multiple times in a periodic way; for example, to poll the status of a non-interrupting device or
to refresh a display device. For these cases, it is known that precise periodic activation cannot be
achieved with a relative sleep( ) or nanosleep( ) function call. Suppose, for example, a periodic
process that is activated at time T0, executes for a while, and then wants to suspend itself until
time T0+T, the period being T. If this process wants to use the nanosleep( ) function, it must first
call clock_gettime( ) to get the current time, then calculate the difference between the current time
and T0+T and, finally, call nanosleep( ) using the computed interval. However, the process could
be preempted by a different process between the two function calls, and in this case the interval
computed would be wrong; the process would wake up later than desired. This problem would
not occur with the absolute clock_nanosleep( ) function, since only one function call would be
necessary to suspend the process until the desired time. In other cases, however, a relative sleep
is needed, and that is why both functionalities are required.
6783
6784
6785
6786
Although it is possible to implement periodic processes using the timers interface, this
implementation would require the use of signals, and the reservation of some signal numbers. In
this regard, the reasons for including an absolute version of the clock_nanosleep( ) function in
IEEE Std 1003.1-2001 are the same as for the inclusion of the relative nanosleep( ).
6787
6788
6789
6790
6791
6792
It is also possible to implement precise periodic processes using pthread_cond_timedwait( ), in
which an absolute timeout is specified that takes effect if the condition variable involved is
never signaled. However, the use of this interface is unnatural, and involves performing other
operations on mutexes and condition variables that imply an unnecessary overhead.
Furthermore, pthread_cond_timedwait( ) is not available in implementations that do not support
threads.
6793
Although the interface of the relative and absolute versions of the new high resolution sleep
service is the same clock_nanosleep( ) function, the rmtp argument is only used in the relative
sleep. This argument is needed in the relative clock_nanosleep( ) function to reissue the function
6794
6795
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
199
clock_nanosleep( )
System Interfaces
call if it is interrupted by a signal, but it is not needed in the absolute clock_nanosleep( ) function
call; if the call is interrupted by a signal, the absolute clock_nanosleep( ) function can be invoked
again with the same rqtp argument used in the interrupted call.
6796
6797
6798
6799
6800
FUTURE DIRECTIONS
None.
6801
6802
6803
SEE ALSO
clock_getres( ), nanosleep( ), pthread_cond_timedwait( ), sleep( ), the Base Definitions volume of
IEEE Std 1003.1-2001, <time.h>
6804
6805
CHANGE HISTORY
First released in Issue 6. Derived from IEEE Std 1003.1j-2000.
200
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
6806
6807
NAME
6808
6809
SYNOPSIS
TMR
#include <time.h>
6810
6811
6812
6813
clock_settime( )
clock_settime — clock and timer functions (REALTIME)
int clock_settime(clockid_t clock_id, const struct timespec *tp);
DESCRIPTION
Refer to clock_getres( ).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
201
clog( )
System Interfaces
6814
6815
NAME
6816
6817
SYNOPSIS
#include <complex.h>
clog, clogf, clogl — complex natural logarithm functions
double complex clog(double complex z);
float complex clogf(float complex z);
long double complex clogl(long double complex z);
6818
6819
6820
6821
6822
6823
6824
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
6825
6826
These functions shall compute the complex natural (base e) logarithm of z, with a branch cut
along the negative real axis.
6827
6828
6829
6830
RETURN VALUE
These functions shall return the complex natural logarithm value, in the range of a strip
mathematically unbounded along the real axis and in the interval [−iπ, +iπ] along the imaginary
axis.
6831
6832
ERRORS
No errors are defined.
6833
6834
EXAMPLES
None.
6835
6836
APPLICATION USAGE
None.
6837
6838
RATIONALE
None.
6839
6840
FUTURE DIRECTIONS
None.
6841
6842
SEE ALSO
cexp( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
6843
6844
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
202
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
6845
6846
NAME
6847
6848
SYNOPSIS
#include <unistd.h>
close( )
close — close a file descriptor
int close(int fildes);
6849
6850
6851
6852
6853
6854
DESCRIPTION
The close( ) function shall deallocate the file descriptor indicated by fildes. To deallocate means
to make the file descriptor available for return by subsequent calls to open( ) or other functions
that allocate file descriptors. All outstanding record locks owned by the process on the file
associated with the file descriptor shall be removed (that is, unlocked).
6855
6856
6857
6858
If close( ) is interrupted by a signal that is to be caught, it shall return −1 with errno set to [EINTR]
and the state of fildes is unspecified. If an I/O error occurred while reading from or writing to the
file system during close( ), it may return −1 with errno set to [EIO]; if this error is returned, the
state of fildes is unspecified.
6859
6860
When all file descriptors associated with a pipe or FIFO special file are closed, any data
remaining in the pipe or FIFO shall be discarded.
6861
6862
When all file descriptors associated with an open file description have been closed, the open file
description shall be freed.
6863
6864
If the link count of the file is 0, when all file descriptors associated with the file are closed, the
space occupied by the file shall be freed and the file shall no longer be accessible.
6865
6866
6867
6868
6869
6870
6871
6872
6873
XSR
If a STREAMS-based fildes is closed and the calling process was previously registered to receive
a SIGPOLL signal for events associated with that STREAM, the calling process shall be
unregistered for events associated with the STREAM. The last close( ) for a STREAM shall cause
the STREAM associated with fildes to be dismantled. If O_NONBLOCK is not set and there have
been no signals posted for the STREAM, and if there is data on the module’s write queue, close( )
shall wait for an unspecified time (for each module and driver) for any output to drain before
dismantling the STREAM. The time delay can be changed via an I_SETCLTIME ioctl ( ) request. If
the O_NONBLOCK flag is set, or if there are any pending signals, close( ) shall not wait for
output to drain, and shall dismantle the STREAM immediately.
If the implementation supports STREAMS-based pipes, and fildes is associated with one end of a
pipe, the last close( ) shall cause a hangup to occur on the other end of the pipe. In addition, if the
other end of the pipe has been named by fattach ( ), then the last close( ) shall force the named end
to be detached by fdetach ( ). If the named end has no open file descriptors associated with it and
gets detached, the STREAM associated with that end shall also be dismantled.
6874
6875
6876
6877
6878
6879
6880
6881
6882
XSI
If fildes refers to the master side of a pseudo-terminal, and this is the last close, a SIGHUP signal
shall be sent to the process group, if any, for which the slave side of the pseudo-terminal is the
controlling terminal. It is unspecified whether closing the master side of the pseudo-terminal
flushes all queued input and output.
6883
6884
XSR
If fildes refers to the slave side of a STREAMS-based pseudo-terminal, a zero-length message
may be sent to the master.
6885
6886
6887
6888
AIO
When there is an outstanding cancelable asynchronous I/O operation against fildes when close( )
is called, that I/O operation may be canceled. An I/O operation that is not canceled completes
as if the close( ) operation had not yet occurred. All operations that are not canceled shall
complete as if the close( ) blocked until the operations completed. The close( ) operation itself
need not block awaiting such I/O completion. Whether any I/O operation is canceled, and
which I/O operation may be canceled upon close( ), is implementation-defined.
6889
6890
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
203
close( )
6891
6892
6893
6894
6895
MF|SHM
System Interfaces
If a shared memory object or a memory mapped file remains referenced at the last close (that is,
a process has it mapped), then the entire contents of the memory object shall persist until the
memory object becomes unreferenced. If this is the last close of a shared memory object or a
memory mapped file and the close results in the memory object becoming unreferenced, and the
memory object has been unlinked, then the memory object shall be removed.
6896
6897
6898
6899
If fildes refers to a socket, close( ) shall cause the socket to be destroyed. If the socket is in
connection-mode, and the SO_LINGER option is set for the socket with non-zero linger time,
and the socket has untransmitted data, then close( ) shall block for up to the current linger
interval until all data is transmitted.
6900
6901
6902
RETURN VALUE
Upon successful completion, 0 shall be returned; otherwise, −1 shall be returned and errno set to
indicate the error.
6903
6904
ERRORS
The close( ) function shall fail if:
6905
[EBADF]
The fildes argument is not a valid file descriptor.
6906
[EINTR]
The close( ) function was interrupted by a signal.
6907
The close( ) function may fail if:
6908
[EIO]
6909
An I/O error occurred while reading from or writing to the file system.
EXAMPLES
6910
Reassigning a File Descriptor
6911
6912
6913
6914
The following example closes the file descriptor associated with standard output for the current
process, re-assigns standard output to a new file descriptor, and closes the original file
descriptor to clean up. This example assumes that the file descriptor 0 (which is the descriptor
for standard input) is not closed.
6915
6916
6917
6918
6919
6920
6921
6922
#include <unistd.h>
...
int pfd;
...
close(1);
dup(pfd);
close(pfd);
...
6923
Incidentally, this is exactly what could be achieved using:
6924
6925
dup2(pfd, 1);
close(pfd);
6926
Closing a File Descriptor
6927
6928
In the following example, close( ) is used to close a file descriptor after an unsuccessful attempt is
made to associate that file descriptor with a stream.
6929
6930
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
6931
204
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
close( )
#define LOCKFILE "/etc/ptmp"
...
int pfd;
FILE *fpfd;
...
if ((fpfd = fdopen (pfd, "w")) == NULL) {
close(pfd);
unlink(LOCKFILE);
exit(1);
}
...
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
APPLICATION USAGE
An application that had used the stdio routine fopen( ) to open a file should use the
corresponding fclose( ) routine rather than close( ). Once a file is closed, the file descriptor no
longer exists, since the integer corresponding to it no longer refers to a file.
6947
6948
6949
6950
RATIONALE
The use of interruptible device close routines should be discouraged to avoid problems with the
implicit closes of file descriptors by exec and exit( ). This volume of IEEE Std 1003.1-2001 only
intends to permit such behavior by specifying the [EINTR] error condition.
6951
6952
FUTURE DIRECTIONS
None.
6953
6954
6955
SEE ALSO
Section 2.6 (on page 38), fattach ( ), fclose( ), fdetach ( ), fopen( ), ioctl ( ), open( ), the Base Definitions
volume of IEEE Std 1003.1-2001, <unistd.h>
6956
6957
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
6958
6959
Issue 5
6960
6961
6962
Issue 6
6963
6964
The DESCRIPTION is updated for alignment with the POSIX Realtime Extension.
The DESCRIPTION related to a STREAMS-based file or pseudo-terminal is marked as part of the
XSI STREAMS Option Group.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
6965
•
The [EIO] error condition is added as an optional error.
6966
6967
•
The DESCRIPTION is updated to describe the state of the fildes file descriptor as unspecified
if an I/O error occurs and an [EIO] error condition is returned.
6968
Text referring to sockets is added to the DESCRIPTION.
6969
6970
6971
The DESCRIPTION is updated for alignment with IEEE Std 1003.1j-2000 by specifying that
shared memory objects and memory mapped files (and not typed memory objects) are the types
of memory objects to which the paragraph on last closes applies.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
205
closedir( )
System Interfaces
6972
6973
NAME
6974
6975
SYNOPSIS
#include <dirent.h>
closedir — close a directory stream
int closedir(DIR *dirp);
6976
6977
6978
6979
6980
DESCRIPTION
The closedir( ) function shall close the directory stream referred to by the argument dirp. Upon
return, the value of dirp may no longer point to an accessible object of the type DIR. If a file
descriptor is used to implement type DIR, that file descriptor shall be closed.
6981
6982
6983
RETURN VALUE
Upon successful completion, closedir( ) shall return 0; otherwise, −1 shall be returned and errno
set to indicate the error.
6984
6985
ERRORS
The closedir( ) function may fail if:
6986
[EBADF]
The dirp argument does not refer to an open directory stream.
6987
[EINTR]
The closedir( ) function was interrupted by a signal.
6988
EXAMPLES
6989
Closing a Directory Stream
6990
The following program fragment demonstrates how the closedir( ) function is used.
6991
6992
6993
6994
6995
6996
6997
...
DIR *dir;
struct dirent *dp;
...
if ((dir = opendir (".")) == NULL) {
...
}
while ((dp = readdir (dir)) != NULL) {
6998
6999
7000
...
}
closedir(dir);
7001
7002
...
7003
7004
APPLICATION USAGE
None.
7005
7006
RATIONALE
None.
7007
7008
FUTURE DIRECTIONS
None.
7009
7010
SEE ALSO
opendir( ), the Base Definitions volume of IEEE Std 1003.1-2001, <dirent.h>
206
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7011
7012
CHANGE HISTORY
First released in Issue 2.
7013
7014
Issue 6
7015
7016
closedir( )
In the SYNOPSIS, the optional include of the <sys/types.h> header is removed.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
7017
7018
7019
•
The requirement to include <sys/types.h> has been removed. Although <sys/types.h> was
required for conforming implementations of previous POSIX specifications, it was not
required for UNIX applications.
7020
•
The [EINTR] error condition is added as an optional error condition.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
207
closelog( )
System Interfaces
7021
7022
NAME
7023
7024
SYNOPSIS
XSI
#include <syslog.h>
closelog, openlog, setlogmask, syslog — control system log
void closelog(void);
void openlog(const char *ident, int logopt, int facility);
int setlogmask(int maskpri);
void syslog(int priority, const char *message, ... /* arguments */);
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
DESCRIPTION
The syslog( ) function shall send a message to an implementation-defined logging facility, which
may log it in an implementation-defined system log, write it to the system console, forward it to
a list of users, or forward it to the logging facility on another host over the network. The logged
message shall include a message header and a message body. The message header contains at
least a timestamp and a tag string.
7036
7037
7038
7039
7040
7041
7042
The message body is generated from the message and following arguments in the same manner
as if these were arguments to printf( ), except that the additional conversion specification %m
shall be recognized; it shall convert no arguments, shall cause the output of the error message
string associated with the value of errno on entry to syslog( ), and may be mixed with argument
specifications of the "%n$" form. If a complete conversion specification with the m conversion
specifier character is not just %m, the behavior is undefined. A trailing <newline> may be added
if needed.
7043
7044
Values of the priority argument are formed by OR’ing together a severity-level value and an
optional facility value. If no facility value is specified, the current default facility value is used.
7045
Possible values of severity level include:
7046
LOG_EMERG
A panic condition.
7047
7048
LOG_ALERT
A condition that should be corrected immediately, such as a corrupted system
database.
7049
LOG_CRIT
Critical conditions, such as hard device errors.
7050
LOG_ERR
Errors.
7051
7052
LOG_WARNING
7053
7054
LOG_NOTICE
Conditions that are not error conditions, but that may require special
handling.
7055
LOG_INFO
Informational messages.
7056
7057
LOG_DEBUG
Messages that contain information normally of use only when debugging a
program.
7058
7059
The facility indicates the application or system component generating the message. Possible
facility values include:
7060
7061
LOG_USER
Messages generated by arbitrary processes. This is the default facility
identifier if none is specified.
7062
LOG_LOCAL0
Reserved for local use.
Warning messages.
208
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
closelog( )
System Interfaces
7063
LOG_LOCAL1
Reserved for local use.
7064
LOG_LOCAL2
Reserved for local use.
7065
LOG_LOCAL3
Reserved for local use.
7066
LOG_LOCAL4
Reserved for local use.
7067
LOG_LOCAL5
Reserved for local use.
7068
LOG_LOCAL6
Reserved for local use.
7069
LOG_LOCAL7
Reserved for local use.
7070
7071
7072
7073
The openlog ( ) function shall set process attributes that affect subsequent calls to syslog( ). The
ident argument is a string that is prepended to every message. The logopt argument indicates
logging options. Values for logopt are constructed by a bitwise-inclusive OR of zero or more of
the following:
7074
7075
LOG_PID
Log the process ID with each message. This is useful for identifying specific
processes.
7076
7077
7078
LOG_CONS
Write messages to the system console if they cannot be sent to the logging
facility. The syslog( ) function ensures that the process does not acquire the
console as a controlling terminal in the process of writing the message.
7079
7080
7081
LOG_NDELAY
Open the connection to the logging facility immediately. Normally the open is
delayed until the first message is logged. This is useful for programs that need
to manage the order in which file descriptors are allocated.
7082
LOG_ODELAY
Delay open until syslog( ) is called.
7083
7084
7085
7086
7087
LOG_NOWAIT
Do not wait for child processes that may have been created during the course
of logging the message. This option should be used by processes that enable
notification of child termination using SIGCHLD, since syslog( ) may
otherwise block waiting for a child whose exit status has already been
collected.
7088
7089
The facility argument encodes a default facility to be assigned to all messages that do not have
an explicit facility already encoded. The initial default facility is LOG_USER.
7090
7091
The openlog ( ) and syslog( ) functions may allocate a file descriptor. It is not necessary to call
openlog ( ) prior to calling syslog( ).
7092
7093
The closelog ( ) function shall close any open file descriptors allocated by previous calls to
openlog ( ) or syslog( ).
7094
7095
7096
7097
7098
The setlogmask( ) function shall set the log priority mask for the current process to maskpri and
return the previous mask. If the maskpri argument is 0, the current log mask is not modified.
Calls by the current process to syslog( ) with a priority not set in maskpri shall be rejected. The
default log mask allows all priorities to be logged. A call to openlog ( ) is not required prior to
calling setlogmask ( ).
7099
7100
Symbolic constants for use as values of the logopt , facility , priority , and maskpri arguments are
defined in the <syslog.h> header.
7101
7102
7103
RETURN VALUE
The setlogmask( ) function shall return the previous log priority mask. The closelog ( ), openlog ( ),
and syslog( ) functions shall not return a value.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
209
closelog( )
System Interfaces
7104
7105
ERRORS
No errors are defined.
7106
EXAMPLES
7107
Using openlog( )
7108
7109
7110
The following example causes subsequent calls to syslog( ) to log the process ID with each
message, and to write messages to the system console if they cannot be sent to the logging
facility.
7111
#include <syslog.h>
7112
7113
7114
7115
7116
char *ident = "Process demo";
int logopt = LOG_PID | LOG_CONS;
int facility = LOG_USER;
...
openlog(ident, logopt, facility);
7117
Using setlogmask( )
7118
7119
The following example causes subsequent calls to syslog( ) to accept error messages or messages
generated by arbitrary processes, and to reject all other messages.
7120
#include <syslog.h>
7121
7122
7123
7124
int result;
int mask = LOG_MASK (LOG_ERR | LOG_USER);
...
result = setlogmask(mask);
7125
Using syslog
7126
7127
The following example sends the message "This is a message" to the default logging
facility, marking the message as an error message generated by random processes.
7128
#include <syslog.h>
7129
7130
7131
7132
char *message = "This is a message";
int priority = LOG_ERR | LOG_USER;
...
syslog(priority, message);
7133
7134
APPLICATION USAGE
None.
7135
7136
RATIONALE
None.
7137
7138
FUTURE DIRECTIONS
None.
7139
7140
SEE ALSO
printf( ), the Base Definitions volume of IEEE Std 1003.1-2001, <syslog.h>
210
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7141
7142
CHANGE HISTORY
First released in Issue 4, Version 2.
7143
7144
Issue 5
closelog( )
Moved from X/OPEN UNIX extension to BASE.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
211
confstr( )
System Interfaces
7145
7146
NAME
7147
7148
SYNOPSIS
#include <unistd.h>
confstr — get configurable variables
size_t confstr(int name, char *buf, size_t len);
7149
7150
7151
7152
DESCRIPTION
The confstr( ) function shall return configuration-defined string values. Its use and purpose are
similar to sysconf( ), but it is used where string values rather than numeric values are returned.
7153
7154
The name argument represents the system variable to be queried. The implementation shall
support the following name values, defined in <unistd.h>. It may support others:
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
_CS_PATH
_CS_POSIX_V6_ILP32_OFF32_CFLAGS
_CS_POSIX_V6_ILP32_OFF32_LDFLAGS
_CS_POSIX_V6_ILP32_OFF32_LIBS
_CS_POSIX_V6_ILP32_OFFBIG_CFLAGS
_CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS
_CS_POSIX_V6_ILP32_OFFBIG_LIBS
_CS_POSIX_V6_LP64_OFF64_CFLAGS
_CS_POSIX_V6_LP64_OFF64_LDFLAGS
_CS_POSIX_V6_LP64_OFF64_LIBS
_CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS
_CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS
_CS_POSIX_V6_LPBIG_OFFBIG_LIBS
_CS_POSIX_V6_WIDTH_RESTRICTED_ENVS
_CS_XBS5_ILP32_OFF32_CFLAGS (LEGACY)
_CS_XBS5_ILP32_OFF32_LDFLAGS (LEGACY)
_CS_XBS5_ILP32_OFF32_LIBS (LEGACY)
_CS_XBS5_ILP32_OFF32_LINTFLAGS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_CFLAGS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_LDFLAGS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_LIBS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_LINTFLAGS (LEGACY)
_CS_XBS5_LP64_OFF64_CFLAGS (LEGACY)
_CS_XBS5_LP64_OFF64_LDFLAGS (LEGACY)
_CS_XBS5_LP64_OFF64_LIBS (LEGACY)
_CS_XBS5_LP64_OFF64_LINTFLAGS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_CFLAGS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_LDFLAGS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_LIBS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_LINTFLAGS (LEGACY)
XSI
7186
7187
7188
7189
7190
If len is not 0, and if name has a configuration-defined value, confstr( ) shall copy that value into
the len-byte buffer pointed to by buf. If the string to be returned is longer than len bytes,
including the terminating null, then confstr( ) shall truncate the string to len−1 bytes and nullterminate the result. The application can detect that the string was truncated by comparing the
value returned by confstr( ) with len.
7191
7192
7193
If len is 0 and buf is a null pointer, then confstr( ) shall still return the integer value as defined
below, but shall not return a string. If len is 0 but buf is not a null pointer, the result is
unspecified.
212
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
confstr( )
System Interfaces
7194
If the implementation supports the POSIX shell option, the string stored in buf after a call to:
7195
confstr(_CS_PATH, buf, sizeof(buf))
7196
7197
can be used as a value of the PATH environment variable that accesses all of the standard
utilities of IEEE Std 1003.1-2001, if the return value is less than or equal to sizeof (buf).
7198
7199
7200
7201
RETURN VALUE
If name has a configuration-defined value, confstr( ) shall return the size of buffer that would be
needed to hold the entire configuration-defined value including the terminating null. If this
return value is greater than len, the string returned in buf is truncated.
7202
If name is invalid, confstr( ) shall return 0 and set errno to indicate the error.
7203
7204
If name does not have a configuration-defined value, confstr( ) shall return 0 and leave errno
unchanged.
7205
7206
7207
ERRORS
The confstr( ) function shall fail if:
[EINVAL]
The value of the name argument is invalid.
7208
7209
EXAMPLES
None.
7210
7211
7212
7213
APPLICATION USAGE
An application can distinguish between an invalid name parameter value and one that
corresponds to a configurable variable that has no configuration-defined value by checking if
errno is modified. This mirrors the behavior of sysconf( ).
7214
7215
7216
7217
7218
7219
The original need for this function was to provide a way of finding the configuration-defined
default value for the environment variable PATH. Since PATH can be modified by the user to
include directories that could contain utilities replacing the standard utilities in the Shell and
Utilities volume of IEEE Std 1003.1-2001, applications need a way to determine the systemsupplied PATH environment variable value that contains the correct search path for the standard
utilities.
7220
An application could use:
7221
confstr(name, (char *)NULL, (size_t)0)
7222
7223
7224
7225
to find out how big a buffer is needed for the string value; use malloc ( ) to allocate a buffer to
hold the string; and call confstr( ) again to get the string. Alternately, it could allocate a fixed,
static buffer that is big enough to hold most answers (perhaps 512 or 1 024 bytes), but then use
malloc ( ) to allocate a larger buffer if it finds that this is too small.
7226
7227
7228
RATIONALE
Application developers can normally determine any configuration variable by means of reading
from the stream opened by a call to:
7229
popen("command -p getconf variable", "r");
7230
7231
7232
The confstr( ) function with a name argument of _CS_PATH returns a string that can be used as a
PATH environment variable setting that will reference the standard shell and utilities as
described in the Shell and Utilities volume of IEEE Std 1003.1-2001.
7233
7234
The confstr( ) function copies the returned string into a buffer supplied by the application instead
of returning a pointer to a string. This allows a cleaner function in some implementations (such
as those with lightweight threads) and resolves questions about when the application must copy
the string returned.
7235
7236
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
213
confstr( )
System Interfaces
7237
7238
FUTURE DIRECTIONS
None.
7239
7240
7241
SEE ALSO
pathconf ( ), sysconf( ), the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>, the Shell
and Utilities volume of IEEE Std 1003.1-2001, c99
7242
7243
CHANGE HISTORY
First released in Issue 4. Derived from the ISO POSIX-2 standard.
7244
7245
7246
Issue 5
7247
7248
7249
Issue 6
A table indicating the permissible values of name is added to the DESCRIPTION. All those
marked EX are new in this issue.
The Open Group Corrigendum U033/7 is applied. The return value for the case returning the
size of the buffer now explicitly states that this includes the terminating null.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
7250
7251
•
7252
7253
7254
The DESCRIPTION is updated with new arguments which can be used to determine
configuration strings for C compiler flags, linker/loader flags, and libraries for each different
supported programming environment. This is a change to support data size neutrality.
The following changes were made to align with the IEEE P1003.1a draft standard:
7255
•
7256
7257
The DESCRIPTION is updated to include text describing how _CS_PATH can be used to
obtain a PATH to access the standard utilities.
The macros associated with the c89 programming models are marked LEGACY and new
equivalent macros associated with c99 are introduced.
7258
7259
214
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7260
7261
NAME
7262
7263
SYNOPSIS
#include <complex.h>
7264
7265
7266
conj( )
conj, conjf, conjl — complex conjugate functions
double complex conj(double complex z);
float complex conjf(float complex z);
long double complex conjl(long double complex z);
7267
7268
7269
7270
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
7271
7272
These functions shall compute the complex conjugate of z, by reversing the sign of its imaginary
part.
7273
7274
RETURN VALUE
These functions return the complex conjugate value.
7275
7276
ERRORS
No errors are defined.
7277
7278
EXAMPLES
None.
7279
7280
APPLICATION USAGE
None.
7281
7282
RATIONALE
None.
7283
7284
FUTURE DIRECTIONS
None.
7285
7286
7287
SEE ALSO
carg( ), cimag( ), cproj( ), creal( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<complex.h>
7288
7289
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
215
connect( )
System Interfaces
7290
7291
NAME
7292
7293
SYNOPSIS
#include <sys/socket.h>
connect — connect a socket
int connect(int socket, const struct sockaddr *address,
socklen_t address_len);
7294
7295
7296
7297
7298
DESCRIPTION
The connect( ) function shall attempt to make a connection on a socket. The function takes the
following arguments:
7299
socket
Specifies the file descriptor associated with the socket.
7300
7301
address
Points to a sockaddr structure containing the peer address. The length and
format of the address depend on the address family of the socket.
7302
7303
address_len
Specifies the length of the sockaddr structure pointed to by the address
argument.
7304
7305
If the socket has not already been bound to a local address, connect( ) shall bind it to an address
which, unless the socket’s address family is AF_UNIX, is an unused local address.
7306
7307
7308
7309
7310
If the initiating socket is not connection-mode, then connect( ) shall set the socket’s peer address,
and no connection is made. For SOCK_DGRAM sockets, the peer address identifies where all
datagrams are sent on subsequent send( ) functions, and limits the remote sender for subsequent
recv( ) functions. If address is a null address for the protocol, the socket’s peer address shall be
reset.
7311
7312
7313
7314
7315
7316
7317
7318
If the initiating socket is connection-mode, then connect( ) shall attempt to establish a connection
to the address specified by the address argument. If the connection cannot be established
immediately and O_NONBLOCK is not set for the file descriptor for the socket, connect( ) shall
block for up to an unspecified timeout interval until the connection is established. If the timeout
interval expires before the connection is established, connect( ) shall fail and the connection
attempt shall be aborted. If connect( ) is interrupted by a signal that is caught while blocked
waiting to establish a connection, connect( ) shall fail and set errno to [EINTR], but the connection
request shall not be aborted, and the connection shall be established asynchronously.
7319
7320
7321
7322
7323
If the connection cannot be established immediately and O_NONBLOCK is set for the file
descriptor for the socket, connect( ) shall fail and set errno to [EINPROGRESS], but the connection
request shall not be aborted, and the connection shall be established asynchronously.
Subsequent calls to connect( ) for the same socket, before the connection is established, shall fail
and set errno to [EALREADY].
7324
7325
When the connection has been established asynchronously, select( ) and poll ( ) shall indicate that
the file descriptor for the socket is ready for writing.
7326
7327
The socket in use may require the process to have appropriate privileges to use the connect( )
function.
7328
7329
7330
RETURN VALUE
Upon successful completion, connect( ) shall return 0; otherwise, −1 shall be returned and errno
set to indicate the error.
7331
7332
ERRORS
The connect( ) function shall fail if:
[EADDRNOTAVAIL]
The specified address is not available from the local machine.
7333
7334
216
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
connect( )
System Interfaces
7335
7336
7337
[EAFNOSUPPORT]
The specified address is not a valid address for the address family of the
specified socket.
7338
[EALREADY]
A connection request is already in progress for the specified socket.
7339
[EBADF]
The socket argument is not a valid file descriptor.
7340
7341
7342
[ECONNREFUSED]
The target address was not listening for connections or refused the connection
request.
7343
7344
7345
[EINPROGRESS] O_NONBLOCK is set for the file descriptor for the socket and the connection
cannot be immediately established; the connection shall be established
asynchronously.
7346
7347
[EINTR]
The attempt to establish a connection was interrupted by delivery of a signal
that was caught; the connection shall be established asynchronously.
7348
[EISCONN]
The specified socket is connection-mode and is already connected.
7349
7350
[ENETUNREACH]
No route to the network is present.
7351
[ENOTSOCK]
7352
7353
[EPROTOTYPE] The specified address has a different type than the socket bound to the
specified peer address.
7354
[ETIMEDOUT]
7355
If the address family of the socket is AF_UNIX, then connect( ) shall fail if:
7356
[EIO]
An I/O error occurred while reading from or writing to the file system.
7357
7358
[ELOOP]
A loop exists in symbolic links encountered during resolution of the pathname
in address.
7359
7360
7361
[ENAMETOOLONG]
A component of a pathname exceeded {NAME_MAX} characters, or an entire
pathname exceeded {PATH_MAX} characters.
7362
7363
[ENOENT]
A component of the pathname does not name an existing file or the pathname
is an empty string.
7364
[ENOTDIR]
A component of the path prefix of the pathname in address is not a directory.
7365
The connect( ) function may fail if:
7366
7367
[EACCES]
7368
[EADDRINUSE] Attempt to establish a connection that uses addresses that are already in use.
7369
[ECONNRESET] Remote host reset the connection request.
7370
7371
7372
[EHOSTUNREACH]
The destination host cannot be reached (probably because the host is down or
a remote router cannot reach it).
7373
[EINVAL]
7374
The socket argument does not refer to a socket.
The attempt to connect timed out before a connection was made.
Search permission is denied for a component of the path prefix; or write
access to the named socket is denied.
The address_len argument is not a valid length for the address family; or
invalid address family in the sockaddr structure.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
217
connect( )
System Interfaces
7375
7376
[ELOOP]
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the pathname in address.
7377
7378
7379
[ENAMETOOLONG]
Pathname resolution of a symbolic link produced an intermediate result
whose length exceeds {PATH_MAX}.
7380
[ENETDOWN]
The local network interface used to reach the destination is down.
7381
[ENOBUFS]
No buffer space is available.
7382
[EOPNOTSUPP] The socket is listening and cannot be connected.
7383
7384
EXAMPLES
None.
7385
7386
7387
APPLICATION USAGE
If connect( ) fails, the state of the socket is unspecified. Conforming applications should close the
file descriptor and create a new socket before attempting to reconnect.
7388
7389
RATIONALE
None.
7390
7391
FUTURE DIRECTIONS
None.
7392
7393
7394
SEE ALSO
accept( ), bind( ), close( ), getsockname( ), poll ( ), select( ), send( ), shutdown( ), socket( ), the Base
Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>
7395
7396
CHANGE HISTORY
First released in Issue 6. Derived from the XNS, Issue 5.2 specification.
The wording of the mandatory [ELOOP] error condition is updated, and a second optional
[ELOOP] error condition is added.
7397
7398
218
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7399
7400
NAME
7401
7402
SYNOPSIS
#include <math.h>
7403
7404
7405
copysign( )
copysign, copysignf, copysignl — number manipulation function
double copysign(double x, double y);
float copysignf(float x, float y);
long double copysignl(long double x, long double y);
7406
7407
7408
7409
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
7410
7411
7412
These functions shall produce a value with the magnitude of x and the sign of y. On
implementations that represent a signed zero but do not treat negative zero consistently in
arithmetic operations, these functions regard the sign of zero as positive.
7413
7414
7415
RETURN VALUE
Upon successful completion, these functions shall return a value with the magnitude of x and
the sign of y.
7416
7417
ERRORS
No errors are defined.
7418
7419
EXAMPLES
None.
7420
7421
APPLICATION USAGE
None.
7422
7423
RATIONALE
None.
7424
7425
FUTURE DIRECTIONS
None.
7426
7427
SEE ALSO
signbit( ), the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>
7428
7429
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
219
cos( )
System Interfaces
7430
7431
NAME
7432
7433
SYNOPSIS
#include <math.h>
cos, cosf, cosl — cosine function
double cos(double x);
float cosf(float x);
long double cosl(long double x);
7434
7435
7436
7437
7438
7439
7440
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
7441
These functions shall compute the cosine of their argument x, measured in radians.
7442
7443
7444
7445
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
7446
7447
RETURN VALUE
Upon successful completion, these functions shall return the cosine of x.
7448
MX
If x is NaN, a NaN shall be returned.
7449
If x is ±0, the value 1.0 shall be returned.
7450
7451
If x is ±Inf, a domain error shall occur, and either a NaN (if supported), or an implementationdefined value shall be returned.
7452
7453
ERRORS
These functions shall fail if:
7454
MX
Domain Error
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [EDOM]. If the integer expression (math_errhandling
& MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception
shall be raised.
7455
7456
7457
7458
7459
The x argument is ±Inf.
EXAMPLES
7460
Taking the Cosine of a 45-Degree Angle
7461
7462
7463
7464
7465
7466
#include <math.h>
...
double radians = 45 * M_PI / 180;
double result;
...
result = cos(radians);
7467
7468
7469
APPLICATION USAGE
These functions may lose accuracy when their argument is near an odd multiple of π/2 or is far
from 0.
7470
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
7471
220
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
cos( )
7472
7473
RATIONALE
None.
7474
7475
FUTURE DIRECTIONS
None.
7476
7477
7478
7479
SEE ALSO
acos( ), feclearexcept( ), fetestexcept( ), isnan( ), sin( ), tan( ), the Base Definitions volume of
IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions,
<math.h>
7480
7481
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
7482
7483
7484
Issue 5
7485
7486
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The cosf( ) and cosl( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
7487
7488
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
7489
7490
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
221
cosh( )
System Interfaces
7491
7492
NAME
7493
7494
SYNOPSIS
#include <math.h>
cosh, coshf, coshl — hyperbolic cosine functions
double cosh(double x);
float coshf(float x);
long double coshl(long double x);
7495
7496
7497
7498
7499
7500
7501
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
7502
These functions shall compute the hyperbolic cosine of their argument x.
7503
7504
7505
7506
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
7507
7508
RETURN VALUE
Upon successful completion, these functions shall return the hyperbolic cosine of x.
If the correct value would cause overflow, a range error shall occur and cosh( ), coshf( ), and
coshl( ) shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL,
respectively.
7509
7510
7511
7512
MX
If x is NaN, a NaN shall be returned.
7513
If x is ±0, the value 1.0 shall be returned.
7514
If x is ±Inf, +Inf shall be returned.
7515
7516
ERRORS
These functions shall fail if:
Range Error
7517
The result would cause an overflow.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow
floating-point exception shall be raised.
7518
7519
7520
7521
7522
7523
EXAMPLES
None.
7524
7525
7526
APPLICATION USAGE
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
For IEEE Std 754-1985 double, 710.5 < |x| implies that cosh(x) has overflowed.
7527
7528
7529
RATIONALE
None.
7530
7531
FUTURE DIRECTIONS
None.
222
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
cosh( )
7532
7533
7534
7535
SEE ALSO
acosh( ), feclearexcept( ), fetestexcept( ), isnan( ), sinh( ), tanh( ), the Base Definitions volume of
IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions,
<math.h>
7536
7537
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
7538
7539
7540
Issue 5
7541
7542
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The coshf( ) and coshl( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
7543
7544
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
7545
7546
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
223
cosl( )
System Interfaces
7547
7548
NAME
7549
7550
SYNOPSIS
#include <math.h>
cosl — cosine function
long double cosl(long double x);
7551
7552
7553
DESCRIPTION
Refer to cos( ).
224
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7554
7555
NAME
7556
7557
SYNOPSIS
#include <complex.h>
7558
7559
7560
7561
cpow( )
cpow, cpowf, cpowl — complex power functions
double complex cpow(double complex x, double complex y);
float complex cpowf(float complex x, float complex y);
long double complex cpowl(long double complex x,
long double complex y);
7562
7563
7564
7565
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
7566
7567
These functions shall compute the complex power function xy, with a branch cut for the first
parameter along the negative real axis.
7568
7569
RETURN VALUE
These functions shall return the complex power function value.
7570
7571
ERRORS
No errors are defined.
7572
7573
EXAMPLES
None.
7574
7575
APPLICATION USAGE
None.
7576
7577
RATIONALE
None.
7578
7579
FUTURE DIRECTIONS
None.
7580
7581
SEE ALSO
cabs( ), csqrt( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
7582
7583
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
225
cproj( )
System Interfaces
7584
7585
NAME
7586
7587
SYNOPSIS
#include <complex.h>
cproj, cprojf, cprojl — complex projection functions
double complex cproj(double complex z);
float complex cprojf(float complex z);
long double complex cprojl(long double complex z);
7588
7589
7590
7591
7592
7593
7594
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
7595
7596
7597
These functions shall compute a projection of z onto the Riemann sphere: z projects to z, except
that all complex infinities (even those with one infinite part and one NaN part) project to
positive infinity on the real axis. If z has an infinite part, then cproj(z) shall be equivalent to:
7598
INFINITY + I * copysign(0.0, cimag(z))
7599
7600
RETURN VALUE
These functions shall return the value of the projection onto the Riemann sphere.
7601
7602
ERRORS
No errors are defined.
7603
7604
EXAMPLES
None.
7605
7606
APPLICATION USAGE
None.
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
RATIONALE
Two topologies are commonly used in complex mathematics: the complex plane with its
continuum of infinities, and the Riemann sphere with its single infinity. The complex plane is
better suited for transcendental functions, the Riemann sphere for algebraic functions. The
complex types with their multiplicity of infinities provide a useful (though imperfect) model for
the complex plane. The cproj( ) function helps model the Riemann sphere by mapping all
infinities to one, and should be used just before any operation, especially comparisons, that
might give spurious results for any of the other infinities. Note that a complex value with one
infinite part and one NaN part is regarded as an infinity, not a NaN, because if one part is
infinite, the complex value is infinite independent of the value of the other part. For the same
reason, cabs( ) returns an infinity if its argument has an infinite part and a NaN part.
7618
7619
FUTURE DIRECTIONS
None.
7620
7621
SEE ALSO
carg( ), cimag( ), conj( ), creal( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
7622
7623
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
226
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7624
7625
NAME
7626
7627
SYNOPSIS
#include <complex.h>
7628
7629
7630
7631
7632
7633
7634
7635
creal, crealf, creall — complex real functions
double creal(double complex z);
float crealf(float complex z);
long double creall(long double complex z);
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the real part of z.
7636
7637
RETURN VALUE
These functions shall return the real part value.
7638
7639
ERRORS
No errors are defined.
7640
7641
EXAMPLES
None.
7642
7643
APPLICATION USAGE
For a variable z of type complex:
7644
creal( )
z == creal(z) + cimag(z)*I
7645
7646
RATIONALE
None.
7647
7648
FUTURE DIRECTIONS
None.
7649
7650
7651
SEE ALSO
carg( ), cimag( ), conj( ), cproj( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<complex.h>
7652
7653
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
227
creat( )
System Interfaces
7654
7655
NAME
7656
7657
7658
SYNOPSIS
OH
#include <sys/stat.h>
#include <fcntl.h>
creat — create a new file or rewrite an existing one
int creat(const char *path, mode_t mode);
7659
7660
7661
DESCRIPTION
The function call:
7662
creat(path, mode)
7663
shall be equivalent to:
7664
open(path, O_WRONLY|O_CREAT|O_TRUNC, mode)
7665
7666
RETURN VALUE
Refer to open( ).
7667
7668
ERRORS
Refer to open( ).
7669
EXAMPLES
7670
Creating a File
7671
7672
7673
The following example creates the file /tmp/file with read and write permissions for the file
owner and read permission for group and others. The resulting file descriptor is assigned to the
fd variable.
7674
7675
7676
7677
7678
7679
7680
7681
#include <fcntl.h>
...
int fd;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *filename = "/tmp/file";
...
fd = creat(filename, mode);
...
7682
7683
APPLICATION USAGE
None.
7684
7685
7686
7687
7688
RATIONALE
The creat( ) function is redundant. Its services are also provided by the open( ) function. It has
been included primarily for historical purposes since many existing applications depend on it. It
is best considered a part of the C binding rather than a function that should be provided in other
languages.
7689
7690
FUTURE DIRECTIONS
None.
7691
7692
7693
SEE ALSO
open( ), the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>, <sys/stat.h>,
<sys/types.h>
228
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7694
7695
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
7696
7697
Issue 6
7698
7699
7700
7701
7702
creat( )
In the SYNOPSIS, the optional include of the <sys/types.h> header is removed.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
•
The requirement to include <sys/types.h> has been removed. Although <sys/types.h> was
required for conforming implementations of previous POSIX specifications, it was not
required for UNIX applications.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
229
crypt( )
System Interfaces
7703
7704
NAME
7705
7706
SYNOPSIS
XSI
#include <unistd.h>
crypt — string encoding function (CRYPT)
char *crypt(const char *key, const char *salt);
7707
7708
7709
7710
DESCRIPTION
The crypt( ) function is a string encoding function. The algorithm is implementation-defined.
7711
7712
The key argument points to a string to be encoded. The salt argument is a string chosen from the
set:
7713
7714
7715
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
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
0 1 2 3 4 5 6 7 8 9 . /
7716
The first two characters of this string may be used to perturb the encoding algorithm.
7717
The return value of crypt( ) points to static data that is overwritten by each call.
7718
7719
The crypt( ) function need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
7720
7721
7722
7723
RETURN VALUE
Upon successful completion, crypt( ) shall return a pointer to the encoded string. The first two
characters of the returned value shall be those of the salt argument. Otherwise, it shall return a
null pointer and set errno to indicate the error.
7724
7725
ERRORS
The crypt( ) function shall fail if:
[ENOSYS]
7726
7727
The functionality is not supported on this implementation.
EXAMPLES
7728
Encoding Passwords
7729
7730
7731
7732
7733
The following example finds a user database entry matching a particular user name and changes
the current password to a new password. The crypt( ) function generates an encoded version of
each password. The first call to crypt( ) produces an encoded version of the old password; that
encoded password is then compared to the password stored in the user database. The second
call to crypt( ) encodes the new password before it is stored.
7734
The putpwent( ) function, used in the following example, is not part of IEEE Std 1003.1-2001.
7735
7736
7737
7738
7739
7740
7741
7742
7743
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>
...
int valid_change;
int pfd; /* Integer for file descriptor returned by open(). */
FILE *fpfd; /* File pointer for use in putpwent(). */
struct passwd *p;
char user[100];
char oldpasswd[100];
char newpasswd[100];
7744
7745
7746
230
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
crypt( )
char savepasswd[100];
...
valid_change = 0;
while ((p = getpwent()) != NULL) {
/* Change entry if found. */
if (strcmp(p->pw_name, user) == 0) {
if (strcmp(p->pw_passwd, crypt(oldpasswd, p->pw_passwd)) == 0) {
strcpy(savepasswd, crypt(newpasswd, user));
p->pw_passwd = savepasswd;
valid_change = 1;
}
else {
fprintf(stderr, "Old password is not valid\n");
}
}
/* Put passwd entry into ptmp. */
putpwent(p, fpfd);
}
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
APPLICATION USAGE
The values returned by this function need not be portable among XSI-conformant systems.
7767
7768
RATIONALE
None.
7769
7770
FUTURE DIRECTIONS
None.
7771
7772
SEE ALSO
encrypt( ), setkey( ), the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>
7773
7774
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
7775
7776
7777
Issue 5
Normative text previously in the APPLICATION USAGE section is moved to the
DESCRIPTION.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
231
csin( )
System Interfaces
7778
7779
NAME
7780
7781
SYNOPSIS
#include <complex.h>
csin, csinf, csinl — complex sine functions
double complex csin(double complex z);
float complex csinf(float complex z);
long double complex csinl(long double complex z);
7782
7783
7784
7785
7786
7787
7788
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the complex sine of z.
7789
7790
7791
RETURN VALUE
These functions shall return the complex sine value.
7792
7793
ERRORS
No errors are defined.
7794
7795
EXAMPLES
None.
7796
7797
APPLICATION USAGE
None.
7798
7799
RATIONALE
None.
7800
7801
FUTURE DIRECTIONS
None.
7802
7803
SEE ALSO
casin( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
7804
7805
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
232
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7806
7807
NAME
7808
7809
SYNOPSIS
#include <complex.h>
7810
7811
7812
7813
7814
7815
7816
7817
csinh( )
csinh, csinhf, csinhl — complex hyperbolic sine functions
double complex csinh(double complex z);
float complex csinhf(float complex z);
long double complex csinhl(long double complex z);
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the complex hyperbolic sine of z.
7818
7819
RETURN VALUE
These functions shall return the complex hyperbolic sine value.
7820
7821
ERRORS
No errors are defined.
7822
7823
EXAMPLES
None.
7824
7825
APPLICATION USAGE
None.
7826
7827
RATIONALE
None.
7828
7829
FUTURE DIRECTIONS
None.
7830
7831
SEE ALSO
casinh( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
7832
7833
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
233
csinl( )
System Interfaces
7834
7835
NAME
7836
7837
SYNOPSIS
#include <complex.h>
csinl — complex sine functions
long double complex csinl(long double complex z);
7838
7839
7840
DESCRIPTION
Refer to csin( ).
234
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7841
7842
NAME
7843
7844
SYNOPSIS
#include <complex.h>
7845
7846
7847
csqrt( )
csqrt, csqrtf, csqrtl — complex square root functions
double complex csqrt(double complex z);
float complex csqrtf(float complex z);
long double complex csqrtl(long double complex z);
7848
7849
7850
7851
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
7852
7853
These functions shall compute the complex square root of z, with a branch cut along the
negative real axis.
7854
7855
7856
RETURN VALUE
These functions shall return the complex square root value, in the range of the right half-plane
(including the imaginary axis).
7857
7858
ERRORS
No errors are defined.
7859
7860
EXAMPLES
None.
7861
7862
APPLICATION USAGE
None.
7863
7864
RATIONALE
None.
7865
7866
FUTURE DIRECTIONS
None.
7867
7868
SEE ALSO
cabs( ), cpow( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
7869
7870
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
235
ctan( )
System Interfaces
7871
7872
NAME
7873
7874
SYNOPSIS
#include <complex.h>
ctan, ctanf, ctanl — complex tangent functions
double complex ctan(double complex z);
float complex ctanf(float complex z);
long double complex ctanl(long double complex z);
7875
7876
7877
7878
7879
7880
7881
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the complex tangent of z.
7882
7883
7884
RETURN VALUE
These functions shall return the complex tangent value.
7885
7886
ERRORS
No errors are defined.
7887
7888
EXAMPLES
None.
7889
7890
APPLICATION USAGE
None.
7891
7892
RATIONALE
None.
7893
7894
FUTURE DIRECTIONS
None.
7895
7896
SEE ALSO
catan( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
7897
7898
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
236
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7899
7900
NAME
7901
7902
SYNOPSIS
#include <complex.h>
7903
7904
7905
7906
7907
7908
7909
7910
ctanh( )
ctanh, ctanhf, ctanhl — complex hyperbolic tangent functions
double complex ctanh(double complex z);
float complex ctanhf(float complex z);
long double complex ctanhl(long double complex z);
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the complex hyperbolic tangent of z.
7911
7912
RETURN VALUE
These functions shall return the complex hyperbolic tangent value.
7913
7914
ERRORS
No errors are defined.
7915
7916
EXAMPLES
None.
7917
7918
APPLICATION USAGE
None.
7919
7920
RATIONALE
None.
7921
7922
FUTURE DIRECTIONS
None.
7923
7924
SEE ALSO
catanh( ), the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>
7925
7926
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
237
ctanl( )
System Interfaces
7927
7928
NAME
7929
7930
SYNOPSIS
#include <complex.h>
ctanl — complex tangent functions
long double complex ctanl(long double complex z);
7931
7932
7933
DESCRIPTION
Refer to ctan( ).
238
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
7934
7935
NAME
7936
7937
SYNOPSIS
CX
#include <stdio.h>
7938
7939
ctermid( )
ctermid — generate a pathname for the controlling terminal
char *ctermid(char *s);
7940
7941
7942
7943
DESCRIPTION
The ctermid( ) function shall generate a string that, when used as a pathname, refers to the
current controlling terminal for the current process. If ctermid( ) returns a pathname, access to the
file is not guaranteed.
7944
7945
If the application uses any of the _POSIX_THREAD_SAFE_FUNCTIONS or _POSIX_THREADS
functions, it shall ensure that the ctermid( ) function is called with a non-NULL parameter.
7946
7947
7948
7949
7950
7951
RETURN VALUE
If s is a null pointer, the string shall be generated in an area that may be static (and therefore may
be overwritten by each call), the address of which shall be returned. Otherwise, s is assumed to
point to a character array of at least L_ctermid bytes; the string is placed in this array and the
value of s shall be returned. The symbolic constant L_ctermid is defined in <stdio.h>, and shall
have a value greater than 0.
7952
7953
The ctermid( ) function shall return an empty string if the pathname that would refer to the
controlling terminal cannot be determined, or if the function is unsuccessful.
7954
7955
ERRORS
No errors are defined.
7956
EXAMPLES
7957
Determining the Controlling Terminal for the Current Process
7958
7959
7960
The following example returns a pointer to a string that identifies the controlling terminal for the
current process. The pathname for the terminal is stored in the array pointed to by the ptr
argument, which has a size of L_ctermid bytes, as indicated by the term argument.
7961
7962
7963
7964
#include <stdio.h>
...
char term[L_ctermid];
char *ptr;
7965
ptr = ctermid(term);
7966
7967
7968
7969
7970
APPLICATION USAGE
The difference between ctermid( ) and ttyname( ) is that ttyname( ) must be handed a file
descriptor and return a path of the terminal associated with that file descriptor, while ctermid( )
returns a string (such as "/dev/tty") that refers to the current controlling terminal if used as a
pathname.
7971
7972
7973
7974
RATIONALE
L_ctermid must be defined appropriately for a given implementation and must be greater than
zero so that array declarations using it are accepted by the compiler. The value includes the
terminating null byte.
7975
Conforming applications that use threads cannot call ctermid( ) with NULL as the parameter if
either _POSIX_THREAD_SAFE_FUNCTIONS or _POSIX_THREADS is defined. If s is not
NULL, the ctermid( ) function generates a string that, when used as a pathname, refers to the
7976
7977
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
239
ctermid( )
System Interfaces
7978
7979
current controlling terminal for the current process. If s is NULL, the return value of ctermid( ) is
undefined.
7980
7981
7982
7983
7984
There is no additional burden on the programmer—changing to use a hypothetical thread-safe
version of ctermid( ) along with allocating a buffer is more of a burden than merely allocating a
buffer. Application code should not assume that the returned string is short, as some
implementations have more than two pathname components before reaching a logical device
name.
7985
7986
FUTURE DIRECTIONS
None.
7987
7988
SEE ALSO
ttyname( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
7989
7990
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
7991
7992
Issue 5
7993
7994
Issue 6
The DESCRIPTION is updated for alignment with the POSIX Threads Extension.
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
240
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
ctime( )
7995
7996
NAME
7997
7998
SYNOPSIS
#include <time.h>
7999
8000
8001
TSF
8002
8003
8004
8005
DESCRIPTION
CX
For ctime( ): The functionality described on this reference page is aligned with the ISO C
standard. Any conflict between the requirements described here and the ISO C standard is
unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
8006
8007
The ctime( ) function shall convert the time pointed to by clock , representing time in seconds
since the Epoch, to local time in the form of a string. It shall be equivalent to:
8008
asctime(localtime(clock))
8009
8010
8011
ctime, ctime_r — convert a time value to a date and time string
CX
The asctime( ), ctime( ), gmtime( ), and localtime ( ) functions shall return values in one of two static
objects: a broken-down time structure and an array of char. Execution of any of the functions
may overwrite the information returned in either of these objects by any of the other functions.
The ctime( ) function need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
8012
8013
8014
8015
8016
char *ctime(const time_t *clock);
char *ctime_r(const time_t *clock, char *buf);
TSF
The ctime_r( ) function shall convert the calendar time pointed to by clock to local time in exactly
the same form as ctime( ) and put the string into the array pointed to by buf (which shall be at
least 26 bytes in size) and return buf.
Unlike ctime( ), the thread-safe version ctime_r( ) is not required to set tzname.
8017
8018
8019
8020
RETURN VALUE
The ctime( ) function shall return the pointer returned by asctime( ) with that broken-down time
as an argument.
8021
8022
TSF
8023
8024
ERRORS
No errors are defined.
8025
8026
EXAMPLES
None.
8027
8028
8029
8030
8031
APPLICATION USAGE
Values for the broken-down time structure can be obtained by calling gmtime( ) or localtime ( ).
The ctime( ) function is included for compatibility with older implementations, and does not
support localized date and time formats. Applications should use the strftime( ) function to
achieve maximum portability.
8032
8033
The ctime_r( ) function is thread-safe and shall return values in a user-supplied buffer instead of
possibly using a static data area that may be overwritten by each call.
8034
8035
Upon successful completion, ctime_r( ) shall return a pointer to the string pointed to by buf.
When an error is encountered, a null pointer shall be returned.
RATIONALE
None.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
241
ctime( )
System Interfaces
8036
8037
FUTURE DIRECTIONS
None.
8038
8039
8040
SEE ALSO
asctime( ), clock ( ), difftime ( ), gmtime( ), localtime ( ), mktime( ), strftime( ), strptime( ), time( ), utime( ),
the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>
8041
8042
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
8043
8044
8045
Issue 5
Normative text previously in the APPLICATION USAGE section is moved to the
DESCRIPTION.
8046
The ctime_r( ) function is included for alignment with the POSIX Threads Extension.
8047
A note indicating that the ctime( ) function need not be reentrant is added to the DESCRIPTION.
8048
8049
Issue 6
Extensions beyond the ISO C standard are marked.
8050
In the DESCRIPTION, the note about reentrancy is expanded to cover thread-safety.
8051
8052
The APPLICATION USAGE section is updated to include a note on the thread-safe function and
its avoidance of possibly using a static data area.
242
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
8053
8054
NAME
8055
8056
SYNOPSIS
XSI
#include <time.h>
8057
8058
8059
8060
daylight
daylight — daylight savings time flag
extern int daylight;
DESCRIPTION
Refer to tzset( ).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
243
dbm_clearerr( )
System Interfaces
8061
8062
8063
NAME
8064
8065
SYNOPSIS
XSI
#include <ndbm.h>
dbm_clearerr, dbm_close, dbm_delete, dbm_error, dbm_fetch, dbm_firstkey, dbm_nextkey,
dbm_open, dbm_store — database functions
int dbm_clearerr(DBM *db);
void dbm_close(DBM *db);
int dbm_delete(DBM *db, datum key);
int dbm_error(DBM *db);
datum dbm_fetch(DBM *db, datum key);
datum dbm_firstkey(DBM *db);
datum dbm_nextkey(DBM *db);
DBM *dbm_open(const char *file, int open_flags, mode_t file_mode);
int dbm_store(DBM *db, datum key, datum content, int store_mode);
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
DESCRIPTION
These functions create, access, and modify a database.
8078
8079
8080
A datum consists of at least two members, dptr and dsize. The dptr member points to an object
that is dsize bytes in length. Arbitrary binary data, as well as character strings, may be stored in
the object pointed to by dptr.
8081
8082
The database is stored in two files. One file is a directory containing a bitmap of keys and has
.dir as its suffix. The second file contains all data and has .pag as its suffix.
8083
8084
8085
8086
8087
8088
The dbm_open( ) function shall open a database. The file argument to the function is the
pathname of the database. The function opens two files named file.dir and file.pag. The
open_flags argument has the same meaning as the flags argument of open( ) except that a database
opened for write-only access opens the files for read and write access and the behavior of the
O_APPEND flag is unspecified. The file_mode argument has the same meaning as the third
argument of open( ).
8089
8090
The dbm_close( ) function shall close a database. The application shall ensure that argument db is
a pointer to a dbm structure that has been returned from a call to dbm_open( ).
8091
8092
These database functions shall support an internal block size large enough to support
key/content pairs of at least 1 023 bytes.
8093
8094
8095
8096
The dbm_fetch( ) function shall read a record from a database. The argument db is a pointer to a
database structure that has been returned from a call to dbm_open( ). The argument key is a
datum that has been initialized by the application to the value of the key that matches the key of
the record the program is fetching.
8097
8098
8099
8100
8101
8102
8103
8104
8105
The dbm_store( ) function shall write a record to a database. The argument db is a pointer to a
database structure that has been returned from a call to dbm_open( ). The argument key is a
datum that has been initialized by the application to the value of the key that identifies (for
subsequent reading, writing, or deleting) the record the application is writing. The argument
content is a datum that has been initialized by the application to the value of the record the
program is writing. The argument store_mode controls whether dbm_store( ) replaces any preexisting record that has the same key that is specified by the key argument. The application shall
set store_mode to either DBM_INSERT or DBM_REPLACE. If the database contains a record that
matches the key argument and store_mode is DBM_REPLACE, the existing record shall be
replaced with the new record. If the database contains a record that matches the key argument
and store_mode is DBM_INSERT, the existing record shall be left unchanged and the new record
8106
8107
244
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
dbm_clearerr( )
8108
8109
ignored. If the database does not contain a record that matches the key argument and store_mode
is either DBM_INSERT or DBM_REPLACE, the new record shall be inserted in the database.
8110
8111
8112
8113
If the sum of a key/content pair exceeds the internal block size, the result is unspecified.
Moreover, the application shall ensure that all key/content pairs that hash together fit on a
single block. The dbm_store( ) function shall return an error in the event that a disk block fills
with inseparable data.
8114
8115
8116
8117
The dbm_delete( ) function shall delete a record and its key from the database. The argument db is
a pointer to a database structure that has been returned from a call to dbm_open( ). The argument
key is a datum that has been initialized by the application to the value of the key that identifies
the record the program is deleting.
8118
8119
The dbm_firstkey( ) function shall return the first key in the database. The argument db is a
pointer to a database structure that has been returned from a call to dbm_open( ).
8120
8121
8122
8123
8124
The dbm_nextkey( ) function shall return the next key in the database. The argument db is a
pointer to a database structure that has been returned from a call to dbm_open( ). The application
shall ensure that the dbm_firstkey( ) function is called before calling dbm_nextkey( ). Subsequent
calls to dbm_nextkey( ) return the next key until all of the keys in the database have been
returned.
8125
8126
The dbm_error( ) function shall return the error condition of the database. The argument db is a
pointer to a database structure that has been returned from a call to dbm_open( ).
8127
8128
The dbm_clearerr( ) function shall clear the error condition of the database. The argument db is a
pointer to a database structure that has been returned from a call to dbm_open( ).
8129
8130
The dptr pointers returned by these functions may point into static storage that may be changed
by subsequent calls.
8131
8132
These functions need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
8133
8134
8135
RETURN VALUE
The dbm_store( ) and dbm_delete( ) functions shall return 0 when they succeed and a negative
value when they fail.
8136
8137
The dbm_store( ) function shall return 1 if it is called with a flags value of DBM_INSERT and the
function finds an existing record with the same key.
8138
8139
The dbm_error( ) function shall return 0 if the error condition is not set and return a non-zero
value if the error condition is set.
8140
The return value of dbm_clearerr( ) is unspecified.
8141
8142
8143
The dbm_firstkey( ) and dbm_nextkey( ) functions shall return a key datum. When the end of the
database is reached, the dptr member of the key is a null pointer. If an error is detected, the dptr
member of the key shall be a null pointer and the error condition of the database shall be set.
8144
8145
8146
The dbm_fetch( ) function shall return a content datum. If no record in the database matches the
key or if an error condition has been detected in the database, the dptr member of the content
shall be a null pointer.
8147
8148
The dbm_open( ) function shall return a pointer to a database structure. If an error is detected
during the operation, dbm_open( ) shall return a (DBM *)0.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
245
dbm_clearerr( )
System Interfaces
8149
8150
ERRORS
No errors are defined.
8151
8152
EXAMPLES
None.
8153
8154
APPLICATION USAGE
The following code can be used to traverse the database:
8155
for(key = dbm_firstkey(db); key.dptr != NULL; key = dbm_nextkey(db))
8156
8157
8158
8159
8160
8161
8162
8163
The dbm_* functions provided in this library should not be confused in any way with those of a
general-purpose database management system. These functions do not provide for multiple
search keys per entry, they do not protect against multi-user access (in other words they do not
lock records or files), and they do not provide the many other useful database functions that are
found in more robust database management systems. Creating and updating databases by use of
these functions is relatively slow because of data copies that occur upon hash collisions. These
functions are useful for applications requiring fast lookup of relatively static information that is
to be indexed by a single key.
8164
8165
8166
8167
8168
8169
8170
8171
Note that a strictly conforming application is extremely limited by these functions: since there is
no way to determine that the keys in use do not all hash to the same value (although that would
be rare), a strictly conforming application cannot be guaranteed that it can store more than one
block’s worth of data in the database. As long as a key collision does not occur, additional data
may be stored, but because there is no way to determine whether an error is due to a key
collision or some other error condition (dbm_error( ) being effectively a Boolean), once an error is
detected, the application is effectively limited to guessing what the error might be if it wishes to
continue using these functions.
8172
8173
The dbm_delete( ) function need not physically reclaim file space, although it does make it
available for reuse by the database.
8174
8175
8176
After calling dbm_store( ) or dbm_delete( ) during a pass through the keys by dbm_firstkey( ) and
dbm_nextkey( ), the application should reset the database by calling dbm_firstkey( ) before again
calling dbm_nextkey( ). The contents of these files are unspecified and may not be portable.
8177
8178
RATIONALE
None.
8179
8180
FUTURE DIRECTIONS
None.
8181
8182
SEE ALSO
open( ), the Base Definitions volume of IEEE Std 1003.1-2001, <ndbm.h>
8183
8184
CHANGE HISTORY
First released in Issue 4, Version 2.
8185
8186
Issue 5
Moved from X/OPEN UNIX extension to BASE.
8187
8188
Normative text previously in the APPLICATION USAGE section is moved to the
DESCRIPTION.
8189
A note indicating that these functions need not be reentrant is added to the DESCRIPTION.
246
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
8190
8191
dbm_clearerr( )
Issue 6
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
247
difftime( )
System Interfaces
8192
8193
NAME
8194
8195
SYNOPSIS
#include <time.h>
difftime — compute the difference between two calendar time values
double difftime(time_t time1, time_t time0);
8196
8197
8198
8199
8200
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
8201
8202
The difftime ( ) function shall compute the difference between two calendar times (as returned by
time( )): time1− time0.
8203
8204
RETURN VALUE
The difftime ( ) function shall return the difference expressed in seconds as a type double.
8205
8206
ERRORS
No errors are defined.
8207
8208
EXAMPLES
None.
8209
8210
APPLICATION USAGE
None.
8211
8212
RATIONALE
None.
8213
8214
FUTURE DIRECTIONS
None.
8215
8216
8217
SEE ALSO
asctime( ), clock ( ), ctime( ), gmtime( ), localtime ( ), mktime( ), strftime( ), strptime( ), time( ), utime( ),
the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>
8218
8219
CHANGE HISTORY
First released in Issue 4. Derived from the ISO C standard.
248
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
8220
8221
NAME
8222
8223
SYNOPSIS
XSI
#include <libgen.h>
8224
8225
dirname( )
dirname — report the parent directory name of a file pathname
char *dirname(char *path);
8226
8227
8228
8229
DESCRIPTION
The dirname( ) function shall take a pointer to a character string that contains a pathname, and
return a pointer to a string that is a pathname of the parent directory of that file. Trailing ’/’
characters in the path are not counted as part of the path.
8230
8231
If path does not contain a ’/’, then dirname( ) shall return a pointer to the string ".". If path is a
null pointer or points to an empty string, dirname( ) shall return a pointer to the string ".".
8232
8233
The dirname( ) function need not be reentrant. A function that is not required to be reentrant is
not required to be thread-safe.
8234
8235
8236
RETURN VALUE
The dirname( ) function shall return a pointer to a string that is the parent directory of path. If
path is a null pointer or points to an empty string, a pointer to a string "." is returned.
8237
8238
The dirname( ) function may modify the string pointed to by path, and may return a pointer to
static storage that may then be overwritten by subsequent calls to dirname( ).
8239
8240
ERRORS
No errors are defined.
8241
8242
8243
EXAMPLES
The following code fragment reads a pathname, changes the current working directory to the
parent directory, and opens the file.
8244
8245
8246
8247
8248
8249
char path[PATH_MAX], *pathcopy;
int fd;
fgets(path, PATH_MAX, stdin);
pathcopy = strdup(path);
chdir(dirname(pathcopy));
fd = open(basename(path), O_RDONLY);
8250
Sample Input and Output Strings for dirname( )
8251
8252
In the following table, the input string is the value pointed to by path, and the output string is
the return value of the dirname( ) function.
______________________________
L
Input String L Output String L
______________________________
L
L
L
"/usr/lib" L "/usr"
L
L
"/usr/"
"/"
L
L
L
"."
L "usr"
L
L
L
L "/"
L
"/"
L
L
L
"."
"."
L
L
L
".."
"."
L_
_____________________________
L
L
8253
8254
8255
8256
8257
8258
8259
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
249
dirname( )
System Interfaces
8260
Changing the Current Directory to the Parent Directory
8261
8262
The following program fragment reads a pathname, changes the current working directory to
the parent directory, and opens the file.
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
#include <unistd.h>
#include <limits.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <libgen.h>
...
char path[PATH_MAX], *pathcopy;
int fd;
...
fgets(path, PATH_MAX, stdin);
pathcopy = strdup(path);
chdir(dirname(pathcopy));
fd = open(basename(path), O_RDONLY);
8277
8278
8279
APPLICATION USAGE
The dirname( ) and basename( ) functions together yield a complete pathname. The expression
dirname(path) obtains the pathname of the directory where basename(path) is found.
8280
8281
Since the meaning of the leading "//" is implementation-defined, dirname("//foo) may return
either "//" or ’/’ (but nothing else).
8282
8283
RATIONALE
None.
8284
8285
FUTURE DIRECTIONS
None.
8286
8287
SEE ALSO
basename( ), the Base Definitions volume of IEEE Std 1003.1-2001, <libgen.h>
8288
8289
CHANGE HISTORY
First released in Issue 4, Version 2.
8290
8291
Issue 5
Moved from X/OPEN UNIX extension to BASE.
8292
8293
Normative text previously in the APPLICATION USAGE section is moved to the
DESCRIPTION.
8294
A note indicating that this function need not be reentrant is added to the DESCRIPTION.
250
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
div( )
System Interfaces
8295
8296
NAME
8297
8298
SYNOPSIS
#include <stdlib.h>
8299
div — compute the quotient and remainder of an integer division
div_t div(int numer, int denom);
8300
8301
8302
8303
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
8304
8305
8306
8307
The div( ) function shall compute the quotient and remainder of the division of the numerator
numer by the denominator denom. If the division is inexact, the resulting quotient is the integer
of lesser magnitude that is the nearest to the algebraic quotient. If the result cannot be
represented, the behavior is undefined; otherwise, quot*denom+rem shall equal numer.
8308
8309
8310
RETURN VALUE
The div( ) function shall return a structure of type div_t, comprising both the quotient and the
remainder. The structure includes the following members, in any order:
8311
8312
int
int
quot;
rem;
/* quotient */
/* remainder */
8313
8314
ERRORS
No errors are defined.
8315
8316
EXAMPLES
None.
8317
8318
APPLICATION USAGE
None.
8319
8320
RATIONALE
None.
8321
8322
FUTURE DIRECTIONS
None.
8323
8324
SEE ALSO
ldiv( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>
8325
8326
CHANGE HISTORY
First released in Issue 4. Derived from the ISO C standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
251
dlclose( )
System Interfaces
8327
8328
NAME
8329
8330
SYNOPSIS
XSI
#include <dlfcn.h>
dlclose — close a dlopen( ) object
int dlclose(void *handle);
8331
8332
8333
8334
8335
DESCRIPTION
The dlclose( ) function shall inform the system that the object referenced by a handle returned
from a previous dlopen( ) invocation is no longer needed by the application.
8336
8337
8338
8339
8340
The use of dlclose( ) reflects a statement of intent on the part of the process, but does not create
any requirement upon the implementation, such as removal of the code or symbols referenced
by handle. Once an object has been closed using dlclose( ) an application should assume that its
symbols are no longer available to dlsym( ). All objects loaded automatically as a result of
invoking dlopen( ) on the referenced object shall also be closed if this is the last reference to it.
8341
8342
8343
8344
8345
8346
8347
8348
Although a dlclose( ) operation is not required to remove structures from an address space,
neither is an implementation prohibited from doing so. The only restriction on such a removal is
that no object shall be removed to which references have been relocated, until or unless all such
references are removed. For instance, an object that had been loaded with a dlopen( ) operation
specifying the RTLD_GLOBAL flag might provide a target for dynamic relocations performed in
the processing of other objects—in such environments, an application may assume that no
relocation, once made, shall be undone or remade unless the object requiring the relocation has
itself been removed.
8349
8350
8351
8352
RETURN VALUE
If the referenced object was successfully closed, dlclose( ) shall return 0. If the object could not be
closed, or if handle does not refer to an open object, dlclose( ) shall return a non-zero value. More
detailed diagnostic information shall be available through dlerror( ).
8353
8354
ERRORS
No errors are defined.
8355
8356
EXAMPLES
The following example illustrates use of dlopen( ) and dlclose( ):
8357
8358
...
/* Open a dynamic library and then close it ... */
8359
8360
8361
#include <dlfcn.h>
void *mylib;
int eret;
8362
8363
8364
8365
mylib = dlopen("mylib.so", RTLD_LOCAL | RTLD_LAZY);
...
eret = dlclose(mylib);
...
8366
8367
8368
8369
8370
8371
8372
APPLICATION USAGE
A conforming application should employ a handle returned from a dlopen( ) invocation only
within a given scope bracketed by the dlopen( ) and dlclose( ) operations. Implementations are
free to use reference counting or other techniques such that multiple calls to dlopen( ) referencing
the same object may return the same object for handle. Implementations are also free to reuse a
handle. For these reasons, the value of a handle must be treated as an opaque object by the
application, used only in calls to dlsym( ) and dlclose( ).
252
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
dlclose( )
8373
8374
RATIONALE
None.
8375
8376
FUTURE DIRECTIONS
None.
8377
8378
SEE ALSO
dlerror( ), dlopen( ), dlsym( ), the Base Definitions volume of IEEE Std 1003.1-2001, <dlfcn.h>
8379
8380
CHANGE HISTORY
First released in Issue 5.
8381
8382
8383
Issue 6
The DESCRIPTION is updated to say that the referenced object is closed ‘‘if this is the last
reference to it’’.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
253
dlerror( )
System Interfaces
8384
8385
NAME
8386
8387
SYNOPSIS
XSI
#include <dlfcn.h>
dlerror — get diagnostic information
char *dlerror(void);
8388
8389
8390
8391
8392
8393
8394
8395
DESCRIPTION
The dlerror( ) function shall return a null-terminated character string (with no trailing <newline>)
that describes the last error that occurred during dynamic linking processing. If no dynamic
linking errors have occurred since the last invocation of dlerror( ), dlerror( ) shall return NULL.
Thus, invoking dlerror( ) a second time, immediately following a prior invocation, shall result in
NULL being returned.
8396
8397
The dlerror( ) function need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
8398
8399
8400
RETURN VALUE
If successful, dlerror( ) shall return a null-terminated character string; otherwise, NULL shall be
returned.
8401
8402
ERRORS
No errors are defined.
8403
8404
EXAMPLES
The following example prints out the last dynamic linking error:
8405
8406
...
#include <dlfcn.h>
8407
char *errstr;
8408
8409
8410
8411
errstr = dlerror();
if (errstr != NULL)
printf ("A dynamic linking error occurred: (%s)\n", errstr);
...
8412
8413
8414
8415
8416
8417
8418
APPLICATION USAGE
The messages returned by dlerror( ) may reside in a static buffer that is overwritten on each call
to dlerror( ). Application code should not write to this buffer. Programs wishing to preserve an
error message should make their own copies of that message. Depending on the application
environment with respect to asynchronous execution events, such as signals or other
asynchronous computation sharing the address space, conforming applications should use a
critical section to retrieve the error pointer and buffer.
8419
8420
RATIONALE
None.
8421
8422
FUTURE DIRECTIONS
None.
8423
8424
SEE ALSO
dlclose( ), dlopen( ), dlsym( ), the Base Definitions volume of IEEE Std 1003.1-2001, <dlfcn.h>
254
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
8425
8426
CHANGE HISTORY
First released in Issue 5.
8427
8428
Issue 6
dlerror( )
In the DESCRIPTION the note about reentrancy and thread-safety is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
255
dlopen( )
System Interfaces
8429
8430
NAME
8431
8432
SYNOPSIS
XSI
#include <dlfcn.h>
dlopen — gain access to an executable object file
void *dlopen(const char *file, int mode);
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
DESCRIPTION
The dlopen( ) function shall make an executable object file specified by file available to the calling
program. The class of files eligible for this operation and the manner of their construction are
implementation-defined, though typically such files are executable objects such as shared
libraries, relocatable files, or programs. Note that some implementations permit the construction
of dependencies between such objects that are embedded within files. In such cases, a dlopen( )
operation shall load such dependencies in addition to the object referenced by file.
Implementations may also impose specific constraints on the construction of programs that can
employ dlopen( ) and its related services.
8444
8445
A successful dlopen( ) shall return a handle which the caller may use on subsequent calls to
dlsym( ) and dlclose( ). The value of this handle should not be interpreted in any way by the caller.
8446
8447
8448
The file argument is used to construct a pathname to the object file. If file contains a slash
character, the file argument is used as the pathname for the file. Otherwise, file is used in an
implementation-defined manner to yield a pathname.
8449
8450
8451
8452
8453
8454
If the value of file is 0, dlopen( ) shall provide a handle on a global symbol object. This object shall
provide access to the symbols from an ordered set of objects consisting of the original program
image file, together with any objects loaded at program start-up as specified by that process
image file (for example, shared libraries), and the set of objects loaded using a dlopen( ) operation
together with the RTLD_GLOBAL flag. As the latter set of objects can change during execution,
the set identified by handle can also change dynamically.
8455
8456
8457
Only a single copy of an object file is brought into the address space, even if dlopen( ) is invoked
multiple times in reference to the file, and even if different pathnames are used to reference the
file.
8458
8459
8460
8461
8462
8463
The mode parameter describes how dlopen( ) shall operate upon file with respect to the processing
of relocations and the scope of visibility of the symbols provided within file. When an object is
brought into the address space of a process, it may contain references to symbols whose
addresses are not known until the object is loaded. These references shall be relocated before the
symbols can be accessed. The mode parameter governs when these relocations take place and
may have the following values:
8464
8465
8466
8467
8468
8469
8470
8471
RTLD_LAZY
Relocations shall be performed at an implementation-defined time,
ranging from the time of the dlopen( ) call until the first reference to a
given symbol occurs. Specifying RTLD_LAZY should improve
performance on implementations supporting dynamic symbol binding as
a process may not reference all of the functions in any given object. And,
for systems supporting dynamic symbol resolution for normal process
execution, this behavior mimics the normal handling of process
execution.
8472
8473
RTLD_NOW
All necessary relocations shall be performed when the object is first
loaded. This may waste some processing if relocations are performed for
functions that are never referenced. This behavior may be useful for
applications that need to know as soon as an object is loaded that all
8474
8475
256
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
dlopen( )
System Interfaces
8476
symbols referenced during execution are available.
8477
8478
8479
8480
8481
8482
Any object loaded by dlopen( ) that requires relocations against global symbols can reference the
symbols in the original process image file, any objects loaded at program start-up, from the
object itself as well as any other object included in the same dlopen( ) invocation, and any objects
that were loaded in any dlopen( ) invocation and which specified the RTLD_GLOBAL flag. To
determine the scope of visibility for the symbols loaded with a dlopen( ) invocation, the mode
parameter should be a bitwise-inclusive OR with one of the following values:
8483
8484
8485
RTLD_GLOBAL
The object’s symbols shall be made available for the relocation processing
of any other object. In addition, symbol lookup using dlopen(0, mode) and
an associated dlsym( ) allows objects loaded with this mode to be searched.
8486
8487
RTLD_LOCAL
The object’s symbols shall not be made available for the relocation
processing of any other object.
8488
8489
If neither RTLD_GLOBAL nor RTLD_LOCAL are specified, then an implementation-defined
default behavior shall be applied.
8490
8491
8492
8493
8494
8495
If a file is specified in multiple dlopen( ) invocations, mode is interpreted at each invocation. Note,
however, that once RTLD_NOW has been specified all relocations shall have been completed
rendering further RTLD_NOW operations redundant and any further RTLD_LAZY operations
irrelevant. Similarly, note that once RTLD_GLOBAL has been specified the object shall maintain
the RTLD_GLOBAL status regardless of any previous or future specification of RTLD_LOCAL,
as long as the object remains in the address space (see dlclose( )).
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
Symbols introduced into a program through calls to dlopen( ) may be used in relocation
activities. Symbols so introduced may duplicate symbols already defined by the program or
previous dlopen( ) operations. To resolve the ambiguities such a situation might present, the
resolution of a symbol reference to symbol definition is based on a symbol resolution order. Two
such resolution orders are defined: load or dependency ordering. Load order establishes an
ordering among symbol definitions, such that the definition first loaded (including definitions
from the image file and any dependent objects loaded with it) has priority over objects added
later (via dlopen( )). Load ordering is used in relocation processing. Dependency ordering uses a
breadth-first order starting with a given object, then all of its dependencies, then any dependents
of those, iterating until all dependencies are satisfied. With the exception of the global symbol
object obtained via a dlopen( ) operation on a file of 0, dependency ordering is used by the
dlsym( ) function. Load ordering is used in dlsym( ) operations upon the global symbol object.
8508
8509
8510
8511
When an object is first made accessible via dlopen( ) it and its dependent objects are added in
dependency order. Once all the objects are added, relocations are performed using load order.
Note that if an object or its dependencies had been previously loaded, the load and dependency
orders may yield different resolutions.
8512
8513
8514
8515
8516
The symbols introduced by dlopen( ) operations and available through dlsym( ) are at a minimum
those which are exported as symbols of global scope by the object. Typically such symbols shall
be those that were specified in (for example) C source code as having extern linkage. The precise
manner in which an implementation constructs the set of exported symbols for a dlopen( ) object
is specified by that implementation.
8517
8518
8519
8520
RETURN VALUE
If file cannot be found, cannot be opened for reading, is not of an appropriate object format for
processing by dlopen( ), or if an error occurs during the process of loading file or relocating its
symbolic references, dlopen( ) shall return NULL. More detailed diagnostic information shall be
available through dlerror( ).
8521
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
257
dlopen( )
System Interfaces
8522
8523
ERRORS
No errors are defined.
8524
8525
EXAMPLES
None.
8526
8527
APPLICATION USAGE
None.
8528
8529
RATIONALE
None.
8530
8531
FUTURE DIRECTIONS
None.
8532
8533
SEE ALSO
dlclose( ), dlerror( ), dlsym( ), the Base Definitions volume of IEEE Std 1003.1-2001, <dlfcn.h>
8534
8535
CHANGE HISTORY
First released in Issue 5.
258
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
dlsym( )
System Interfaces
8536
8537
NAME
8538
8539
SYNOPSIS
XSI
#include <dlfcn.h>
8540
8541
dlsym — obtain the address of a symbol from a dlopen( ) object
void *dlsym(void *restrict handle, const char *restrict name);
8542
8543
8544
8545
8546
DESCRIPTION
The dlsym( ) function shall obtain the address of a symbol defined within an object made
accessible through a dlopen( ) call. The handle argument is the value returned from a call to
dlopen( ) (and which has not since been released via a call to dlclose( )), and name is the symbol’s
name as a character string.
8547
8548
8549
8550
The dlsym( ) function shall search for the named symbol in all objects loaded automatically as a
result of loading the object referenced by handle (see dlopen( )). Load ordering is used in dlsym( )
operations upon the global symbol object. The symbol resolution algorithm used shall be
dependency order as described in dlopen( ).
8551
The RTLD_DEFAULT and RTLD_NEXT flags are reserved for future use.
8552
8553
8554
8555
RETURN VALUE
If handle does not refer to a valid object opened by dlopen( ), or if the named symbol cannot be
found within any of the objects associated with handle, dlsym( ) shall return NULL. More
detailed diagnostic information shall be available through dlerror( ).
8556
8557
ERRORS
No errors are defined.
8558
8559
8560
EXAMPLES
The following example shows how dlopen( ) and dlsym( ) can be used to access either function or
data objects. For simplicity, error checking has been omitted.
8561
8562
void
int
*handle;
*iptr, (*fptr)(int);
8563
8564
/* open the needed object */
handle = dlopen("/usr/home/me/libfoo.so", RTLD_LOCAL | RTLD_LAZY);
8565
8566
8567
/* find the address of function and data objects */
fptr = (int (*)(int))dlsym(handle, "my_function");
iptr = (int *)dlsym(handle, "my_object");
8568
8569
/* invoke function, passing value of integer as a parameter */
(*fptr)(*iptr);
8570
8571
8572
APPLICATION USAGE
Special purpose values for handle are reserved for future use. These values and their meanings
are:
8573
8574
8575
RTLD_DEFAULT The symbol lookup happens in the normal global scope; that is, a search for a
symbol using this handle would find the same definition as a direct use of this
symbol in the program code.
8576
8577
RTLD_NEXT
8578
8579
8580
Specifies the next object after this one that defines name. This one refers to the
object containing the invocation of dlsym( ). The next object is the one found
upon the application of a load order symbol resolution algorithm (see
dlopen( )). The next object is either one of global scope (because it was
introduced as part of the original process image or because it was added with
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
259
dlsym( )
System Interfaces
8581
8582
a dlopen( ) operation including the RTLD_GLOBAL flag), or is an object that
was included in the same dlopen( ) operation that loaded this one.
8583
8584
8585
8586
8587
8588
The RTLD_NEXT flag is useful to navigate an intentionally created hierarchy
of multiply-defined symbols created through interposition. For example, if a
program wished to create an implementation of malloc ( ) that embedded some
statistics gathering about memory allocations, such an implementation could
use the real malloc ( ) definition to perform the memory allocation—and itself
only embed the necessary logic to implement the statistics gathering function.
8589
8590
RATIONALE
None.
8591
8592
FUTURE DIRECTIONS
None.
8593
8594
SEE ALSO
dlclose( ), dlerror( ), dlopen( ), the Base Definitions volume of IEEE Std 1003.1-2001, <dlfcn.h>
8595
8596
CHANGE HISTORY
First released in Issue 5.
8597
8598
8599
Issue 6
The restrict keyword is added to the dlsym( ) prototype for alignment with the
ISO/IEC 9899: 1999 standard.
The RTLD_DEFAULT and RTLD_NEXT flags are reserved for future use.
8600
260
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
drand48( )
System Interfaces
8601
8602
8603
NAME
8604
8605
SYNOPSIS
XSI
#include <stdlib.h>
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
drand48, erand48, jrand48, lcong48, lrand48, mrand48, nrand48, seed48, srand48 — generate
uniformly distributed pseudo-random numbers
double drand48(void);
double erand48(unsigned short xsubi[3]);
long jrand48(unsigned short xsubi[3]);
void lcong48(unsigned short param[7]);
long lrand48(void);
long mrand48(void);
long nrand48(unsigned short xsubi[3]);
unsigned short *seed48(unsigned short seed16v[3]);
void srand48(long seedval);
8616
8617
8618
DESCRIPTION
This family of functions shall generate pseudo-random numbers using a linear congruential
algorithm and 48-bit integer arithmetic.
8619
8620
The drand48( ) and erand48( ) functions shall return non-negative, double-precision, floatingpoint values, uniformly distributed over the interval [0.0,1.0).
8621
8622
The lrand48( ) and nrand48( ) functions shall return non-negative, long integers, uniformly
31
distributed over the interval [0,2 ).
8623
8624
The mrand48( ) and jrand48( ) functions shall return signed long integers uniformly distributed
31 31
over the interval [−2 ,2 ).
8625
8626
8627
8628
8629
8630
The srand48( ), seed48( ), and lcong48 ( ) functions are initialization entry points, one of which
should be invoked before either drand48( ), lrand48( ), or mrand48( ) is called. (Although it is not
recommended practice, constant default initializer values shall be supplied automatically if
drand48( ), lrand48( ), or mrand48( ) is called without a prior call to an initialization entry point.)
The erand48( ), nrand48( ), and jrand48( ) functions do not require an initialization entry point to
be called first.
8631
8632
All the routines work by generating a sequence of 48-bit integer values, Xi , according to the
linear congruential formula:
8633
8634
8635
Xn +1 = (aXn + c)mod m
n≥ 0
The parameter m = 248 ; hence 48-bit integer arithmetic is performed. Unless lcong48 ( ) is invoked,
the multiplier value a and the addend value c are given by:
8636
a = 5DEECE66D 16 = 273673163155 8
8637
c = B 16 = 13 8
8638
8639
8640
8641
The value returned by any of the drand48( ), erand48( ), jrand48( ), lrand48( ), mrand48( ), or
nrand48( ) functions is computed by first generating the next 48-bit Xi in the sequence. Then the
appropriate number of bits, according to the type of data item to be returned, are copied from
the high-order (leftmost) bits of Xi and transformed into the returned value.
8642
8643
The drand48( ), lrand48( ), and mrand48( ) functions store the last 48-bit Xi generated in an
internal buffer; that is why the application shall ensure that these are initialized prior to being
invoked. The erand48( ), nrand48( ), and jrand48( ) functions require the calling program to
provide storage for the successive Xi values in the array specified as an argument when the
8644
8645
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
261
drand48( )
System Interfaces
8646
8647
8648
8649
8650
8651
functions are invoked. That is why these routines do not have to be initialized; the calling
program merely has to place the desired initial value of Xi into the array and pass it as an
argument. By using different arguments, erand48( ), nrand48( ), and jrand48( ) allow separate
modules of a large program to generate several independent streams of pseudo-random numbers;
that is, the sequence of numbers in each stream shall not depend upon how many times the
routines are called to generate numbers for the other streams.
8652
8653
The initializer function srand48( ) sets the high-order 32 bits of Xi to the low-order 32 bits
contained in its argument. The low-order 16 bits of Xi are set to the arbitrary value 330E16 .
8654
8655
8656
8657
8658
8659
8660
8661
The initializer function seed48( ) sets the value of Xi to the 48-bit value specified in the argument
array. The low-order 16 bits of Xi are set to the low-order 16 bits of seed16v[0]. The mid-order 16
bits of Xi are set to the low-order 16 bits of seed16v[1]. The high-order 16 bits of Xi are set to the
low-order 16 bits of seed16v[2]. In addition, the previous value of Xi is copied into a 48-bit
internal buffer, used only by seed48( ), and a pointer to this buffer is the value returned by
seed48( ). This returned pointer, which can just be ignored if not needed, is useful if a program is
to be restarted from a given point at some future time—use the pointer to get at and store the
last Xi value, and then use this value to reinitialize via seed48( ) when the program is restarted.
8662
8663
8664
8665
8666
The initializer function lcong48 ( ) allows the user to specify the initial Xi , the multiplier value a,
and the addend value c. Argument array elements param[0-2] specify Xi , param[3-5] specify the
multiplier a, and param[6] specifies the 16-bit addend c. After lcong48 ( ) is called, a subsequent
call to either srand48( ) or seed48( ) shall restore the standard multiplier and addend values, a and
c, specified above.
8667
8668
The drand48( ), lrand48( ), and mrand48( ) functions need not be reentrant. A function that is not
required to be reentrant is not required to be thread-safe.
8669
8670
RETURN VALUE
As described in the DESCRIPTION above.
8671
8672
ERRORS
No errors are defined.
8673
8674
EXAMPLES
None.
8675
8676
APPLICATION USAGE
None.
8677
8678
RATIONALE
None.
8679
8680
FUTURE DIRECTIONS
None.
8681
8682
SEE ALSO
rand( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>
8683
8684
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
8685
8686
Issue 5
8687
8688
Issue 6
A note indicating that these functions need not be reentrant is added to the DESCRIPTION.
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
262
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
dup( )
System Interfaces
8689
8690
NAME
8691
8692
SYNOPSIS
#include <unistd.h>
8693
8694
8695
8696
8697
dup, dup2 — duplicate an open file descriptor
int dup(int fildes);
int dup2(int fildes, int fildes2);
DESCRIPTION
The dup( ) and dup2( ) functions provide an alternative interface to the service provided by
fcntl( ) using the F_DUPFD command. The call:
8698
fid = dup(fildes);
8699
shall be equivalent to:
8700
fid = fcntl(fildes, F_DUPFD, 0);
8701
The call:
8702
fid = dup2(fildes, fildes2);
8703
shall be equivalent to:
8704
8705
close(fildes2);
fid = fcntl(fildes, F_DUPFD, fildes2);
8706
except for the following:
8707
8708
•
If fildes2 is less than 0 or greater than or equal to {OPEN_MAX}, dup2( ) shall return −1 with
errno set to [EBADF].
8709
8710
•
If fildes is a valid file descriptor and is equal to fildes2 , dup2( ) shall return fildes2 without
closing it.
8711
•
If fildes is not a valid file descriptor, dup2( ) shall return −1 and shall not close fildes2 .
8712
8713
•
The value returned shall be equal to the value of fildes2 upon successful completion, or −1
upon failure.
8714
8715
8716
RETURN VALUE
Upon successful completion a non-negative integer, namely the file descriptor, shall be returned;
otherwise, −1 shall be returned and errno set to indicate the error.
8717
8718
ERRORS
The dup( ) function shall fail if:
8719
[EBADF]
The fildes argument is not a valid open file descriptor.
8720
8721
[EMFILE]
The number of file descriptors in use by this process would exceed
{OPEN_MAX}.
8722
The dup2( ) function shall fail if:
8723
8724
[EBADF]
The fildes argument is not a valid open file descriptor or the argument fildes2 is
negative or greater than or equal to {OPEN_MAX}.
8725
[EINTR]
The dup2( ) function was interrupted by a signal.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
263
dup( )
8726
System Interfaces
EXAMPLES
8727
Redirecting Standard Output to a File
8728
8729
The following example closes standard output for the current processes, re-assigns standard
output to go to the file referenced by pfd, and closes the original file descriptor to clean up.
8730
8731
8732
8733
8734
8735
8736
8737
#include <unistd.h>
...
int pfd;
...
close(1);
dup(pfd);
close(pfd);
...
8738
Redirecting Error Messages
8739
The following example redirects messages from stderr to stdout.
8740
8741
8742
8743
#include <unistd.h>
...
dup2(1, 2);
...
8744
8745
APPLICATION USAGE
None.
8746
8747
8748
8749
RATIONALE
The dup( ) and dup2( ) functions are redundant. Their services are also provided by the fcntl( )
function. They have been included in this volume of IEEE Std 1003.1-2001 primarily for historical
reasons, since many existing applications use them.
8750
8751
8752
8753
8754
While the brief code segment shown is very similar in behavior to dup2( ), a conforming
implementation based on other functions defined in this volume of IEEE Std 1003.1-2001 is
significantly more complex. Least obvious is the possible effect of a signal-catching function that
could be invoked between steps and allocate or deallocate file descriptors. This could be avoided
by blocking signals.
8755
8756
The dup2( ) function is not marked obsolescent because it presents a type-safe version of
functionality provided in a type-unsafe version by fcntl( ). It is used in the POSIX Ada binding.
8757
The dup2( ) function is not intended for use in critical regions as a synchronization mechanism.
8758
8759
8760
8761
In the description of [EBADF], the case of fildes being out of range is covered by the given case of
fildes not being valid. The descriptions for fildes and fildes2 are different because the only kind of
invalidity that is relevant for fildes2 is whether it is out of range; that is, it does not matter
whether fildes2 refers to an open file when the dup2( ) call is made.
8762
8763
FUTURE DIRECTIONS
None.
8764
8765
SEE ALSO
close( ), fcntl( ), open( ), the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>
264
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
8766
8767
dup( )
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
265
ecvt( )
System Interfaces
8768
8769
NAME
8770
8771
SYNOPSIS
XSI
#include <stdlib.h>
ecvt, fcvt, gcvt — convert a floating-point number to a string (LEGACY)
char *ecvt(double
int *restrict
char *fcvt(double
int *restrict
char *gcvt(double
8772
8773
8774
8775
8776
8777
value, int ndigit, int *restrict decpt,
sign);
value, int ndigit, int *restrict decpt,
sign);
value, int ndigit, char *buf);
8778
8779
8780
DESCRIPTION
The ecvt( ), fcvt( ), and gcvt( ) functions shall convert floating-point numbers to null-terminated
strings.
8781
8782
8783
8784
8785
8786
8787
8788
The ecvt( ) function shall convert value to a null-terminated string of ndigit digits (where ndigit is
reduced to an unspecified limit determined by the precision of a double) and return a pointer to
the string. The high-order digit shall be non-zero, unless the value is 0. The low-order digit shall
be rounded in an implementation-defined manner. The position of the radix character relative to
the beginning of the string shall be stored in the integer pointed to by decpt (negative means to
the left of the returned digits). If value is zero, it is unspecified whether the integer pointed to by
decpt would be 0 or 1. The radix character shall not be included in the returned string. If the sign
of the result is negative, the integer pointed to by sign shall be non-zero; otherwise, it shall be 0.
8789
8790
If the converted value is out of range or is not representable, the contents of the returned string
are unspecified.
8791
8792
8793
The fcvt( ) function shall be equivalent to ecvt( ), except that ndigit specifies the number of digits
desired after the radix character. The total number of digits in the result string is restricted to an
unspecified limit as determined by the precision of a double.
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
The gcvt( ) function shall convert value to a null-terminated string (similar to that of the %g
conversion specification format of printf( )) in the array pointed to by buf and shall return buf. It
shall produce ndigit significant digits (limited to an unspecified value determined by the
precision of a double) in the %f conversion specification format of printf( ) if possible, or the %e
conversion specification format of printf( ) (scientific notation) otherwise. A minus sign shall be
included in the returned string if value is less than 0. A radix character shall be included in the
returned string if value is not a whole number. Trailing zeros shall be suppressed where value is
not a whole number. The radix character is determined by the current locale. If setlocale ( ) has not
been called successfully, the default locale, POSIX, is used. The default locale specifies a period
(’.’) as the radix character. The LC_NUMERIC category determines the value of the radix
character within the current locale.
8805
8806
These functions need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
8807
8808
RETURN VALUE
The ecvt( ) and fcvt( ) functions shall return a pointer to a null-terminated string of digits.
8809
The gcvt( ) function shall return buf.
8810
8811
The return values from ecvt( ) and fcvt( ) may point to static data which may be overwritten by
subsequent calls to these functions.
266
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
8812
8813
ERRORS
No errors are defined.
8814
8815
EXAMPLES
None.
8816
8817
APPLICATION USAGE
The sprintf( ) function is preferred over this function.
8818
8819
RATIONALE
None.
8820
8821
FUTURE DIRECTIONS
These functions may be withdrawn in a future version.
8822
8823
SEE ALSO
printf( ), setlocale ( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>
8824
8825
CHANGE HISTORY
First released in Issue 4, Version 2.
8826
8827
Issue 5
ecvt( )
Moved from X/OPEN UNIX extension to BASE.
8828
8829
Normative text previously in the APPLICATION USAGE section is moved to the
DESCRIPTION.
8830
A note indicating that these functions need not be reentrant is added to the DESCRIPTION.
8831
8832
Issue 6
In the DESCRIPTION, the note about reentrancy is expanded to cover thread-safety.
8833
This function is marked LEGACY.
8834
8835
The restrict keyword is added to the ecvt( ) and fcvt( ) prototypes for alignment with the
ISO/IEC 9899: 1999 standard.
8836
8837
The DESCRIPTION is updated to explicitly use ‘‘conversion specification’’ to describe %g, %f,
and %e.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
267
encrypt( )
System Interfaces
8838
8839
NAME
8840
8841
SYNOPSIS
XSI
#include <unistd.h>
encrypt — encoding function (CRYPT)
void encrypt(char block[64], int edflag);
8842
8843
8844
8845
8846
DESCRIPTION
The encrypt( ) function shall provide access to an implementation-defined encoding algorithm.
The key generated by setkey( ) is used to encrypt the string block with encrypt( ).
8847
8848
8849
8850
8851
The block argument to encrypt( ) shall be an array of length 64 bytes containing only the bytes
with values of 0 and 1. The array is modified in place to a similar array using the key set by
setkey( ). If edflag is 0, the argument is encoded. If edflag is 1, the argument may be decoded (see
the APPLICATION USAGE section); if the argument is not decoded, errno shall be set to
[ENOSYS].
8852
8853
8854
The encrypt( ) function shall not change the setting of errno if successful. An application wishing
to check for error situations should set errno to 0 before calling encrypt( ). If errno is non-zero on
return, an error has occurred.
8855
8856
The encrypt( ) function need not be reentrant. A function that is not required to be reentrant is
not required to be thread-safe.
8857
8858
RETURN VALUE
The encrypt( ) function shall not return a value.
8859
8860
ERRORS
The encrypt( ) function shall fail if:
[ENOSYS]
8861
The functionality is not supported on this implementation.
8862
8863
EXAMPLES
None.
8864
8865
APPLICATION USAGE
Historical implementations of the encrypt( ) function used a rather primitive encoding algorithm.
8866
8867
8868
8869
In some environments, decoding might not be implemented. This is related to some Government
restrictions on encryption and decryption routines. Historical practice has been to ship a
different version of the encryption library without the decryption feature in the routines
supplied. Thus the exported version of encrypt( ) does encoding but not decoding.
8870
8871
RATIONALE
None.
8872
8873
FUTURE DIRECTIONS
None.
8874
8875
SEE ALSO
crypt( ), setkey( ), the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>
8876
8877
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
268
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
8878
8879
Issue 5
8880
8881
Issue 6
encrypt( )
A note indicating that this function need not be reentrant is added to the DESCRIPTION.
In the DESCRIPTION, the note about reentrancy is expanded to cover thread-safety.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
269
endgrent( )
System Interfaces
8882
8883
NAME
8884
8885
SYNOPSIS
XSI
#include <grp.h>
endgrent, getgrent, setgrent — group database entry functions
void endgrent(void);
struct group *getgrent(void);
void setgrent(void);
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
DESCRIPTION
The getgrent( ) function shall return a pointer to a structure containing the broken-out fields of an
entry in the group database. When first called, getgrent( ) shall return a pointer to a group
structure containing the first entry in the group database. Thereafter, it shall return a pointer to a
group structure containing the next group structure in the group database, so successive calls
may be used to search the entire database.
8896
8897
8898
8899
8900
An implementation that provides extended security controls may impose further
implementation-defined restrictions on accessing the group database. In particular, the system
may deny the existence of some or all of the group database entries associated with groups other
than those groups associated with the caller and may omit users other than the caller from the
list of members of groups in database entries that are returned.
8901
The setgrent( ) function shall rewind the group database to allow repeated searches.
8902
The endgrent( ) function may be called to close the group database when processing is complete.
8903
8904
These functions need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
8905
8906
8907
8908
8909
RETURN VALUE
When first called, getgrent( ) shall return a pointer to the first group structure in the group
database. Upon subsequent calls it shall return the next group structure in the group database.
The getgrent( ) function shall return a null pointer on end-of-file or an error and errno may be set
to indicate the error.
8910
8911
The return value may point to a static area which is overwritten by a subsequent call to
getgrgid( ), getgrnam( ), or getgrent( ).
8912
8913
ERRORS
The getgrent( ) function may fail if:
8914
[EINTR]
A signal was caught during the operation.
8915
[EIO]
An I/O error has occurred.
8916
[EMFILE]
{OPEN_MAX} file descriptors are currently open in the calling process.
8917
[ENFILE]
The maximum allowable number of files is currently open in the system.
270
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
endgrent( )
System Interfaces
8918
8919
EXAMPLES
None.
8920
8921
8922
8923
8924
APPLICATION USAGE
These functions are provided due to their historical usage. Applications should avoid
dependencies on fields in the group database, whether the database is a single file, or where in
the file system name space the database resides. Applications should use getgrnam( ) and
getgrgid( ) whenever possible because it avoids these dependencies.
8925
8926
RATIONALE
None.
8927
8928
FUTURE DIRECTIONS
None.
8929
8930
8931
SEE ALSO
getgrgid( ), getgrnam( ), getlogin ( ),
IEEE Std 1003.1-2001, <grp.h>
8932
8933
CHANGE HISTORY
First released in Issue 4, Version 2.
8934
8935
Issue 5
getpwent( ),
the
Base
Definitions
volume
of
Moved from X/OPEN UNIX extension to BASE.
8936
8937
Normative text previously in the APPLICATION USAGE section is moved to the RETURN
VALUE section.
8938
A note indicating that these functions need not be reentrant is added to the DESCRIPTION.
8939
8940
Issue 6
In the DESCRIPTION, the note about reentrancy is expanded to cover thread-safety.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
271
endhostent( )
System Interfaces
8941
8942
NAME
8943
8944
SYNOPSIS
#include <netdb.h>
endhostent, gethostent, sethostent — network host database functions
void endhostent(void);
struct hostent *gethostent(void);
void sethostent(int stayopen);
8945
8946
8947
8948
8949
8950
8951
DESCRIPTION
These functions shall retrieve information about hosts. This information is considered to be
stored in a database that can be accessed sequentially or randomly. The implementation of this
database is unspecified.
In many cases this database is implemented by the Domain Name System, as documented in
RFC 1034, RFC 1035, and RFC 1886.
8952
8953
Note:
8954
8955
8956
8957
The sethostent( ) function shall open a connection to the database and set the next entry for
retrieval to the first entry in the database. If the stayopen argument is non-zero, the connection
shall not be closed by a call to gethostent( ), gethostbyname( ), or gethostbyaddr( ), and the
implementation may maintain an open file descriptor.
8958
8959
The gethostent( ) function shall read the next entry in the database, opening and closing a
connection to the database as necessary.
8960
8961
Entries shall be returned in hostent structures. Refer to gethostbyaddr( ) for a definition of the
hostent structure.
8962
8963
The endhostent( ) function shall close the connection to the database, releasing any open file
descriptor.
8964
8965
These functions need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
8966
8967
8968
8969
RETURN VALUE
Upon successful completion, the gethostent( ) function shall return a pointer to a hostent
structure if the requested entry was found, and a null pointer if the end of the database was
reached or the requested entry was not found.
8970
8971
ERRORS
No errors are defined for endhostent( ), gethostent( ), and sethostent( ).
8972
8973
EXAMPLES
None.
8974
8975
8976
APPLICATION USAGE
The gethostent( ) function may return pointers to static data, which may be overwritten by
subsequent calls to any of these functions.
8977
8978
RATIONALE
None.
8979
8980
FUTURE DIRECTIONS
None.
8981
8982
SEE ALSO
endservent( ), gethostbyaddr( ), the Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>
272
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
8983
8984
endhostent( )
CHANGE HISTORY
First released in Issue 6. Derived from the XNS, Issue 5.2 specification.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
273
endnetent( )
System Interfaces
8985
8986
NAME
8987
8988
SYNOPSIS
#include <netdb.h>
endnetent, getnetbyaddr, getnetbyname, getnetent, setnetent — network database functions
void endnetent(void);
struct netent *getnetbyaddr(uint32_t net, int type);
struct netent *getnetbyname(const char *name);
struct netent *getnetent(void);
void setnetent(int stayopen);
8989
8990
8991
8992
8993
8994
8995
8996
8997
DESCRIPTION
These functions shall retrieve information about networks. This information is considered to be
stored in a database that can be accessed sequentially or randomly. The implementation of this
database is unspecified.
8998
8999
9000
9001
The setnetent( ) function shall open and rewind the database. If the stayopen argument is nonzero, the connection to the net database shall not be closed after each call to getnetent( ) (either
directly, or indirectly through one of the other getnet*( ) functions), and the implementation may
maintain an open file descriptor to the database.
9002
9003
The getnetent( ) function shall read the next entry of the database, opening and closing a
connection to the database as necessary.
9004
9005
9006
9007
The getnetbyaddr( ) function shall search the database from the beginning, and find the first entry
for which the address family specified by type matches the n_addrtype member and the network
number net matches the n_net member, opening and closing a connection to the database as
necessary. The net argument shall be the network number in host byte order.
9008
9009
9010
The getnetbyname( ) function shall search the database from the beginning and find the first entry
for which the network name specified by name matches the n_name member, opening and
closing a connection to the database as necessary.
9011
9012
9013
The getnetbyaddr( ), getnetbyname( ), and getnetent( ) functions shall each return a pointer to a
netent structure, the members of which shall contain the fields of an entry in the network
database.
9014
The endnetent( ) function shall close the database, releasing any open file descriptor.
9015
9016
These functions need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
9017
9018
9019
9020
9021
RETURN VALUE
Upon successful completion, getnetbyaddr( ), getnetbyname( ), and getnetent( ) shall return a
pointer to a netent structure if the requested entry was found, and a null pointer if the end of the
database was reached or the requested entry was not found. Otherwise, a null pointer shall be
returned.
9022
9023
ERRORS
No errors are defined.
274
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
endnetent( )
9024
9025
EXAMPLES
None.
9026
9027
9028
APPLICATION USAGE
The getnetbyaddr( ), getnetbyname( ), and getnetent( ) functions may return pointers to static data,
which may be overwritten by subsequent calls to any of these functions.
9029
9030
RATIONALE
None.
9031
9032
FUTURE DIRECTIONS
None.
9033
9034
SEE ALSO
The Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>
9035
9036
CHANGE HISTORY
First released in Issue 6. Derived from the XNS, Issue 5.2 specification.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
275
endprotoent( )
System Interfaces
9037
9038
9039
NAME
9040
9041
SYNOPSIS
#include <netdb.h>
endprotoent, getprotobyname, getprotobynumber, getprotoent, setprotoent — network protocol
database functions
void endprotoent(void);
struct protoent *getprotobyname(const char *name);
struct protoent *getprotobynumber(int proto);
struct protoent *getprotoent(void);
void setprotoent(int stayopen);
9042
9043
9044
9045
9046
9047
9048
9049
9050
DESCRIPTION
These functions shall retrieve information about protocols. This information is considered to be
stored in a database that can be accessed sequentially or randomly. The implementation of this
database is unspecified.
9051
9052
9053
9054
9055
The setprotoent( ) function shall open a connection to the database, and set the next entry to the
first entry. If the stayopen argument is non-zero, the connection to the network protocol database
shall not be closed after each call to getprotoent( ) (either directly, or indirectly through one of the
other getproto*( ) functions), and the implementation may maintain an open file descriptor for
the database.
9056
9057
9058
The getprotobyname( ) function shall search the database from the beginning and find the first
entry for which the protocol name specified by name matches the p_name member, opening and
closing a connection to the database as necessary.
9059
9060
9061
The getprotobynumber( ) function shall search the database from the beginning and find the first
entry for which the protocol number specified by proto matches the p_proto member, opening
and closing a connection to the database as necessary.
9062
9063
The getprotoent( ) function shall read the next entry of the database, opening and closing a
connection to the database as necessary.
9064
9065
9066
The getprotobyname( ), getprotobynumber( ), and getprotoent( ) functions shall each return a pointer
to a protoent structure, the members of which shall contain the fields of an entry in the network
protocol database.
9067
9068
The endprotoent( ) function shall close the connection to the database, releasing any open file
descriptor.
9069
9070
These functions need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
9071
9072
9073
9074
9075
RETURN VALUE
Upon successful completion, getprotobyname( ), getprotobynumber( ), and getprotoent( ) return a
pointer to a protoent structure if the requested entry was found, and a null pointer if the end of
the database was reached or the requested entry was not found. Otherwise, a null pointer is
returned.
9076
9077
ERRORS
No errors are defined.
276
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
endprotoent( )
9078
9079
EXAMPLES
None.
9080
9081
9082
APPLICATION USAGE
The getprotobyname( ), getprotobynumber( ), and getprotoent( ) functions may return pointers to
static data, which may be overwritten by subsequent calls to any of these functions.
9083
9084
RATIONALE
None.
9085
9086
FUTURE DIRECTIONS
None.
9087
9088
SEE ALSO
The Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>
9089
9090
CHANGE HISTORY
First released in Issue 6. Derived from the XNS, Issue 5.2 specification.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
277
endpwent( )
System Interfaces
9091
9092
NAME
9093
9094
SYNOPSIS
XSI
#include <pwd.h>
endpwent, getpwent, setpwent — user database functions
void endpwent(void);
struct passwd *getpwent(void);
void setpwent(void);
9095
9096
9097
9098
9099
9100
DESCRIPTION
These functions shall retrieve information about users.
9101
9102
9103
9104
9105
The getpwent( ) function shall return a pointer to a structure containing the broken-out fields of
an entry in the user database. Each entry in the user database contains a passwd structure. When
first called, getpwent( ) shall return a pointer to a passwd structure containing the first entry in
the user database. Thereafter, it shall return a pointer to a passwd structure containing the next
entry in the user database. Successive calls can be used to search the entire user database.
9106
If an end-of-file or an error is encountered on reading, getpwent( ) shall return a null pointer.
9107
9108
9109
9110
An implementation that provides extended security controls may impose further
implementation-defined restrictions on accessing the user database. In particular, the system
may deny the existence of some or all of the user database entries associated with users other
than the caller.
9111
The setpwent( ) function effectively rewinds the user database to allow repeated searches.
9112
The endpwent( ) function may be called to close the user database when processing is complete.
9113
9114
These functions need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
9115
9116
RETURN VALUE
The getpwent( ) function shall return a null pointer on end-of-file or error.
9117
9118
ERRORS
The getpwent( ), setpwent( ), and endpwent( ) functions may fail if:
9119
[EIO]
9120
In addition, getpwent( ) and setpwent( ) may fail if:
9121
[EMFILE]
{OPEN_MAX} file descriptors are currently open in the calling process.
9122
[ENFILE]
The maximum allowable number of files is currently open in the system.
9123
9124
The return value may point to a static area which is overwritten by a subsequent call to
getpwuid( ), getpwnam( ), or getpwent( ).
278
An I/O error has occurred.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
endpwent( )
System Interfaces
9125
EXAMPLES
9126
Searching the User Database
9127
9128
9129
The following example uses the getpwent( ) function to get successive entries in the user
database, returning a pointer to a passwd structure that contains information about each user.
The call to endpwent( ) closes the user database and cleans up.
9130
9131
9132
9133
9134
9135
9136
#include <pwd.h>
...
struct passwd *p;
...
while ((p = getpwent ()) != NULL) {
...
}
9137
9138
endpwent();
...
9139
9140
9141
9142
9143
APPLICATION USAGE
These functions are provided due to their historical usage. Applications should avoid
dependencies on fields in the password database, whether the database is a single file, or where
in the file system name space the database resides. Applications should use getpwuid( )
whenever possible because it avoids these dependencies.
9144
9145
RATIONALE
None.
9146
9147
FUTURE DIRECTIONS
None.
9148
9149
9150
SEE ALSO
endgrent( ), getlogin ( ), getpwnam( ),
IEEE Std 1003.1-2001, <pwd.h>
9151
9152
CHANGE HISTORY
First released in Issue 4, Version 2.
9153
9154
Issue 5
getpwuid( ),
the
Base
Definitions
volume
of
Moved from X/OPEN UNIX extension to BASE.
9155
9156
Normative text previously in the APPLICATION USAGE section is moved to the RETURN
VALUE section.
9157
A note indicating that these functions need not be reentrant is added to the DESCRIPTION.
9158
9159
Issue 6
In the DESCRIPTION, the note about reentrancy is expanded to cover thread-safety.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
279
endservent( )
System Interfaces
9160
9161
9162
NAME
9163
9164
SYNOPSIS
#include <netdb.h>
endservent, getservbyname, getservbyport, getservent, setservent — network services database
functions
void endservent(void);
struct servent *getservbyname(const char *name, const char *proto);
struct servent *getservbyport(int port, const char *proto);
struct servent *getservent(void);
void setservent(int stayopen);
9165
9166
9167
9168
9169
9170
9171
9172
9173
DESCRIPTION
These functions shall retrieve information about network services. This information is
considered to be stored in a database that can be accessed sequentially or randomly. The
implementation of this database is unspecified.
9174
9175
9176
9177
The setservent( ) function shall open a connection to the database, and set the next entry to the
first entry. If the stayopen argument is non-zero, the net database shall not be closed after each
call to the getservent( ) function (either directly, or indirectly through one of the other getserv*( )
functions), and the implementation may maintain an open file descriptor for the database.
9178
9179
The getservent( ) function shall read the next entry of the database, opening and closing a
connection to the database as necessary.
9180
9181
9182
9183
9184
The getservbyname( ) function shall search the database from the beginning and find the first
entry for which the service name specified by name matches the s_name member and the protocol
name specified by proto matches the s_proto member, opening and closing a connection to the
database as necessary. If proto is a null pointer, any value of the s_proto member shall be
matched.
9185
9186
9187
9188
9189
The getservbyport( ) function shall search the database from the beginning and find the first entry
for which the port specified by port matches the s_port member and the protocol name specified
by proto matches the s_proto member, opening and closing a connection to the database as
necessary. If proto is a null pointer, any value of the s_proto member shall be matched. The port
argument shall be in network byte order.
9190
9191
9192
The getservbyname( ), getservbyport( ), and getservent( ) functions shall each return a pointer to a
servent structure, the members of which shall contain the fields of an entry in the network
services database.
9193
The endservent( ) function shall close the database, releasing any open file descriptor.
9194
9195
These functions need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
9196
9197
9198
9199
RETURN VALUE
Upon successful completion, getservbyname( ), getservbyport( ), and getservent( ) return a pointer to
a servent structure if the requested entry was found, and a null pointer if the end of the database
was reached or the requested entry was not found. Otherwise, a null pointer is returned.
9200
9201
ERRORS
No errors are defined.
280
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
endservent( )
System Interfaces
9202
9203
EXAMPLES
None.
9204
9205
9206
APPLICATION USAGE
The port argument of getservbyport( ) need not be compatible with the port values of all address
families.
9207
9208
The getservbyname( ), getservbyport( ), and getservent( ) functions may return pointers to static
data, which may be overwritten by subsequent calls to any of these functions.
9209
9210
RATIONALE
None.
9211
9212
FUTURE DIRECTIONS
None.
9213
9214
9215
SEE ALSO
endhostent( ), endprotoent( ), htonl( ),
IEEE Std 1003.1-2001, <netdb.h>
9216
9217
CHANGE HISTORY
First released in Issue 6. Derived from the XNS, Issue 5.2 specification.
inet_addr( ),
the
Base
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Definitions
volume
of
281
endutxent( )
System Interfaces
9218
9219
9220
NAME
9221
9222
SYNOPSIS
XSI
#include <utmpx.h>
endutxent, getutxent, getutxid, getutxline, pututxline, setutxent — user accounting database
functions
void endutxent(void);
struct utmpx *getutxent(void);
struct utmpx *getutxid(const struct utmpx *id);
struct utmpx *getutxline(const struct utmpx *line);
struct utmpx *pututxline(const struct utmpx *utmpx);
void setutxent(void);
9223
9224
9225
9226
9227
9228
9229
9230
9231
DESCRIPTION
These functions shall provide access to the user accounting database.
9232
9233
The getutxent( ) function shall read the next entry from the user accounting database. If the
database is not already open, it shall open it. If it reaches the end of the database, it shall fail.
9234
9235
9236
9237
9238
9239
9240
The getutxid( ) function shall search forward from the current point in the database. If the
ut_type value of the utmpx structure pointed to by id is BOOT_TIME, OLD_TIME, or
NEW_TIME, then it shall stop when it finds an entry with a matching ut_type value. If the
ut_type value is INIT_PROCESS, LOGIN_PROCESS, USER_PROCESS, or DEAD_PROCESS,
then it shall stop when it finds an entry whose type is one of these four and whose ut_id member
matches the ut_id member of the utmpx structure pointed to by id. If the end of the database is
reached without a match, getutxid( ) shall fail.
9241
9242
9243
9244
The getutxline( ) function shall search forward from the current point in the database until it
finds an entry of the type LOGIN_PROCESS or USER_PROCESS which also has a ut_line value
matching that in the utmpx structure pointed to by line. If the end of the database is reached
without a match, getutxline( ) shall fail.
9245
9246
9247
The getutxid( ) or getutxline( ) function may cache data. For this reason, to use getutxline( ) to
search for multiple occurrences, the application shall zero out the static data after each success,
or getutxline( ) may return a pointer to the same utmpx structure.
9248
9249
9250
9251
9252
There is one exception to the rule about clearing the structure before further reads are done. The
implicit read done by pututxline( ) (if it finds that it is not already at the correct place in the user
accounting database) shall not modify the static structure returned by getutxent( ), getutxid( ), or
getutxline( ), if the application has modified this structure and passed the pointer back to
pututxline( ).
9253
9254
9255
For all entries that match a request, the ut_type member indicates the type of the entry. Other
members of the entry shall contain meaningful data based on the value of the ut_type member as
follows:
282
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
endutxent( )
System Interfaces
9266
_________________________________________________________________________
L
ut_type Member L
Other Members with Meaningful Data
_L ________________________________________________________________________
L
L
L
EMPTY
No others
L
L
L
BOOT_TIME
ut_tv
L
L
L
ut_tv
L OLD_TIME
L
L
L NEW_TIME
L
L
ut_tv
L
L
USER_PROCESS
ut_id, ut_user (login name of the user), ut_line, ut_pid, ut_tv L
L
L
L
INIT_PROCESS
ut_id, ut_pid, ut_tv
L
L
L
LOGIN_PROCESS L ut_id, ut_user (implementation-defined name of the login L
L
process), ut_pid, ut_tv
L
L
L
L
L
L
DEAD_PROCESS
ut_id,
ut_pid,
ut_tv
________________________________________________________________________
L
L
L_
9267
9268
9269
9270
An implementation that provides extended security controls may impose implementationdefined restrictions on accessing the user accounting database. In particular, the system may
deny the existence of some or all of the user accounting database entries associated with users
other than the caller.
9271
9272
9273
9274
If the process has appropriate privileges, the pututxline( ) function shall write out the structure
into the user accounting database. It shall use getutxid( ) to search for a record that satisfies the
request. If this search succeeds, then the entry shall be replaced. Otherwise, a new entry shall be
made at the end of the user accounting database.
9275
The endutxent( ) function shall close the user accounting database.
9276
9277
The setutxent( ) function shall reset the input to the beginning of the database. This should be
done before each search for a new entry if it is desired that the entire database be examined.
9278
9279
These functions need not be reentrant. A function that is not required to be reentrant is not
required to be thread-safe.
9280
9281
9282
9283
RETURN VALUE
Upon successful completion, getutxent( ), getutxid( ), and getutxline( ) shall return a pointer to a
utmpx structure containing a copy of the requested entry in the user accounting database.
Otherwise, a null pointer shall be returned.
9284
9285
The return value may point to a static area which is overwritten by a subsequent call to
getutxid( ) or getutxline( ).
9286
9287
9288
Upon successful completion, pututxline( ) shall return a pointer to a utmpx structure containing a
copy of the entry added to the user accounting database. Otherwise, a null pointer shall be
returned.
9289
The endutxent( ) and setutxent( ) functions shall not return a value.
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9290
9291
9292
ERRORS
No errors are defined for the endutxent( ), getutxent( ), getutxid( ), getutxline( ), and setutxent( )
functions.
9293
The pututxline( ) function may fail if:
9294
[EPERM]
The process does not have appropriate privileges.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
283
endutxent( )
System Interfaces
9295
9296
EXAMPLES
None.
9297
9298
APPLICATION USAGE
The sizes of the arrays in the structure can be found using the sizeof operator.
9299
9300
RATIONALE
None.
9301
9302
FUTURE DIRECTIONS
None.
9303
9304
SEE ALSO
The Base Definitions volume of IEEE Std 1003.1-2001, <utmpx.h>
9305
9306
CHANGE HISTORY
First released in Issue 4, Version 2.
9307
9308
Issue 5
Moved from X/OPEN UNIX extension to BASE.
9309
9310
Normative text previously in the APPLICATION USAGE section is moved to the
DESCRIPTION.
9311
A note indicating that these functions need not be reentrant is added to the DESCRIPTION.
9312
9313
Issue 6
In the DESCRIPTION, the note about reentrancy is expanded to cover thread-safety.
284
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
environ
9314
9315
NAME
9316
9317
SYNOPSIS
extern char **environ;
9318
9319
9320
DESCRIPTION
Refer to the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables
and exec.
environ — array of character pointers to the environment strings
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
285
erand48( )
System Interfaces
9321
9322
NAME
9323
9324
SYNOPSIS
XSI
#include <stdlib.h>
erand48 — generate uniformly distributed pseudo-random numbers
double erand48(unsigned short xsubi[3]);
9325
9326
9327
9328
DESCRIPTION
Refer to drand48( ).
286
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
erf( )
System Interfaces
9329
9330
NAME
9331
9332
SYNOPSIS
#include <math.h>
erf, erff, erfl — error functions
double erf(double x);
float erff(float x);
long double erfl(long double x);
9333
9334
9335
9336
9337
9338
9339
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the error function of their argument x, defined as:
9340
x
_2__ e −t dt
∫
√MMπ 0
2
9341
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
9342
9343
9344
9345
9346
9347
RETURN VALUE
Upon successful completion, these functions shall return the value of the error function.
9348
MX
If x is NaN, a NaN shall be returned.
9349
If x is ±0, ±0 shall be returned.
9350
If x is ±Inf, ±1 shall be returned.
9351
If x is subnormal, a range error may occur, and 2 * x/sqrt(π) should be returned.
9352
9353
ERRORS
These functions may fail if:
9354
MX
Range Error
The result underflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
9355
9356
9357
9358
9359
9360
EXAMPLES
None.
9361
9362
APPLICATION USAGE
Underflow occurs when |x| < DBL_MIN * (sqrt(π)/2).
9363
9364
9365
9366
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
RATIONALE
None.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
287
erf( )
System Interfaces
9367
9368
FUTURE DIRECTIONS
None.
9369
9370
9371
SEE ALSO
erfc( ), feclearexcept( ), fetestexcept( ), isnan( ), the Base Definitions volume of IEEE Std 1003.1-2001,
Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
9372
9373
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
9374
9375
9376
Issue 5
9377
9378
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The erf( ) function is no longer marked as an extension.
9379
The erfc( ) function is now split out onto its own reference page.
9380
The erff( ) and erfl( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
9381
9382
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
9383
9384
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
288
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
erfc( )
System Interfaces
9385
9386
NAME
9387
9388
SYNOPSIS
#include <math.h>
erfc, erfcf, erfcl — complementary error functions
double erfc(double x);
float erfcf(float x);
long double erfcl(long double x);
9389
9390
9391
9392
9393
9394
9395
DESCRIPTION
CX
The functionality described on this reference page is aligned with the ISO C standard. Any
conflict between the requirements described here and the ISO C standard is unintentional. This
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
9396
These functions shall compute the complementary error function 1.0 − erf(x).
9397
9398
9399
9400
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
9401
9402
9403
RETURN VALUE
Upon successful completion, these functions shall return the value of the complementary error
function.
9404
9405
MX
If the correct value would cause underflow and is not representable, a range error may occur
and either 0.0 (if representable), oran implementation-defined value shall be returned.
9406
MX
If x is NaN, a NaN shall be returned.
9407
If x is ±0, +1 shall be returned.
9408
If x is −Inf, +2 shall be returned.
9409
If x is +Inf, +0 shall be returned.
9410
9411
If the correct value would cause underflow and is representable, a range error may occur and the
correct value shall be returned.
9412
9413
9414
ERRORS
These functions may fail if:
Range Error
The result underflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
9415
9416
9417
9418
9419
9420
EXAMPLES
None.
9421
9422
9423
APPLICATION USAGE
The erfc( ) function is provided because of the extreme loss of relative accuracy if erf(x) is called
for large x and the result subtracted from 1.0.
9424
Note for IEEE Std 754-1985 double, 26.55 < x implies erfc(x) has underflowed.
9425
9426
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
289
erfc( )
System Interfaces
9427
9428
RATIONALE
None.
9429
9430
FUTURE DIRECTIONS
None.
9431
9432
9433
SEE ALSO
erf( ), feclearexcept( ), fetestexcept( ), isnan( ), the Base Definitions volume of IEEE Std 1003.1-2001,
Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
9434
9435
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
9436
9437
9438
Issue 5
9439
9440
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The erfc( ) function is no longer marked as an extension.
9441
These functions are split out from the erf( ) reference page.
9442
9443
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
9444
9445
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
290
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
9446
9447
NAME
9448
9449
SYNOPSIS
#include <math.h>
9450
9451
9452
9453
erff( )
erff, erfl — error functions
float erff(float x);
long double erfl(long double x);
DESCRIPTION
Refer to erf( ).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
291
errno
System Interfaces
9454
9455
NAME
9456
9457
SYNOPSIS
#include <errno.h>
9458
9459
DESCRIPTION
The lvalue errno is used by many functions to return error values.
errno — error return value
9460
9461
9462
9463
9464
9465
Many functions provide an error number in errno, which has type int and is defined in
<errno.h>. The value of errno shall be defined only after a call to a function for which it is
explicitly stated to be set and until it is changed by the next function call or if the application
assigns it a value. The value of errno should only be examined when it is indicated to be valid by
a function’s return value. Applications shall obtain the definition of errno by the inclusion of
<errno.h>. No function in this volume of IEEE Std 1003.1-2001 shall set errno to 0.
9466
9467
9468
It is unspecified whether errno is a macro or an identifier declared with external linkage. If a
macro definition is suppressed in order to access an actual object, or a program defines an
identifier with the name errno, the behavior is undefined.
9469
9470
The symbolic values stored in errno are documented in the ERRORS sections on all relevant
pages.
9471
9472
RETURN VALUE
None.
9473
9474
ERRORS
None.
9475
9476
EXAMPLES
None.
9477
9478
9479
9480
APPLICATION USAGE
Previously both POSIX and X/Open documents were more restrictive than the ISO C standard
in that they required errno to be defined as an external variable, whereas the ISO C standard
required only that errno be defined as a modifiable lvalue with type int.
9481
9482
An application that needs to examine the value of errno to determine the error should set it to 0
before a function call, then inspect it before a subsequent function call.
9483
9484
RATIONALE
None.
9485
9486
FUTURE DIRECTIONS
None.
9487
9488
SEE ALSO
Section 2.3, the Base Definitions volume of IEEE Std 1003.1-2001, <errno.h>
9489
9490
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
9491
9492
9493
9494
Issue 5
The following sentence is deleted from the DESCRIPTION: ‘‘The value of errno is 0 at program
start-up, but is never set to 0 by any XSI function’’. The DESCRIPTION also no longer states that
conforming implementations may support the declaration:
extern int errno;
9495
292
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
9496
9497
errno
Issue 6
Obsolescent text regarding defining errno as:
9498
extern int errno
9499
is removed.
9500
9501
Text regarding no function setting errno to zero to indicate an error is changed to no function
shall set errno to zero. This is for alignment with the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
293
exec
System Interfaces
9502
9503
NAME
9504
9505
SYNOPSIS
#include <unistd.h>
environ, execl, execv, execle, execve, execlp, execvp — execute a file
extern char **environ;
int execl(const char *path, const char *arg0, ... /*, (char *)0 */);
int execv(const char *path, char *const argv[]);
int execle(const char *path, const char *arg0, ... /*,
(char *)0, char *const envp[]*/);
int execve(const char *path, char *const argv[], char *const envp[]);
int execlp(const char *file, const char *arg0, ... /*, (char *)0 */);
int execvp(const char *file, char *const argv[]);
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
DESCRIPTION
The exec family of functions shall replace the current process image with a new process image.
The new image shall be constructed from a regular, executable file called the new process image
file. There shall be no return from a successful exec, because the calling process image is overlaid
by the new process image.
9519
9520
When a C-language program is executed as a result of this call, it shall be entered as a Clanguage function call as follows:
9521
int main (int argc, char *argv[]);
9522
9523
where argc is the argument count and argv is an array of character pointers to the arguments
themselves. In addition, the following variable:
9524
extern char **environ;
9525
9526
9527
is initialized as a pointer to an array of character pointers to the environment strings. The argv
and environ arrays are each terminated by a null pointer. The null pointer terminating the argv
array is not counted in argc.
9528
9529
9530
9531
THR
Conforming multi-threaded applications shall not use the environ variable to access or modify
any environment variable while any other thread is concurrently modifying any environment
variable. A call to any function dependent on any environment variable shall be considered a use
of the environ variable to access that environment variable.
9532
9533
The arguments specified by a program with one of the exec functions shall be passed on to the
new process image in the corresponding main( ) arguments.
9534
The argument path points to a pathname that identifies the new process image file.
9535
9536
9537
9538
9539
9540
The argument file is used to construct a pathname that identifies the new process image file. If
the file argument contains a slash character, the file argument shall be used as the pathname for
this file. Otherwise, the path prefix for this file is obtained by a search of the directories passed
as the environment variable PATH (see the Base Definitions volume of IEEE Std 1003.1-2001,
Chapter 8, Environment Variables). If this environment variable is not present, the results of the
search are implementation-defined.
9541
9542
9543
9544
There are two distinct ways in which the contents of the process image file may cause the
execution to fail, distinguished by the setting of errno to either [ENOEXEC] or [EINVAL] (see the
ERRORS section). In the cases where the other members of the exec family of functions would
fail and set errno to [ENOEXEC], the execlp( ) and execvp( ) functions shall execute a command
interpreter and the environment of the executed command shall be as if the process invoked the
sh utility using execl( ) as follows:
9545
9546
294
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
exec
9547
execl(<shell path>, arg0, file, arg1, ..., (char *)0);
9548
9549
9550
where <shell path> is an unspecified pathname for the sh utility, file is the process image file, and
for execvp( ), where arg0, arg1, and so on correspond to the values passed to execvp( ) in argv[0],
argv[1], and so on.
9551
9552
9553
9554
The arguments represented by arg0, . . . are pointers to null-terminated character strings. These
strings shall constitute the argument list available to the new process image. The list is
terminated by a null pointer. The argument arg0 should point to a filename that is associated
with the process being started by one of the exec functions.
9555
9556
9557
9558
The argument argv is an array of character pointers to null-terminated strings. The application
shall ensure that the last member of this array is a null pointer. These strings shall constitute the
argument list available to the new process image. The value in argv[0] should point to a filename
that is associated with the process being started by one of the exec functions.
9559
9560
9561
The argument envp is an array of character pointers to null-terminated strings. These strings
shall constitute the environment for the new process image. The envp array is terminated by a
null pointer.
9562
9563
9564
For those forms not containing an envp pointer (execl( ), execv( ), execlp( ), and execvp( )), the
environment for the new process image shall be taken from the external variable environ in the
calling process.
9565
9566
9567
The number of bytes available for the new process’ combined argument and environment lists is
{ARG_MAX}. It is implementation-defined whether null terminators, pointers, and/or any
alignment bytes are included in this total.
9568
9569
9570
9571
9572
File descriptors open in the calling process image shall remain open in the new process image,
except for those whose close-on-exec flag FD_CLOEXEC is set. For those file descriptors that
remain open, all attributes of the open file description remain unchanged. For any file descriptor
that is closed for this reason, file locks are removed as a result of the close as described in close( ).
Locks that are not removed by closing of file descriptors remain unchanged.
9573
Directory streams open in the calling process image shall be closed in the new process image.
9574
The state of the floating-point environment in the new process image shall be set to the default.
9575
9576
XSI
The state of conversion descriptors and message catalog descriptors in the new process image is
undefined. For the new process image, the equivalent of:
9577
setlocale(LC_ALL, "C")
9578
shall be executed at start-up.
9579
9580
9581
9582
9583
9584
9585
9586
Signals set to the default action (SIG_DFL) in the calling process image shall be set to the default
action in the new process image. Except for SIGCHLD, signals set to be ignored (SIG_IGN) by
the calling process image shall be set to be ignored by the new process image. Signals set to be
caught by the calling process image shall be set to the default action in the new process image
(see <signal.h>). If the SIGCHLD signal is set to be ignored by the calling process image, it is
unspecified whether the SIGCHLD signal is set to be ignored or to the default action in the new
process image. After a successful call to any of the exec functions, alternate signal stacks are not
preserved and the SA_ONSTACK flag shall be cleared for all signals.
XSI
After a successful call to any of the exec functions, any functions previously registered by atexit( )
are no longer registered.
9587
9588
9589
9590
9591
XSI
If the ST_NOSUID bit is set for the file system containing the new process image file, then the
effective user ID, effective group ID, saved set-user-ID, and saved set-group-ID are unchanged
in the new process image. Otherwise, if the set-user-ID mode bit of the new process image file is
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
295
exec
System Interfaces
set, the effective user ID of the new process image shall be set to the user ID of the new process
image file. Similarly, if the set-group-ID mode bit of the new process image file is set, the
effective group ID of the new process image shall be set to the group ID of the new process
image file. The real user ID, real group ID, and supplementary group IDs of the new process
image shall remain the same as those of the calling process image. The effective user ID and
effective group ID of the new process image shall be saved (as the saved set-user-ID and the
saved set-group-ID) for use by setuid( ).
9592
9593
9594
9595
9596
9597
9598
9599
9600
XSI
Any shared memory segments attached to the calling process image shall not be attached to the
new process image.
9601
9602
SEM
Any named semaphores open in the calling process shall be closed as if by appropriate calls to
sem_close( ).
9603
9604
TYM
Any blocks of typed memory that were mapped in the calling process are unmapped, as if
munmap( ) was implicitly called to unmap them.
9605
9606
9607
9608
9609
ML
Memory locks established by the calling process via calls to mlockall ( ) or mlock( ) shall be
removed. If locked pages in the address space of the calling process are also mapped into the
address spaces of other processes and are locked by those processes, the locks established by the
other processes shall be unaffected by the call by this process to the exec function. If the exec
function fails, the effect on memory locks is unspecified.
9610
9611
MF|SHM
Memory mappings created in the process are unmapped before the address space is rebuilt for
the new process image.
9612
9613
9614
PS
For the SCHED_FIFO and SCHED_RR scheduling policies, the policy and priority settings shall
not be changed by a call to an exec function. For other scheduling policies, the policy and priority
settings on exec are implementation-defined.
9615
9616
TMR
Per-process timers created by the calling process shall be deleted before replacing the current
process image with the new process image.
9617
9618
MSG
All open message queue descriptors in the calling process shall be closed, as described in
mq_close( ).
9619
9620
9621
9622
9623
9624
9625
AIO
Any outstanding asynchronous I/O operations may be canceled. Those asynchronous I/O
operations that are not canceled shall complete as if the exec function had not yet occurred, but
any associated signal notifications shall be suppressed. It is unspecified whether the exec
function itself blocks awaiting such I/O completion. In no event, however, shall the new process
image created by the exec function be affected by the presence of outstanding asynchronous I/O
operations at the time the exec function is called. Whether any I/O is canceled, and which I/O
may be canceled upon exec, is implementation-defined.
9626
9627
9628
9629
CPT
The new process image shall inherit the CPU-time clock of the calling process image. This
inheritance means that the process CPU-time clock of the process being exec-ed shall not be
reinitialized or altered as a result of the exec function other than to reflect the time spent by the
process executing the exec function itself.
9630
9631
TCT
The initial value of the CPU-time clock of the initial thread of the new process image shall be set
to zero.
9632
9633
9634
9635
TRC
If the calling process is being traced, the new process image shall continue to be traced into the
same trace stream as the original process image, but the new process image shall not inherit the
mapping of trace event names to trace event type identifiers that was defined by calls to the
posix_trace_eventid_open( ) or the posix_trace_trid_eventid_open( ) functions in the calling process
image.
9636
296
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
exec
9637
9638
If the calling process is a trace controller process, any trace streams that were created by the
calling process shall be shut down as described in the posix_trace_shutdown( ) function.
9639
The new process shall inherit at least the following attributes from the calling process image:
9640
XSI
•
Nice value (see nice( ))
9641
XSI
•
semadj values (see semop( ))
9642
•
Process ID
9643
•
Parent process ID
9644
•
Process group ID
9645
•
Session membership
9646
•
Real user ID
9647
•
Real group ID
9648
•
Supplementary group IDs
9649
•
Time left until an alarm clock signal (see alarm( ))
9650
•
Current working directory
9651
•
Root directory
9652
•
File mode creation mask (see umask( ))
•
File size limit (see ulimit( ))
9654
•
Process signal mask (see sigprocmask ( ))
9655
•
Pending signal (see sigpending( ))
9656
•
tms_utime, tms_stime, tms_cutime, and tms_cstime (see times( ))
9653
XSI
9657
XSI
•
Resource limits
9658
XSI
•
Controlling terminal
9659
XSI
•
Interval timers
9660
9661
9662
All other process attributes defined in this volume of IEEE Std 1003.1-2001 shall be the same in
the new and old process images. The inheritance of process attributes not defined by this
volume of IEEE Std 1003.1-2001 is implementation-defined.
9663
9664
9665
A call to any exec function from a process with more than one thread shall result in all threads
being terminated and the new executable image being loaded and executed. No destructor
functions shall be called.
9666
9667
9668
9669
9670
9671
9672
9673
9674
Upon successful completion, the exec functions shall mark for update the st_atime field of the file.
If an exec function failed but was able to locate the process image file, whether the st_atime field
is marked for update is unspecified. Should the exec function succeed, the process image file
shall be considered to have been opened with open( ). The corresponding close( ) shall be
considered to occur at a time after this open, but before process termination or successful
completion of a subsequent call to one of the exec functions, posix_spawn ( ), or posix_spawnp ( ).
The argv[ ] and envp[ ] arrays of pointers and the strings to which those arrays point shall not be
modified by a call to one of the exec functions, except as a consequence of replacing the process
image.
9675
9676
XSI
The saved resource limits in the new process image are set to be a copy of the process’
corresponding hard and soft limits.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
297
exec
System Interfaces
9677
9678
9679
RETURN VALUE
If one of the exec functions returns to the calling process image, an error has occurred; the return
value shall be −1, and errno shall be set to indicate the error.
9680
9681
ERRORS
The exec functions shall fail if:
9682
9683
9684
[E2BIG]
The number of bytes used by the new process image’s argument list and
environment list is greater than the system-imposed limit of {ARG_MAX}
bytes.
9685
9686
9687
9688
[EACCES]
Search permission is denied for a directory listed in the new process image
file’s path prefix, or the new process image file denies execution permission,
or the new process image file is not a regular file and the implementation does
not support execution of files of its type.
9689
9690
9691
[EINVAL]
The new process image file has the appropriate permission and has a
recognized executable binary format, but the system does not support
execution of a file with this format.
9692
9693
[ELOOP]
A loop exists in symbolic links encountered during resolution of the path or file
argument.
9694
9695
9696
[ENAMETOOLONG]
The length of the path or file arguments exceeds {PATH_MAX} or a pathname
component is longer than {NAME_MAX}.
9697
9698
[ENOENT]
A component of path or file does not name an existing file or path or file is an
empty string.
9699
[ENOTDIR]
A component of the new process image file’s path prefix is not a directory.
9700
The exec functions, except for execlp( ) and execvp( ), shall fail if:
9701
9702
[ENOEXEC]
9703
The exec functions may fail if:
9704
9705
[ELOOP]
9706
9707
9708
[ENAMETOOLONG]
As a result of encountering a symbolic link in resolution of the path argument,
the length of the substituted pathname string exceeded {PATH_MAX}.
9709
9710
[ENOMEM]
The new process image requires more memory than is allowed by the
hardware or system-imposed memory management constraints.
9711
9712
[ETXTBSY]
The new process image file is a pure procedure (shared text) file that is
currently open for writing by some process.
298
The new process image file has the appropriate access permission but has an
unrecognized format.
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path or file argument.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
9713
exec
EXAMPLES
9714
Using execl( )
9715
9716
9717
The following example executes the ls command, specifying the pathname of the executable
(/bin/ls) and using arguments supplied directly to the command to produce single-column
output.
9718
#include <unistd.h>
9719
9720
9721
int ret;
...
ret = execl ("/bin/ls", "ls", "-1", (char *)0);
9722
Using execle( )
9723
9724
The following example is similar to Using execl( ). In addition, it specifies the environment for
the new process image using the env argument.
9725
#include <unistd.h>
9726
9727
9728
9729
int ret;
char *env[] = { "HOME=/usr/home", "LOGNAME=home", (char *)0 };
...
ret = execle ("/bin/ls", "ls", "-l", (char *)0, env);
9730
Using execlp( )
9731
9732
The following example searches for the location of the ls command among the directories
specified by the PATH environment variable.
9733
#include <unistd.h>
9734
9735
9736
int ret;
...
ret = execlp ("ls", "ls", "-l", (char *)0);
9737
Using execv( )
9738
The following example passes arguments to the ls command in the cmd array.
9739
#include <unistd.h>
9740
9741
9742
9743
int ret;
char *cmd[] = { "ls", "-l", (char *)0 };
...
ret = execv ("/bin/ls", cmd);
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
299
exec
System Interfaces
9744
Using execve( )
9745
9746
The following example passes arguments to the ls command in the cmd array, and specifies the
environment for the new process image using the env argument.
9747
#include <unistd.h>
9748
9749
9750
9751
9752
int ret;
char *cmd[] = { "ls", "-l", (char *)0 };
char *env[] = { "HOME=/usr/home", "LOGNAME=home", (char *)0 };
...
ret = execve ("/bin/ls", cmd, env);
9753
Using execvp( )
9754
9755
9756
The following example searches for the location of the ls command among the directories
specified by the PATH environment variable, and passes arguments to the ls command in the
cmd array.
9757
#include <unistd.h>
9758
9759
9760
9761
int ret;
char *cmd[] = { "ls", "-l", (char *)0 };
...
ret = execvp ("ls", cmd);
9762
9763
9764
9765
APPLICATION USAGE
As the state of conversion descriptors and message catalog descriptors in the new process image
is undefined, conforming applications should not rely on their use and should close them prior
to calling one of the exec functions.
9766
9767
Applications that require other than the default POSIX locale should call setlocale ( ) with the
appropriate parameters to establish the locale of the new process.
9768
The environ array should not be accessed directly by the application.
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
RATIONALE
Early proposals required that the value of argc passed to main( ) be ‘‘one or greater’’. This was
driven by the same requirement in drafts of the ISO C standard. In fact, historical
implementations have passed a value of zero when no arguments are supplied to the caller of
the exec functions. This requirement was removed from the ISO C standard and subsequently
removed from this volume of IEEE Std 1003.1-2001 as well. The wording, in particular the use of
the word should, requires a Strictly Conforming POSIX Application to pass at least one argument
to the exec function, thus guaranteeing that argc be one or greater when invoked by such an
application. In fact, this is good practice, since many existing applications reference argv[0]
without first checking the value of argc.
9779
9780
9781
9782
9783
9784
9785
The requirement on a Strictly Conforming POSIX Application also states that the value passed
as the first argument be a filename associated with the process being started. Although some
existing applications pass a pathname rather than a filename in some circumstances, a filename
is more generally useful, since the common usage of argv[0] is in printing diagnostics. In some
cases the filename passed is not the actual filename of the file; for example, many
implementations of the login utility use a convention of prefixing a hyphen (’−’) to the actual
filename, which indicates to the command interpreter being invoked that it is a ‘‘login shell’’.
9786
Historically there have been two ways that implementations can exec shell scripts.
300
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
exec
9787
9788
9789
9790
9791
9792
9793
9794
One common historical implementation is that the execl( ), execv( ), execle( ), and execve( )
functions return an [ENOEXEC] error for any file not recognizable as executable, including a
shell script. When the execlp( ) and execvp( ) functions encounter such a file, they assume the file
to be a shell script and invoke a known command interpreter to interpret such files. This is now
required by IEEE Std 1003.1-2001. These implementations of execvp( ) and execlp( ) only give the
[ENOEXEC] error in the rare case of a problem with the command interpreter’s executable file.
Because of these implementations, the [ENOEXEC] error is not mentioned for execlp( ) or
execvp( ), although implementations can still give it.
9795
9796
9797
Another way that some historical implementations handle shell scripts is by recognizing the first
two bytes of the file as the character string "#!" and using the remainder of the first line of the
file as the name of the command interpreter to execute.
9798
9799
9800
One potential source of confusion noted by the standard developers is over how the contents of
a process image file affect the behavior of the exec family of functions. The following is a
description of the actions taken:
9801
9802
1. If the process image file is a valid executable (in a format that is executable and valid and
having appropriate permission) for this system, then the system executes the file.
9803
9804
9805
2. If the process image file has appropriate permission and is in a format that is executable
but not valid for this system (such as a recognized binary for another architecture), then
this is an error and errno is set to [EINVAL] (see later RATIONALE on [EINVAL]).
9806
3. If the process image file has appropriate permission but is not otherwise recognized:
9807
9808
a. If this is a call to execlp( ) or execvp( ), then they invoke a command interpreter
assuming that the process image file is a shell script.
9809
9810
b. If this is not a call to execlp( ) or execvp( ), then an error occurs and errno is set to
[ENOEXEC].
9811
Applications that do not require to access their arguments may use the form:
9812
main(void)
9813
9814
as specified in the ISO C standard. However, the implementation will always provide the two
arguments argc and argv, even if they are not used.
9815
9816
9817
9818
9819
9820
9821
9822
9823
Some implementations provide a third argument to main( ) called envp. This is defined as a
pointer to the environment. The ISO C standard specifies invoking main( ) with two arguments,
so implementations must support applications written this way. Since this volume of
IEEE Std 1003.1-2001 defines the global variable environ, which is also provided by historical
implementations and can be used anywhere that envp could be used, there is no functional need
for the envp argument. Applications should use the getenv( ) function rather than accessing the
environment directly via either envp or environ. Implementations are required to support the
two-argument calling sequence, but this does not prohibit an implementation from supporting
envp as an optional third argument.
9824
9825
9826
9827
9828
9829
9830
This volume of IEEE Std 1003.1-2001 specifies that signals set to SIG_IGN remain set to
SIG_IGN, and that the process signal mask be unchanged across an exec. This is consistent with
historical implementations, and it permits some useful functionality, such as the nohup
command. However, it should be noted that many existing applications wrongly assume that
they start with certain signals set to the default action and/or unblocked. In particular,
applications written with a simpler signal model that does not include blocking of signals, such
as the one in the ISO C standard, may not behave properly if invoked with some signals blocked.
Therefore, it is best not to block or ignore signals across execs without explicit reason to do so,
and especially not to block signals across execs of arbitrary (not closely co-operating) programs.
9831
9832
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
301
exec
System Interfaces
9833
9834
9835
The exec functions always save the value of the effective user ID and effective group ID of the
process at the completion of the exec, whether or not the set-user-ID or the set-group-ID bit of
the process image file is set.
9836
9837
9838
9839
9840
9841
9842
9843
9845
9846
9847
9848
9849
The statement about argv[ ] and envp[ ] being constants is included to make explicit to future
writers of language bindings that these objects are completely constant. Due to a limitation of
the ISO C standard, it is not possible to state that idea in standard C. Specifying two levels of
const−qualification for the argv[ ] and envp[ ] parameters for the exec functions may seem to be the
natural choice, given that these functions do not modify either the array of pointers or the
characters to which the function points, but this would disallow existing correct code. Instead,
only the array of pointers is noted as constant. The table of assignment compatibility for dst=src
derived from the ISO C standard summarizes the compatibility:
_______________________________________________________________________________
L
dst: L char *[ ] L const char *[ ] L char *const[ ] L const char *const[ ] L
_______________________________________________________________________________
L
L
L
L
L
L
src:
L
L
L
L
L
L
char *[ ]
VALID L
—
VALID
—
L
L
L
L
L
—
VALID
—
VALID
L
L
L
L
L const char *[ ]
L
L char * const [ ]
L
L
L
L
L
—
—
VALID
—
L
L
L
L
L
L
const char *const[ ] L
—
—
—
VALID
L
L
L
______________________________________________________________________________
L
L_
9850
9851
9852
9853
9854
Since all existing code has a source type matching the first row, the column that gives the most
valid combinations is the third column. The only other possibility is the fourth column, but
using it would require a cast on the argv or envp arguments. It is unfortunate that the fourth
column cannot be used, because the declaration a non-expert would naturally use would be that
in the second row.
9855
9856
9857
9858
9859
9860
9861
The ISO C standard and this volume of IEEE Std 1003.1-2001 do not conflict on the use of
environ, but some historical implementations of environ may cause a conflict. As long as environ
is treated in the same way as an entry point (for example, fork ( )), it conforms to both standards.
A library can contain fork ( ), but if there is a user-provided fork ( ), that fork ( ) is given precedence
and no problem ensues. The situation is similar for environ: the definition in this volume of
IEEE Std 1003.1-2001 is to be used if there is no user-provided environ to take precedence. At
least three implementations are known to exist that solve this problem.
9862
9863
[E2BIG]
The limit {ARG_MAX} applies not just to the size of the argument list, but to
the sum of that and the size of the environment list.
9864
9865
[EFAULT]
Some historical systems return [EFAULT] rather than [ENOEXEC] when the
new process image file is corrupted. They are non-conforming.
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
[EINVAL]
This error condition was added to IEEE Std 1003.1-2001 to allow an
implementation to detect executable files generated for different architectures,
and indicate this situation to the application. Historical implementations of
shells, execvp( ), and execlp( ) that encounter an [ENOEXEC] error will execute
a shell on the assumption that the file is a shell script. This will not produce
the desired effect when the file is a valid executable for a different
architecture. An implementation may now choose to avoid this problem by
returning [EINVAL] when a valid executable for a different architecture is
encountered. Some historical implementations return [EINVAL] to indicate
that the path argument contains a character with the high order bit set. The
standard developers chose to deviate from historical practice for the following
reasons:
9844
1. The new utilization of [EINVAL] will provide some measure of utility to
the user community.
9878
9879
302
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
exec
System Interfaces
9880
9881
2. Historical use of [EINVAL] is not acceptable in an internationalized
operating environment.
9882
9883
9884
9885
[ENAMETOOLONG]
Since the file pathname may be constructed by taking elements in the PATH
variable and putting them together with the filename, the
[ENAMETOOLONG] error condition could also be reached this way.
9886
9887
9888
[ETXTBSY]
9889
9890
9891
Other systems (such as System V) may return [EINTR] from exec. This is not addressed by this
volume of IEEE Std 1003.1-2001, but implementations may have a window between the call to
exec and the time that a signal could cause one of the exec calls to return with [EINTR].
9892
9893
9894
9895
9896
An explicit statement regarding the floating-point environment (as defined in the <fenv.h>
header) was added to make it clear that the floating-point environment is set to its default when
a call to one of the exec functions succeeds. The requirements for inheritance or setting to the
default for other process and thread start-up functions is covered by more generic statements in
their descriptions and can be summarized as follows:
9897
posix_spawn ( )
Set to default.
9898
fork ( )
Inherit.
9899
pthread_create( )
Inherit.
9900
9901
FUTURE DIRECTIONS
None.
9902
9903
9904
9905
9906
9907
SEE ALSO
alarm( ), atexit( ), chmod( ), close( ), exit( ), fcntl( ), fork ( ), fstatvfs ( ), getenv( ), getitimer( ), getrlimit( ),
mmap( ),
nice( ),
posix_spawn ( ),
posix_trace_eventid_open( ),
posix_trace_shutdown( ),
posix_trace_trid_eventid_open( ), putenv( ), semop( ), setlocale ( ), shmat( ), sigaction ( ), sigaltstack ( ),
sigpending( ), sigprocmask ( ), system( ), times( ), ulimit( ), umask( ), the Base Definitions volume of
IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <unistd.h>
9908
9909
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
9910
9911
9912
Issue 5
The DESCRIPTION is updated for alignment with the POSIX Realtime Extension and the POSIX
Threads Extension.
Large File Summit extensions are added.
9913
9914
9915
9916
System V returns this error when the executable file is currently open for
writing by some process. This volume of IEEE Std 1003.1-2001 neither requires
nor prohibits this behavior.
Issue 6
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
9917
9918
•
In the DESCRIPTION, behavior is defined for when the process image file is not a valid
executable.
9919
9920
9921
•
In this issue, _POSIX_SAVED_IDS is mandated, thus the effective user ID and effective group
ID of the new process image shall be saved (as the saved set-user-ID and the saved setgroup-ID) for use by the setuid( ) function.
9922
•
The [ELOOP] mandatory error condition is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
303
exec
System Interfaces
9923
•
A second [ENAMETOOLONG] is added as an optional error condition.
9924
•
The [ETXTBSY] optional error condition is added.
The following changes were made to align with the IEEE P1003.1a draft standard:
9925
9926
•
The [EINVAL] mandatory error condition is added.
9927
•
The [ELOOP] optional error condition is added.
9928
The description of CPU-time clock semantics is added for alignment with IEEE Std 1003.1d-1999.
9929
9930
The DESCRIPTION is updated for alignment with IEEE Std 1003.1j-2000 by adding semantics for
typed memory.
9931
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
9932
The description of tracing semantics is added for alignment with IEEE Std 1003.1q-2000.
9933
IEEE PASC Interpretation 1003.1 #132 is applied.
9934
9935
The DESCRIPTION is updated to make it explicit that the floating-point environment in the new
process image is set to the default.
9936
9937
The DESCRIPTION and RATIONALE are updated to include clarifications of how the contents
of a process image file affect the behavior of the exec functions.
304
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
exit( )
System Interfaces
9938
9939
NAME
9940
9941
SYNOPSIS
#include <stdlib.h>
exit, _Exit, _exit — terminate a process
9942
9943
void exit(int status);
void _Exit(int status);
9944
#include <unistd.h>
9945
void _exit(int status);
9946
9947
9948
9949
DESCRIPTION
CX
For exit( ) and _Exit( ): The functionality described on this reference page is aligned with the
ISO C standard. Any conflict between the requirements described here and the ISO C standard is
unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
9950
9951
CX
The value of status may be 0, EXIT_SUCCESS, EXIT_FAILURE, or any other value, though only
the least significant 8 bits (that is, status & 0377) shall be available to a waiting parent process.
9952
9953
9954
9955
9956
The exit( ) function shall first call all functions registered by atexit( ), in the reverse order of their
registration, except that a function is called after any previously registered functions that had
already been called at the time it was registered. Each function is called as many times as it was
registered. If, during the call to any such function, a call to the longjmp( ) function is made that
would terminate the call to the registered function, the behavior is undefined.
9957
9958
9959
If a function registered by a call to atexit( ) fails to return, the remaining registered functions shall
not be called and the rest of the exit( ) processing shall not be completed. If exit( ) is called more
than once, the behavior is undefined.
9960
9961
9962
The exit( ) function shall then flush all open streams with unwritten buffered data, close all open
streams, and remove all files created by tmpfile( ). Finally, control shall be terminated with the
consequences described below.
9963
CX
The _Exit( ) and _exit( ) functions shall be functionally equivalent.
9964
9965
9966
9967
CX
The _Exit( ) and _exit( ) functions shall not call functions registered with atexit( ) nor any
registered signal handlers. Whether open streams are flushed or closed, or temporary files are
removed is implementation-defined. Finally, the calling process is terminated with the
consequences described below.
9968
CX
These functions shall terminate the calling process with the following consequences:
Note:
9969
9970
These consequences are all extensions to the ISO C standard and are not further CX shaded.
However, XSI extensions are shaded.
9971
9972
XSI
•
All of the file descriptors, directory streams, conversion descriptors, and message catalog
descriptors open in the calling process shall be closed.
9973
9974
9975
9976
9977
XSI
•
If the parent process of the calling process is executing a wait( ) or waitpid ( ), and has neither
set its SA_NOCLDWAIT flag nor set SIGCHLD to SIG_IGN, it shall be notified of the calling
process’ termination and the low-order eight bits (that is, bits 0377) of status are made
available to it. If the parent is not waiting, the child’s status shall be made available to it
when the parent subsequently executes wait( ) or waitpid ( ).
9978
XSI
9979
9980
9981
XSI
The semantics of the waitid ( ) function shall be equivalent to wait( ).
•
If the parent process of the calling process is not executing a wait( ) or waitpid ( ), and has
neither set its SA_NOCLDWAIT flag nor set SIGCHLD to SIG_IGN, the calling process shall
be transformed into a zombie process. A zombie process is an inactive process and it shall be
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
305
exit( )
System Interfaces
deleted at some later time when its parent process executes wait( ) or waitpid ( ).
9982
9983
The semantics of the waitid ( ) function shall be equivalent to wait( ).
XSI
9984
9985
•
Termination of a process does not directly terminate its children. The sending of a SIGHUP
signal as described below indirectly terminates children in some circumstances.
9986
•
Either:
9987
9988
If the implementation supports the SIGCHLD signal, a SIGCHLD shall be sent to the parent
process.
9989
Or:
9990
9991
9992
9993
If the parent process has set its SA_NOCLDWAIT flag, or set SIGCHLD to SIG_IGN, the
status shall be discarded, and the lifetime of the calling process shall end immediately. If
SA_NOCLDWAIT is set, it is implementation-defined whether a SIGCHLD signal is sent to
the parent process.
XSI
•
The parent process ID of all of the calling process’ existing child processes and zombie
processes shall be set to the process ID of an implementation-defined system process. That is,
these processes shall be inherited by a special system process.
XSI
•
Each attached shared-memory segment is detached and the value of shm_nattch (see
shmget( )) in the data structure associated with its shared memory ID shall be decremented by
1.
10000 XSI
10001
•
For each semaphore for which the calling process has set a semadj value (see semop( )), that
value shall be added to the semval of the specified semaphore.
10002
10003
•
If the process is a controlling process, the SIGHUP signal shall be sent to each process in the
foreground process group of the controlling terminal belonging to the calling process.
10004
10005
10006
•
If the process is a controlling process, the controlling terminal associated with the session
shall be disassociated from the session, allowing it to be acquired by a new controlling
process.
10007
10008
10009
•
If the exit of the process causes a process group to become orphaned, and if any member of
the newly-orphaned process group is stopped, then a SIGHUP signal followed by a
SIGCONT signal shall be sent to each process in the newly-orphaned process group.
10010 SEM
10011
•
All open named semaphores in the calling process shall be closed as if by appropriate calls to
sem_close( ).
10012 ML
10013
10014
10015
•
Any memory locks established by the process via calls to mlockall ( ) or mlock( ) shall be
removed. If locked pages in the address space of the calling process are also mapped into the
address spaces of other processes and are locked by those processes, the locks established by
the other processes shall be unaffected by the call by this process to _Exit( ) or _exit( ).
10016 MF|SHM
10017
•
Memory mappings that were created in the process shall be unmapped before the process is
destroyed.
10018 TYM
10019
•
Any blocks of typed memory that were mapped in the calling process shall be unmapped, as
if munmap( ) was implicitly called to unmap them.
10020 MSG
10021
•
All open message queue descriptors in the calling process shall be closed as if by appropriate
calls to mq_close( ).
10022 AIO
•
Any outstanding cancelable asynchronous I/O operations may be canceled. Those
asynchronous I/O operations that are not canceled shall complete as if the _Exit( ) or _exit( )
operation had not yet occurred, but any associated signal notifications shall be suppressed.
9994
9995
9996
9997
9998
9999
10023
10024
306
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
exit( )
The _Exit( ) or _exit( ) operation may block awaiting such I/O completion. Whether any I/O
is canceled, and which I/O may be canceled upon _Exit( ) or _exit( ), is implementationdefined.
10025
10026
10027
10028
10029
•
Threads terminated by a call to _Exit( ) or _exit( ) shall not invoke their cancelation cleanup
handlers or per-thread data destructors.
10030 TRC
10031
10032
10033
•
If the calling process is a trace controller process, any trace streams that were created by the
calling process shall be shut down as described by the posix_trace_shutdown( ) function, and
any process’ mapping of trace event names to trace event type identifiers built for these trace
streams may be deallocated.
10034
10035
RETURN VALUE
These functions do not return.
10036
10037
ERRORS
No errors are defined.
10038
10039
EXAMPLES
None.
10040
10041
APPLICATION USAGE
Normally applications should use exit( ) rather than _Exit( ) or _exit( ).
10042
RATIONALE
10043
Process Termination
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
Early proposals drew a distinction between normal and abnormal process termination.
Abnormal termination was caused only by certain signals and resulted in implementationdefined ‘‘actions’’, as discussed below. Subsequent proposals distinguished three types of
termination: normal termination (as in the current specification), simple abnormal termination, and
abnormal termination with actions. Again the distinction between the two types of abnormal
termination was that they were caused by different signals and that implementation-defined
actions would result in the latter case. Given that these actions were completely
implementation-defined, the early proposals were only saying when the actions could occur and
how their occurrence could be detected, but not what they were. This was of little or no use to
conforming applications, and thus the distinction is not made in this volume of
IEEE Std 1003.1-2001.
10055
10056
10057
10058
The implementation-defined actions usually include, in most historical implementations, the
creation of a file named core in the current working directory of the process. This file contains an
image of the memory of the process, together with descriptive information about the process,
perhaps sufficient to reconstruct the state of the process at the receipt of the signal.
10059
10060
10061
10062
10063
There is a potential security problem in creating a core file if the process was set-user-ID and the
current user is not the owner of the program, if the process was set-group-ID and none of the
user’s groups match the group of the program, or if the user does not have permission to write in
the current directory. In this situation, an implementation either should not create a core file or
should make it unreadable by the user.
10064
10065
10066
10067
Despite the silence of this volume of IEEE Std 1003.1-2001 on this feature, applications are
advised not to create files named core because of potential conflicts in many implementations.
Some implementations use a name other than core for the file; for example, by appending the
process ID to the filename.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
307
exit( )
System Interfaces
10068
Terminating a Process
10069
10070
10071
10072
It is important that the consequences of process termination as described occur regardless of
whether the process called _exit( ) (perhaps indirectly through exit( )) or instead was terminated
due to a signal or for some other reason. Note that in the specific case of exit( ) this means that
the status argument to exit( ) is treated in the same way as the status argument to _exit( ).
10073
10074
10075
10076
10077
A language other than C may have other termination primitives than the C-language exit( )
function, and programs written in such a language should use its native termination primitives,
but those should have as part of their function the behavior of _exit( ) as described.
Implementations in languages other than C are outside the scope of this version of this volume
of IEEE Std 1003.1-2001, however.
10078
10079
10080
As required by the ISO C standard, using return from main( ) has the same behavior (other than
with respect to language scope issues) as calling exit( ) with the returned value. Reaching the end
of the main( ) function has the same behavior as calling exit(0).
10081
10082
10083
10084
10085
10086
A value of zero (or EXIT_SUCCESS, which is required to be zero) for the argument status
conventionally indicates successful termination. This corresponds to the specification for exit( )
in the ISO C standard. The convention is followed by utilities such as make and various shells,
which interpret a zero status from a child process as success. For this reason, applications should
not call exit(0) or _exit(0) when they terminate unsuccessfully; for example, in signal-catching
functions.
10087
10088
Historically, the implementation-defined process that inherits children whose parents have
terminated without waiting on them is called init and has a process ID of 1.
10089
10090
10091
10092
10093
10094
10095
10096
10097
The sending of a SIGHUP to the foreground process group when a controlling process
terminates corresponds to somewhat different historical implementations. In System V, the
kernel sends a SIGHUP on termination of (essentially) a controlling process. In 4.2 BSD, the
kernel does not send SIGHUP in a case like this, but the termination of a controlling process is
usually noticed by a system daemon, which arranges to send a SIGHUP to the foreground
process group with the vhangup( ) function. However, in 4.2 BSD, due to the behavior of the
shells that support job control, the controlling process is usually a shell with no other processes
in its process group. Thus, a change to make _exit( ) behave this way in such systems should not
cause problems with existing applications.
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
The termination of a process may cause a process group to become orphaned in either of two
ways. The connection of a process group to its parent(s) outside of the group depends on both
the parents and their children. Thus, a process group may be orphaned by the termination of the
last connecting parent process outside of the group or by the termination of the last direct
descendant of the parent process(es). In either case, if the termination of a process causes a
process group to become orphaned, processes within the group are disconnected from their job
control shell, which no longer has any information on the existence of the process group.
Stopped processes within the group would languish forever. In order to avoid this problem,
newly orphaned process groups that contain stopped processes are sent a SIGHUP signal and a
SIGCONT signal to indicate that they have been disconnected from their session. The SIGHUP
signal causes the process group members to terminate unless they are catching or ignoring
SIGHUP. Under most circumstances, all of the members of the process group are stopped if any
of them are stopped.
10111
10112
10113
The action of sending a SIGHUP and a SIGCONT signal to members of a newly orphaned
process group is similar to the action of 4.2 BSD, which sends SIGHUP and SIGCONT to each
stopped child of an exiting process. If such children exit in response to the SIGHUP, any
additional descendants receive similar treatment at that time. In this volume of
IEEE Std 1003.1-2001, the signals are sent to the entire process group at the same time. Also, in
10114
10115
308
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
exit( )
10116
10117
10118
this volume of IEEE Std 1003.1-2001, but not in 4.2 BSD, stopped processes may be orphaned, but
may be members of a process group that is not orphaned; therefore, the action taken at _exit( )
must consider processes other than child processes.
10119
10120
10121
10122
10123
10124
It is possible for a process group to be orphaned by a call to setpgid( ) or setsid( ), as well as by
process termination. This volume of IEEE Std 1003.1-2001 does not require sending SIGHUP and
SIGCONT in those cases, because, unlike process termination, those cases are not caused
accidentally by applications that are unaware of job control. An implementation can choose to
send SIGHUP and SIGCONT in those cases as an extension; such an extension must be
documented as required in <signal.h>.
10125
10126
10127
The ISO/IEC 9899: 1999 standard adds the _Exit( ) function that results in immediate program
termination without triggering signals or atexit( )-registered functions. In IEEE Std 1003.1-2001,
this is equivalent to the _exit( ) function.
10128
10129
FUTURE DIRECTIONS
None.
10130
10131
10132
10133
SEE ALSO
atexit( ), close( ), fclose( ), longjmp( ), posix_trace_shutdown( ), posix_trace_trid_eventid_open( ),
semop( ), shmget( ), sigaction ( ), wait( ), waitid ( ), waitpid ( ), the Base Definitions volume of
IEEE Std 1003.1-2001, <stdlib.h>, <unistd.h>
10134
10135
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
10136
10137
10138
Issue 5
The DESCRIPTION is updated for alignment with the POSIX Realtime Extension and the POSIX
Threads Extension.
10139
Interactions with the SA_NOCLDWAIT flag and SIGCHLD signal are further clarified.
10140
The values of status from exit( ) are better described.
10141
10142
Issue 6
Extensions beyond the ISO C standard are marked.
10143
10144
The DESCRIPTION is updated for alignment with IEEE Std 1003.1j-2000 by adding semantics for
typed memory.
10145
The following changes are made for alignment with the ISO/IEC 9899: 1999 standard:
10146
•
The _Exit( ) function is included.
10147
•
The DESCRIPTION is updated.
10148
The description of tracing semantics is added for alignment with IEEE Std 1003.1q-2000.
10149
References to the wait3( ) function are removed.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
309
exp( )
System Interfaces
10150
10151
NAME
10152
10153
SYNOPSIS
#include <math.h>
exp, expf, expl — exponential function
double exp(double x);
float expf(float x);
long double expl(long double x);
10154
10155
10156
10157 DESCRIPTION
10158 CX
The functionality described on this reference page is aligned with the ISO C standard.
10159
conflict between the requirements described here and the ISO C standard is unintentional.
10160
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
10161
These functions shall compute the base-e exponential of x.
10162
10163
10164
10165
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
10166
10167
RETURN VALUE
Upon successful completion, these functions shall return the exponential value of x.
10168
10169
If the correct value would cause overflow, a range error shall occur and exp( ), expf( ), and expl( )
shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively.
10170
10171 MX
If the correct value would cause underflow, and is not representable, a range error may occur,
and either 0.0 (if supported), or an implementation-defined value shall be returned.
10172 MX
If x is NaN, a NaN shall be returned.
10173
If x is ±0, 1 shall be returned.
10174
If x is −Inf, +0 shall be returned.
10175
If x is +Inf, x shall be returned.
10176
10177
If the correct value would cause underflow, and is representable, a range error may occur and
the correct value shall be returned.
10178
10179
ERRORS
These functions shall fail if:
Range Error
10180
The result overflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow
floating-point exception shall be raised.
10181
10182
10183
10184
10185
These functions may fail if:
10186
Range Error
The result underflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
10187
10188
10189
10190
310
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
exp( )
10191
10192
EXAMPLES
None.
10193
10194
10195
APPLICATION USAGE
Note that for IEEE Std 754-1985 double, 709.8 < x implies exp(x) has overflowed. The value
x< −708.4 implies exp(x) has underflowed.
10196
10197
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
10198
10199
RATIONALE
None.
10200
10201
FUTURE DIRECTIONS
None.
10202
10203
10204
SEE ALSO
feclearexcept( ), fetestexcept( ), isnan( ), log( ), the Base Definitions volume of IEEE Std 1003.1-2001,
Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
10205
10206
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
10207
10208
10209
Issue 5
10210
10211
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The expf( ) and expl( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
10212
10213
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
10214
10215
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
311
exp2( )
System Interfaces
10216
10217
NAME
10218
10219
SYNOPSIS
#include <math.h>
exp2, exp2f, exp2l — exponential base 2 functions
double exp2(double x);
float exp2f(float x);
long double exp2l(long double x);
10220
10221
10222
10223 DESCRIPTION
10224 CX
The functionality described on this reference page is aligned with the ISO C standard.
10225
conflict between the requirements described here and the ISO C standard is unintentional.
10226
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
10227
These functions shall compute the base-2 exponential of x.
10228
10229
10230
10231
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
10232
10233
RETURN VALUE
Upon successful completion, these functions shall return 2x.
10234
10235
10236
If the correct value would cause overflow, a range error shall occur and exp2( ), exp2f( ), and
exp2l( ) shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL,
respectively.
10237
10238 MX
If the correct value would cause underflow, and is not representable, a range error may occur,
and either 0.0 (if supported), or an implementation-defined value shall be returned.
10239 MX
If x is NaN, a NaN shall be returned.
10240
If x is ±0, 1 shall be returned.
10241
If x is −Inf, +0 shall be returned.
10242
If x is +Inf, x shall be returned.
10243
10244
If the correct value would cause underflow, and is representable, a range error may occur and
the correct value shall be returned.
10245
10246
ERRORS
These functions shall fail if:
Range Error
10247
The result overflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow
floating-point exception shall be raised.
10248
10249
10250
10251
10252
These functions may fail if:
10253
Range Error
The result underflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
10254
10255
10256
10257
312
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
exp2( )
10258
10259
EXAMPLES
None.
10260
10261
10262
APPLICATION USAGE
For IEEE Std 754-1985 double, 1024 <= x implies exp2(x) has overflowed. The value x< −1022
implies exp(x) has underflowed.
10263
10264
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
10265
10266
RATIONALE
None.
10267
10268
FUTURE DIRECTIONS
None.
10269
10270
10271
10272
SEE ALSO
exp( ), feclearexcept( ), fetestexcept( ), isnan( ), log( ), the Base Definitions volume of
IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions,
<math.h>
10273
10274
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
313
expm1( )
System Interfaces
10275
10276
NAME
10277
10278
SYNOPSIS
#include <math.h>
expm1, expm1f, expm1l — compute exponential functions
double expm1(double x);
float expm1f(float x);
long double expm1l(long double x);
10279
10280
10281
10282 DESCRIPTION
10283 CX
The functionality described on this reference page is aligned with the ISO C standard.
10284
conflict between the requirements described here and the ISO C standard is unintentional.
10285
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
x
10286
These functions shall compute e −1.0.
10287
10288
10289
10290
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
10291
10292
RETURN VALUE
Upon successful completion, these functions return ex−1.0.
10293
10294
10295
If the correct value would cause overflow, a range error shall occur and expm1( ), expm1f( ), and
expm1l( ) shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL,
respectively.
10296 MX
If x is NaN, a NaN shall be returned.
10297
If x is ±0, ±0 shall be returned.
10298
If x is −Inf, −1 shall be returned.
10299
If x is +Inf, x shall be returned.
10300
If x is subnormal, a range error may occur and x should be returned.
10301
10302
ERRORS
These functions shall fail if:
Range Error
10303
The result overflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow
floating-point exception shall be raised.
10304
10305
10306
10307
10308
These functions may fail if:
10309 MX
Range Error
The value of x is subnormal.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
10310
10311
10312
10313
314
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
expm1( )
System Interfaces
10314
10315
EXAMPLES
None.
10316
10317
APPLICATION USAGE
The value of expm1(x) may be more accurate than exp(x)−1.0 for small values of x.
n
10318
The expm1( ) and log1p ( ) functions are useful for financial calculations of ((1+x) −1)/x, namely:
10319
expm1(n * log1p(x))/x
10320
10321
when x is very small (for example, when calculating small daily interest rates). These functions
also simplify writing accurate inverse hyperbolic functions.
10322
For IEEE Std 754-1985 double, 709.8 < x implies expm1(x) has overflowed.
10323
10324
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
10325
10326
RATIONALE
None.
10327
10328
FUTURE DIRECTIONS
None.
10329
10330
10331
10332
SEE ALSO
exp( ), feclearexcept( ), fetestexcept( ), ilogb ( ), log1p ( ), the Base Definitions volume of
IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions,
<math.h>
10333
10334
CHANGE HISTORY
First released in Issue 4, Version 2.
10335
10336
Issue 5
10337
10338
10339
Issue 6
Moved from X/OPEN UNIX extension to BASE.
The expm1f( ) and expm1l( ) functions are added for alignment with the ISO/IEC 9899: 1999
standard.
10340
The expm1( ) function is no longer marked as an extension.
10341
10342
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
10343
10344
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
315
fabs( )
System Interfaces
10345
10346
NAME
10347
10348
SYNOPSIS
#include <math.h>
fabs, fabsf, fabsl — absolute value function
double fabs(double x);
float fabsf(float x);
long double fabsl(long double x);
10349
10350
10351
10352 DESCRIPTION
10353 CX
The functionality described on this reference page is aligned with the ISO C standard.
10354
conflict between the requirements described here and the ISO C standard is unintentional.
10355
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
These functions shall compute the absolute value of their argument x,|x|.
10356
10357
10358
Any
This
RETURN VALUE
Upon successful completion, these functions shall return the absolute value of x.
10359 MX
If x is NaN, a NaN shall be returned.
10360
If x is ±0, +0 shall be returned.
10361
If x is ±Inf, +Inf shall be returned.
10362
10363
ERRORS
No errors are defined.
10364
10365
EXAMPLES
None.
10366
10367
APPLICATION USAGE
None.
10368
10369
RATIONALE
None.
10370
10371
FUTURE DIRECTIONS
None.
10372
10373
SEE ALSO
isnan( ), the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>
10374
10375
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
10376
10377
10378
Issue 5
10379
10380
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The fabsf( ) and fabsl( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
10381
10382
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
10383
10384
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
316
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fattach( )
System Interfaces
10385
10386
10387
NAME
fattach — attach a STREAMS-based file descriptor to a file in the file system name space
(STREAMS)
10388 SYNOPSIS
10389 XSR
#include
10390
10391
<stropts.h>
int fattach(int fildes, const char *path);
10392
10393
10394
10395
10396
10397
10398
10399
10400
DESCRIPTION
The fattach ( ) function shall attach a STREAMS-based file descriptor to a file, effectively
associating a pathname with fildes. The application shall ensure that the fildes argument is a
valid open file descriptor associated with a STREAMS file. The path argument points to a
pathname of an existing file. The application shall have the appropriate privileges or be the
owner of the file named by path and have write permission. A successful call to fattach ( ) shall
cause all pathnames that name the file named by path to name the STREAMS file associated with
fildes, until the STREAMS file is detached from the file. A STREAMS file can be attached to more
than one file and can have several pathnames associated with it.
10401
10402
10403
10404
10405
10406
The attributes of the named STREAMS file shall be initialized as follows: the permissions, user
ID, group ID, and times are set to those of the file named by path, the number of links is set to 1,
and the size and device identifier are set to those of the STREAMS file associated with fildes. If
any attributes of the named STREAMS file are subsequently changed (for example, by chmod( )),
neither the attributes of the underlying file nor the attributes of the STREAMS file to which fildes
refers shall be affected.
10407
10408
File descriptors referring to the underlying file, opened prior to an fattach ( ) call, shall continue to
refer to the underlying file.
10409
10410
10411
RETURN VALUE
Upon successful completion, fattach ( ) shall return 0. Otherwise, −1 shall be returned and errno
set to indicate the error.
10412
10413
ERRORS
The fattach ( ) function shall fail if:
10414
10415
10416
[EACCES]
Search permission is denied for a component of the path prefix, or the process
is the owner of path but does not have write permissions on the file named by
path.
10417
[EBADF]
The fildes argument is not a valid open file descriptor.
10418
10419
[EBUSY]
The file named by path is currently a mount point or has a STREAMS file
attached to it.
10420
10421
[ELOOP]
A loop exists in symbolic links encountered during resolution of the path
argument.
10422
10423
10424
[ENAMETOOLONG]
The size of path exceeds {PATH_MAX} or a component of path is longer than
{NAME_MAX}.
10425
[ENOENT]
A component of path does not name an existing file or path is an empty string.
10426
[ENOTDIR]
A component of the path prefix is not a directory.
10427
10428
[EPERM]
The effective user ID of the process is not the owner of the file named by path
and the process does not have appropriate privilege.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
317
fattach( )
System Interfaces
10429
The fattach ( ) function may fail if:
10430
[EINVAL]
The fildes argument does not refer to a STREAMS file.
10431
10432
[ELOOP]
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path argument.
10433
10434
10435
[ENAMETOOLONG]
Pathname resolution of a symbolic link produced an intermediate result
whose length exceeds {PATH_MAX}.
10436
[EXDEV]
10437
A link to a file on another file system was attempted.
EXAMPLES
10438
Attaching a File Descriptor to a File
10439
10440
10441
10442
In the following example, fd refers to an open STREAMS file. The call to fattach ( ) associates this
STREAM with the file /tmp/named-STREAM, such that any future calls to open /tmp/namedSTREAM, prior to breaking the attachment via a call to fdetach ( ), will instead create a new file
handle referring to the STREAMS file associated with fd.
10443
10444
10445
10446
10447
#include <stropts.h>
...
int fd;
char *filename = "/tmp/named-STREAM";
int ret;
ret = fattach(fd, filename);
10448
10449
10450
10451
10452
APPLICATION USAGE
The fattach ( ) function behaves similarly to the traditional mount( ) function in the way a file is
temporarily replaced by the root directory of the mounted file system. In the case of fattach ( ), the
replaced file need not be a directory and the replacing file is a STREAMS file.
10453
10454
10455
10456
10457
10458
10459
RATIONALE
The file attributes of a file which has been the subject of an fattach ( ) call are specifically set
because of an artefact of the original implementation. The internal mechanism was the same as
for the mount( ) function. Since mount( ) is typically only applied to directories, the effects when
applied to a regular file are a little surprising, especially as regards the link count which rigidly
remains one, even if there were several links originally and despite the fact that all original links
refer to the STREAM as long as the fattach ( ) remains in effect.
10460
10461
FUTURE DIRECTIONS
None.
10462
10463
SEE ALSO
fdetach ( ), isastream( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stropts.h>
10464
10465
CHANGE HISTORY
First released in Issue 4, Version 2.
10466
10467
Issue 5
Moved from X/OPEN UNIX extension to BASE.
The [EXDEV] error is added to the list of optional errors in the ERRORS section.
10468
318
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
10469
10470
fattach( )
Issue 6
This function is marked as part of the XSI STREAMS Option Group.
10471
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
10472
10473
The wording of the mandatory [ELOOP] error condition is updated, and a second optional
[ELOOP] error condition is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
319
fchdir( )
10474
10475
System Interfaces
NAME
fchdir — change working directory
10476 SYNOPSIS
10477 XSI
#include
<unistd.h>
int fchdir(int fildes);
10478
10479
10480
10481
10482
DESCRIPTION
The fchdir( ) function shall be equivalent to chdir( ) except that the directory that is to be the new
current working directory is specified by the file descriptor fildes.
10483
10484
A conforming application can obtain a file descriptor for a file of type directory using open( ),
provided that the file status flags and access modes do not contain O_WRONLY or O_RDWR.
10485
10486
10487
RETURN VALUE
Upon successful completion, fchdir( ) shall return 0. Otherwise, it shall return −1 and set errno to
indicate the error. On failure the current working directory shall remain unchanged.
10488
10489
ERRORS
The fchdir( ) function shall fail if:
10490
[EACCES]
Search permission is denied for the directory referenced by fildes.
10491
[EBADF]
The fildes argument is not an open file descriptor.
10492
[ENOTDIR]
The open file descriptor fildes does not refer to a directory.
10493
The fchdir( ) may fail if:
10494
[EINTR]
A signal was caught during the execution of fchdir( ).
10495
[EIO]
An I/O error occurred while reading from or writing to the file system.
10496
10497
EXAMPLES
None.
10498
10499
APPLICATION USAGE
None.
10500
10501
RATIONALE
None.
10502
10503
FUTURE DIRECTIONS
None.
10504
10505
SEE ALSO
chdir( ), the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>
10506
10507
CHANGE HISTORY
First released in Issue 4, Version 2.
10508
10509
Issue 5
Moved from X/OPEN UNIX extension to BASE.
320
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fchmod( )
System Interfaces
10510
10511
NAME
10512
10513
SYNOPSIS
#include <sys/stat.h>
fchmod — change mode of a file
int fchmod(int fildes, mode_t mode);
10514
10515
10516
10517
DESCRIPTION
The fchmod( ) function shall be equivalent to chmod( ) except that the file whose permissions are
changed is specified by the file descriptor fildes.
10518 SHM
10519
If fildes references a shared memory object, the fchmod( ) function need only affect the S_IRUSR,
S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH file permission bits.
10520 TYM
If fildes references a typed memory object, the behavior of fchmod( ) is unspecified.
10521
If fildes refers to a socket, the behavior of fchmod( ) is unspecified.
10522 XSR
10523
If fildes refers to a STREAM (which is fattach ( )-ed into the file system name space) the call
returns successfully, doing nothing.
10524
10525
10526
RETURN VALUE
Upon successful completion, fchmod( ) shall return 0. Otherwise, it shall return −1 and set errno to
indicate the error.
10527
10528
ERRORS
The fchmod( ) function shall fail if:
10529
[EBADF]
The fildes argument is not an open file descriptor.
10530
10531
[EPERM]
The effective user ID does not match the owner of the file and the process
does not have appropriate privilege.
10532
[EROFS]
The file referred to by fildes resides on a read-only file system.
10533
The fchmod( ) function may fail if:
10534 XSI
[EINTR]
The fchmod( ) function was interrupted by a signal.
10535 XSI
[EINVAL]
The value of the mode argument is invalid.
10536
10537
[EINVAL]
The fildes argument refers to a pipe and the implementation disallows
execution of fchmod( ) on a pipe.
10538
EXAMPLES
10539
Changing the Current Permissions for a File
10540
10541
10542
The following example shows how to change the permissions for a file named /home/cnd/mod1
so that the owner and group have read/write/execute permissions, but the world only has
read/write permissions.
10543
10544
#include <sys/stat.h>
#include <fcntl.h>
10545
10546
10547
10548
mode_t mode;
int
fildes;
...
fildes = open("/home/cnd/mod1", O_RDWR);
fchmod(fildes, S_IRWXU | S_IRWXG | S_IROTH | S_IWOTH);
10549
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
321
fchmod( )
System Interfaces
10550
10551
APPLICATION USAGE
None.
10552
10553
RATIONALE
None.
10554
10555
FUTURE DIRECTIONS
None.
10556
10557
10558
SEE ALSO
chmod( ), chown( ), creat( ), fcntl( ), fstatvfs ( ), mknod( ), open( ), read( ), stat( ), write( ), the Base
Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>
10559
10560
CHANGE HISTORY
First released in Issue 4, Version 2.
10561
10562
10563
10564
Issue 5
10565
10566
10567
Issue 6
Moved from X/OPEN UNIX extension to BASE and aligned with fchmod( ) in the POSIX
Realtime Extension. Specifically, the second paragraph of the DESCRIPTION is added and a
second instance of [EINVAL] is defined in the list of optional errors.
The DESCRIPTION is updated for alignment with IEEE Std 1003.1j-2000 by stating that fchmod( )
behavior is unspecified for typed memory objects.
322
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fchown( )
System Interfaces
10568
10569
NAME
10570
10571
SYNOPSIS
#include <unistd.h>
fchown — change owner and group of a file
int fchown(int fildes, uid_t owner, gid_t group);
10572
10573
10574
10575
DESCRIPTION
The fchown( ) function shall be equivalent to chown( ) except that the file whose owner and group
are changed is specified by the file descriptor fildes.
10576
10577
10578
RETURN VALUE
Upon successful completion, fchown( ) shall return 0. Otherwise, it shall return −1 and set errno to
indicate the error.
10579
10580
ERRORS
The fchown( ) function shall fail if:
10581
[EBADF]
The fildes argument is not an open file descriptor.
10582
10583
10584
[EPERM]
The effective user ID does not match the owner of the file or the process does
not have appropriate privilege and _POSIX_CHOWN_RESTRICTED indicates
that such privilege is required.
10585
[EROFS]
The file referred to by fildes resides on a read-only file system.
10586
The fchown( ) function may fail if:
10587
10588 XSR
10589
[EINVAL]
The owner or group ID is not a value supported by the implementation. The
fildes argument refers to a pipe or socket or an fattach ( )-ed STREAM and the
implementation disallows execution of fchown( ) on a pipe.
10590
[EIO]
A physical I/O error has occurred.
10591
[EINTR]
The fchown( ) function was interrupted by a signal which was caught.
10592
EXAMPLES
10593
Changing the Current Owner of a File
10594
10595
The following example shows how to change the owner of a file named /home/cnd/mod1 to
‘‘jones’’ and the group to ‘‘cnd’’.
10596
10597
10598
10599
The numeric value for the user ID is obtained by extracting the user ID from the user database
entry associated with ‘‘jones’’. Similarly, the numeric value for the group ID is obtained by
extracting the group ID from the group database entry associated with ‘‘cnd’’. This example
assumes the calling program has appropriate privileges.
10600
10601
10602
10603
10604
#include
#include
#include
#include
#include
10605
10606
10607
struct passwd *pwd;
struct group *grp;
int
fildes;
...
fildes = open("/home/cnd/mod1", O_RDWR);
pwd = getpwnam("jones");
10608
10609
10610
<sys/types.h>
<unistd.h>
<fcntl.h>
<pwd.h>
<grp.h>
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
323
fchown( )
System Interfaces
grp = getgrnam("cnd");
fchown(fildes, pwd->pw_uid, grp->gr_gid);
10611
10612
10613
10614
APPLICATION USAGE
None.
10615
10616
RATIONALE
None.
10617
10618
FUTURE DIRECTIONS
None.
10619
10620
SEE ALSO
chown( ), the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>
10621
10622
CHANGE HISTORY
First released in Issue 4, Version 2.
10623
10624
Issue 5
10625
10626
Issue 6
Moved from X/OPEN UNIX extension to BASE.
The following changes were made to align with the IEEE P1003.1a draft standard:
•
10627
Clarification is added that a call to fchown( ) may not be allowed on a pipe.
The fchown( ) function is now defined as mandatory.
10628
324
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fclose( )
System Interfaces
10629
10630
NAME
10631
10632
SYNOPSIS
#include <stdio.h>
fclose — close a stream
int fclose(FILE *stream);
10633
10634 DESCRIPTION
10635 CX
The functionality described on this reference page is aligned with the ISO C standard.
10636
conflict between the requirements described here and the ISO C standard is unintentional.
10637
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
10638
10639
10640
10641
10642
10643
The fclose( ) function shall cause the stream pointed to by stream to be flushed and the associated
file to be closed. Any unwritten buffered data for the stream shall be written to the file; any
unread buffered data shall be discarded. Whether or not the call succeeds, the stream shall be
disassociated from the file and any buffer set by the setbuf( ) or setvbuf( ) function shall be
disassociated from the stream. If the associated buffer was automatically allocated, it shall be
deallocated.
10644 CX
10645
10646
10647
The fclose( ) function shall mark for update the st_ctime and st_mtime fields of the underlying file,
if the stream was writable, and if buffered data remains that has not yet been written to the file.
The fclose( ) function shall perform the equivalent of a close( ) on the file descriptor that is
associated with the stream pointed to by stream.
10648
After the call to fclose( ), any use of stream results in undefined behavior.
10649 RETURN VALUE
10650 CX
Upon successful completion,
10651
indicate the error.
10652
10653
fclose( ) shall return 0; otherwise, it shall return EOF and set errno to
ERRORS
The fclose( ) function shall fail if:
10654 CX
10655
[EAGAIN]
The O_NONBLOCK flag is set for the file descriptor underlying stream and the
process would be delayed in the write operation.
10656 CX
[EBADF]
The file descriptor underlying stream is not valid.
10657 CX
[EFBIG]
An attempt was made to write a file that exceeds the maximum file size.
10658 XSI
[EFBIG]
An attempt was made to write a file that exceeds the process’ file size limit.
10659 CX
10660
[EFBIG]
The file is a regular file and an attempt was made to write at or beyond the
offset maximum associated with the corresponding stream.
10661 CX
[EINTR]
The fclose( ) function was interrupted by a signal.
10662 CX
10663
10664
10665
[EIO]
The process is a member of a background process group attempting to write
to its controlling terminal, TOSTOP is set, the process is neither ignoring nor
blocking SIGTTOU, and the process group of the process is orphaned. This
error may also be returned under implementation-defined conditions.
10666 CX
[ENOSPC]
There was no free space remaining on the device containing the file.
10667 CX
10668
[EPIPE]
An attempt is made to write to a pipe or FIFO that is not open for reading by
any process. A SIGPIPE signal shall also be sent to the thread.
10669
The fclose( ) function may fail if:
10670 CX
10671
[ENXIO]
A request was made of a nonexistent device, or the request was outside the
capabilities of the device.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
325
fclose( )
System Interfaces
10672
10673
EXAMPLES
None.
10674
10675
APPLICATION USAGE
None.
10676
10677
RATIONALE
None.
10678
10679
FUTURE DIRECTIONS
None.
10680
10681
10682
SEE ALSO
close( ), fopen( ), getrlimit( ), ulimit( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<stdio.h>
10683
10684
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
10685
10686
Issue 5
10687
10688
Issue 6
Large File Summit extensions are added.
Extensions beyond the ISO C standard are marked.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
10689
10690
10691
•
The [EFBIG] error is added as part of the large file support extensions.
10692
•
The [ENXIO] optional error condition is added.
The DESCRIPTION is updated to note that the stream and any buffer are disassociated whether
or not the call succeeds. This is for alignment with the ISO/IEC 9899: 1999 standard.
10693
10694
326
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fcntl( )
System Interfaces
10695
10696
NAME
fcntl — file control
10697 SYNOPSIS
10698 OH
#include
10699
#include
10700
10701
10702
10703
<unistd.h>
<fcntl.h>
int fcntl(int fildes, int cmd, ...);
DESCRIPTION
The fcntl( ) function shall perform the operations described below on open files. The fildes
argument is a file descriptor.
10704
The available values for cmd are defined in <fcntl.h> and are as follows:
10705
10706
10707
10708
10709
10710
10711
F_DUPFD
Return a new file descriptor which shall be the lowest numbered available
(that is, not already open) file descriptor greater than or equal to the third
argument, arg, taken as an integer of type int. The new file descriptor shall
refer to the same open file description as the original file descriptor, and shall
share any locks. The FD_CLOEXEC flag associated with the new file
descriptor shall be cleared to keep the file open across calls to one of the exec
functions.
10712
10713
10714
F_GETFD
Get the file descriptor flags defined in <fcntl.h> that are associated with the
file descriptor fildes. File descriptor flags are associated with a single file
descriptor and do not affect other file descriptors that refer to the same file.
10715
10716
10717
10718
10719
F_SETFD
Set the file descriptor flags defined in <fcntl.h>, that are associated with fildes,
to the third argument, arg, taken as type int. If the FD_CLOEXEC flag in the
third argument is 0, the file shall remain open across the exec functions;
otherwise, the file shall be closed upon successful execution of one of the exec
functions.
10720
10721
10722
10723
10724
10725
F_GETFL
Get the file status flags and file access modes, defined in <fcntl.h>, for the file
description associated with fildes. The file access modes can be extracted from
the return value using the mask O_ACCMODE, which is defined in <fcntl.h>.
File status flags and file access modes are associated with the file description
and do not affect other file descriptors that refer to the same file with different
open file descriptions.
10726
10727
10728
10729
10730
10731
F_SETFL
Set the file status flags, defined in <fcntl.h>, for the file description associated
with fildes from the corresponding bits in the third argument, arg, taken as
type int. Bits corresponding to the file access mode and the file creation flags,
as defined in <fcntl.h>, that are set in arg shall be ignored. If any bits in arg
other than those mentioned here are changed by the application, the result is
unspecified.
10732
10733
10734
10735
F_GETOWN
If fildes refers to a socket, get the process or process group ID specified to
receive SIGURG signals when out-of-band data is available. Positive values
indicate a process ID; negative values, other than −1, indicate a process group
ID. If fildes does not refer to a socket, the results are unspecified.
10736
10737
10738
F_SETOWN
If fildes refers to a socket, set the process or process group ID specified to
receive SIGURG signals when out-of-band data is available, using the value of
the third argument, arg, taken as type int. Positive values indicate a process
ID; negative values, other than −1, indicate a process group ID. If fildes does
not refer to a socket, the results are unspecified.
10739
10740
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
327
fcntl( )
System Interfaces
10741
10742
The following values for cmd are available for advisory record locking. Record locking shall be
supported for regular files, and may be supported for other files.
10743
10744
10745
10746
10747
10748
F_GETLK
Get the first lock which blocks the lock description pointed to by the third
argument, arg, taken as a pointer to type struct flock, defined in <fcntl.h>.
The information retrieved shall overwrite the information passed to fcntl( ) in
the structure flock. If no lock is found that would prevent this lock from
being created, then the structure shall be left unchanged except for the lock
type which shall be set to F_UNLCK.
10749
10750
10751
10752
10753
10754
10755
F_SETLK
Set or clear a file segment lock according to the lock description pointed to by
the third argument, arg, taken as a pointer to type struct flock, defined in
<fcntl.h>. F_SETLK can establish shared (or read) locks (F_RDLCK) or
exclusive (or write) locks (F_WRLCK), as well as to remove either type of lock
(F_UNLCK). F_RDLCK, F_WRLCK, and F_UNLCK are defined in <fcntl.h>.
If a shared or exclusive lock cannot be set, fcntl( ) shall return immediately
with a return value of −1.
10756
10757
10758
10759
10760
10761
F_SETLKW
This command shall be equivalent to F_SETLK except that if a shared or
exclusive lock is blocked by other locks, the thread shall wait until the request
can be satisfied. If a signal that is to be caught is received while fcntl( ) is
waiting for a region, fcntl( ) shall be interrupted. Upon return from the signal
handler, fcntl( ) shall return −1 with errno set to [EINTR], and the lock
operation shall not be done.
10762
10763
Additional implementation-defined values for cmd may be defined in <fcntl.h>. Their names
shall start with F_.
10764
10765
10766
10767
When a shared lock is set on a segment of a file, other processes shall be able to set shared locks
on that segment or a portion of it. A shared lock prevents any other process from setting an
exclusive lock on any portion of the protected area. A request for a shared lock shall fail if the
file descriptor was not opened with read access.
10768
10769
10770
An exclusive lock shall prevent any other process from setting a shared lock or an exclusive lock
on any portion of the protected area. A request for an exclusive lock shall fail if the file
descriptor was not opened with write access.
10771
10772
The structure flock describes the type (l_type), starting offset (l_whence), relative offset (l_start),
size (l_len), and process ID (l_pid ) of the segment of the file to be affected.
10773
10774
10775
10776
10777
10778
10779
The value of l_whence is SEEK_SET, SEEK_CUR, or SEEK_END, to indicate that the relative
offset l_start bytes shall be measured from the start of the file, current position, or end of the file,
respectively. The value of l_len is the number of consecutive bytes to be locked. The value of
l_len may be negative (where the definition of off_t permits negative values of l_len). The l_pid
field is only used with F_GETLK to return the process ID of the process holding a blocking lock.
After a successful F_GETLK request, when a blocking lock is found, the values returned in the
flock structure shall be as follows:
10780
l_type
Type of blocking lock found.
10781
l_whence
SEEK_SET.
10782
l_start
Start of the blocking lock.
10783
l_len
Length of the blocking lock.
10784
l_pid
Process ID of the process that holds the blocking lock.
328
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fcntl( )
System Interfaces
10785
10786
10787
10788
If the command is F_SETLKW and the process must wait for another process to release a lock,
then the range of bytes to be locked shall be determined before the fcntl( ) function blocks. If the
file size or file descriptor seek offset change while fcntl( ) is blocked, this shall not affect the
range of bytes locked.
10789
10790
10791
10792
10793
10794
If l_len is positive, the area affected shall start at l_start and end at l_start+l_len−1. If l_len is
negative, the area affected shall start at l_start+l_len and end at l_start−1. Locks may start and
extend beyond the current end of a file, but shall not extend before the beginning of the file. A
lock shall be set to extend to the largest possible value of the file offset for that file by setting
l_len to 0. If such a lock also has l_start set to 0 and l_whence is set to SEEK_SET, the whole file
shall be locked.
10795
10796
10797
10798
10799
10800
10801
There shall be at most one type of lock set for each byte in the file. Before a successful return
from an F_SETLK or an F_SETLKW request when the calling process has previously existing
locks on bytes in the region specified by the request, the previous lock type for each byte in the
specified region shall be replaced by the new lock type. As specified above under the
descriptions of shared locks and exclusive locks, an F_SETLK or an F_SETLKW request
(respectively) shall fail or block when another process has existing locks on bytes in the specified
region and the type of any of those locks conflicts with the type specified in the request.
10802
10803
10804
All locks associated with a file for a given process shall be removed when a file descriptor for
that file is closed by that process or the process holding that file descriptor terminates. Locks are
not inherited by a child process.
10805
10806
10807
A potential for deadlock occurs if a process controlling a locked region is put to sleep by
attempting to lock another process’ locked region. If the system detects that sleeping until a
locked region is unlocked would cause a deadlock, fcntl( ) shall fail with an [EDEADLK] error.
10808
10809
10810
10811
10812
An unlock (F_UNLCK) request in which l_len is non-zero and the offset of the last byte of the
requested segment is the maximum value for an object of type off_t, when the process has an
existing lock in which l_len is 0 and which includes the last byte of the requested segment, shall
be treated as a request to unlock from the start of the requested segment with an l_len equal to 0.
Otherwise, an unlock (F_UNLCK) request shall attempt to unlock only the requested segment.
10813 SHM
10814
10815
When the file descriptor fildes refers to a shared memory object, the behavior of fcntl( ) shall be
the same as for a regular file except the effect of the following values for the argument cmd shall
be unspecified: F_SETFL, F_GETLK, F_SETLK, and F_SETLKW.
10816 TYM
If fildes refers to a typed memory object, the result of the fcntl( ) function is unspecified.
10817
10818
RETURN VALUE
Upon successful completion, the value returned shall depend on cmd as follows:
10819
F_DUPFD
A new file descriptor.
10820
F_GETFD
Value of flags defined in <fcntl.h>. The return value shall not be negative.
10821
F_SETFD
Value other than −1.
10822
F_GETFL
Value of file status flags and access modes. The return value is not negative.
10823
F_SETFL
Value other than −1.
10824
F_GETLK
Value other than −1.
10825
F_SETLK
Value other than −1.
10826
F_SETLKW
Value other than −1.
10827
F_GETOWN
Value of the socket owner process or process group; this will not be −1.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
329
fcntl( )
System Interfaces
Value other than −1.
10828
F_SETOWN
10829
Otherwise, −1 shall be returned and errno set to indicate the error.
10830
10831
ERRORS
The fcntl( ) function shall fail if:
10832
10833
10834
10835
10836
10837
[EACCES] or [EAGAIN]
The cmd argument is F_SETLK; the type of lock (l_type) is a shared (F_RDLCK)
or exclusive (F_WRLCK) lock and the segment of a file to be locked is already
exclusive-locked by another process, or the type is an exclusive lock and some
portion of the segment of a file to be locked is already shared-locked or
exclusive-locked by another process.
10838
10839
10840
10841
10842
[EBADF]
The fildes argument is not a valid open file descriptor, or the argument cmd is
F_SETLK or F_SETLKW, the type of lock, l_type, is a shared lock (F_RDLCK),
and fildes is not a valid file descriptor open for reading, or the type of lock,
l_type, is an exclusive lock (F_WRLCK), and fildes is not a valid file descriptor
open for writing.
10843
[EINTR]
The cmd argument is F_SETLKW and the function was interrupted by a signal.
10844
10845
10846
10847
[EINVAL]
The cmd argument is invalid, or the cmd argument is F_DUPFD and arg is
negative or greater than or equal to {OPEN_MAX}, or the cmd argument is
F_GETLK, F_SETLK, or F_SETLKW and the data pointed to by arg is not valid,
or fildes refers to a file that does not support locking.
10848
10849
10850
[EMFILE]
The argument cmd is F_DUPFD and {OPEN_MAX} file descriptors are
currently open in the calling process, or no file descriptors greater than or
equal to arg are available.
10851
10852
10853
[ENOLCK]
The argument cmd is F_SETLK or F_SETLKW and satisfying the lock or unlock
request would result in the number of locked regions in the system exceeding
a system-imposed limit.
10854
[EOVERFLOW]
One of the values to be returned cannot be represented correctly.
10855
10856
10857
[EOVERFLOW]
The cmd argument is F_GETLK, F_SETLK, or F_SETLKW and the smallest or,
if l_len is non-zero, the largest offset of any byte in the requested segment
cannot be represented correctly in an object of type off_t.
10858
The fcntl( ) function may fail if:
10859
10860
10861
[EDEADLK]
The cmd argument is F_SETLKW, the lock is blocked by a lock from another
process, and putting the calling process to sleep to wait for that lock to
become free would cause a deadlock.
10862
10863
EXAMPLES
None.
10864
10865
APPLICATION USAGE
None.
10866
10867
10868
10869
RATIONALE
The ellipsis in the SYNOPSIS is the syntax specified by the ISO C standard for a variable number
of arguments. It is used because System V uses pointers for the implementation of file locking
functions.
10870
10871
The arg values to F_GETFD, F_SETFD, F_GETFL, and F_SETFL all represent flag values to allow
for future growth. Applications using these functions should do a read-modify-write operation
330
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fcntl( )
10872
10873
10874
on them, rather than assuming that only the values defined by this volume of
IEEE Std 1003.1-2001 are valid. It is a common error to forget this, particularly in the case of
F_SETFD.
10875
10876
10877
10878
This volume of IEEE Std 1003.1-2001 permits concurrent read and write access to file data using
the fcntl( ) function; this is a change from the 1984 /usr/group standard and early proposals.
Without concurrency controls, this feature may not be fully utilized without occasional loss of
data.
10879
10880
10881
10882
10883
10884
10885
Data losses occur in several ways. One case occurs when several processes try to update the
same record, without sequencing controls; several updates may occur in parallel and the last
writer ‘‘wins’’. Another case is a bit-tree or other internal list-based database that is undergoing
reorganization. Without exclusive use to the tree segment by the updating process, other reading
processes chance getting lost in the database when the index blocks are split, condensed,
inserted, or deleted. While fcntl( ) is useful for many applications, it is not intended to be overly
general and does not handle the bit-tree example well.
10886
10887
This facility is only required for regular files because it is not appropriate for many devices such
as terminals and network connections.
10888
10889
10890
Since fcntl( ) works with ‘‘any file descriptor associated with that file, however it is obtained’’,
the file descriptor may have been inherited through a fork ( ) or exec operation and thus may
affect a file that another process also has open.
10891
10892
10893
10894
The use of the open file description to identify what to lock requires extra calls and presents
problems if several processes are sharing an open file description, but there are too many
implementations of the existing mechanism for this volume of IEEE Std 1003.1-2001 to use
different specifications.
10895
10896
10897
10898
10899
10900
Another consequence of this model is that closing any file descriptor for a given file (whether or
not it is the same open file description that created the lock) causes the locks on that file to be
relinquished for that process. Equivalently, any close for any file/process pair relinquishes the
locks owned on that file for that process. But note that while an open file description may be
shared through fork ( ), locks are not inherited through fork ( ). Yet locks may be inherited through
one of the exec functions.
10901
10902
10903
The identification of a machine in a network environment is outside the scope of this volume of
IEEE Std 1003.1-2001. Thus, an l_sysid member, such as found in System V, is not included in the
locking structure.
10904
Changing of lock types can result in a previously locked region being split into smaller regions.
10905
Mandatory locking was a major feature of the 1984 /usr/group standard.
10906
10907
10908
10909
10910
10911
10912
For advisory file record locking to be effective, all processes that have access to a file must
cooperate and use the advisory mechanism before doing I/O on the file. Enforcement-mode
record locking is important when it cannot be assumed that all processes are cooperating. For
example, if one user uses an editor to update a file at the same time that a second user executes
another process that updates the same file and if only one of the two processes is using advisory
locking, the processes are not cooperating. Enforcement-mode record locking would protect
against accidental collisions.
10913
10914
10915
Secondly, advisory record locking requires a process using locking to bracket each I/O operation
with lock (or test) and unlock operations. With enforcement-mode file and record locking, a
process can lock the file once and unlock when all I/O operations have been completed.
Enforcement-mode record locking provides a base that can be enhanced; for example, with
sharable locks. That is, the mechanism could be enhanced to allow a process to lock a file so
other processes could read it, but none of them could write it.
10916
10917
10918
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
331
fcntl( )
System Interfaces
Mandatory locks were omitted for several reasons:
10919
10920
10921
1. Mandatory lock setting was done by multiplexing the set-group-ID bit in most
implementations; this was confusing, at best.
10922
2. The relationship to file truncation as supported in 4.2 BSD was not well specified.
10923
10924
10925
3. Any publicly readable file could be locked by anyone. Many historical implementations
keep the password database in a publicly readable file. A malicious user could thus
prohibit logins. Another possibility would be to hold open a long-distance telephone line.
10926
10927
4. Some demand-paged historical implementations offer memory mapped files, and
enforcement cannot be done on that type of file.
10928
10929
10930
10931
Since sleeping on a region is interrupted with any signal, alarm( ) may be used to provide a
timeout facility in applications requiring it. This is useful in deadlock detection. Since
implementation of full deadlock detection is not always feasible, the [EDEADLK] error was
made optional.
10932
10933
FUTURE DIRECTIONS
None.
10934
10935
10936
SEE ALSO
alarm( ), close( ), exec, open( ), sigaction ( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<fcntl.h>, <signal.h>, <unistd.h>
10937
10938
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
10939
10940
10941
Issue 5
The DESCRIPTION is updated for alignment with the POSIX Realtime Extension and the POSIX
Threads Extension.
Large File Summit extensions are added.
10942
10943
10944
Issue 6
In the SYNOPSIS, the optional include of the <sys/types.h> header is removed.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
10945
10946
10947
10948
10949
•
The requirement to include <sys/types.h> has been removed. Although <sys/types.h> was
required for conforming implementations of previous POSIX specifications, it was not
required for UNIX applications.
10950
10951
10952
•
In the DESCRIPTION, sentences describing behavior when l_len is negative are now
mandated, and the description of unlock (F_UNLOCK) when l_len is non-negative is
mandated.
10953
10954
•
In the ERRORS section, the [EINVAL] error condition has the case mandated when the cmd is
invalid, and two [EOVERFLOW] error conditions are added.
10955
The F_GETOWN and F_SETOWN values are added for sockets.
10956
The following changes were made to align with the IEEE P1003.1a draft standard:
•
10957
10958
Clarification is added that the extent of the bytes locked is determined prior to the blocking
action.
The DESCRIPTION is updated for alignment with IEEE Std 1003.1j-2000 by specifying that
fcntl( ) results are unspecified for typed memory objects.
10959
10960
332
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
10961
fcntl( )
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
333
fcvt( )
10962
10963
System Interfaces
NAME
fcvt — convert a floating-point number to a string (LEGACY)
10964 SYNOPSIS
10965 XSI
#include
char *fcvt(double value, int ndigit, int *restrict decpt,
int *restrict sign);
10966
10967
10968
10969
10970
<stdlib.h>
DESCRIPTION
Refer to ecvt( ).
334
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fdatasync( )
System Interfaces
10971
10972
NAME
fdatasync — synchronize the data of a file (REALTIME)
10973 SYNOPSIS
10974 SIO
#include
<unistd.h>
int fdatasync(int fildes);
10975
10976
10977
10978
10979
DESCRIPTION
The fdatasync ( ) function shall force all currently queued I/O operations associated with the file
indicated by file descriptor fildes to the synchronized I/O completion state.
10980
10981
10982
The functionality shall be equivalent to fsync( ) with the symbol _POSIX_SYNCHRONIZED_IO
defined, with the exception that all I/O operations shall be completed as defined for
synchronized I/O data integrity completion.
10983
10984
10985
10986
RETURN VALUE
If successful, the fdatasync ( ) function shall return the value 0; otherwise, the function shall return
the value −1 and set errno to indicate the error. If the fdatasync ( ) function fails, outstanding I/O
operations are not guaranteed to have been completed.
10987
10988
ERRORS
The fdatasync ( ) function shall fail if:
10989
[EBADF]
The fildes argument is not a valid file descriptor open for writing.
10990
[EINVAL]
This implementation does not support synchronized I/O for this file.
10991
10992
In the event that any of the queued I/O operations fail, fdatasync ( ) shall return the error
conditions defined for read( ) and write( ).
10993
10994
EXAMPLES
None.
10995
10996
APPLICATION USAGE
None.
10997
10998
RATIONALE
None.
10999
11000
FUTURE DIRECTIONS
None.
11001
11002
11003
SEE ALSO
aio_fsync ( ), fcntl( ), fsync( ), open( ), read( ), write( ), the Base Definitions volume
IEEE Std 1003.1-2001, <unistd.h>
11004
11005
CHANGE HISTORY
First released in Issue 5. Included for alignment with the POSIX Realtime Extension.
11006
11007
11008
Issue 6
11009
of
The [ENOSYS] error condition has been removed as stubs need not be provided if an
implementation does not support the Synchronized Input and Output option.
The fdatasync ( ) function is marked as part of the Synchronized Input and Output option.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
335
fdetach( )
11010
11011
System Interfaces
NAME
fdetach — detach a name from a STREAMS-based file descriptor (STREAMS)
11012 SYNOPSIS
11013 XSR
#include
<stropts.h>
int fdetach(const char *path);
11014
11015
11016
11017
11018
11019
11020
11021
11022
DESCRIPTION
The fdetach ( ) function shall detach a STREAMS-based file from the file to which it was attached
by a previous call to fattach ( ). The path argument points to the pathname of the attached
STREAMS file. The process shall have appropriate privileges or be the owner of the file. A
successful call to fdetach ( ) shall cause all pathnames that named the attached STREAMS file to
again name the file to which the STREAMS file was attached. All subsequent operations on path
shall operate on the underlying file and not on the STREAMS file.
11023
11024
All open file descriptions established while the STREAMS file was attached to the file referenced
by path shall still refer to the STREAMS file after the fdetach ( ) has taken effect.
11025
11026
If there are no open file descriptors or other references to the STREAMS file, then a successful
call to fdetach ( ) shall be equivalent to performing the last close( ) on the attached file.
11027
11028
11029
RETURN VALUE
Upon successful completion, fdetach ( ) shall return 0; otherwise, it shall return −1 and set errno to
indicate the error.
11030
11031
ERRORS
The fdetach ( ) function shall fail if:
11032
[EACCES]
Search permission is denied on a component of the path prefix.
11033
[EINVAL]
The path argument names a file that is not currently attached.
11034
11035
[ELOOP]
A loop exists in symbolic links encountered during resolution of the path
argument.
11036
11037
11038
[ENAMETOOLONG]
The size of a pathname exceeds {PATH_MAX} or a pathname component is
longer than {NAME_MAX}.
11039
[ENOENT]
A component of path does not name an existing file or path is an empty string.
11040
[ENOTDIR]
A component of the path prefix is not a directory.
11041
11042
[EPERM]
The effective user ID is not the owner of path and the process does not have
appropriate privileges.
11043
The fdetach ( ) function may fail if:
11044
11045
[ELOOP]
11046
11047
11048
[ENAMETOOLONG]
Pathname resolution of a symbolic link produced an intermediate result
whose length exceeds {PATH_MAX}.
336
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path argument.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11049
fdetach( )
EXAMPLES
11050
Detaching a File
11051
11052
11053
The following example detaches the STREAMS-based file /tmp/named-STREAM from the file to
which it was attached by a previous, successful call to fattach ( ). Subsequent calls to open this
file refer to the underlying file, not to the STREAMS file.
11054
11055
11056
11057
#include <stropts.h>
...
char *filename = "/tmp/named-STREAM";
int ret;
ret = fdetach(filename);
11058
11059
11060
APPLICATION USAGE
None.
11061
11062
RATIONALE
None.
11063
11064
FUTURE DIRECTIONS
None.
11065
11066
SEE ALSO
fattach ( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stropts.h>
11067
11068
CHANGE HISTORY
First released in Issue 4, Version 2.
11069
11070
Issue 5
11071
11072
Issue 6
11073
11074
Moved from X/OPEN UNIX extension to BASE.
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
The wording of the mandatory [ELOOP] error condition is updated, and a second optional
[ELOOP] error condition is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
337
fdim( )
System Interfaces
11075
11076
NAME
11077
11078
SYNOPSIS
#include <math.h>
fdim, fdimf, fdiml — compute positive difference between two floating-point numbers
double fdim(double x, double y);
float fdimf(float x, float y);
long double fdiml(long double x, long double y);
11079
11080
11081
11082 DESCRIPTION
11083 CX
The functionality described on this reference page is aligned with the ISO C standard.
11084
conflict between the requirements described here and the ISO C standard is unintentional.
11085
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11086
11087
These functions shall determine the positive difference between their arguments. If x is greater
than y, x−y is returned. If x is less than or equal to y, +0 is returned.
11088
11089
11090
11091
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
11092
11093
RETURN VALUE
Upon successful completion, these functions shall return the positive difference value.
11094
11095
If x−y is positive and overflows, a range error shall occur and fdim( ), fdimf( ), and fdiml( ) shall
return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively.
11096 XSI
11097
If x−y is positive and underflows, a range error may occur, and either (x−y) (if representable), or
0.0 (if supported),or an implementation-defined value shall be returned.
11098 MX
If x or y is NaN, a NaN shall be returned.
11099
11100
ERRORS
The fdim( ) function shall fail if:
Range Error
11101
The result overflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow
floating-point exception shall be raised.
11102
11103
11104
11105
11106
The fdim( ) function may fail if:
11107
Range Error
The result underflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
11108
11109
11110
11111
338
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fdim( )
11112
11113
EXAMPLES
None.
11114
11115
11116
11117
APPLICATION USAGE
On implementations supporting IEEE Std 754-1985, x−y cannot underflow, and hence the 0.0
return value is shaded as an extension for implementations supporting the XSI extension rather
than an MX extension.
11118
11119
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
11120
11121
RATIONALE
None.
11122
11123
FUTURE DIRECTIONS
None.
11124
11125
11126
SEE ALSO
feclearexcept( ), fetestexcept( ), fmax( ), fmin( ), the Base Definitions volume of IEEE Std 1003.1-2001,
Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
11127
11128
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
339
fdopen( )
11129
11130
System Interfaces
NAME
fdopen — associate a stream with a file descriptor
11131 SYNOPSIS
11132 CX
#include
<stdio.h>
11133
11134
FILE *fdopen(int fildes, const char *mode);
11135
11136
DESCRIPTION
The fdopen( ) function shall associate a stream with a file descriptor.
11137
The mode argument is a character string having one of the following values:
11138
r or rb
Open a file for reading.
11139
w or wb
Open a file for writing.
11140
a or ab
Open a file for writing at end-of-file.
11141
r+ or rb+ or r+b
Open a file for update (reading and writing).
11142
w+ or wb+ or w+b
Open a file for update (reading and writing).
11143
a+ or ab+ or a+b
Open a file for update (reading and writing) at end-of-file.
11144
11145
The meaning of these flags is exactly as specified in fopen( ), except that modes beginning with w
shall not cause truncation of the file.
11146
Additional values for the mode argument may be supported by an implementation.
11147
11148
11149
11150
The application shall ensure that the mode of the stream as expressed by the mode argument is
allowed by the file access mode of the open file description to which fildes refers. The file
position indicator associated with the new stream is set to the position indicated by the file
offset associated with the file descriptor.
11151
11152
The error and end-of-file indicators for the stream shall be cleared. The fdopen( ) function may
cause the st_atime field of the underlying file to be marked for update.
11153 SHM
If fildes refers to a shared memory object, the result of the fdopen( ) function is unspecified.
11154 TYM
If fildes refers to a typed memory object, the result of the fdopen( ) function is unspecified.
11155
11156
The fdopen( ) function shall preserve the offset maximum previously set for the open file
description corresponding to fildes.
11157
11158
11159
RETURN VALUE
Upon successful completion, fdopen( ) shall return a pointer to a stream; otherwise, a null pointer
shall be returned and errno set to indicate the error.
11160
11161
ERRORS
The fdopen( ) function may fail if:
11162
[EBADF]
The fildes argument is not a valid file descriptor.
11163
[EINVAL]
The mode argument is not a valid mode.
11164
[EMFILE]
{FOPEN_MAX} streams are currently open in the calling process.
11165
[EMFILE]
{STREAM_MAX} streams are currently open in the calling process.
11166
[ENOMEM]
Insufficient space to allocate a buffer.
340
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fdopen( )
11167
11168
EXAMPLES
None.
11169
11170
11171
APPLICATION USAGE
File descriptors are obtained from calls like open( ), dup( ), creat( ), or pipe( ), which open files but
do not return streams.
11172
11173
11174
11175
RATIONALE
The file descriptor may have been obtained from open( ), creat( ), pipe( ), dup( ), or fcntl( );
inherited through fork ( ) or exec; or perhaps obtained by implementation-defined means, such as
the 4.3 BSD socket( ) call.
11176
11177
11178
11179
11180
11181
The meanings of the mode arguments of fdopen( ) and fopen( ) differ. With fdopen( ), open for write
(w or w+) does not truncate, and append (a or a+) cannot create for writing. The mode argument
formats that include a b are allowed for consistency with the ISO C standard function fopen( ).
The b has no effect on the resulting stream. Although not explicitly required by this volume of
IEEE Std 1003.1-2001, a good implementation of append (a) mode would cause the O_APPEND
flag to be set.
11182
11183
FUTURE DIRECTIONS
None.
11184
11185
11186
SEE ALSO
Section 2.5.1 (on page 35), fclose( ), fopen( ), open( ), the Base Definitions volume of
IEEE Std 1003.1-2001, <stdio.h>
11187
11188
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
11189
11190
Issue 5
The DESCRIPTION is updated for alignment with the POSIX Realtime Extension.
Large File Summit extensions are added.
11191
11192
11193
11194
Issue 6
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
11195
11196
•
In the DESCRIPTION, the use and setting of the mode argument are changed to include
binary streams.
11197
11198
•
In the DESCRIPTION, text is added for large file support to indicate setting of the offset
maximum in the open file description.
11199
•
All errors identified in the ERRORS section are added.
11200
11201
•
In the DESCRIPTION, text is added that the fdopen( ) function may cause st_atime to be
updated.
11202
11203
11204
11205
11206
The following changes were made to align with the IEEE P1003.1a draft standard:
•
Clarification is added that it is the responsibility of the application to ensure that the mode is
compatible with the open file descriptor.
The DESCRIPTION is updated for alignment with IEEE Std 1003.1j-2000 by specifying that
fdopen( ) results are unspecified for typed memory objects.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
341
feclearexcept( )
System Interfaces
11207
11208
NAME
11209
11210
SYNOPSIS
#include <fenv.h>
feclearexcept — clear floating-point exception
int feclearexcept(int excepts);
11211
11212 DESCRIPTION
11213 CX
The functionality described on this reference page is aligned with the ISO C standard.
11214
conflict between the requirements described here and the ISO C standard is unintentional.
11215
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11216
11217
The feclearexcept( ) function shall attempt to clear the supported floating-point exceptions
represented by excepts.
11218
11219
11220
RETURN VALUE
If the argument is zero or if all the specified exceptions were successfully cleared, feclearexcept( )
shall return zero. Otherwise, it shall return a non-zero value.
11221
11222
ERRORS
No errors are defined.
11223
11224
EXAMPLES
None.
11225
11226
APPLICATION USAGE
None.
11227
11228
RATIONALE
None.
11229
11230
FUTURE DIRECTIONS
None.
11231
11232
11233
SEE ALSO
fegetexceptflag( ), feraiseexcept( ), fesetexceptflag( ), fetestexcept( ), the Base Definitions volume of
IEEE Std 1003.1-2001, <fenv.h>
11234
11235
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
ISO/IEC 9899: 1999 standard, Technical Corrigendum No. 1 is incorporated.
11236
342
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11237
11238
NAME
11239
11240
SYNOPSIS
#include <fenv.h>
11241
11242
fegetenv( )
fegetenv, fesetenv — get and set current floating-point environment
int fegetenv(fenv_t *envp);
int fesetenv(const fenv_t *envp);
11243 DESCRIPTION
11244 CX
The functionality described on this reference page is aligned with the ISO C standard.
11245
conflict between the requirements described here and the ISO C standard is unintentional.
11246
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11247
11248
The fegetenv( ) function shall attempt to store the current floating-point environment in the object
pointed to by envp.
11249
11250
11251
11252
11253
The fesetenv( ) function shall attempt to establish the floating-point environment represented by
the object pointed to by envp. The argument envp shall point to an object set by a call to
fegetenv( ) or feholdexcept ( ), or equal a floating-point environment macro. The fesetenv( ) function
does not raise floating-point exceptions, but only installs the state of the floating-point status
flags represented through its argument.
11254
11255
11256
11257
RETURN VALUE
If the representation was successfully stored, fegetenv( ) shall return zero. Otherwise, it shall
return a non-zero value. If the environment was successfully established, fesetenv( ) shall return
zero. Otherwise, it shall return a non-zero value.
11258
11259
ERRORS
No errors are defined.
11260
11261
EXAMPLES
None.
11262
11263
APPLICATION USAGE
None.
11264
11265
RATIONALE
None.
11266
11267
FUTURE DIRECTIONS
None.
11268
11269
SEE ALSO
feholdexcept ( ), feupdateenv( ), the Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>
11270
11271
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
11272
ISO/IEC 9899: 1999 standard, Technical Corrigendum No. 1 is incorporated.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
343
fegetexceptflag( )
System Interfaces
11273
11274
NAME
11275
11276
SYNOPSIS
#include <fenv.h>
fegetexceptflag, fesetexceptflag — get and set floating-point status flags
int fegetexceptflag(fexcept_t *flagp, int excepts);
int fesetexceptflag(const fexcept_t *flagp, int excepts);
11277
11278
11279 DESCRIPTION
11280 CX
The functionality described on this reference page is aligned with the ISO C standard.
11281
conflict between the requirements described here and the ISO C standard is unintentional.
11282
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11283
11284
11285
The fegetexceptflag( ) function shall attempt to store an implementation-defined representation of
the states of the floating-point status flags indicated by the argument excepts in the object
pointed to by the argument flagp .
11286
11287
11288
11289
11290
The fesetexceptflag( ) function shall attempt to set the floating-point status flags indicated by the
argument excepts to the states stored in the object pointed to by flagp . The value pointed to by
flagp shall have been set by a previous call to fegetexceptflag( ) whose second argument
represented at least those floating-point exceptions represented by the argument excepts. This
function does not raise floating-point exceptions, but only sets the state of the flags.
11291
11292
11293
11294
11295
RETURN VALUE
If the representation was successfully stored, fegetexceptflag( ) shall return zero. Otherwise, it
shall return a non-zero value. If the excepts argument is zero or if all the specified exceptions
were successfully set, fesetexceptflag( ) shall return zero. Otherwise, it shall return a non-zero
value.
11296
11297
ERRORS
No errors are defined.
11298
11299
EXAMPLES
None.
11300
11301
APPLICATION USAGE
None.
11302
11303
RATIONALE
None.
11304
11305
FUTURE DIRECTIONS
None.
11306
11307
11308
SEE ALSO
feclearexcept( ), feraiseexcept( ), fetestexcept( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<fenv.h>
11309
11310
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
ISO/IEC 9899: 1999 standard, Technical Corrigendum No. 1 is incorporated.
11311
344
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11312
11313
NAME
11314
11315
SYNOPSIS
#include <fenv.h>
11316
11317
fegetround( )
fegetround, fesetround — get and set current rounding direction
int fegetround(void);
int fesetround(int round);
11318 DESCRIPTION
11319 CX
The functionality described on this reference page is aligned with the ISO C standard.
11320
conflict between the requirements described here and the ISO C standard is unintentional.
11321
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11322
The fegetround( ) function shall get the current rounding direction.
11323
11324
11325
The fesetround( ) function shall establish the rounding direction represented by its argument
round. If the argument is not equal to the value of a rounding direction macro, the rounding
direction is not changed.
11326
11327
11328
11329
RETURN VALUE
The fegetround( ) function shall return the value of the rounding direction macro representing the
current rounding direction or a negative value if there is no such rounding direction macro or
the current rounding direction is not determinable.
11330
11331
The fesetround( ) function shall return a zero value if and only if the requested rounding direction
was established.
11332
11333
ERRORS
No errors are defined.
11334
11335
11336
EXAMPLES
The following example saves, sets, and restores the rounding direction, reporting an error and
aborting if setting the rounding direction fails:
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
#include <fenv.h>
#include <assert.h>
void f(int round_dir)
{
#pragma STDC FENV_ACCESS ON
int save_round;
int setround_ok;
save_round = fegetround();
setround_ok = fesetround(round_dir);
assert(setround_ok == 0);
/* ... */
fesetround(save_round);
/* ... */
}
11351
11352
APPLICATION USAGE
None.
11353
11354
RATIONALE
None.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
345
fegetround( )
System Interfaces
11355
11356
FUTURE DIRECTIONS
None.
11357
11358
SEE ALSO
The Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>
11359
11360
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
ISO/IEC 9899: 1999 standard, Technical Corrigendum No. 1 is incorporated.
11361
346
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11362
11363
NAME
11364
11365
SYNOPSIS
#include <fenv.h>
11366
feholdexcept( )
feholdexcept — save current floating-point environment
int feholdexcept(fenv_t *envp);
11367 DESCRIPTION
11368 CX
The functionality described on this reference page is aligned with the ISO C standard.
11369
conflict between the requirements described here and the ISO C standard is unintentional.
11370
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11371
11372
11373
The feholdexcept ( ) function shall save the current floating-point environment in the object
pointed to by envp, clear the floating-point status flags, and then install a non-stop (continue on
floating-point exceptions) mode, if available, for all floating-point exceptions.
11374
11375
11376
RETURN VALUE
The feholdexcept ( ) function shall return zero if and only if non-stop floating-point exception
handling was successfully installed.
11377
11378
ERRORS
No errors are defined.
11379
11380
EXAMPLES
None.
11381
11382
APPLICATION USAGE
None.
11383
11384
11385
11386
11387
RATIONALE
The feholdexcept ( ) function should be effective on typical IEC 60559: 1989 standard
implementations which have the default non-stop mode and at least one other mode for trap
handling or aborting. If the implementation provides only the non-stop mode, then installing the
non-stop mode is trivial.
11388
11389
FUTURE DIRECTIONS
None.
11390
11391
11392
SEE ALSO
fegetenv( ), fesetenv( ), feupdateenv( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<fenv.h>
11393
11394
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
347
feof( )
System Interfaces
11395
11396
NAME
11397
11398
SYNOPSIS
#include <stdio.h>
feof — test end-of-file indicator on a stream
int feof(FILE *stream);
11399
11400 DESCRIPTION
11401 CX
The functionality described on this reference page is aligned with the ISO C standard.
11402
conflict between the requirements described here and the ISO C standard is unintentional.
11403
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
The feof( ) function shall test the end-of-file indicator for the stream pointed to by stream.
11404
11405
11406
RETURN VALUE
The feof( ) function shall return non-zero if and only if the end-of-file indicator is set for stream.
11407
11408
ERRORS
No errors are defined.
11409
11410
EXAMPLES
None.
11411
11412
APPLICATION USAGE
None.
11413
11414
RATIONALE
None.
11415
11416
FUTURE DIRECTIONS
None.
11417
11418
SEE ALSO
clearerr( ), ferror( ), fopen( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
11419
11420
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
348
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11421
11422
NAME
11423
11424
SYNOPSIS
#include <fenv.h>
11425
feraiseexcept( )
feraiseexcept — raise floating-point exception
int feraiseexcept(int excepts);
11426 DESCRIPTION
11427 CX
The functionality described on this reference page is aligned with the ISO C standard.
11428
conflict between the requirements described here and the ISO C standard is unintentional.
11429
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11430
11431
11432
11433
11434
The feraiseexcept( ) function shall attempt to raise the supported floating-point exceptions
represented by the argument excepts. The order in which these floating-point exceptions are
raised is unspecified. Whether the feraiseexcept( ) function additionally raises the inexact
floating-point exception whenever it raises the overflow or underflow floating-point exception is
implementation-defined.
11435
11436
11437
RETURN VALUE
If the argument is zero or if all the specified exceptions were successfully raised, feraiseexcept( )
shall return zero. Otherwise, it shall return a non-zero value.
11438
11439
ERRORS
No errors are defined.
11440
11441
EXAMPLES
None.
11442
11443
11444
APPLICATION USAGE
The effect is intended to be similar to that of floating-point exceptions raised by arithmetic
operations. Hence, enabled traps for floating-point exceptions raised by this function are taken.
11445
11446
11447
11448
11449
RATIONALE
Raising overflow or underflow is allowed to also raise inexact because on some architectures the
only practical way to raise an exception is to execute an instruction that has the exception as a
side effect. The function is not restricted to accept only valid coincident expressions for atomic
operations, so the function can be used to raise exceptions accrued over several operations.
11450
11451
FUTURE DIRECTIONS
None.
11452
11453
11454
SEE ALSO
feclearexcept( ), fegetexceptflag( ), fesetexceptflag( ), fetestexcept( ), the Base Definitions volume of
IEEE Std 1003.1-2001, <fenv.h>
11455
11456
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
11457
ISO/IEC 9899: 1999 standard, Technical Corrigendum No. 1 is incorporated.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
349
ferror( )
System Interfaces
11458
11459
NAME
11460
11461
SYNOPSIS
#include <stdio.h>
ferror — test error indicator on a stream
int ferror(FILE *stream);
11462
11463 DESCRIPTION
11464 CX
The functionality described on this reference page is aligned with the ISO C standard.
11465
conflict between the requirements described here and the ISO C standard is unintentional.
11466
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
The ferror( ) function shall test the error indicator for the stream pointed to by stream.
11467
11468
11469
RETURN VALUE
The ferror( ) function shall return non-zero if and only if the error indicator is set for stream.
11470
11471
ERRORS
No errors are defined.
11472
11473
EXAMPLES
None.
11474
11475
APPLICATION USAGE
None.
11476
11477
RATIONALE
None.
11478
11479
FUTURE DIRECTIONS
None.
11480
11481
SEE ALSO
clearerr( ), feof( ), fopen( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
11482
11483
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
350
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11484
11485
NAME
11486
11487
SYNOPSIS
#include <fenv.h>
11488
11489
11490
fesetenv( )
fesetenv — set current floating-point environment
int fesetenv(const fenv_t *envp);
DESCRIPTION
Refer to fegetenv( ).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
351
fesetexceptflag( )
System Interfaces
11491
11492
NAME
11493
11494
SYNOPSIS
#include <fenv.h>
fesetexceptflag — set floating-point status flags
int fesetexceptflag(const fexcept_t *flagp, int excepts);
11495
11496
11497
DESCRIPTION
Refer to fegetexceptflag( ).
352
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11498
11499
NAME
11500
11501
SYNOPSIS
#include <fenv.h>
11502
11503
11504
fesetround( )
fesetround — set current rounding direction
int fesetround(int round);
DESCRIPTION
Refer to fegetround( ).
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
353
fetestexcept( )
System Interfaces
11505
11506
NAME
11507
11508
SYNOPSIS
#include <fenv.h>
fetestexcept — test floating-point exception flags
int fetestexcept(int excepts);
11509
11510 DESCRIPTION
11511 CX
The functionality described on this reference page is aligned with the ISO C standard.
11512
conflict between the requirements described here and the ISO C standard is unintentional.
11513
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11514
11515
11516
The fetestexcept( ) function shall determine which of a specified subset of the floating-point
exception flags are currently set. The excepts argument specifies the floating-point status flags to
be queried.
11517
11518
11519
11520
RETURN VALUE
The fetestexcept( ) function shall return the value of the bitwise-inclusive OR of the floating-point
exception macros corresponding to the currently set floating-point exceptions included in
excepts.
11521
11522
ERRORS
No errors are defined.
11523
11524
11525
EXAMPLES
The following example calls function f( ) if an invalid exception is set, and then function g( ) if an
overflow exception is set:
#include <fenv.h>
/* ... */
{
#
pragma STDC FENV_ACCESS ON
int set_excepts;
feclearexcept(FE_INVALID | FE_OVERFLOW);
// maybe raise exceptions
set_excepts = fetestexcept(FE_INVALID | FE_OVERFLOW);
if (set_excepts & FE_INVALID) f();
if (set_excepts & FE_OVERFLOW) g();
/* ... */
}
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
APPLICATION USAGE
None.
11540
11541
RATIONALE
None.
11542
11543
FUTURE DIRECTIONS
None.
11544
11545
11546
SEE ALSO
feclearexcept( ), fegetexceptflag( ),
IEEE Std 1003.1-2001, <fenv.h>
354
feraiseexcept( ),
the
Base
Definitions
volume
of
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11547
11548
fetestexcept( )
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
355
feupdateenv( )
System Interfaces
11549
11550
NAME
11551
11552
SYNOPSIS
#include <fenv.h>
feupdateenv — update floating-point environment
int feupdateenv(const fenv_t *envp);
11553
11554 DESCRIPTION
11555 CX
The functionality described on this reference page is aligned with the ISO C standard.
11556
conflict between the requirements described here and the ISO C standard is unintentional.
11557
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11558
11559
11560
11561
11562
The feupdateenv( ) function shall attempt to save the currently raised floating-point exceptions in
its automatic storage, attempt to install the floating-point environment represented by the object
pointed to by envp, and then attempt to raise the saved floating-point exceptions. The argument
envp shall point to an object set by a call to feholdexcept ( ) or fegetenv( ), or equal a floating-point
environment macro.
11563
11564
11565
RETURN VALUE
The feupdateenv( ) function shall return a zero value if and only if all the required actions were
successfully carried out.
11566
11567
ERRORS
No errors are defined.
11568
11569
11570
EXAMPLES
The following example shows sample code to hide spurious underflow floating-point
exceptions:
#include <fenv.h>
double f(double x)
{
#
pragma STDC FENV_ACCESS ON
double result;
fenv_t save_env;
feholdexcept(&save_env);
// compute result
if (/* test spurious underflow */)
feclearexcept(FE_UNDERFLOW);
feupdateenv(&save_env);
return result;
}
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
APPLICATION USAGE
None.
11586
11587
RATIONALE
None.
11588
11589
FUTURE DIRECTIONS
None.
11590
11591
SEE ALSO
fegetenv( ), feholdexcept ( ), the Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>
356
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11592
11593
11594
feupdateenv( )
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
ISO/IEC 9899: 1999 standard, Technical Corrigendum No. 1 is incorporated.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
357
fflush( )
System Interfaces
11595
11596
NAME
11597
11598
SYNOPSIS
#include <stdio.h>
fflush — flush a stream
int fflush(FILE *stream);
11599
11600 DESCRIPTION
11601 CX
The functionality described on this reference page is aligned with the ISO C standard.
11602
conflict between the requirements described here and the ISO C standard is unintentional.
11603
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11604
11605 CX
11606
If stream points to an output stream or an update stream in which the most recent operation was
not input, fflush( ) shall cause any unwritten data for that stream to be written to the file, and the
st_ctime and st_mtime fields of the underlying file shall be marked for update.
11607
11608
If stream is a null pointer, fflush( ) shall perform this flushing action on all streams for which the
behavior is defined above.
11609 RETURN VALUE
11610
Upon successful completion, fflush( ) shall return 0; otherwise,
11611 CX
the stream, return EOF, and set errno to indicate the error.
11612
11613
it shall set the error indicator for
ERRORS
The fflush( ) function shall fail if:
11614 CX
11615
[EAGAIN]
The O_NONBLOCK flag is set for the file descriptor underlying stream and the
process would be delayed in the write operation.
11616 CX
[EBADF]
The file descriptor underlying stream is not valid.
11617 CX
[EFBIG]
An attempt was made to write a file that exceeds the maximum file size.
11618 XSI
[EFBIG]
An attempt was made to write a file that exceeds the process’ file size limit.
11619 CX
11620
[EFBIG]
The file is a regular file and an attempt was made to write at or beyond the
offset maximum associated with the corresponding stream.
11621 CX
[EINTR]
The fflush( ) function was interrupted by a signal.
11622 CX
11623
11624
11625
[EIO]
The process is a member of a background process group attempting to write
to its controlling terminal, TOSTOP is set, the process is neither ignoring nor
blocking SIGTTOU, and the process group of the process is orphaned. This
error may also be returned under implementation-defined conditions.
11626 CX
[ENOSPC]
There was no free space remaining on the device containing the file.
11627 CX
11628
[EPIPE]
An attempt is made to write to a pipe or FIFO that is not open for reading by
any process. A SIGPIPE signal shall also be sent to the thread.
11629
The fflush( ) function may fail if:
11630 CX
11631
[ENXIO]
358
A request was made of a nonexistent device, or the request was outside the
capabilities of the device.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11632
fflush( )
EXAMPLES
11633
Sending Prompts to Standard Output
11634
11635
11636
11637
11638
The following example uses printf( ) calls to print a series of prompts for information the user
must enter from standard input. The fflush( ) calls force the output to standard output. The
fflush( ) function is used because standard output is usually buffered and the prompt may not
immediately be printed on the output or terminal. The gets( ) calls read strings from standard
input and place the results in variables, for use later in the program.
11639
11640
11641
11642
11643
11644
11645
11646
11647
#include <stdio.h>
...
char user[100];
char oldpasswd[100];
char newpasswd[100];
...
printf("User name: ");
fflush(stdout);
gets(user);
11648
11649
11650
printf("Old password: ");
fflush(stdout);
gets(oldpasswd);
11651
11652
11653
11654
printf("New password: ");
fflush(stdout);
gets(newpasswd);
...
11655
11656
APPLICATION USAGE
None.
11657
11658
11659
11660
RATIONALE
Data buffered by the system may make determining the validity of the position of the current
file descriptor impractical. Thus, enforcing the repositioning of the file descriptor after fflush( )
on streams open for read( ) is not mandated by IEEE Std 1003.1-2001.
11661
11662
FUTURE DIRECTIONS
None.
11663
11664
SEE ALSO
getrlimit( ), ulimit( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
11665
11666
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
11667
11668
Issue 5
11669
11670
Issue 6
11671
11672
Large File Summit extensions are added.
Extensions beyond the ISO C standard are marked.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
11673
•
The [EFBIG] error is added as part of the large file support extensions.
11674
•
The [ENXIO] optional error condition is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
359
fflush( )
System Interfaces
The RETURN VALUE section is updated to note that the error indicator shall be set for the
stream. This is for alignment with the ISO/IEC 9899: 1999 standard.
11675
11676
360
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
ffs( )
System Interfaces
11677
11678
NAME
ffs — find first set bit
11679 SYNOPSIS
11680 XSI
#include
<strings.h>
int ffs(int i);
11681
11682
11683
11684
11685
DESCRIPTION
The ffs( ) function shall find the first bit set (beginning with the least significant bit) in i, and
return the index of that bit. Bits are numbered starting at one (the least significant bit).
11686
11687
RETURN VALUE
The ffs( ) function shall return the index of the first bit set. If i is 0, then ffs( ) shall return 0.
11688
11689
ERRORS
No errors are defined.
11690
11691
EXAMPLES
None.
11692
11693
APPLICATION USAGE
None.
11694
11695
RATIONALE
None.
11696
11697
FUTURE DIRECTIONS
None.
11698
11699
SEE ALSO
The Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>
11700
11701
CHANGE HISTORY
First released in Issue 4, Version 2.
11702
11703
Issue 5
Moved from X/OPEN UNIX extension to BASE.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
361
fgetc( )
System Interfaces
11704
11705
NAME
11706
11707
SYNOPSIS
#include <stdio.h>
fgetc — get a byte from a stream
int fgetc(FILE *stream);
11708
11709 DESCRIPTION
11710 CX
The functionality described on this reference page is aligned with the ISO C standard.
11711
conflict between the requirements described here and the ISO C standard is unintentional.
11712
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11713
11714
11715
11716
11717
If the end-of-file indicator for the input stream pointed to by stream is not set and a next byte is
present, the fgetc( ) function shall obtain the next byte as an unsigned char converted to an int,
from the input stream pointed to by stream, and advance the associated file position indicator for
the stream (if defined). Since fgetc( ) operates on bytes, reading a character consisting of multiple
bytes (or ‘‘a multi-byte character’’) may require multiple calls to fgetc( ).
11718 CX
11719
11720
11721
The fgetc( ) function may mark the st_atime field of the file associated with stream for update. The
st_atime field shall be marked for update by the first successful execution of fgetc( ), fgets( ),
fgetwc( ), fgetws( ), fread( ), fscanf( ), getc( ), getchar( ), gets( ), or scanf( ) using stream that returns
data not supplied by a prior call to ungetc( ) or ungetwc( ).
11722 RETURN VALUE
11723
Upon successful completion, fgetc( ) shall return the next byte from the input stream pointed to
11724
by stream. If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the
11725
end-of-file indicator for the stream shall be set and fgetc( ) shall return EOF. If a read error occurs,
11726 CX
the error indicator for the stream shall be set, fgetc( ) shall return EOF, and shall set errno to
11727
indicate the error.
11728
11729
ERRORS
The fgetc( ) function shall fail if data needs to be read and:
11730 CX
11731
[EAGAIN]
The O_NONBLOCK flag is set for the file descriptor underlying stream and the
process would be delayed in the fgetc( ) operation.
11732 CX
11733
[EBADF]
The file descriptor underlying stream is not a valid file descriptor open for
reading.
11734 CX
11735
[EINTR]
The read operation was terminated due to the receipt of a signal, and no data
was transferred.
11736 CX
11737
11738
11739
[EIO]
A physical I/O error has occurred, or the process is in a background process
group attempting to read from its controlling terminal, and either the process
is ignoring or blocking the SIGTTIN signal or the process group is orphaned.
This error may also be generated for implementation-defined reasons.
11740 CX
11741
[EOVERFLOW]
The file is a regular file and an attempt was made to read at or beyond the
offset maximum associated with the corresponding stream.
11742
The fgetc( ) function may fail if:
11743 CX
[ENOMEM]
Insufficient storage space is available.
11744 CX
11745
[ENXIO]
A request was made of a nonexistent device, or the request was outside the
capabilities of the device.
362
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fgetc( )
11746
11747
EXAMPLES
None.
11748
11749
11750
11751
APPLICATION USAGE
If the integer value returned by fgetc( ) is stored into a variable of type char and then compared
against the integer constant EOF, the comparison may never succeed, because sign-extension of
a variable of type char on widening to integer is implementation-defined.
11752
11753
The ferror( ) or feof( ) functions must be used to distinguish between an error condition and an
end-of-file condition.
11754
11755
RATIONALE
None.
11756
11757
FUTURE DIRECTIONS
None.
11758
11759
11760
SEE ALSO
feof( ), ferror( ), fopen( ), getchar( ), getc( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<stdio.h>
11761
11762
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
11763
11764
Issue 5
11765
11766
Issue 6
11767
11768
Large File Summit extensions are added.
Extensions beyond the ISO C standard are marked.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
11769
•
The [EIO] and [EOVERFLOW] mandatory error conditions are added.
11770
•
The [ENOMEM] and [ENXIO] optional error conditions are added.
11771
The following changes are made for alignment with the ISO/IEC 9899: 1999 standard:
11772
11773
•
The DESCRIPTION is updated to clarify the behavior when the end-of-file indicator for the
input stream is not set.
11774
11775
•
The RETURN VALUE section is updated to note that the error indicator shall be set for the
stream.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
363
fgetpos( )
System Interfaces
11776
11777
NAME
11778
11779
SYNOPSIS
#include <stdio.h>
fgetpos — get current file position information
int fgetpos(FILE *restrict stream, fpos_t *restrict pos);
11780
11781 DESCRIPTION
11782 CX
The functionality described on this reference page is aligned with the ISO C standard.
11783
conflict between the requirements described here and the ISO C standard is unintentional.
11784
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11785
11786
11787
11788
The fgetpos( ) function shall store the current values of the parse state (if any) and file position
indicator for the stream pointed to by stream in the object pointed to by pos. The value stored
contains unspecified information usable by fsetpos( ) for repositioning the stream to its position
at the time of the call to fgetpos( ).
11789
11790
11791
RETURN VALUE
Upon successful completion, fgetpos( ) shall return 0; otherwise, it shall return a non-zero value
and set errno to indicate the error.
11792
11793
ERRORS
The fgetpos( ) function shall fail if:
11794 CX
11795
[EOVERFLOW]
The current value of the file position cannot be represented correctly in an
object of type fpos_t.
11796
The fgetpos( ) function may fail if:
11797 CX
[EBADF]
The file descriptor underlying stream is not valid.
11798 CX
11799
[ESPIPE]
The file descriptor underlying stream is associated with a pipe, FIFO, or socket.
11800
11801
EXAMPLES
None.
11802
11803
APPLICATION USAGE
None.
11804
11805
RATIONALE
None.
11806
11807
FUTURE DIRECTIONS
None.
11808
11809
SEE ALSO
fopen( ), ftell( ), rewind( ), ungetc( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
11810
11811
CHANGE HISTORY
First released in Issue 4. Derived from the ISO C standard.
11812
11813
Issue 5
11814
11815
Issue 6
Large File Summit extensions are added.
Extensions beyond the ISO C standard are marked.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
11816
11817
364
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11818
•
fgetpos( )
The [EBADF] and [ESPIPE] optional error conditions are added.
11819
An additional [ESPIPE] error condition is added for sockets.
11820
The prototype for fgetpos( ) is changed for alignment with the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
365
fgets( )
System Interfaces
11821
11822
NAME
11823
11824
SYNOPSIS
#include <stdio.h>
fgets — get a string from a stream
char *fgets(char *restrict s, int n, FILE *restrict stream);
11825
11826 DESCRIPTION
11827 CX
The functionality described on this reference page is aligned with the ISO C standard.
11828
conflict between the requirements described here and the ISO C standard is unintentional.
11829
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11830
11831
11832
The fgets( ) function shall read bytes from stream into the array pointed to by s, until n−1 bytes
are read, or a <newline> is read and transferred to s, or an end-of-file condition is encountered.
The string is then terminated with a null byte.
11833 CX
11834
11835
11836
The fgets( ) function may mark the st_atime field of the file associated with stream for update. The
st_atime field shall be marked for update by the first successful execution of fgetc( ), fgets( ),
fgetwc( ), fgetws( ), fread( ), fscanf( ), getc( ), getchar( ), gets( ), or scanf( ) using stream that returns
data not supplied by a prior call to ungetc( ) or ungetwc( ).
11837 RETURN VALUE
11838
Upon successful completion, fgets( ) shall return s. If the stream is at end-of-file, the end-of-file
11839
indicator for the stream shall be set and fgets( ) shall return a null pointer. If a read error occurs,
11840 CX
the error indicator for the stream shall be set, fgets( ) shall return a null pointer, and shall set
11841
errno to indicate the error.
11842
11843
ERRORS
Refer to fgetc( ).
11844
EXAMPLES
11845
Reading Input
11846
11847
The following example uses fgets( ) to read each line of input. {LINE_MAX}, which defines the
maximum size of the input line, is defined in the <limits.h> header.
11848
11849
11850
11851
11852
11853
11854
11855
#include <stdio.h>
...
char line[LINE_MAX];
...
while (fgets(line, LINE_MAX, fp) != NULL) {
...
}
...
11856
11857
APPLICATION USAGE
None.
11858
11859
RATIONALE
None.
11860
11861
FUTURE DIRECTIONS
None.
366
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11862
11863
SEE ALSO
fopen( ), fread( ), gets( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
11864
11865
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
11866
11867
Issue 6
11868
fgets( )
Extensions beyond the ISO C standard are marked.
The prototype for fgets( ) is changed for alignment with the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
367
fgetwc( )
System Interfaces
11869
11870
NAME
11871
11872
11873
SYNOPSIS
#include <stdio.h>
#include <wchar.h>
fgetwc — get a wide-character code from a stream
wint_t fgetwc(FILE *stream);
11874
11875 DESCRIPTION
11876 CX
The functionality described on this reference page is aligned with the ISO C standard.
11877
conflict between the requirements described here and the ISO C standard is unintentional.
11878
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11879
11880
11881
The fgetwc( ) function shall obtain the next character (if present) from the input stream pointed to
by stream, convert that to the corresponding wide-character code, and advance the associated
file position indicator for the stream (if defined).
11882
If an error occurs, the resulting value of the file position indicator for the stream is unspecified.
11883 CX
11884
11885
11886
The fgetwc( ) function may mark the st_atime field of the file associated with stream for update.
The st_atime field shall be marked for update by the first successful execution of fgetc( ), fgets( ),
fgetwc( ), fgetws( ), fread( ), fscanf( ), getc( ), getchar( ), gets( ), or scanf( ) using stream that returns
data not supplied by a prior call to ungetc( ) or ungetwc( ).
11887 RETURN VALUE
11888
Upon successful completion, the fgetwc( ) function shall return the wide-character code of the
11889
character read from the input stream pointed to by stream converted to a type wint_t. If the
11890
stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgetwc( ) shall
11891
return WEOF. If a read error occurs, the error indicator for the stream shall be set, fgetwc( ) shall
11892 CX
return WEOF, and shall set errno to indicate the error. If an encoding error occurs, the error
11893
indicator for the stream shall be set, fgetwc( ) shall return WEOF, and shall set errno to indicate
11894
the error.
11895
11896
ERRORS
The fgetwc( ) function shall fail if data needs to be read and:
11897 CX
11898
[EAGAIN]
The O_NONBLOCK flag is set for the file descriptor underlying stream and the
process would be delayed in the fgetwc( ) operation.
11899 CX
11900
[EBADF]
The file descriptor underlying stream is not a valid file descriptor open for
reading.
11901
[EILSEQ]
The data obtained from the input stream does not form a valid character.
11902 CX
11903
[EINTR]
The read operation was terminated due to the receipt of a signal, and no data
was transferred.
11904 CX
11905
11906
11907
[EIO]
A physical I/O error has occurred, or the process is in a background process
group attempting to read from its controlling terminal, and either the process
is ignoring or blocking the SIGTTIN signal or the process group is orphaned.
This error may also be generated for implementation-defined reasons.
11908 CX
11909
[EOVERFLOW]
The file is a regular file and an attempt was made to read at or beyond the
offset maximum associated with the corresponding stream.
11910
The fgetwc( ) function may fail if:
11911 CX
[ENOMEM]
368
Insufficient storage space is available.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fgetwc( )
System Interfaces
11912 CX
11913
[ENXIO]
A request was made of a nonexistent device, or the request was outside the
capabilities of the device.
11914
11915
EXAMPLES
None.
11916
11917
11918
APPLICATION USAGE
The ferror( ) or feof( ) functions must be used to distinguish between an error condition and an
end-of-file condition.
11919
11920
RATIONALE
None.
11921
11922
FUTURE DIRECTIONS
None.
11923
11924
11925
SEE ALSO
feof( ), ferror( ), fopen( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>,
<wchar.h>
11926
11927
CHANGE HISTORY
First released in Issue 4. Derived from the MSE working draft.
11928
11929
Issue 5
The Optional Header (OH) marking is removed from <stdio.h>.
Large File Summit extensions are added.
11930
11931
11932
11933
11934
Issue 6
Extensions beyond the ISO C standard are marked.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
11935
•
The [EIO] and [EOVERFLOW] mandatory error conditions are added.
11936
•
The [ENOMEM] and [ENXIO] optional error conditions are added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
369
fgetws( )
System Interfaces
11937
11938
NAME
11939
11940
11941
SYNOPSIS
#include <stdio.h>
#include <wchar.h>
fgetws — get a wide-character string from a stream
wchar_t *fgetws(wchar_t *restrict ws, int n,
FILE *restrict stream);
11942
11943
11944 DESCRIPTION
11945 CX
The functionality described on this reference page is aligned with the ISO C standard.
11946
conflict between the requirements described here and the ISO C standard is unintentional.
11947
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
11948
11949
11950
11951
11952
The fgetws( ) function shall read characters from the stream, convert these to the corresponding
wide-character codes, place them in the wchar_t array pointed to by ws, until n−1 characters are
read, or a <newline> is read, converted, and transferred to ws, or an end-of-file condition is
encountered. The wide-character string, ws, shall then be terminated with a null wide-character
code.
11953
If an error occurs, the resulting value of the file position indicator for the stream is unspecified.
11954 CX
11955
11956
11957
The fgetws( ) function may mark the st_atime field of the file associated with stream for update.
The st_atime field shall be marked for update by the first successful execution of fgetc( ), fgets( ),
fgetwc( ), fgetws( ), fread( ), fscanf( ), getc( ), getchar( ), gets( ), or scanf( ) using stream that returns
data not supplied by a prior call to ungetc( ) or ungetwc( ).
11958 RETURN VALUE
11959
Upon successful completion, fgetws( ) shall return ws. If the stream is at end-of-file, the end-of11960
file indicator for the stream shall be set and fgetws( ) shall return a null pointer. If a read error
11961 CX
occurs, the error indicator for the stream shall be set, fgetws( ) shall return a null pointer, and
11962
shall set errno to indicate the error.
11963
11964
ERRORS
Refer to fgetwc( ).
11965
11966
EXAMPLES
None.
11967
11968
APPLICATION USAGE
None.
11969
11970
RATIONALE
None.
11971
11972
FUTURE DIRECTIONS
None.
11973
11974
SEE ALSO
fopen( ), fread( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, <wchar.h>
11975
11976
CHANGE HISTORY
First released in Issue 4. Derived from the MSE working draft.
11977
11978
Issue 5
The Optional Header (OH) marking is removed from <stdio.h>.
370
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
11979
11980
11981
fgetws( )
Issue 6
Extensions beyond the ISO C standard are marked.
The prototype for fgetws( ) is changed for alignment with the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
371
fileno( )
11982
11983
System Interfaces
NAME
fileno — map a stream pointer to a file descriptor
11984 SYNOPSIS
11985 CX
#include
<stdio.h>
int fileno(FILE *stream);
11986
11987
11988
11989
11990
DESCRIPTION
The fileno ( ) function shall return the integer file descriptor associated with the stream pointed to
by stream.
11991
11992
11993
11994
RETURN VALUE
Upon successful completion, fileno ( ) shall return the integer value of the file descriptor
associated with stream. Otherwise, the value −1 shall be returned and errno set to indicate the
error.
11995
11996
ERRORS
The fileno ( ) function may fail if:
[EBADF]
11997
The stream argument is not a valid stream.
11998
11999
EXAMPLES
None.
12000
12001
APPLICATION USAGE
None.
12002
12003
12004
12005
12006
RATIONALE
Without some specification of which file descriptors are associated with these streams, it is
impossible for an application to set up the streams for another application it starts with fork ( )
and exec. In particular, it would not be possible to write a portable version of the sh command
interpreter (although there may be other constraints that would prevent that portability).
12007
12008
FUTURE DIRECTIONS
None.
12009
12010
12011
SEE ALSO
Section 2.5.1 (on page 35), fdopen( ), fopen( ), stdin, the Base Definitions volume of
IEEE Std 1003.1-2001, <stdio.h>
12012
12013
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
12014
12015
12016
Issue 6
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
•
12017
372
The [EBADF] optional error condition is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
flockfile( )
System Interfaces
12018
12019
NAME
flockfile, ftrylockfile, funlockfile — stdio locking functions
12020 SYNOPSIS
12021 TSF
#include
12022
12023
12024
12025
12026
12027
12028
12029
<stdio.h>
void flockfile(FILE *file);
int ftrylockfile(FILE *file);
void funlockfile(FILE *file);
DESCRIPTION
These functions shall provide for explicit application-level locking of stdio (FILE *) objects.
These functions can be used by a thread to delineate a sequence of I/O statements that are
executed as a unit.
12030
The flockfile ( ) function shall acquire for a thread ownership of a (FILE *) object.
12031
12032
The ftrylockfile ( ) function shall acquire for a thread ownership of a (FILE *) object if the object is
available; ftrylockfile ( ) is a non-blocking version of flockfile ( ).
12033
12034
The funlockfile ( ) function shall relinquish the ownership granted to the thread. The behavior is
undefined if a thread other than the current owner calls the funlockfile ( ) function.
12035
12036
12037
12038
12039
12040
12041
12042
The functions shall behave as if there is a lock count associated with each (FILE *) object. This
count is implicitly initialized to zero when the (FILE *) object is created. The (FILE *) object is
unlocked when the count is zero. When the count is positive, a single thread owns the (FILE *)
object. When the flockfile ( ) function is called, if the count is zero or if the count is positive and
the caller owns the (FILE *) object, the count shall be incremented. Otherwise, the calling thread
shall be suspended, waiting for the count to return to zero. Each call to funlockfile ( ) shall
decrement the count. This allows matching calls to flockfile ( ) (or successful calls to ftrylockfile ( ))
and funlockfile ( ) to be nested.
12043
12044
All functions that reference (FILE *) objects shall behave as if they use flockfile ( ) and funlockfile ( )
internally to obtain ownership of these (FILE *) objects.
12045
12046
12047
12048
RETURN VALUE
None for flockfile ( ) and funlockfile ( ).
The ftrylockfile ( ) function shall return zero for success and non-zero to indicate that the lock
cannot be acquired.
12049
12050
ERRORS
No errors are defined.
12051
12052
EXAMPLES
None.
12053
12054
12055
APPLICATION USAGE
Applications using these functions may be subject to priority inversion, as discussed in the Base
Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.
12056
12057
12058
12059
RATIONALE
The flockfile ( ) and funlockfile ( ) functions provide an orthogonal mutual-exclusion lock for each
FILE. The ftrylockfile ( ) function provides a non-blocking attempt to acquire a file lock,
analogous to pthread_mutex_trylock( ).
12060
12061
12062
These locks behave as if they are the same as those used internally by stdio for thread-safety.
This both provides thread-safety of these functions without requiring a second level of internal
locking and allows functions in stdio to be implemented in terms of other stdio functions.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
373
flockfile( )
System Interfaces
12063
12064
12065
12066
12067
12068
12069
12070
Application writers and implementors should be aware that there are potential deadlock
problems on FILE objects. For example, the line-buffered flushing semantics of stdio (requested
via {_IOLBF}) require that certain input operations sometimes cause the buffered contents of
implementation-defined line-buffered output streams to be flushed. If two threads each hold the
lock on the other’s FILE, deadlock ensues. This type of deadlock can be avoided by acquiring
FILE locks in a consistent order. In particular, the line-buffered output stream deadlock can
typically be avoided by acquiring locks on input streams before locks on output streams if a
thread would be acquiring both.
12071
12072
12073
12074
In summary, threads sharing stdio streams with other threads can use flockfile ( ) and funlockfile ( )
to cause sequences of I/O performed by a single thread to be kept bundled. The only case where
the use of flockfile ( ) and funlockfile ( ) is required is to provide a scope protecting uses of the
*_unlocked( ) functions/macros. This moves the cost/performance tradeoff to the optimal point.
12075
12076
FUTURE DIRECTIONS
None.
12077
12078
SEE ALSO
getc_unlocked ( ), putc_unlocked( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
12079
12080
CHANGE HISTORY
First released in Issue 5. Included for alignment with the POSIX Threads Extension.
12081
12082
Issue 6
These functions are marked as part of the Thread-Safe Functions option.
374
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
floor( )
System Interfaces
12083
12084
NAME
12085
12086
SYNOPSIS
#include <math.h>
floor, floorf, floorl — floor function
double floor(double x);
float floorf(float x);
long double floorl(long double x);
12087
12088
12089
12090 DESCRIPTION
12091 CX
The functionality described on this reference page is aligned with the ISO C standard.
12092
conflict between the requirements described here and the ISO C standard is unintentional.
12093
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
12094
These functions shall compute the largest integral value not greater than x.
12095
12096
12097
12098
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
12099
12100
12101
12102
RETURN VALUE
Upon successful completion, these functions shall return the largest integral value not greater
than x, expressed as a double, float, or long double, as appropriate for the return type of the
function.
12103 MX
If x is NaN, a NaN shall be returned.
12104
If x is ±0 or ±Inf, x shall be returned.
12105 XSI
12106
12107
If the correct value would cause overflow, a range error shall occur and floor ( ), floorf ( ), and
floorl ( ) shall return the value of the macro −HUGE_VAL, −HUGE_VALF, and −HUGE_VALL,
respectively.
12108
12109
ERRORS
These functions shall fail if:
12110 XSI
Range Error
The result would cause an overflow.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow
floating-point exception shall be raised.
12111
12112
12113
12114
12115
12116
EXAMPLES
None.
12117
12118
12119
12120
APPLICATION USAGE
The integral value returned by these functions might not be expressible as an int or long. The
return value should be tested before assigning it to an integer type to avoid the undefined results
of an integer overflow.
12121
12122
The floor ( ) function can only overflow when the floating-point representation has
DBL_MANT_DIG > DBL_MAX_EXP.
12123
12124
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
375
floor( )
System Interfaces
12125
12126
RATIONALE
None.
12127
12128
FUTURE DIRECTIONS
None.
12129
12130
12131
SEE ALSO
ceil( ), feclearexcept( ), fetestexcept( ), isnan( ), the Base Definitions volume of IEEE Std 1003.1-2001,
Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
12132
12133
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
12134
12135
12136
Issue 5
12137
12138
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The floorf ( ) and floorl ( ) functions are added for alignment with the ISO/IEC 9899: 1999 standard.
12139
12140
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
12141
12142
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
376
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fma( )
System Interfaces
12143
12144
NAME
12145
12146
SYNOPSIS
#include <math.h>
fma, fmaf, fmal — floating-point multiply-add
double fma(double x, double y, double z);
float fmaf(float x, float y, float z);
long double fmal(long double x, long double y, long double z);
12147
12148
12149
12150 DESCRIPTION
12151 CX
The functionality described on this reference page is aligned with the ISO C standard.
12152
conflict between the requirements described here and the ISO C standard is unintentional.
12153
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
12154
12155
12156
These functions shall compute (x * y) + z, rounded as one ternary operation: they shall compute
the value (as if) to infinite precision and round once to the result format, according to the
rounding mode characterized by the value of FLT_ROUNDS.
12157
12158
12159
12160
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
12161
12162
12163
RETURN VALUE
Upon successful completion, these functions shall return (x * y) + z, rounded as one ternary
operation.
12164 MX
If x or y are NaN, a NaN shall be returned.
12165
12166
12167
If x multiplied by y is an exact infinity and z is also an infinity but with the opposite sign, a
domain error shall occur, and either a NaN (if supported), or an implementation-defined value
shall be returned.
12168
12169
If one of x and y is infinite, the other is zero, and z is not a NaN, a domain error shall occur, and
either a NaN (if supported), or an implementation-defined value shall be returned.
12170
12171
If one of x and y is infinite, the other is zero, and z is a NaN, a NaN shall be returned and a
domain error may occur.
12172
If x*y is not 0*Inf nor Inf*0 and z is a NaN, a NaN shall be returned.
12173
12174
ERRORS
These functions shall fail if:
12175 MX
Domain Error
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [EDOM]. If the integer expression (math_errhandling
& MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception
shall be raised.
12176
12177
12178
12179
12180 MX
12181
12182
12183
12184
12185
The value of x*y+z is invalid, or the value x*y is invalid and z is not a NaN.
Range Error
The result overflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow
floating-point exception shall be raised.
These functions may fail if:
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
377
fma( )
12186 MX
System Interfaces
Domain Error
The value x*y is invalid and z is a NaN.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [EDOM]. If the integer expression (math_errhandling
& MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception
shall be raised.
12187
12188
12189
12190
12191 MX
Range Error
The result underflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
12192
12193
12194
12195
12196
12197
EXAMPLES
None.
12198
12199
12200
APPLICATION USAGE
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
12201
12202
12203
12204
12205
12206
RATIONALE
In many cases, clever use of floating (fused) multiply-add leads to much improved code; but its
unexpected use by the compiler can undermine carefully written code. The FP_CONTRACT
macro can be used to disallow use of floating multiply-add; and the fma( ) function guarantees
its use where desired. Many current machines provide hardware floating multiply-add
instructions; software implementation can be used for others.
12207
12208
FUTURE DIRECTIONS
None.
12209
12210
12211
SEE ALSO
feclearexcept( ), fetestexcept( ), the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18,
Treatment of Error Conditions for Mathematical Functions, <math.h>
12212
12213
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
378
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
12214
12215
NAME
12216
12217
SYNOPSIS
#include <math.h>
fmax( )
fmax, fmaxf, fmaxl — determine maximum numeric value of two floating-point numbers
double fmax(double x, double y);
float fmaxf(float x, float y);
long double fmaxl(long double x, long double y);
12218
12219
12220
12221 DESCRIPTION
12222 CX
The functionality described on this reference page is aligned with the ISO C standard.
12223
conflict between the requirements described here and the ISO C standard is unintentional.
12224
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
12225
12226
12227
These functions shall determine the maximum numeric value of their arguments. NaN
arguments shall be treated as missing data: if one argument is a NaN and the other numeric,
then these functions shall choose the numeric value.
12228
12229
12230
RETURN VALUE
Upon successful completion, these functions shall return the maximum numeric value of their
arguments.
12231
If just one argument is a NaN, the other argument shall be returned.
12232 MX
If x and y are NaN, a NaN shall be returned.
12233
12234
ERRORS
No errors are defined.
12235
12236
EXAMPLES
None.
12237
12238
APPLICATION USAGE
None.
12239
12240
RATIONALE
None.
12241
12242
FUTURE DIRECTIONS
None.
12243
12244
SEE ALSO
fdim( ), fmin( ), the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>
12245
12246
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
379
fmin( )
System Interfaces
12247
12248
NAME
12249
12250
SYNOPSIS
#include <math.h>
fmin, fminf, fminl — determine minimum numeric value of two floating-point numbers
double fmin(double x, double y);
float fminf(float x, float y);
long double fminl(long double x, long double y);
12251
12252
12253
12254 DESCRIPTION
12255 CX
The functionality described on this reference page is aligned with the ISO C standard.
12256
conflict between the requirements described here and the ISO C standard is unintentional.
12257
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
12258
12259
12260
These functions shall determine the minimum numeric value of their arguments. NaN
arguments shall be treated as missing data: if one argument is a NaN and the other numeric,
then these functions shall choose the numeric value.
12261
12262
12263
RETURN VALUE
Upon successful completion, these functions shall return the minimum numeric value of their
arguments.
12264
If just one argument is a NaN, the other argument shall be returned.
12265 MX
If x and y are NaN, a NaN shall be returned.
12266
12267
ERRORS
No errors are defined.
12268
12269
EXAMPLES
None.
12270
12271
APPLICATION USAGE
None.
12272
12273
RATIONALE
None.
12274
12275
FUTURE DIRECTIONS
None.
12276
12277
SEE ALSO
fdim( ), fmax( ), the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>
12278
12279
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
380
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fmod( )
System Interfaces
12280
12281
NAME
12282
12283
SYNOPSIS
#include <math.h>
fmod, fmodf, fmodl — floating-point remainder value function
double fmod(double x, double y);
float fmodf(float x, float y);
long double fmodl(long double x, long double y);
12284
12285
12286
12287 DESCRIPTION
12288 CX
The functionality described on this reference page is aligned with the ISO C standard.
12289
conflict between the requirements described here and the ISO C standard is unintentional.
12290
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
12291
These functions shall return the floating-point remainder of the division of x by y.
12292
12293
12294
12295
An application wishing to check for error situations should set errno to zero and call
feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is nonzero, an error has occurred.
12296
12297
12298
RETURN VALUE
These functions shall return the value x−i*y, for some integer i such that, if y is non-zero, the
result has the same sign as x and magnitude less than the magnitude of y.
12299
12300 MX
If the correct value would cause underflow, and is not representable, a range error may occur,
and either 0.0 (if supported), or an implementation-defined value shall be returned.
12301 MX
If x or y is NaN, a NaN shall be returned.
12302
12303
If y is zero, a domain error shall occur, and either a NaN (if supported), or an implementationdefined value shall be returned.
12304
12305
If x is infinite, a domain error shall occur, and either a NaN (if supported), or an
implementation-defined value shall be returned.
12306
If x is ±0 and y is not zero, ±0 shall be returned.
12307
If x is not infinite and y is ±Inf, x shall be returned.
12308
12309
If the correct value would cause underflow, and is representable, a range error may occur and
the correct value shall be returned.
12310
12311
ERRORS
These functions shall fail if:
12312 MX
Domain Error
The x argument is infinite or y is zero.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [EDOM]. If the integer expression (math_errhandling
& MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception
shall be raised.
12313
12314
12315
12316
12317
These functions may fail if:
12318
Range Error
12319
12320
12321
12322
The result underflows.
If the integer expression (math_errhandling & MATH_ERRNO) is non-zero,
then errno shall be set to [ERANGE]. If the integer expression
(math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow
floating-point exception shall be raised.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
381
fmod( )
System Interfaces
12323
12324
EXAMPLES
None.
12325
12326
12327
APPLICATION USAGE
On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling &
MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.
12328
12329
RATIONALE
None.
12330
12331
FUTURE DIRECTIONS
None.
12332
12333
12334
SEE ALSO
feclearexcept( ), fetestexcept( ), isnan( ), the Base Definitions volume of IEEE Std 1003.1-2001,
Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>
12335
12336
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
12337
12338
12339
Issue 5
12340
12341
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The behavior for when the y argument is zero is now defined.
12342
12343
The fmodf( ) and fmodl( ) functions are added for alignment with the ISO/IEC 9899: 1999
standard.
12344
12345
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
12346
12347
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
382
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fmtmsg( )
System Interfaces
12348
12349
NAME
fmtmsg — display a message in the specified format on standard error and/or a system console
12350 SYNOPSIS
12351 XSI
#include
<fmtmsg.h>
12352
12353
12354
int fmtmsg(long classification, const char *label, int severity,
const char *text, const char *action, const char *tag);
12355
12356
12357
DESCRIPTION
The fmtmsg( ) function shall display messages in a specified format instead of the traditional
printf( ) function.
12358
12359
Based on a message’s classification component, fmtmsg( ) shall write a formatted message either
to standard error, to the console, or to both.
12360
12361
12362
A formatted message consists of up to five components as defined below. The component
classification is not part of a message displayed to the user, but defines the source of the message
and directs the display of the formatted message.
12363
12364
12365
12366
12367
12368
12369
classification
Contains the sum of identifying values constructed from the constants defined
below. Any one identifier from a subclass may be used in combination with a
single identifier from a different subclass. Two or more identifiers from the
same subclass should not be used together, with the exception of identifiers
from the display subclass. (Both display subclass identifiers may be used so
that messages can be displayed to both standard error and the system
console.)
12370
12371
12372
Major Classifications
Identifies the source of the condition. Identifiers are: MM_HARD
(hardware), MM_SOFT (software), and MM_FIRM (firmware).
12373
12374
12375
12376
Message Source Subclassifications
Identifies the type of software in which the problem is detected.
Identifiers are: MM_APPL (application), MM_UTIL (utility), and
MM_OPSYS (operating system).
12377
12378
12379
12380
12381
Display Subclassifications
Indicates where the message is to be displayed. Identifiers are:
MM_PRINT to display the message on the standard error stream,
MM_CONSOLE to display the message on the system console. One or
both identifiers may be used.
12382
12383
12384
12385
Status Subclassifications
Indicates whether the application can recover from the condition.
Identifiers are: MM_RECOVER (recoverable) and MM_NRECOV (nonrecoverable).
12386
12387
An additional identifier, MM_NULLMC, indicates that no classification
component is supplied for the message.
12388
12389
label
Identifies the source of the message. The format is two fields separated by a
colon. The first field is up to 10 bytes, the second is up to 14 bytes.
12390
severity
Indicates the seriousness of the condition. Identifiers for the levels of severity
are:
12391
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
383
fmtmsg( )
System Interfaces
12392
12393
MM_HALT
Indicates that the application has encountered a severe fault
and is halting. Produces the string "HALT".
12394
12395
MM_ERROR
Indicates that the application has detected a fault. Produces
the string "ERROR".
12396
12397
12398
MM_WARNING Indicates a condition that is out of the ordinary, that might
be a problem, and should be watched. Produces the string
"WARNING".
12399
12400
MM_INFO
Provides information about a condition that is not in error.
Produces the string "INFO".
12401
MM_NOSEV
Indicates that no severity level is supplied for the message.
12402
12403
12404
text
Describes the error condition that produced the message. The character string
is not limited to a specific size. If the character string is empty, then the text
produced is unspecified.
12405
12406
12407
action
Describes the first step to be taken in the error-recovery process. The fmtmsg( )
function precedes the action string with the prefix: "TO FIX:". The action
string is not limited to a specific size.
12408
12409
12410
tag
An identifier that references on-line documentation for the message.
Suggested usage is that tag includes the label and a unique identifying number.
A sample tag is "XSI:cat:146".
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
The MSGVERB environment variable (for message verbosity) shall determine for fmtmsg( )
which message components it is to select when writing messages to standard error. The value of
MSGVERB shall be a colon-separated list of optional keywords. Valid keywords are: label,
severity, text, action, and tag. If MSGVERB contains a keyword for a component and the
component’s value is not the component’s null value, fmtmsg( ) shall include that component in
the message when writing the message to standard error. If MSGVERB does not include a
keyword for a message component, that component shall not be included in the display of the
message. The keywords may appear in any order. If MSGVERB is not defined, if its value is the
null string, if its value is not of the correct format, or if it contains keywords other than the valid
ones listed above, fmtmsg( ) shall select all components.
12421
12422
MSGVERB shall determine which components are selected for display to standard error. All
message components shall be included in console messages.
12423
12424
RETURN VALUE
The fmtmsg( ) function shall return one of the following values:
12425
MM_OK
The function succeeded.
12426
MM_NOTOK
The function failed completely.
12427
12428
MM_NOMSG
The function was unable to generate a message on standard error, but
otherwise succeeded.
12429
12430
MM_NOCON
The function was unable to generate a console message, but otherwise
succeeded.
12431
12432
ERRORS
None.
384
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
12433
fmtmsg( )
EXAMPLES
1. The following example of fmtmsg( ):
12434
12435
12436
fmtmsg(MM_PRINT, "XSI:cat", MM_ERROR, "illegal option",
"refer to cat in user’s reference manual", "XSI:cat:001")
12437
produces a complete message in the specified message format:
12438
12439
XSI:cat: ERROR: illegal option
TO FIX: refer to cat in user’s reference manual XSI:cat:001
2. When the environment variable MSGVERB is set as follows:
12440
12441
MSGVERB=severity:text:action
12442
and Example 1 is used, fmtmsg( ) produces:
12443
12444
ERROR: illegal option
TO FIX: refer to cat in user’s reference manual
12445
12446
12447
APPLICATION USAGE
One or more message components may be systematically omitted from messages generated by
an application by using the null value of the argument for that component.
12448
12449
RATIONALE
None.
12450
12451
FUTURE DIRECTIONS
None.
12452
12453
SEE ALSO
printf( ), the Base Definitions volume of IEEE Std 1003.1-2001, <fmtmsg.h>
12454
12455
CHANGE HISTORY
First released in Issue 4, Version 2.
12456
12457
Issue 5
Moved from X/OPEN UNIX extension to BASE.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
385
fnmatch( )
System Interfaces
12458
12459
NAME
12460
12461
SYNOPSIS
#include <fnmatch.h>
fnmatch — match a filename or a pathname
12462
int fnmatch(const char *pattern, const char *string, int flags);
12463
12464
12465
12466
12467
DESCRIPTION
The fnmatch( ) function shall match patterns as described in the Shell and Utilities volume of
IEEE Std 1003.1-2001, Section 2.13.1, Patterns Matching a Single Character, and Section 2.13.2,
Patterns Matching Multiple Characters. It checks the string specified by the string argument to
see if it matches the pattern specified by the pattern argument.
12468
12469
12470
12471
12472
12473
The flags argument shall modify the interpretation of pattern and string. It is the bitwise-inclusive
OR of zero or more of the flags defined in <fnmatch.h>. If the FNM_PATHNAME flag is set in
flags, then a slash character (’/’) in string shall be explicitly matched by a slash in pattern; it shall
not be matched by either the asterisk or question-mark special characters, nor by a bracket
expression. If the FNM_PATHNAME flag is not set, the slash character shall be treated as an
ordinary character.
12474
12475
12476
12477
If FNM_NOESCAPE is not set in flags, a backslash character (’\’) in pattern followed by any
other character shall match that second character in string. In particular, "\\" shall match a
backslash in string. If FNM_NOESCAPE is set, a backslash character shall be treated as an
ordinary character.
12478
12479
12480
12481
If FNM_PERIOD is set in flags, then a leading period (’.’) in string shall match a period in
pattern; as described by rule 2 in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section
2.13.3, Patterns Used for Filename Expansion where the location of ‘‘leading’’ is indicated by the
value of FNM_PATHNAME:
12482
12483
•
If FNM_PATHNAME is set, a period is ‘‘leading’’ if it is the first character in string or if it
immediately follows a slash.
12484
•
If FNM_PATHNAME is not set, a period is ‘‘leading’’ only if it is the first character of string.
12485
If FNM_PERIOD is not set, then no special restrictions are placed on matching a period.
12486
12487
12488
12489
RETURN VALUE
If string matches the pattern specified by pattern, then fnmatch( ) shall return 0. If there is no
match, fnmatch( ) shall return FNM_NOMATCH, which is defined in <fnmatch.h>. If an error
occurs, fnmatch( ) shall return another non-zero value.
12490
12491
ERRORS
No errors are defined.
12492
12493
EXAMPLES
None.
12494
12495
12496
12497
12498
APPLICATION USAGE
The fnmatch( ) function has two major uses. It could be used by an application or utility that
needs to read a directory and apply a pattern against each entry. The find utility is an example of
this. It can also be used by the pax utility to process its pattern operands, or by applications that
need to match strings in a similar manner.
12499
12500
The name fnmatch( ) is intended to imply filename match, rather than pathname match. The default
action of this function is to match filenames, rather than pathnames, since it gives no special
significance to the slash character. With the FNM_PATHNAME flag, fnmatch( ) does match
pathnames, but without tilde expansion, parameter expansion, or special treatment for a period
12501
12502
386
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fnmatch( )
at the beginning of a filename.
12503
12504
12505
12506
12507
12508
12509
RATIONALE
This function replaced the REG_FILENAME flag of regcomp( ) in early proposals of this volume
of IEEE Std 1003.1-2001. It provides virtually the same functionality as the regcomp( ) and
regexec( ) functions using the REG_FILENAME and REG_FSLASH flags (the REG_FSLASH flag
was proposed for regcomp( ), and would have had the opposite effect from FNM_PATHNAME),
but with a simpler function and less system overhead.
12510
12511
FUTURE DIRECTIONS
None.
12512
12513
12514
SEE ALSO
glob( ), wordexp( ), the Base Definitions volume of IEEE Std 1003.1-2001, <fnmatch.h>, the Shell
and Utilities volume of IEEE Std 1003.1-2001
12515
12516
CHANGE HISTORY
First released in Issue 4. Derived from the ISO POSIX-2 standard.
12517
12518
Issue 5
Moved from POSIX2 C-language Binding to BASE.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
387
fopen( )
System Interfaces
12519
12520
NAME
12521
12522
SYNOPSIS
#include <stdio.h>
fopen — open a stream
FILE *fopen(const char *restrict filename, const char *restrict mode);
12523
12524 DESCRIPTION
12525 CX
The functionality described on this reference page is aligned with the ISO C standard.
12526
conflict between the requirements described here and the ISO C standard is unintentional.
12527
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
12528
12529
The fopen( ) function shall open the file whose pathname is the string pointed to by filename, and
associates a stream with it.
12530
12531
The mode argument points to a string. If the string is one of the following, the file shall be opened
in the indicated mode. Otherwise, the behavior is undefined.
12532
r or rb
Open file for reading.
12533
w or wb
Truncate to zero length or create file for writing.
12534
a or ab
Append; open or create file for writing at end-of-file.
12535
r+ or rb+ or r+b
Open file for update (reading and writing).
12536
w+ or wb+ or w+b
Truncate to zero length or create file for update.
12537
a+ or ab+ or a+b
Append; open or create file for update, writing at end-of-file.
12538 CX
12539
12540
The character ’b’ shall have no effect, but is allowed for ISO C standard conformance. Opening
a file with read mode (r as the first character in the mode argument) shall fail if the file does not
exist or cannot be read.
12541
12542
12543
Opening a file with append mode (a as the first character in the mode argument) shall cause all
subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening
calls to fseek( ).
12544
12545
12546
12547
12548
12549
When a file is opened with update mode (’+’ as the second or third character in the mode
argument), both input and output may be performed on the associated stream. However, the
application shall ensure that output is not directly followed by input without an intervening call
to fflush( ) or to a file positioning function (fseek( ), fsetpos( ), or rewind( )), and input is not directly
followed by output without an intervening call to a file positioning function, unless the input
operation encounters end-of-file.
12550
12551
When opened, a stream is fully buffered if and only if it can be determined not to refer to an
interactive device. The error and end-of-file indicators for the stream shall be cleared.
12552 CX
12553
12554
If mode is w, wb, a, ab, w+, wb+, w+b, a+, ab+, or a+b, and the file did not previously exist, upon
successful completion, the fopen( ) function shall mark for update the st_atime, st_ctime, and
st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory.
12555
12556
12557
If mode is w, wb, w+, wb+, or w+b, and the file did previously exist, upon successful completion,
fopen( ) shall mark for update the st_ctime and st_mtime fields of the file. The fopen( ) function
shall allocate a file descriptor as open( ) does.
12558 XSI
12559
After a successful call to the fopen( ) function, the orientation of the stream shall be cleared, the
encoding rule shall be cleared, and the associated mbstate_t object shall be set to describe an
initial conversion state.
12560
388
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fopen( )
System Interfaces
12561 CX
12562
The largest value that can be represented correctly in an object of type off_t shall be established
as the offset maximum in the open file description.
12563 RETURN VALUE
12564
Upon successful completion, fopen( ) shall return a pointer to the object controlling the
12565 CX
Otherwise, a null pointer shall be returned, and errno shall be set to indicate the error.
12566
12567
stream.
ERRORS
The fopen( ) function shall fail if:
12568 CX
12569
12570
12571
[EACCES]
Search permission is denied on a component of the path prefix, or the file
exists and the permissions specified by mode are denied, or the file does not
exist and write permission is denied for the parent directory of the file to be
created.
12572 CX
[EINTR]
A signal was caught during fopen( ).
12573 CX
[EISDIR]
The named file is a directory and mode requires write access.
12574 CX
12575
[ELOOP]
A loop exists in symbolic links encountered during resolution of the path
argument.
12576 CX
[EMFILE]
{OPEN_MAX} file descriptors are currently open in the calling process.
12577 CX
12578
12579
[ENAMETOOLONG]
The length of the filename argument exceeds {PATH_MAX} or a pathname
component is longer than {NAME_MAX}.
12580 CX
[ENFILE]
The maximum allowable number of files is currently open in the system.
12581 CX
12582
[ENOENT]
A component of filename does not name an existing file or filename is an empty
string.
12583 CX
12584
[ENOSPC]
The directory or file system that would contain the new file cannot be
expanded, the file does not exist, and the file was to be created.
12585 CX
[ENOTDIR]
A component of the path prefix is not a directory.
12586 CX
12587
[ENXIO]
The named file is a character special or block special file, and the device
associated with this special file does not exist.
12588 CX
12589
[EOVERFLOW]
The named file is a regular file and the size of the file cannot be represented
correctly in an object of type off_t.
12590 CX
12591
[EROFS]
The named file resides on a read-only file system and mode requires write
access.
12592
The fopen( ) function may fail if:
12593 CX
[EINVAL]
The value of the mode argument is not valid.
12594 CX
12595
[ELOOP]
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path argument.
12596 CX
[EMFILE]
{FOPEN_MAX} streams are currently open in the calling process.
12597 CX
[EMFILE]
{STREAM_MAX} streams are currently open in the calling process.
12598 CX
12599
[ENAMETOOLONG]
Pathname resolution of a symbolic link produced an intermediate result
whose length exceeds {PATH_MAX}.
12600
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
389
fopen( )
System Interfaces
12601 CX
[ENOMEM]
Insufficient storage space is available.
12602 CX
12603
[ETXTBSY]
The file is a pure procedure (shared text) file that is being executed and mode
requires write access.
12604
EXAMPLES
12605
Opening a File
12606
12607
12608
The following example tries to open the file named file for reading. The fopen( ) function returns
a file pointer that is used in subsequent fgets( ) and fclose( ) calls. If the program cannot open the
file, it just ignores it.
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
#include <stdio.h>
...
FILE *fp;
...
void rgrep(const char *file)
{
...
if ((fp = fopen(file, "r")) == NULL)
return;
...
}
12620
12621
APPLICATION USAGE
None.
12622
12623
RATIONALE
None.
12624
12625
FUTURE DIRECTIONS
None.
12626
12627
SEE ALSO
fclose( ), fdopen( ), freopen( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
12628
12629
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
12630
12631
Issue 5
12632
12633
Issue 6
Large File Summit extensions are added.
Extensions beyond the ISO C standard are marked.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
12634
12635
12636
12637
•
In the DESCRIPTION, text is added to indicate setting of the offset maximum in the open file
description. This change is to support large files.
12638
12639
•
In the ERRORS section, the [EOVERFLOW] condition is added. This change is to support
large files.
12640
•
The [ELOOP] mandatory error condition is added.
12641
•
The [EINVAL], [EMFILE], [ENAMETOOLONG], [ENOMEM], and [ETXTBSY] optional error
conditions are added.
12642
390
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fopen( )
12643
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
12644
The following changes are made for alignment with the ISO/IEC 9899: 1999 standard:
12645
•
The prototype for fopen( ) is updated.
12646
12647
•
The DESCRIPTION is updated to note that if the argument mode points to a string other than
those listed, then the behavior is undefined.
12648
12649
The wording of the mandatory [ELOOP] error condition is updated, and a second optional
[ELOOP] error condition is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
391
fork( )
System Interfaces
12650
12651
NAME
12652
12653
SYNOPSIS
#include <unistd.h>
fork — create a new process
pid_t fork(void);
12654
12655
12656
12657
DESCRIPTION
The fork ( ) function shall create a new process. The new process (child process) shall be an exact
copy of the calling process (parent process) except as detailed below:
12658
•
The child process shall have a unique process ID.
12659
•
The child process ID also shall not match any active process group ID.
12660
12661
•
The child process shall have a different parent process ID, which shall be the process ID of
the calling process.
12662
12663
12664
•
The child process shall have its own copy of the parent’s file descriptors. Each of the child’s
file descriptors shall refer to the same open file description with the corresponding file
descriptor of the parent.
12665
12666
12667
•
The child process shall have its own copy of the parent’s open directory streams. Each open
directory stream in the child process may share directory stream positioning with the
corresponding directory stream of the parent.
12668 XSI
•
The child process shall have its own copy of the parent’s message catalog descriptors.
12669
•
The child process’ values of tms_utime, tms_stime, tms_cutime, and tms_cstime shall be set to 0.
12670
12671
•
The time left until an alarm clock signal shall be reset to zero, and the alarm, if any, shall be
canceled; see alarm( ).
12672 XSI
•
All semadj values shall be cleared.
12673
•
File locks set by the parent process shall not be inherited by the child process.
12674
•
The set of signals pending for the child process shall be initialized to the empty set.
12675 XSI
•
Interval timers shall be reset in the child process.
12676 SEM
•
Any semaphores that are open in the parent process shall also be open in the child process.
12677 ML
12678
•
The child process shall not inherit any address space memory locks established by the parent
process via calls to mlockall ( ) or mlock( ).
12679 MF|SHM
12680
12681
12682
12683
12684
12685
•
Memory mappings created in the parent shall be retained in the child process.
MAP_PRIVATE mappings inherited from the parent shall also be MAP_PRIVATE mappings
in the child, and any modifications to the data in these mappings made by the parent prior to
calling fork ( ) shall be visible to the child. Any modifications to the data in MAP_PRIVATE
mappings made by the parent after fork ( ) returns shall be visible only to the parent.
Modifications to the data in MAP_PRIVATE mappings made by the child shall be visible only
to the child.
12686 PS
12687
12688
•
For the SCHED_FIFO and SCHED_RR scheduling policies, the child process shall inherit the
policy and priority settings of the parent process during a fork ( ) function. For other
scheduling policies, the policy and priority settings on fork ( ) are implementation-defined.
12689 TMR
•
Per-process timers created by the parent shall not be inherited by the child process.
12690 MSG
12691
•
The child process shall have its own copy of the message queue descriptors of the parent.
Each of the message descriptors of the child shall refer to the same open message queue
392
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fork( )
System Interfaces
description as the corresponding message descriptor of the parent.
12692
12693 AIO
12694
•
No asynchronous input or asynchronous output operations shall be inherited by the child
process.
12695
12696
12697
12698
12699 THR
12700
•
A process shall be created with a single thread. If a multi-threaded process calls fork ( ), the
new process shall contain a replica of the calling thread and its entire address space, possibly
including the states of mutexes and other resources. Consequently, to avoid errors, the child
process may only execute async-signal-safe operations until such time as one of the exec
functions is called. Fork handlers may be established by means of the pthread_atfork( )
function in order to maintain application invariants across fork ( ) calls.
12701 TRC TRI
•
If the Trace option and the Trace Inherit option are both supported:
If the calling process was being traced in a trace stream that had its inheritance policy set to
POSIX_TRACE_INHERITED, the child process shall be traced into that trace stream, and the
child process shall inherit the parent’s mapping of trace event names to trace event type
identifiers. If the trace stream in which the calling process was being traced had its
inheritance policy set to POSIX_TRACE_CLOSE_FOR_CHILD, the child process shall not be
traced into that trace stream. The inheritance policy is set by a call to the
posix_trace_attr_setinherited( ) function.
12702
12703
12704
12705
12706
12707
12708
12709 TRC
•
If the Trace option is supported, but the Trace Inherit option is not supported:
The child process shall not be traced into any of the trace streams of its parent process.
12710
12711 TRC
12712
•
If the Trace option is supported, the child process of a trace controller process shall not
control the trace streams controlled by its parent process.
12713 CPT
•
The initial value of the CPU-time clock of the child process shall be set to zero.
12714 TCT
12715
•
The initial value of the CPU-time clock of the single thread of the child process shall be set to
zero.
12716
12717
12718
All other process characteristics defined by IEEE Std 1003.1-2001 shall be the same in the parent
and child processes. The inheritance of process characteristics not defined by
IEEE Std 1003.1-2001 is unspecified by IEEE Std 1003.1-2001.
12719
12720
After fork ( ), both the parent and the child processes shall be capable of executing independently
before either one terminates.
12721
12722
12723
12724
12725
RETURN VALUE
Upon successful completion, fork ( ) shall return 0 to the child process and shall return the
process ID of the child process to the parent process. Both processes shall continue to execute
from the fork ( ) function. Otherwise, −1 shall be returned to the parent process, no child process
shall be created, and errno shall be set to indicate the error.
12726
12727
ERRORS
The fork ( ) function shall fail if:
12728
12729
12730
[EAGAIN]
The system lacked the necessary resources to create another process, or the
system-imposed limit on the total number of processes under execution
system-wide or by a single user {CHILD_MAX} would be exceeded.
12731
The fork ( ) function may fail if:
12732
[ENOMEM]
Insufficient storage space is available.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
393
fork( )
System Interfaces
12733
12734
EXAMPLES
None.
12735
12736
APPLICATION USAGE
None.
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
RATIONALE
Many historical implementations have timing windows where a signal sent to a process group
(for example, an interactive SIGINT) just prior to or during execution of fork ( ) is delivered to the
parent following the fork ( ) but not to the child because the fork ( ) code clears the child’s set of
pending signals. This volume of IEEE Std 1003.1-2001 does not require, or even permit, this
behavior. However, it is pragmatic to expect that problems of this nature may continue to exist
in implementations that appear to conform to this volume of IEEE Std 1003.1-2001 and pass
available verification suites. This behavior is only a consequence of the implementation failing to
make the interval between signal generation and delivery totally invisible. From the
application’s perspective, a fork ( ) call should appear atomic. A signal that is generated prior to
the fork ( ) should be delivered prior to the fork ( ). A signal sent to the process group after the
fork ( ) should be delivered to both parent and child. The implementation may actually initialize
internal data structures corresponding to the child’s set of pending signals to include signals
sent to the process group during the fork ( ). Since the fork ( ) call can be considered as atomic
from the application’s perspective, the set would be initialized as empty and such signals would
have arrived after the fork ( ); see also <signal.h>.
12753
12754
12755
12756
12757
One approach that has been suggested to address the problem of signal inheritance across fork ( )
is to add an [EINTR] error, which would be returned when a signal is detected during the call.
While this is preferable to losing signals, it was not considered an optimal solution. Although it
is not recommended for this purpose, such an error would be an allowable extension for an
implementation.
12758
12759
12760
12761
12762
12763
12764
12765
The [ENOMEM] error value is reserved for those implementations that detect and distinguish
such a condition. This condition occurs when an implementation detects that there is not enough
memory to create the process. This is intended to be returned when [EAGAIN] is inappropriate
because there can never be enough memory (either primary or secondary storage) to perform the
operation. Since fork ( ) duplicates an existing process, this must be a condition where there is
sufficient memory for one such process, but not for two. Many historical implementations
actually return [ENOMEM] due to temporary lack of memory, a case that is not generally
distinct from [EAGAIN] from the perspective of a conforming application.
12766
12767
12768
Part of the reason for including the optional error [ENOMEM] is because the SVID specifies it
and it should be reserved for the error condition specified there. The condition is not applicable
on many implementations.
12769
12770
12771
12772
12773
12774
12775
IEEE Std 1003.1-1988 neglected to require concurrent execution of the parent and child of fork ( ).
A system that single-threads processes was clearly not intended and is considered an
unacceptable ‘‘toy implementation’’ of this volume of IEEE Std 1003.1-2001. The only objection
anticipated to the phrase ‘‘executing independently’’ is testability, but this assertion should be
testable. Such tests require that both the parent and child can block on a detectable action of the
other, such as a write to a pipe or a signal. An interactive exchange of such actions should be
possible for the system to conform to the intent of this volume of IEEE Std 1003.1-2001.
12776
12777
12778
The [EAGAIN] error exists to warn applications that such a condition might occur. Whether it
occurs or not is not in any practical sense under the control of the application because the
condition is usually a consequence of the user’s use of the system, not of the application’s code.
Thus, no application can or should rely upon its occurrence under any circumstances, nor
should the exact semantics of what concept of ‘‘user’’ is used be of concern to the application
writer. Validation writers should be cognizant of this limitation.
12779
12780
12781
394
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fork( )
12782
12783
12784
12785
There are two reasons why POSIX programmers call fork ( ). One reason is to create a new thread
of control within the same program (which was originally only possible in POSIX by creating a
new process); the other is to create a new process running a different program. In the latter case,
the call to fork ( ) is soon followed by a call to one of the exec functions.
12786
12787
12788
12789
12790
12791
12792
12793
The general problem with making fork ( ) work in a multi-threaded world is what to do with all
of the threads. There are two alternatives. One is to copy all of the threads into the new process.
This causes the programmer or implementation to deal with threads that are suspended on
system calls or that might be about to execute system calls that should not be executed in the
new process. The other alternative is to copy only the thread that calls fork ( ). This creates the
difficulty that the state of process-local resources is usually held in process memory. If a thread
that is not calling fork ( ) holds a resource, that resource is never released in the child process
because the thread whose job it is to release the resource does not exist in the child process.
12794
12795
12796
12797
When a programmer is writing a multi-threaded program, the first described use of fork ( ),
creating new threads in the same program, is provided by the pthread_create( ) function. The
fork ( ) function is thus used only to run new programs, and the effects of calling functions that
require certain resources between the call to fork ( ) and the call to an exec function are undefined.
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
The addition of the forkall ( ) function to the standard was considered and rejected. The forkall ( )
function lets all the threads in the parent be duplicated in the child. This essentially duplicates
the state of the parent in the child. This allows threads in the child to continue processing and
allows locks and the state to be preserved without explicit pthread_atfork( ) code. The calling
process has to ensure that the threads processing state that is shared between the parent and
child (that is, file descriptors or MAP_SHARED memory) behaves properly after forkall ( ). For
example, if a thread is reading a file descriptor in the parent when forkall ( ) is called, then two
threads (one in the parent and one in the child) are reading the file descriptor after the forkall ( ).
If this is not desired behavior, the parent process has to synchronize with such threads before
calling forkall ( ).
12808
12809
12810
12811
12812
12813
When forkall ( ) is called, threads, other than the calling thread, that are in functions that can
return with an [EINTR] error may have those functions return [EINTR] if the implementation
cannot ensure that the function behaves correctly in the parent and child. In particular,
pthread_cond_wait( ) and pthread_cond_timedwait( ) need to return in order to ensure that the
condition has not changed. These functions can be awakened by a spurious condition wakeup
rather than returning [EINTR].
12814
12815
FUTURE DIRECTIONS
None.
12816
12817
12818
SEE ALSO
alarm( ), exec, fcntl( ), posix_trace_attr_getinherited( ), posix_trace_trid_eventid_open( ), semop( ),
signal( ), times( ), the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>
12819
12820
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
12821
12822
12823
Issue 5
12824
12825
12826
Issue 6
12827
12828
The DESCRIPTION is changed for alignment with the POSIX Realtime Extension and the POSIX
Threads Extension.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
•
The requirement to include <sys/types.h> has been removed. Although <sys/types.h> was
required for conforming implementations of previous POSIX specifications, it was not
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
395
fork( )
System Interfaces
required for UNIX applications.
12829
The following changes were made to align with the IEEE P1003.1a draft standard:
12830
•
12831
The effect of fork ( ) on a pending alarm call in the child process is clarified.
12832
The description of CPU-time clock semantics is added for alignment with IEEE Std 1003.1d-1999.
12833
The description of tracing semantics is added for alignment with IEEE Std 1003.1q-2000.
396
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
12834
12835
NAME
12836
12837
SYNOPSIS
#include <unistd.h>
fpathconf, pathconf — get configurable pathname variables
long fpathconf(int fildes, int name);
long pathconf(const char *path, int name);
12838
12839
12840
12841
12842
fpathconf( )
DESCRIPTION
The fpathconf ( ) and pathconf ( ) functions shall determine the current value of a configurable limit
or option (variable) that is associated with a file or directory.
12843
For pathconf ( ), the path argument points to the pathname of a file or directory.
12844
For fpathconf ( ), the fildes argument is an open file descriptor.
12845
12846
12847
12848
12849
12850
12851
The name argument represents the variable to be queried relative to that file or directory.
Implementations shall support all of the variables listed in the following table and may support
others. The variables in the following table come from <limits.h> or <unistd.h> and the
symbolic constants, defined in <unistd.h>, are the corresponding values used for name. Support
for some pathname configuration variables is dependent on implementation options (see
shading and margin codes in the table below). Where an implementation option is not
supported, the variable need not be supported.
_____________________________________________________________________________
L
L
Variable
Value of name
Requirements L
_L ____________________________________________________________________________
L
L
L
L
{FILESIZEBITS}
_PC_FILESIZEBITS
3, 4
L
L
L
L
{LINK_MAX}
_PC_LINK_MAX
1
L
L
L
L
_PC_MAX_CANON
2
L {MAX_CANON}
L
L
L
L {MAX_INPUT}
L
L
L
_PC_MAX_INPUT
2
L
L
L
L
{NAME_MAX}
_PC_NAME_MAX
3, 4
L
L
L
L
{PATH_MAX}
_PC_PATH_MAX
4, 5
L
L
L
L
{PIPE_BUF}
_PC_PIPE_BUF
6
L
L
L
L
_PC_ALLOC_SIZE_MIN
L {POSIX_ALLOC_SIZE_MIN}
L
L
L
L {POSIX_REC_INCR_XFER_SIZE}
L
L
_PC_REC_INCR_XFER_SIZE L
L
L
{POSIX_REC_MAX_XFER_SIZE} L _PC_REC_MAX_XFER_SIZE L
L
L
L
L
{POSIX_REC_MIN_XFER_SIZE}
_PC_REC_MIN_XFER_SIZE
L
L
L
L
{POSIX_REC_XFER_ALIGN}
_PC_REC_XFER_ALIGN
L
L
L
L
_PC_SYMLINK_MAX
4, 9
L {SYMLINK_MAX}
L
L
L
L _POSIX_CHOWN_RESTRICTED
L
L
_PC_CHOWN_RESTRICTED L 7
L
L
L
L
_POSIX_NO_TRUNC
_PC_NO_TRUNC
3, 4
L
L
L
L
_POSIX_VDISABLE
_PC_VDISABLE
2
L
L
L
L
_POSIX_ASYNC_IO
_PC_ASYNC_IO
8
L
L
L
L
_PC_PRIO_IO
8
L _POSIX_PRIO_IO
L
L
L
L _POSIX_SYNC_IO
L
L
L
_PC_SYNC_IO
8
____________________________________________________________________________
L
L
L
L_
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
ADV
ADV
ADV
ADV
ADV
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
397
fpathconf( )
System Interfaces
Requirements
12873
12874
1. If path or fildes refers to a directory, the value returned shall apply to the directory itself.
12875
12876
2. If path or fildes does not refer to a terminal file, it is unspecified whether an implementation
supports an association of the variable name with the specified file.
12877
12878
3. If path or fildes refers to a directory, the value returned shall apply to filenames within the
directory.
12879
12880
4. If path or fildes does not refer to a directory, it is unspecified whether an implementation
supports an association of the variable name with the specified file.
12881
12882
5. If path or fildes refers to a directory, the value returned shall be the maximum length of a
relative pathname when the specified directory is the working directory.
12883
12884
12885
12886
12887
6. If path refers to a FIFO, or fildes refers to a pipe or FIFO, the value returned shall apply to
the referenced object. If path or fildes refers to a directory, the value returned shall apply to
any FIFO that exists or can be created within the directory. If path or fildes refers to any
other type of file, it is unspecified whether an implementation supports an association of
the variable name with the specified file.
12888
12889
7. If path or fildes refers to a directory, the value returned shall apply to any files, other than
directories, that exist or can be created within the directory.
12890
12891
8. If path or fildes refers to a directory, it is unspecified whether an implementation supports
an association of the variable name with the specified file.
12892
12893
9. If path or fildes refers to a directory, the value returned shall be the maximum length of the
string that a symbolic link in that directory can contain.
12894
12895
12896
RETURN VALUE
If name is an invalid value, both pathconf ( ) and fpathconf ( ) shall return −1 and set errno to
indicate the error.
12897
12898
12899
12900
12901
12902
If the variable corresponding to name has no limit for the path or file descriptor, both pathconf ( )
and fpathconf ( ) shall return −1 without changing errno. If the implementation needs to use path
to determine the value of name and the implementation does not support the association of name
with the file specified by path, or if the process did not have appropriate privileges to query the
file specified by path, or path does not exist, pathconf ( ) shall return −1 and set errno to indicate the
error.
12903
12904
12905
If the implementation needs to use fildes to determine the value of name and the implementation
does not support the association of name with the file specified by fildes, or if fildes is an invalid
file descriptor, fpathconf ( ) shall return −1 and set errno to indicate the error.
12906
12907
12908
12909
Otherwise, pathconf ( ) or fpathconf ( ) shall return the current variable value for the file or
directory without changing errno. The value returned shall not be more restrictive than the
corresponding value available to the application when it was compiled with the
implementation’s <limits.h> or <unistd.h>.
12910
12911
ERRORS
The pathconf ( ) function shall fail if:
12912
[EINVAL]
The value of name is not valid.
12913
12914
[ELOOP]
A loop exists in symbolic links encountered during resolution of the path
argument.
12915
The pathconf ( ) function may fail if:
398
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fpathconf( )
System Interfaces
12916
[EACCES]
Search permission is denied for a component of the path prefix.
12917
12918
[EINVAL]
The implementation does not support an association of the variable name with
the specified file.
12919
12920
[ELOOP]
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path argument.
12921
12922
12923
[ENAMETOOLONG]
The length of the path argument exceeds {PATH_MAX} or a pathname
component is longer than {NAME_MAX}.
12924
12925
12926
[ENAMETOOLONG]
As a result of encountering a symbolic link in resolution of the path argument,
the length of the substituted pathname string exceeded {PATH_MAX}.
12927
[ENOENT]
A component of path does not name an existing file or path is an empty string.
12928
[ENOTDIR]
A component of the path prefix is not a directory.
12929
The fpathconf ( ) function shall fail if:
12930
[EINVAL]
12931
The fpathconf ( ) function may fail if:
12932
[EBADF]
The fildes argument is not a valid file descriptor.
12933
12934
[EINVAL]
The implementation does not support an association of the variable name with
the specified file.
The value of name is not valid.
12935
12936
EXAMPLES
None.
12937
12938
APPLICATION USAGE
None.
12939
12940
12941
12942
RATIONALE
The pathconf ( ) function was proposed immediately after the sysconf( ) function when it was
realized that some configurable values may differ across file system, directory, or device
boundaries.
12943
12944
12945
12946
For example, {NAME_MAX} frequently changes between System V and BSD-based file systems;
System V uses a maximum of 14, BSD 255. On an implementation that provides both types of file
systems, an application would be forced to limit all pathname components to 14 bytes, as this
would be the value specified in <limits.h> on such a system.
12947
12948
Therefore, various useful values can be queried on any pathname or file descriptor, assuming
that the appropriate permissions are in place.
12949
12950
12951
12952
The value returned for the variable {PATH_MAX} indicates the longest relative pathname that
could be given if the specified directory is the process’ current working directory. A process may
not always be able to generate a name that long and use it if a subdirectory in the pathname
crosses into a more restrictive file system.
12953
12954
12955
12956
The value returned for the variable _POSIX_CHOWN_RESTRICTED also applies to directories
that do not have file systems mounted on them. The value may change when crossing a mount
point, so applications that need to know should check for each directory. (An even easier check
is to try the chown( ) function and look for an error in case it happens.)
12957
12958
Unlike the values returned by sysconf( ), the pathname-oriented variables are potentially more
volatile and are not guaranteed to remain constant throughout the process’ lifetime. For
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
399
fpathconf( )
System Interfaces
12959
12960
example, in between two calls to pathconf ( ), the file system in question may have been
unmounted and remounted with different characteristics.
12961
12962
12963
12964
Also note that most of the errors are optional. If one of the variables always has the same value
on an implementation, the implementation need not look at path or fildes to return that value and
is, therefore, not required to detect any of the errors except the meaning of [EINVAL] that
indicates that the value of name is not valid for that variable.
12965
12966
12967
12968
If the value of any of the limits is unspecified (logically infinite), they will not be defined in
<limits.h> and the pathconf ( ) and fpathconf ( ) functions return −1 without changing errno. This
can be distinguished from the case of giving an unrecognized name argument because errno is set
to [EINVAL] in this case.
12969
12970
Since −1 is a valid return value for the pathconf ( ) and fpathconf ( ) functions, applications should
set errno to zero before calling them and check errno only if the return value is −1.
12971
12972
For the case of {SYMLINK_MAX}, since both pathconf ( ) and open( ) follow symbolic links, there
is no way that path or fildes could refer to a symbolic link.
12973
12974
FUTURE DIRECTIONS
None.
12975
12976
12977
SEE ALSO
confstr( ), sysconf( ), the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <unistd.h>,
the Shell and Utilities volume of IEEE Std 1003.1-2001
12978
12979
CHANGE HISTORY
First released in Issue 3. Included for alignment with the POSIX.1-1988 standard.
12980
12981
Issue 5
The DESCRIPTION is updated for alignment with the POSIX Realtime Extension.
Large File Summit extensions are added.
12982
12983
12984
12985
Issue 6
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
12986
•
The DESCRIPTION is updated to include {FILESIZEBITS}.
12987
•
The [ELOOP] mandatory error condition is added.
12988
•
A second [ENAMETOOLONG] is added as an optional error condition.
The following changes were made to align with the IEEE P1003.1a draft standard:
12989
•
12990
The _PC_SYMLINK_MAX entry is added to the table in the DESCRIPTION.
The following pathconf ( ) variables and their associated names are added for alignment with
IEEE Std 1003.1d-1999:
12991
12992
{POSIX_ALLOC_SIZE_MIN}
{POSIX_REC_INCR_XFER_SIZE}
{POSIX_REC_MAX_XFER_SIZE}
{POSIX_REC_MIN_XFER_SIZE}
{POSIX_REC_XFER_ALIGN}
12993
12994
12995
12996
12997
400
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fpclassify( )
System Interfaces
12998
12999
NAME
13000
13001
SYNOPSIS
#include <math.h>
13002
fpclassify — classify real floating type
int fpclassify(real-floating x);
13003 DESCRIPTION
13004 CX
The functionality described on this reference page is aligned with the ISO C standard.
13005
conflict between the requirements described here and the ISO C standard is unintentional.
13006
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
13007
13008
13009
13010
The fpclassify ( ) macro shall classify its argument value as NaN, infinite, normal, subnormal,
zero, or into another implementation-defined category. First, an argument represented in a
format wider than its semantic type is converted to its semantic type. Then classification is based
on the type of the argument.
13011
13012
13013
RETURN VALUE
The fpclassify ( ) macro shall return the value of the number classification macro appropriate to
the value of its argument.
13014
13015
ERRORS
No errors are defined.
13016
13017
EXAMPLES
None.
13018
13019
APPLICATION USAGE
None.
13020
13021
RATIONALE
None.
13022
13023
FUTURE DIRECTIONS
None.
13024
13025
13026
SEE ALSO
isfinite ( ), isinf( ), isnan( ), isnormal( ),
IEEE Std 1003.1-2001, <math.h>
13027
13028
CHANGE HISTORY
First released in Issue 6. Derived from the ISO/IEC 9899: 1999 standard.
signbit( ),
the
Base
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
Definitions
volume
of
401
fprintf( )
System Interfaces
13029
13030
NAME
13031
13032
SYNOPSIS
#include <stdio.h>
fprintf, printf, snprintf, sprintf — print formatted output
int fprintf(FILE *restrict stream, const char *restrict format, ...);
int printf(const char *restrict format, ...);
int snprintf(char *restrict s, size_t n,
const char *restrict format, ...);
int sprintf(char *restrict s, const char *restrict format, ...);
13033
13034
13035
13036
13037
13038 DESCRIPTION
13039 CX
The functionality described on this reference page is aligned with the ISO C standard.
13040
conflict between the requirements described here and the ISO C standard is unintentional.
13041
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
13042
13043
13044
13045
The fprintf( ) function shall place output on the named output stream. The printf( ) function shall
place output on the standard output stream stdout. The sprintf( ) function shall place output
followed by the null byte, ’\0’, in consecutive bytes starting at *s; it is the user’s responsibility
to ensure that enough space is available.
13046
13047
13048
13049
13050
The snprintf( ) function shall be equivalent to sprintf( ), with the addition of the n argument
which states the size of the buffer referred to by s. If n is zero, nothing shall be written and s may
be a null pointer. Otherwise, output bytes beyond the n-1st shall be discarded instead of being
written to the array, and a null byte is written at the end of the bytes actually written into the
array.
13051
13052
If copying takes place between objects that overlap as a result of a call to sprintf( ) or snprintf( ),
the results are undefined.
13053
13054
13055
13056
13057
13058
13059
Each of these functions converts, formats, and prints its arguments under control of the format.
The format is a character string, beginning and ending in its initial shift state, if any. The format is
composed of zero or more directives: ordinary characters, which are simply copied to the output
stream, and conversion specifications, each of which shall result in the fetching of zero or more
arguments. The results are undefined if there are insufficient arguments for the format. If the
format is exhausted while arguments remain, the excess arguments shall be evaluated but are
otherwise ignored.
13060 XSI
13061
13062
13063
13064
13065
Conversions can be applied to the nth argument after the format in the argument list, rather than
to the next unused argument. In this case, the conversion specifier character % (see below) is
replaced by the sequence "%n$", where n is a decimal integer in the range [1,{NL_ARGMAX}],
giving the position of the argument in the argument list. This feature provides for the definition
of format strings that select arguments in an order appropriate to specific languages (see the
EXAMPLES section).
13066
13067
13068
13069
13070
13071
The format can contain either numbered argument conversion specifications (that is, "%n$" and
"*m$"), or unnumbered argument conversion specifications (that is, % and *), but not both. The
only exception to this is that %% can be mixed with the "%n$" form. The results of mixing
numbered and unnumbered argument specifications in a format string are undefined. When
numbered argument specifications are used, specifying the Nth argument requires that all the
leading arguments, from the first to the (N−1)th, are specified in the format string.
13072
13073
In format strings containing the "%n$" form of conversion specification, numbered arguments
in the argument list can be referenced from the format string as many times as required.
13074
13075
In format strings containing the % form of conversion specification, each conversion specification
uses the first unused argument in the argument list.
402
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fprintf( )
13076 CX
13077
13078
13079
All forms of the fprintf( ) functions allow for the insertion of a language-dependent radix
character in the output string. The radix character is defined in the program’s locale (category
LC_NUMERIC). In the POSIX locale, or in a locale where the radix character is not defined, the
radix character shall default to a period (’.’).
13080 XSI
13081
Each conversion specification is introduced by the ’%’ character or by the character sequence
"%n$",after which the following appear in sequence:
13082
•
Zero or more flags (in any order), which modify the meaning of the conversion specification.
13083
13084
13085
13086
•
An optional minimum field width. If the converted value has fewer bytes than the field
width, it shall be padded with spaces by default on the left; it shall be padded on the right if
the left-adjustment flag (’−’), described below, is given to the field width. The field width
takes the form of an asterisk (’*’), described below, or a decimal integer.
13087
13088
13089
13090
13091 XSI
13092
13093
13094
•
An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x,
and X conversion specifiers; the number of digits to appear after the radix character for the a,
A, e, E, f, and F conversion specifiers; the maximum number of significant digits for the g
and G conversion specifiers; or the maximum number of bytes to be printed from a string in
the s and S conversion specifiers. The precision takes the form of a period (’.’) followed
either by an asterisk (’*’), described below, or an optional decimal digit string, where a null
digit string is treated as zero. If a precision appears with any other conversion specifier, the
behavior is undefined.
13095
•
An optional length modifier that specifies the size of the argument.
13096
•
A conversion specifier character that indicates the type of conversion to be applied.
13097
13098
13099
13100
13101 XSI
13102
13103
13104
13105
A field width, or precision, or both, may be indicated by an asterisk (’*’). In this case an
argument of type int supplies the field width or precision. Applications shall ensure that
arguments specifying field width, or precision, or both appear in that order before the argument,
if any, to be converted. A negative field width is taken as a ’−’ flag followed by a positive field
width. A negative precision is taken as if the precision were omitted. In format strings
containing the "%n$" form of a conversion specification, a field width or precision may be
indicated by the sequence "*m$", where m is a decimal integer in the range [1,{NL_ARGMAX}]
giving the position in the argument list (after the format argument) of an integer argument
containing the field width or precision, for example:
13106
printf("%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec);
13107
The flag characters and their meanings are:
13108 XSI
13109
13110
’
The integer portion of the result of a decimal conversion (%i, %d, %u, %f, %F, %g, or %G)
shall be formatted with thousands’ grouping characters. For other conversions the
behavior is undefined. The non-monetary grouping character is used.
−
The result of the conversion shall be left-justified within the field. The conversion is
right-justified if this flag is not specified.
13113
13114
13115
+
The result of a signed conversion shall always begin with a sign (’+’ or ’−’). The
conversion shall begin with a sign only when a negative value is converted if this flag is
not specified.
13116
13117
13118
<space> If the first character of a signed conversion is not a sign or if a signed conversion results
in no characters, a <space> shall be prefixed to the result. This means that if the
<space> and ’+’ flags both appear, the <space> flag shall be ignored.
13119
13120
#
13111
13112
Specifies that the value is to be converted to an alternative form. For o conversion, it
increases the precision (if necessary) to force the first digit of the result to be zero. For x
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
403
fprintf( )
System Interfaces
or X conversion specifiers, a non-zero result shall have 0x (or 0X) prefixed to it. For a, A,
e, E, f, F, g, and G conversion specifiers, the result shall always contain a radix
character, even if no digits follow the radix character. Without this flag, a radix
character appears in the result of these conversions only if a digit follows it. For g and G
conversion specifiers, trailing zeros shall not be removed from the result as they
normally are. For other conversion specifiers, the behavior is undefined.
13121
13122
13123
13124
13125
13126
For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversion specifiers, leading zeros
(following any indication of sign or base) are used to pad to the field width; no space
padding is performed. If the ’0’ and ’−’ flags both appear, the ’0’ flag is ignored. For
d, i, o, u, x, and X conversion specifiers, if a precision is specified, the ’0’ flag is
ignored. If the ’0’ and ’’’ flags both appear, the grouping characters are inserted
before zero padding. For other conversions, the behavior is undefined.
13127
13128
13129
13130
13131 XSI
13132
0
13133
The length modifiers and their meanings are:
13134
13135
13136
13137
13138
hh
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char
or unsigned char argument (the argument will have been promoted according to the
integer promotions, but its value shall be converted to signed char or unsigned char
before printing); or that a following n conversion specifier applies to a pointer to a
signed char argument.
13139
13140
13141
13142
13143
h
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a short or
unsigned short argument (the argument will have been promoted according to the
integer promotions, but its value shall be converted to short or unsigned short before
printing); or that a following n conversion specifier applies to a pointer to a short
argument.
13144
13145
13146
13147
13148
l (ell)
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long or
unsigned long argument; that a following n conversion specifier applies to a pointer to
a long argument; that a following c conversion specifier applies to a wint_t argument;
that a following s conversion specifier applies to a pointer to a wchar_t argument; or
has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.
13149
13150
13151
13152
ll (ell-ell)
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long long or
unsigned long long argument; or that a following n conversion specifier applies to a
pointer to a long long argument.
13153
13154
13155
j
Specifies that a following d, i, o, u, x, or X conversion specifier applies to an intmax_t
or uintmax_t argument; or that a following n conversion specifier applies to a pointer
to an intmax_t argument.
13156
13157
13158
z
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a size_t or the
corresponding signed integer type argument; or that a following n conversion specifier
applies to a pointer to a signed integer type corresponding to a size_t argument.
13159
13160
13161
t
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or
the corresponding unsigned type argument; or that a following n conversion specifier
applies to a pointer to a ptrdiff_t argument.
13162
13163
L
Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long
double argument.
13164
If a length modifier appears with any conversion specifier other than as specified above, the
behavior is undefined.
13165
404
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fprintf( )
13166
The conversion specifiers and their meanings are:
13167
13168
13169
13170
13171
d, i
The int argument shall be converted to a signed decimal in the style "[−]dddd". The
precision specifies the minimum number of digits to appear; if the value being
converted can be represented in fewer digits, it shall be expanded with leading zeros.
The default precision is 1. The result of converting zero with an explicit precision of
zero shall be no characters.
13172
13173
13174
13175
13176
o
The unsigned argument shall be converted to unsigned octal format in the style
"dddd". The precision specifies the minimum number of digits to appear; if the value
being converted can be represented in fewer digits, it shall be expanded with leading
zeros. The default precision is 1. The result of converting zero with an explicit precision
of zero shall be no characters.
13177
13178
13179
13180
13181
u
The unsigned argument shall be converted to unsigned decimal format in the style
"dddd". The precision specifies the minimum number of digits to appear; if the value
being converted can be represented in fewer digits, it shall be expanded with leading
zeros. The default precision is 1. The result of converting zero with an explicit precision
of zero shall be no characters.
13182
13183
13184
13185
13186
x
The unsigned argument shall be converted to unsigned hexadecimal format in the style
"dddd"; the letters "abcdef" are used. The precision specifies the minimum number
of digits to appear; if the value being converted can be represented in fewer digits, it
shall be expanded with leading zeros. The default precision is 1. The result of
converting zero with an explicit precision of zero shall be no characters.
13187
13188
X
Equivalent to the x conversion specifier, except that letters "ABCDEF" are used instead
of "abcdef".
13189
13190
13191
13192
13193
13194
f, F
The double argument shall be converted to decimal notation in the style
"[−]ddd.ddd", where the number of digits after the radix character is equal to the
precision specification. If the precision is missing, it shall be taken as 6; if the precision
is explicitly zero and no ’#’ flag is present, no radix character shall appear. If a radix
character appears, at least one digit appears before it. The low-order digit shall be
rounded in an implementation-defined manner.
A double argument representing an infinity shall be converted in one of the styles
"[−]inf" or "[−]infinity"; which style is implementation-defined. A double
argument representing a NaN shall be converted in one of the styles "[−]nan(nchar-sequence)" or "[−]nan"; which style, and the meaning of any n-char-sequence,
is implementation-defined. The F conversion specifier produces "INF", "INFINITY",
or "NAN" instead of "inf", "infinity", or "nan", respectively.
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
e, E
A double argument representing an infinity or NaN shall be converted in the style of
an f or F conversion specifier.
13209
13210
13211
13212
The double argument shall be converted in the style "[−]d.ddde±dd", where there is
one digit before the radix character (which is non-zero if the argument is non-zero) and
the number of digits after it is equal to the precision; if the precision is missing, it shall
be taken as 6; if the precision is zero and no ’#’ flag is present, no radix character shall
appear. The low-order digit shall be rounded in an implementation-defined manner.
The E conversion specifier shall produce a number with ’E’ instead of ’e’
introducing the exponent. The exponent shall always contain at least two digits. If the
value is zero, the exponent shall be zero.
g, G
The double argument shall be converted in the style f or e (or in the style F or E in the
case of a G conversion specifier), with the precision specifying the number of significant
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
405
fprintf( )
System Interfaces
13213
13214
13215
13216
13217
digits. If an explicit precision is zero, it shall be taken as 1. The style used depends on
the value converted; style e (or E) shall be used only if the exponent resulting from
such a conversion is less than −4 or greater than or equal to the precision. Trailing zeros
shall be removed from the fractional portion of the result; a radix character shall appear
only if it is followed by a digit or a ’#’ flag is present.
13218
13219
A double argument representing an infinity or NaN shall be converted in the style of
an f or F conversion specifier.
a, A
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
A double argument representing a floating-point number shall be converted in the
style "[−]0xh.hhhhp±d", where there is one hexadecimal digit (which shall be nonzero if the argument is a normalized floating-point number and is otherwise
unspecified) before the decimal-point character and the number of hexadecimal digits
after it is equal to the precision; if the precision is missing and FLT_RADIX is a power
of 2, then the precision shall be sufficient for an exact representation of the value; if the
precision is missing and FLT_RADIX is not a power of 2, then the precision shall be
sufficient to distinguish values of type double, except that trailing zeros may be
omitted; if the precision is zero and the ’#’ flag is not specified, no decimal-point
character shall appear. The letters "abcdef" shall be used for a conversion and the
letters "ABCDEF" for A conversion. The A conversion specifier produces a number with
’X’ and ’P’ instead of ’x’ and ’p’. The exponent shall always contain at least one
digit, and only as many more digits as necessary to represent the decimal exponent of
2. If the value is zero, the exponent shall be zero.
A double argument representing an infinity or NaN shall be converted in the style of
an f or F conversion specifier.
13234
13235
c
13236
13237
The int argument shall be converted to an unsigned char, and the resulting byte shall
be written.
If an l (ell) qualifier is present, the wint_t argument shall be converted as if by an ls
conversion specification with no precision and an argument that points to a twoelement array of type wchar_t, the first element of which contains the wint_t argument
to the ls conversion specification and the second element contains a null wide
character.
13238
13239
13240
13241
13242
s
13243
13244
13245
13246
13247
The argument shall be a pointer to an array of char. Bytes from the array shall be
written up to (but not including) any terminating null byte. If the precision is specified,
no more than that many bytes shall be written. If the precision is not specified or is
greater than the size of the array, the application shall ensure that the array contains a
null byte.
If an l (ell) qualifier is present, the argument shall be a pointer to an array of type
wchar_t. Wide characters from the array shall be converted to characters (each as if by
a call to the wcrtomb( ) function, with the conversion state described by an mbstate_t
object initialized to zero before the first wide character is converted) up to and
including a terminating null wide character. The resulting characters shall be written
up to (but not including) the terminating null character (byte). If no precision is
specified, the application shall ensure that the array contains a null wide character. If a
precision is specified, no more than that many characters (bytes) shall be written
(including shift sequences, if any), and the array shall contain a null wide character if,
to equal the character sequence length given by the precision, the function would need
to access a wide character one past the end of the array. In no case shall a partial
character be written.
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
406
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fprintf( )
13260
13261
p
The argument shall be a pointer to void. The value of the pointer is converted to a
sequence of printable characters, in an implementation-defined manner.
13262
13263
13264
n
The argument shall be a pointer to an integer into which is written the number of bytes
written to the output so far by this call to one of the fprintf ( ) functions. No argument is
converted.
13265 XSI
C
Equivalent to lc.
13266 XSI
S
Equivalent to ls.
13267
13268
%
Print a ’%’ character; no argument is converted. The complete conversion specification
shall be %%.
13269
13270
13271
If a conversion specification does not match one of the above forms, the behavior is undefined. If
any argument is not the correct type for the corresponding conversion specification, the
behavior is undefined.
13272
13273
13274
In no case shall a nonexistent or small field width cause truncation of a field; if the result of a
conversion is wider than the field width, the field shall be expanded to contain the conversion
result. Characters generated by fprintf ( ) and printf( ) are printed as if fputc( ) had been called.
13275
13276
For the a and A conversion specifiers, if FLT_RADIX is a power of 2, the value shall be correctly
rounded to a hexadecimal floating number with the given precision.
13277
13278
13279
13280
For a and A conversions, if FLT_RADIX is not a power of 2 and the result is not exactly
representable in the given precision, the result should be one of the two adjacent numbers in
hexadecimal floating style with the given precision, with the extra stipulation that the error
should have a correct sign for the current rounding direction.
13281
13282
13283
13284
13285
13286
13287
13288
For the e, E, f, F, g, and G conversion specifiers, if the number of significant decimal digits is at
most DECIMAL_DIG, then the result should be correctly rounded. If the number of significant
decimal digits is more than DECIMAL_DIG but the source value is exactly representable with
DECIMAL_DIG digits, then the result should be an exact representation with trailing zeros.
Otherwise, the source value is bounded by two adjacent decimal strings L < U, both having
DECIMAL_DIG significant digits; the value of the resultant decimal string D should satisfy L <=
D <= U, with the extra stipulation that the error should have a correct sign for the current
rounding direction.
13289 CX
13290
13291
The st_ctime and st_mtime fields of the file shall be marked for update between the call to a
successful execution of fprintf( ) or printf( ) and the next successful completion of a call to fflush( )
or fclose( ) on the same stream or a call to exit( ) or abort( ).
13292
13293
13294
RETURN VALUE
Upon successful completion, the fprintf ( ) and printf( ) functions shall return the number of bytes
transmitted.
13295
13296
Upon successful completion, the sprintf( ) function shall return the number of bytes written to s,
excluding the terminating null byte.
13297
13298
Upon successful completion, the snprintf( ) function shall return the number of bytes that would
be written to s had n been sufficiently large excluding the terminating null byte.
13299
If an output error was encountered, these functions shall return a negative value.
13300
13301
If the value of n is zero on a call to snprintf( ), nothing shall be written, the number of bytes that
would have been written had n been sufficiently large excluding the terminating null shall be
returned, and s may be a null pointer.
13302
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
407
fprintf( )
13303
13304
13305
System Interfaces
ERRORS
For the conditions under which fprintf ( ) and printf( ) fail and may fail, refer to fputc( ) or
fputwc( ).
13306
In addition, all forms of fprintf( ) may fail if:
13307 XSI
13308
[EILSEQ]
A wide-character code that does not correspond to a valid character has been
detected.
13309 XSI
[EINVAL]
There are insufficient arguments.
13310
The printf( ) and fprintf( ) functions may fail if:
13311 XSI
[ENOMEM]
13312
The snprintf( ) function shall fail if:
13313 XSI
13314
[EOVERFLOW]
13315
Insufficient storage space is available.
The value of n is greater than {INT_MAX} or the number of bytes needed to
hold the output excluding the terminating null is greater than {INT_MAX}.
EXAMPLES
13316
Printing Language-Independent Date and Time
13317
13318
The following statement can be used to print date and time using a language-independent
format:
13319
printf(format, weekday, month, day, hour, min);
13320
For American usage, format could be a pointer to the following string:
13321
"%s, %s %d, %d:%.2d\n"
13322
This example would produce the following message:
13323
Sunday, July 3, 10:02
13324
For German usage, format could be a pointer to the following string:
13325
"%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
13326
This definition of format would produce the following message:
13327
Sonntag, 3. Juli, 10:02
13328
Printing File Information
13329
13330
The following example prints information about the type, permissions, and number of links of a
specific file in a directory.
13331
13332
13333
The first two calls to printf( ) use data decoded from a previous stat( ) call. The user-defined
strperm( ) function shall return a string similar to the one at the beginning of the output for the
following command:
13334
ls −l
13335
13336
13337
The next call to printf( ) outputs the owner’s name if it is found using getpwuid( ); the getpwuid( )
function shall return a passwd structure from which the name of the user is extracted. If the user
name is not found, the program instead prints out the numeric value of the user ID.
13338
The next call prints out the group name if it is found using getgrgid( ); getgrgid( ) is very similar to
getpwuid( ) except that it shall return group information based on the group number. Once
again, if the group is not found, the program prints the numeric value of the group for the entry.
13339
13340
408
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fprintf( )
System Interfaces
13341
The final call to printf( ) prints the size of the file.
13342
13343
13344
13345
#include
#include
#include
#include
13346
13347
13348
13349
13350
13351
13352
13353
char *strperm (mode_t);
...
struct stat statbuf;
struct passwd *pwd;
struct group *grp;
...
printf("%10.10s", strperm (statbuf.st_mode));
printf("%4d", statbuf.st_nlink);
13354
13355
13356
13357
if ((pwd = getpwuid(statbuf.st_uid)) != NULL)
printf(" %−8.8s", pwd->pw_name);
else
printf(" %−8ld", (long) statbuf.st_uid);
13358
13359
13360
13361
if ((grp = getgrgid(statbuf.st_gid)) != NULL)
printf(" %−8.8s", grp->gr_name);
else
printf(" %−8ld", (long) statbuf.st_gid);
13362
13363
printf("%9jd", (intmax_t) statbuf.st_size);
...
13364
Printing a Localized Date String
13365
13366
13367
13368
13369
The following example gets a localized date string. The nl_langinfo ( ) function shall return the
localized date string, which specifies the order and layout of the date. The strftime( ) function
takes this information and, using the tm structure for values, places the date and time
information into datestring. The printf( ) function then outputs datestring and the name of the
entry.
13370
13371
13372
13373
13374
13375
13376
13377
13378
#include <stdio.h>
#include <time.h>
#include <langinfo.h>
...
struct dirent *dp;
struct tm *tm;
char datestring[256];
...
strftime(datestring, sizeof(datestring), nl_langinfo (D_T_FMT), tm);
13379
13380
printf(" %s %s\n", datestring, dp->d_name);
...
<stdio.h>
<sys/types.h>
<pwd.h>
<grp.h>
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
409
fprintf( )
System Interfaces
13381
Printing Error Information
13382
The following example uses fprintf ( ) to write error information to standard error.
13383
13384
13385
13386
In the first group of calls, the program tries to open the password lock file named LOCKFILE. If
the file already exists, this is an error, as indicated by the O_EXCL flag on the open( ) function. If
the call fails, the program assumes that someone else is updating the password file, and the
program exits.
13387
13388
The next group of calls saves a new password file as the current password file by creating a link
between LOCKFILE and the new password file PASSWDFILE.
13389
13390
13391
13392
13393
13394
13395
13396
#include
#include
#include
#include
#include
#include
#include
#include
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
#define LOCKFILE "/etc/ptmp"
#define PASSWDFILE "/etc/passwd"
...
int pfd;
...
if ((pfd = open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == −1)
{
fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
exit(1);
}
...
if (link(LOCKFILE,PASSWDFILE) == -1) {
fprintf(stderr, "Link error: %s\n", strerror(errno));
exit(1);
}
...
13414
Printing Usage Information
13415
13416
The following example checks to make sure the program has the necessary arguments, and uses
fprintf( ) to print usage information if the expected number of arguments is not present.
13417
13418
13419
13420
13421
13422
13423
13424
13425
#include <stdio.h>
#include <stdlib.h>
...
char *Options = "hdbtl";
...
if (argc < 2) {
fprintf(stderr, "Usage: %s -%s <file\n", argv[0], Options); exit(1);
}
...
410
<sys/types.h>
<sys/stat.h>
<fcntl.h>
<stdio.h>
<stdlib.h>
<unistd.h>
<string.h>
<errno.h>
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fprintf( )
13426
Formatting a Decimal String
13427
13428
13429
The following example prints a key and data pair on stdout. Note use of the ’*’ (asterisk) in the
format string; this ensures the correct number of decimal places for the element based on the
number of elements requested.
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
#include <stdio.h>
...
long i;
char *keystr;
int elementlen, len;
...
while (len < elementlen) {
...
printf("%s Element%0*ld\n", keystr, elementlen, i);
...
}
13441
Creating a Filename
13442
13443
The following example creates a filename using information from a previous getpwnam( )
function that returned the HOME directory of the user.
13444
13445
13446
13447
13448
13449
13450
13451
13452
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
...
char filename[PATH_MAX+1];
struct passwd *pw;
...
sprintf(filename, "%s/%d.out", pw->pw_dir, getpid());
...
13453
Reporting an Event
13454
13455
13456
The following example loops until an event has timed out. The pause( ) function waits forever
unless it receives a signal. The fprintf ( ) statement should never occur due to the possible return
values of pause( ).
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
...
while (!event_complete) {
...
if (pause() != −1 || errno != EINTR)
fprintf(stderr, "pause: unknown error: %s\n", strerror(errno));
}
...
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
411
fprintf( )
System Interfaces
13468
Printing Monetary Information
13469
13470
13471
The following example uses strfmon( ) to convert a number and store it as a formatted monetary
string named convbuf. If the first number is printed, the program prints the format and the
description; otherwise, it just prints the number.
13472
13473
13474
13475
13476
13477
13478
#include <monetary.h>
#include <stdio.h>
...
struct tblfmt {
char *format;
char *description;
};
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
struct tblfmt table[] = {
{ "%n", "default formatting" },
{ "%11n", "right align within an 11 character field" },
{ "%#5n", "aligned columns for values up to 99 999" },
{ "%=*#5n", "specify a fill character" },
{ "%=0#5n", "fill characters do not use grouping" },
{ "%ˆ#5n", "disable the grouping separator" },
{ "%ˆ#5.0n", "round off to whole units" },
{ "%ˆ#5.4n", "increase the precision" },
{ "%(#5n", "use an alternative pos/neg style" },
{ "%!(#5n", "disable the currency symbol" },
};
...
float input[3];
int i, j;
char convbuf[100];
...
strfmon(convbuf, sizeof(convbuf), table[i].format, input[j]);
13497
13498
13499
13500
13501
13502
13503
13504
if (j == 0) {
printf("%s%s%s\n", table[i].format,
convbuf, table[i].description);
}
else {
printf("%s\n", convbuf);
}
...
13505
Printing Wide Characters
13506
13507
The following example prints a series of wide characters. Suppose that "L‘@‘" expands to three
bytes:
13508
13509
wchar_t wz [3] = L"@@";
wchar_t wn [3] = L"@@@";
// Zero-terminated
// Unterminated
13510
13511
13512
fprintf
fprintf
fprintf
fprintf
fprintf
//
//
//
//
//
13513
13514
412
(stdout,"%ls", wz);
(stdout,"%ls", wn);
(stdout,"%4ls", wz);
(stdout,"%4ls", wn);
(stdout,"%9ls", wz);
Outputs 6
Undefined
Outputs 3
Outputs 3
Outputs 6
bytes
because wn has no terminator
bytes
bytes; no terminator needed
bytes
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fprintf( )
System Interfaces
13515
13516
13517
fprintf (stdout,"%9ls", wn); // Outputs 9 bytes; no terminator needed
fprintf (stdout,"%10ls", wz); // Outputs 6 bytes
fprintf (stdout,"%10ls", wn); // Undefined because wn has no terminator
13518
13519
13520
13521
In the last line of the example, after processing three characters, nine bytes have been output.
The fourth character must then be examined to determine whether it converts to one byte or
more. If it converts to more than one byte, the output is only nine bytes. Since there is no fourth
character in the array, the behavior is undefined.
13522
13523
13524
APPLICATION USAGE
If the application calling fprintf( ) has any objects of type wint_t or wchar_t, it must also include
the <wchar.h> header to have these objects defined.
13525
13526
RATIONALE
None.
13527
13528
FUTURE DIRECTIONS
None.
13529
13530
13531
SEE ALSO
fputc( ), fscanf( ), setlocale ( ), strfmon( ), wcrtomb( ), the Base
IEEE Std 1003.1-2001, Chapter 7, Locale, <stdio.h>, <wchar.h>
13532
13533
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
13534
13535
13536
Issue 5
volume
of
Aligned with ISO/IEC 9899: 1990/Amendment 1: 1995 (E). Specifically, the l (ell) qualifier can
now be used with c and s conversion specifiers.
The snprintf( ) function is new in Issue 5.
13537
13538
13539
Definitions
Issue 6
Extensions beyond the ISO C standard are marked.
13540
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
13541
The following changes are made for alignment with the ISO/IEC 9899: 1999 standard:
13542
13543
•
The prototypes for fprintf( ), printf( ), snprintf( ), and sprintf( ) are updated, and the XSI
shading is removed from snprintf( ).
13544
13545
13546
•
The description of snprintf( ) is aligned with the ISO C standard. Note that this supersedes
the snprintf( ) description in The Open Group Base Resolution bwg98-006, which changed the
behavior from Issue 5.
13547
•
The DESCRIPTION is updated.
13548
13549
The DESCRIPTION is updated to use the terms ‘‘conversion specifier’’ and ‘‘conversion
specification’’ consistently.
13550
ISO/IEC 9899: 1999 standard, Technical Corrigendum No. 1 is incorporated.
13551
An example of printing wide characters is added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
413
fputc( )
System Interfaces
13552
13553
NAME
13554
13555
SYNOPSIS
#include <stdio.h>
fputc — put a byte on a stream
int fputc(int c, FILE *stream);
13556
13557 DESCRIPTION
13558 CX
The functionality described on this reference page is aligned with the ISO C standard.
13559
conflict between the requirements described here and the ISO C standard is unintentional.
13560
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
13561
13562
13563
13564
13565
The fputc( ) function shall write the byte specified by c (converted to an unsigned char) to the
output stream pointed to by stream, at the position indicated by the associated file-position
indicator for the stream (if defined), and shall advance the indicator appropriately. If the file
cannot support positioning requests, or if the stream was opened with append mode, the byte
shall be appended to the output stream.
13566 CX
13567
13568
The st_ctime and st_mtime fields of the file shall be marked for update between the successful
execution of fputc( ) and the next successful completion of a call to fflush( ) or fclose( ) on the same
stream or a call to exit( ) or abort( ).
13569 RETURN VALUE
13570
Upon successful completion, fputc( ) shall return the value it has written. Otherwise, it shall
13571 CX
return EOF, the error indicator for the stream shall be set, and errno shall be set to indicate the
13572
error.
13573
13574
13575
ERRORS
The fputc( ) function shall fail if either the stream is unbuffered or the stream’s buffer needs to be
flushed, and:
13576 CX
13577
[EAGAIN]
The O_NONBLOCK flag is set for the file descriptor underlying stream and the
process would be delayed in the write operation.
13578 CX
13579
[EBADF]
The file descriptor underlying stream is not a valid file descriptor open for
writing.
13580 CX
[EFBIG]
An attempt was made to write to a file that exceeds the maximum file size.
13581 XSI
[EFBIG]
An attempt was made to write to a file that exceeds the process’ file size limit.
13582 CX
13583
[EFBIG]
The file is a regular file and an attempt was made to write at or beyond the
offset maximum.
13584 CX
13585
[EINTR]
The write operation was terminated due to the receipt of a signal, and no data
was transferred.
13586 CX
13587
13588
13589
13590
[EIO]
A physical I/O error has occurred, or the process is a member of a
background process group attempting to write to its controlling terminal,
TOSTOP is set, the process is neither ignoring nor blocking SIGTTOU, and the
process group of the process is orphaned. This error may also be returned
under implementation-defined conditions.
13591 CX
[ENOSPC]
There was no free space remaining on the device containing the file.
13592 CX
13593
[EPIPE]
An attempt is made to write to a pipe or FIFO that is not open for reading by
any process. A SIGPIPE signal shall also be sent to the thread.
13594
The fputc( ) function may fail if:
414
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fputc( )
System Interfaces
13595 CX
[ENOMEM]
Insufficient storage space is available.
13596 CX
13597
[ENXIO]
A request was made of a nonexistent device, or the request was outside the
capabilities of the device.
13598
13599
EXAMPLES
None.
13600
13601
APPLICATION USAGE
None.
13602
13603
RATIONALE
None.
13604
13605
FUTURE DIRECTIONS
None.
13606
13607
13608
SEE ALSO
ferror( ), fopen( ), getrlimit( ), putc( ), puts( ), setbuf( ), ulimit( ), the Base Definitions volume of
IEEE Std 1003.1-2001, <stdio.h>
13609
13610
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
13611
13612
Issue 5
13613
13614
Issue 6
13615
13616
Large File Summit extensions are added.
Extensions beyond the ISO C standard are marked.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
13617
•
The [EIO] and [EFBIG] mandatory error conditions are added.
13618
•
The [ENOMEM] and [ENXIO] optional error conditions are added.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
415
fputs( )
System Interfaces
13619
13620
NAME
13621
13622
SYNOPSIS
#include <stdio.h>
fputs — put a string on a stream
int fputs(const char *restrict s, FILE *restrict stream);
13623
13624 DESCRIPTION
13625 CX
The functionality described on this reference page is aligned with the ISO C standard.
13626
conflict between the requirements described here and the ISO C standard is unintentional.
13627
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
13628
13629
The fputs( ) function shall write the null-terminated string pointed to by s to the stream pointed
to by stream. The terminating null byte shall not be written.
13630 CX
13631
13632
The st_ctime and st_mtime fields of the file shall be marked for update between the successful
execution of fputs( ) and the next successful completion of a call to fflush( ) or fclose( ) on the same
stream or a call to exit( ) or abort( ).
13633 RETURN VALUE
13634
Upon successful completion, fputs( ) shall return a non-negative number. Otherwise,
13635 CX
return EOF, set an error indicator for the stream, and set errno to indicate the error.
13636
13637
ERRORS
Refer to fputc( ).
13638
EXAMPLES
it shall
13639
Printing to Standard Output
13640
13641
13642
The following example gets the current time, converts it to a string using localtime ( ) and
asctime( ), and prints it to standard output using fputs( ). It then prints the number of minutes to
an event for which it is waiting.
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
#include <time.h>
#include <stdio.h>
...
time_t now;
int minutes_to_event;
...
time(&now);
printf("The time is ");
fputs(asctime(localtime(&now)), stdout);
printf("There are still %d minutes to the event.\n",
minutes_to_event);
...
13655
13656
APPLICATION USAGE
The puts( ) function appends a <newline> while fputs( ) does not.
13657
13658
RATIONALE
None.
13659
13660
FUTURE DIRECTIONS
None.
416
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
13661
13662
SEE ALSO
fopen( ), putc( ), puts( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>
13663
13664
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
13665
13666
Issue 6
13667
fputs( )
Extensions beyond the ISO C standard are marked.
The fputs( ) prototype is updated for alignment with the ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
417
fputwc( )
System Interfaces
13668
13669
NAME
13670
13671
13672
SYNOPSIS
#include <stdio.h>
#include <wchar.h>
fputwc — put a wide-character code on a stream
wint_t fputwc(wchar_t wc, FILE *stream);
13673
13674 DESCRIPTION
13675 CX
The functionality described on this reference page is aligned with the ISO C standard.
13676
conflict between the requirements described here and the ISO C standard is unintentional.
13677
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
13678
13679
13680
13681
13682
13683
The fputwc( ) function shall write the character corresponding to the wide-character code wc to
the output stream pointed to by stream, at the position indicated by the associated file-position
indicator for the stream (if defined), and advances the indicator appropriately. If the file cannot
support positioning requests, or if the stream was opened with append mode, the character is
appended to the output stream. If an error occurs while writing the character, the shift state of
the output file is left in an undefined state.
13684 CX
13685
13686
The st_ctime and st_mtime fields of the file shall be marked for update between the successful
execution of fputwc( ) and the next successful completion of a call to fflush( ) or fclose( ) on the
same stream or a call to exit( ) or abort( ).
13687 RETURN VALUE
13688
Upon successful completion, fputwc( ) shall return wc.
13689 CX
indicator for the stream shall be set, and errno shall be
13690
13691
13692
Otherwise, it shall return WEOF, the error
set to indicate the error.
ERRORS
The fputwc( ) function shall fail if either the stream is unbuffered or data in the stream’s buffer
needs to be written, and:
13693 CX
13694
[EAGAIN]
The O_NONBLOCK flag is set for the file descriptor underlying stream and the
process would be delayed in the write operation.
13695 CX
13696
[EBADF]
The file descriptor underlying stream is not a valid file descriptor open for
writing.
13697 CX
13698
[EFBIG]
An attempt was made to write to a file that exceeds the maximum file size or
the process’ file size limit.
13699 CX
13700
[EFBIG]
The file is a regular file and an attempt was made to write at or beyond the
offset maximum associated with the corresponding stream.
13701
[EILSEQ]
The wide-character code wc does not correspond to a valid character.
13702 CX
13703
[EINTR]
The write operation was terminated due to the receipt of a signal, and no data
was transferred.
13704 CX
13705
13706
13707
13708
[EIO]
A physical I/O error has occurred, or the process is a member of a
background process group attempting to write to its controlling terminal,
TOSTOP is set, the process is neither ignoring nor blocking SIGTTOU, and the
process group of the process is orphaned. This error may also be returned
under implementation-defined conditions.
13709 CX
[ENOSPC]
There was no free space remaining on the device containing the file.
13710 CX
13711
[EPIPE]
An attempt is made to write to a pipe or FIFO that is not open for reading by
any process. A SIGPIPE signal shall also be sent to the thread.
418
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fputwc( )
System Interfaces
13712
The fputwc( ) function may fail if:
13713 CX
[ENOMEM]
Insufficient storage space is available.
13714 CX
13715
[ENXIO]
A request was made of a nonexistent device, or the request was outside the
capabilities of the device.
13716
13717
EXAMPLES
None.
13718
13719
APPLICATION USAGE
None.
13720
13721
RATIONALE
None.
13722
13723
FUTURE DIRECTIONS
None.
13724
13725
13726
SEE ALSO
ferror( ), fopen( ), setbuf( ), ulimit( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<stdio.h>, <wchar.h>
13727
13728
CHANGE HISTORY
First released in Issue 4. Derived from the MSE working draft.
13729
13730
13731
Issue 5
Aligned with ISO/IEC 9899: 1990/Amendment 1: 1995 (E). Specifically, the type of argument wc
is changed from wint_t to wchar_t.
13732
The Optional Header (OH) marking is removed from <stdio.h>.
13733
Large File Summit extensions are added.
13734
13735
13736
13737
Issue 6
Extensions beyond the ISO C standard are marked.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
13738
•
The [EFBIG] and [EIO] mandatory error conditions are added.
13739
•
The [ENOMEM] and [ENXIO] optional error conditions are addd.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
419
fputws( )
System Interfaces
13740
13741
NAME
13742
13743
13744
SYNOPSIS
#include <stdio.h>
#include <wchar.h>
fputws — put a wide-character string on a stream
int fputws(const wchar_t *restrict ws, FILE *restrict stream);
13745
13746 DESCRIPTION
13747 CX
The functionality described on this reference page is aligned with the ISO C standard.
13748
conflict between the requirements described here and the ISO C standard is unintentional.
13749
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
13750
13751
13752
The fputws( ) function shall write a character string corresponding to the (null-terminated)
wide-character string pointed to by ws to the stream pointed to by stream. No character
corresponding to the terminating null wide-character code shall be written.
13753 CX
13754
13755
The st_ctime and st_mtime fields of the file shall be marked for update between the successful
execution of fputws( ) and the next successful completion of a call to fflush( ) or fclose( ) on the
same stream or a call to exit( ) or abort( ).
13756 RETURN VALUE
13757
Upon successful completion, fputws( ) shall return a non-negative number. Otherwise,
13758 CX
return −1, set an error indicator for the stream, and set errno to indicate the error.
13759
13760
ERRORS
Refer to fputwc( ).
13761
13762
EXAMPLES
None.
13763
13764
APPLICATION USAGE
The fputws( ) function does not append a <newline>.
13765
13766
RATIONALE
None.
13767
13768
FUTURE DIRECTIONS
None.
13769
13770
SEE ALSO
fopen( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, <wchar.h>
13771
13772
CHANGE HISTORY
First released in Issue 4. Derived from the MSE working draft.
13773
13774
Issue 5
13775
13776
Issue 6
it shall
The Optional Header (OH) marking is removed from <stdio.h>.
Extensions beyond the ISO C standard are marked.
The fputws( ) prototype is updated for alignment with the ISO/IEC 9899: 1999 standard.
13777
420
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
13778
13779
NAME
13780
13781
SYNOPSIS
#include <stdio.h>
fread( )
fread — binary input
size_t fread(void *restrict ptr, size_t size, size_t nitems,
FILE *restrict stream);
13782
13783
13784 DESCRIPTION
13785 CX
The functionality described on this reference page is aligned with the ISO C standard.
13786
conflict between the requirements described here and the ISO C standard is unintentional.
13787
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
13788
13789
13790
13791
13792
13793
13794
The fread( ) function shall read into the array pointed to by ptr up to nitems elements whose size
is specified by size in bytes, from the stream pointed to by stream. For each object, size calls shall
be made to the fgetc( ) function and the results stored, in the order read, in an array of unsigned
char exactly overlaying the object. The file position indicator for the stream (if defined) shall be
advanced by the number of bytes successfully read. If an error occurs, the resulting value of the
file position indicator for the stream is unspecified. If a partial element is read, its value is
unspecified.
13795 CX
13796
13797
13798
The fread( ) function may mark the st_atime field of the file associated with stream for update. The
st_atime field shall be marked for update by the first successful execution of fgetc( ), fgets( ),
fgetwc( ), fgetws( ), fread( ), fscanf( ), getc( ), getchar( ), gets( ), or scanf( ) using stream that returns
data not supplied by a prior call to ungetc( ) or ungetwc( ).
13799 RETURN VALUE
13800
Upon successful completion, fread( ) shall return the number of elements successfully read which
13801
is less than nitems only if a read error or end-of-file is encountered. If size or nitems is 0, fread( )
13802
shall return 0 and the contents of the array and the state of the stream remain unchanged.
13803 CX
Otherwise, if a read error occurs, the error indicator for the stream shall be set, and errno shall be
13804
set to indicate the error.
13805
13806
ERRORS
Refer to fgetc( ).
13807
EXAMPLES
13808
Reading from a Stream
13809
The following example reads a single element from the fp stream into the array pointed to by buf.
13810
13811
13812
13813
13814
13815
13816
13817
#include <stdio.h>
...
size_t bytes_read;
char buf[100];
FILE *fp;
...
bytes_read = fread(buf, sizeof(buf), 1, fp);
...
13818
13819
13820
APPLICATION USAGE
The ferror( ) or feof( ) functions must be used to distinguish between an error condition and an
end-of-file condition.
13821
13822
Because of possible differences in element length and byte ordering, files written using fwrite( )
are application-dependent, and possibly cannot be read using fread( ) by a different application
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
421
fread( )
System Interfaces
or by the same application on a different processor.
13823
13824
13825
RATIONALE
None.
13826
13827
FUTURE DIRECTIONS
None.
13828
13829
13830
SEE ALSO
feof( ), ferror( ), fgetc( ), fopen( ), getc( ), gets( ), scanf( ), the Base Definitions volume of
IEEE Std 1003.1-2001, <stdio.h>
13831
13832
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
13833
13834
Issue 6
Extensions beyond the ISO C standard are marked.
The following changes are made for alignment with the ISO/IEC 9899: 1999 standard:
13835
13836
•
The fread( ) prototype is updated.
13837
•
The DESCRIPTION is updated to describe how the bytes from a call to fgetc( ) are stored.
422
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
13838
13839
NAME
13840
13841
SYNOPSIS
#include <stdlib.h>
free( )
free — free allocated memory
void free(void *ptr);
13842
13843 DESCRIPTION
13844 CX
The functionality described on this reference page is aligned with the ISO C standard.
13845
conflict between the requirements described here and the ISO C standard is unintentional.
13846
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
13847
13848
13849 ADV
13850 XSI
13851
The free( ) function shall cause the space pointed to by ptr to be deallocated; that is, made
available for further allocation. If ptr is a null pointer, no action shall occur. Otherwise, if the
argument does not match a pointer earlier returned by the calloc ( ), malloc ( ), posix_memalign( ),
realloc ( ), or strdup( ) function, or if the space has been deallocated by a call to free( ) or realloc ( ),
the behavior is undefined.
13852
Any use of a pointer that refers to freed space results in undefined behavior.
13853
13854
RETURN VALUE
The free( ) function shall not return a value.
13855
13856
ERRORS
No errors are defined.
13857
13858
EXAMPLES
None.
13859
13860
APPLICATION USAGE
There is now no requirement for the implementation to support the inclusion of <malloc.h>.
13861
13862
RATIONALE
None.
13863
13864
FUTURE DIRECTIONS
None.
13865
13866
SEE ALSO
calloc ( ), malloc ( ), realloc ( ), the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>
13867
13868
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
13869
13870
Issue 6
Reference to the valloc ( ) function is removed.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
423
freeaddrinfo( )
System Interfaces
13871
13872
NAME
13873
13874
13875
SYNOPSIS
#include <sys/socket.h>
#include <netdb.h>
freeaddrinfo, getaddrinfo — get address information
void freeaddrinfo(struct addrinfo *ai);
int getaddrinfo(const char *restrict nodename,
const char *restrict servname,
const struct addrinfo *restrict hints,
struct addrinfo **restrict res);
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
DESCRIPTION
The freeaddrinfo ( ) function shall free one or more addrinfo structures returned by getaddrinfo ( ),
along with any additional storage associated with those structures. If the ai_next field of the
structure is not null, the entire list of structures shall be freed. The freeaddrinfo ( ) function shall
support the freeing of arbitrary sublists of an addrinfo list originally returned by getaddrinfo ( ).
13886
13887
13888
The getaddrinfo ( ) function shall translate the name of a service location (for example, a host
name) and/or a service name and shall return a set of socket addresses and associated
information to be used in creating a socket with which to address the specified service.
13889
The freeaddrinfo ( ) and getaddrinfo ( ) functions shall be thread-safe.
13890
13891
13892
The nodename and servname arguments are either null pointers or pointers to null-terminated
strings. One or both of these two arguments shall be supplied by the application as a non-null
pointer.
13893
13894
13895
13896
The format of a valid name depends on the address family or families. If a specific family is not
given and the name could be interpreted as valid within multiple supported families, the
implementation shall attempt to resolve the name in all supported families and, in absence of
errors, one or more results shall be returned.
13897
13898 IP6
13899
13900
If the nodename argument is not null, it can be a descriptive name or can be an address string. If
the specified address family is AF_INET, AF_INET6, or AF_UNSPEC, valid descriptive names
include host names. If the specified address family is AF_INET or AF_UNSPEC, address strings
using Internet standard dot notation as specified in inet_addr( ) are valid.
13901 IP6
13902
If the specified address family is AF_INET6 or AF_UNSPEC, standard IPv6 text forms described
in inet_ntop( ) are valid.
13903
13904
If nodename is not null, the requested service location is named by nodename; otherwise, the
requested service location is local to the caller.
13905
13906
13907
13908 IP6
13909
If servname is null, the call shall return network-level addresses for the specified nodename. If
servname is not null, it is a null-terminated character string identifying the requested service. This
can be either a descriptive name or a numeric representation suitable for use with the address
family or families. If the specified address family is AF_INET, AF_INET6, or AF_UNSPEC, the
service can be specified as a string specifying a decimal port number.
13910
13911
13912
13913
13914
If the hints argument is not null, it refers to a structure containing input values that may direct
the operation by providing options and by limiting the returned information to a specific socket
type, address family, and/or protocol. In this hints structure every member other than ai_flags ,
ai_family , ai_socktype , and ai_protocol shall be set to zero or a null pointer. A value of
AF_UNSPEC for ai_family means that the caller shall accept any address family. A value of zero
for ai_socktype means that the caller shall accept any socket type. A value of zero for ai_protocol
means that the caller shall accept any protocol. If hints is a null pointer, the behavior shall be as if
13915
13916
424
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
freeaddrinfo( )
13917
13918
it referred to a structure containing the value zero for the ai_flags , ai_socktype , and ai_protocol
fields, and AF_UNSPEC for the ai_family field.
13919
13920
13921
The ai_flags field to which the hints parameter points shall be set to zero or be the bitwiseinclusive OR of one or more of the values AI_PASSIVE, AI_CANONNAME,
AI_NUMERICHOST, and AI_NUMERICSERV.
13922
13923
13924
13925
13926
13927
13928
13929
If the AI_PASSIVE flag is specified, the returned address information shall be suitable for use in
binding a socket for accepting incoming connections for the specified service. In this case, if the
nodename argument is null, then the IP address portion of the socket address structure shall be
set to INADDR_ANY for an IPv4 address or IN6ADDR_ANY_INIT for an IPv6 address. If the
AI_PASSIVE flag is not specified, the returned address information shall be suitable for a call to
connect( ) (for a connection-mode protocol) or for a call to connect( ), sendto( ), or sendmsg( ) (for a
connectionless protocol). In this case, if the nodename argument is null, then the IP address
portion of the socket address structure shall be set to the loopback address.
13930
13931
13932
If the AI_CANONNAME flag is specified and the nodename argument is not null, the function
shall attempt to determine the canonical name corresponding to nodename (for example, if
nodename is an alias or shorthand notation for a complete name).
13933
13934
13935
If the AI_NUMERICHOST flag is specified, then a non-null nodename string supplied shall be a
numeric host address string. Otherwise, an [EAI_NONAME] error is returned. This flag shall
prevent any type of name resolution service (for example, the DNS) from being invoked.
13936
13937
13938
If the AI_NUMERICSERV flag is specified, then a non-null servname string supplied shall be a
numeric port string. Otherwise, an [EAI_NONAME] error shall be returned. This flag shall
prevent any type of name resolution service (for example, NIS+) from being invoked.
13939 IP6
13940
13941
13942
13943
If the AI_V4MAPPED flag is specified along with an ai_family of AF_INET6, then getaddrinfo ( )
shall return IPv4-mapped IPv6 addresses on finding no matching IPv6 addresses (ai_addrlen
shall be 16). The AI_V4MAPPED flag shall be ignored unless ai_family equals AF_INET6. If the
AI_ALL flag is used with the AI_V4MAPPED flag, then getaddrinfo ( ) shall return all matching
IPv6 and IPv4 addresses. The AI_ALL flag without the AI_V4MAPPED flag is ignored.
13944
13945
13946
13947
13948
13949
The ai_socktype field to which argument hints points specifies the socket type for the service, as
defined in socket( ). If a specific socket type is not given (for example, a value of zero) and the
service name could be interpreted as valid with multiple supported socket types, the
implementation shall attempt to resolve the service name for all supported socket types and, in
the absence of errors, all possible results shall be returned. A non-zero socket type value shall
limit the returned information to values with the specified socket type.
13950
13951
13952
13953
13954
13955
If the ai_family field to which hints points has the value AF_UNSPEC, addresses shall be
returned for use with any address family that can be used with the specified nodename and/or
servname. Otherwise, addresses shall be returned for use only with the specified address family.
If ai_family is not AF_UNSPEC and ai_protocol is not zero, then addresses are returned for use
only with the specified address family and protocol; the value of ai_protocol shall be interpreted
as in a call to the socket( ) function with the corresponding values of ai_family and ai_protocol .
13956
13957
13958
RETURN VALUE
A zero return value for getaddrinfo ( ) indicates successful completion; a non-zero return value
indicates failure. The possible values for the failures are listed in the ERRORS section.
13959
13960
13961
Upon successful return of getaddrinfo ( ), the location to which res points shall refer to a linked list
of addrinfo structures, each of which shall specify a socket address and information for use in
creating a socket with which to use that socket address. The list shall include at least one
addrinfo structure. The ai_next field of each structure contains a pointer to the next structure on
the list, or a null pointer if it is the last structure on the list. Each structure on the list shall
13962
13963
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
425
freeaddrinfo( )
System Interfaces
13964
13965
13966
13967
13968
13969
include values for use with a call to the socket( ) function, and a socket address for use with the
connect( ) function or, if the AI_PASSIVE flag was specified, for use with the bind( ) function. The
fields ai_family , ai_socktype , and ai_protocol shall be usable as the arguments to the socket( )
function to create a socket suitable for use with the returned address. The fields ai_addr and
ai_addrlen are usable as the arguments to the connect( ) or bind( ) functions with such a socket,
according to the AI_PASSIVE flag.
13970
13971
13972
13973
13974
If nodename is not null, and if requested by the AI_CANONNAME flag, the ai_canonname field of
the first returned addrinfo structure shall point to a null-terminated string containing the
canonical name corresponding to the input nodename; if the canonical name is not available, then
ai_canonname shall refer to the nodename argument or a string with the same contents. The
contents of the ai_flags field of the returned structures are undefined.
13975
13976
All fields in socket address structures returned by getaddrinfo ( ) that are not filled in through an
explicit argument (for example, sin6_flowinfo) shall be set to zero.
13977
Note:
13978
13979
This makes it easier to compare socket address structures.
ERRORS
The getaddrinfo ( ) function shall fail and return the corresponding value if:
13980
[EAI_AGAIN]
The name could not be resolved at this time. Future attempts may succeed.
13981
13982
[EAI_BADFLAGS]
The flags parameter had an invalid value.
13983
[EAI_FAIL]
A non-recoverable error occurred when attempting to resolve the name.
13984
[EAI_FAMILY]
The address family was not recognized.
13985
13986
[EAI_MEMORY] There was a memory allocation failure when trying to allocate storage for the
return value.
13987
[EAI_NONAME] The name does not resolve for the supplied parameters.
Neither nodename nor servname were supplied. At least one of these shall be
supplied.
13988
13989
13990
[EAI_SERVICE]
The service passed was not recognized for the specified socket type.
13991
13992
[EAI_SOCKTYPE]
The intended socket type was not recognized.
13993
[EAI_SYSTEM]
13994
13995
[EAI_OVERFLOW]
An argument buffer overflowed.
A system error occurred; the error code can be found in errno.
13996
13997
EXAMPLES
None.
13998
13999
14000
APPLICATION USAGE
If the caller handles only TCP and not UDP, for example, then the ai_protocol member of the hints
structure should be set to IPPROTO_TCP when getaddrinfo ( ) is called.
14001
14002
If the caller handles only IPv4 and not IPv6, then the ai_family member of the hints structure
should be set to AF_INET when getaddrinfo ( ) is called.
14003
14004
RATIONALE
None.
426
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
freeaddrinfo( )
14005
14006
FUTURE DIRECTIONS
None.
14007
14008
14009
SEE ALSO
connect( ), gai_strerror( ), gethostbyaddr( ), getnameinfo( ), getservbyname( ), socket( ), the Base
Definitions volume of IEEE Std 1003.1-2001, <netdb.h>, <sys/socket.h>
14010
14011
CHANGE HISTORY
First released in Issue 6. Derived from the XNS, Issue 5.2 specification.
14012
14013
The restrict keyword is added to the getaddrinfo ( ) prototype for alignment with the
ISO/IEC 9899: 1999 standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
427
freopen( )
System Interfaces
14014
14015
NAME
14016
14017
SYNOPSIS
#include <stdio.h>
freopen — open a stream
FILE *freopen(const char *restrict filename, const char *restrict mode,
FILE *restrict stream);
14018
14019
14020 DESCRIPTION
14021 CX
The functionality described on this reference page is aligned with the ISO C standard.
14022
conflict between the requirements described here and the ISO C standard is unintentional.
14023
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
14024
14025
14026
The freopen( ) function shall first attempt to flush the stream and close any file descriptor
associated with stream. Failure to flush or close the file descriptor successfully shall be ignored.
The error and end-of-file indicators for the stream shall be cleared.
14027
14028
14029
The freopen( ) function shall open the file whose pathname is the string pointed to by filename and
associate the stream pointed to by stream with it. The mode argument shall be used just as in
fopen( ).
14030
The original stream shall be closed regardless of whether the subsequent open succeeds.
14031
14032
14033
14034
If filename is a null pointer, the freopen( ) function shall attempt to change the mode of the stream
to that specified by mode, as if the name of the file currently associated with the stream had been
used. It is implementation-defined which changes of mode are permitted (if any), and under
what circumstances.
14035 XSI
14036
14037
After a successful call to the freopen( ) function, the orientation of the stream shall be cleared, the
encoding rule shall be cleared, and the associated mbstate_t object shall be set to describe an
initial conversion state.
14038 CX
14039
The largest value that can be represented correctly in an object of type off_t shall be established
as the offset maximum in the open file description.
14040 RETURN VALUE
14041
Upon successful completion, freopen( ) shall return the value
14042 CX
shall be returned, and errno shall be set to indicate the error.
14043
14044
of stream. Otherwise, a null pointer
ERRORS
The freopen( ) function shall fail if:
14045 CX
14046
14047
14048
[EACCES]
Search permission is denied on a component of the path prefix, or the file
exists and the permissions specified by mode are denied, or the file does not
exist and write permission is denied for the parent directory of the file to be
created.
14049 CX
[EINTR]
A signal was caught during freopen( ).
14050 CX
[EISDIR]
The named file is a directory and mode requires write access.
14051 CX
14052
[ELOOP]
A loop exists in symbolic links encountered during resolution of the path
argument.
14053 CX
[EMFILE]
{OPEN_MAX} file descriptors are currently open in the calling process.
14054 CX
[ENAMETOOLONG]
The length of the filename argument exceeds {PATH_MAX} or a pathname
component is longer than {NAME_MAX}.
14055
14056
428
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
freopen( )
System Interfaces
14057 CX
[ENFILE]
The maximum allowable number of files is currently open in the system.
14058 CX
14059
[ENOENT]
A component of filename does not name an existing file or filename is an empty
string.
14060 CX
14061
[ENOSPC]
The directory or file system that would contain the new file cannot be
expanded, the file does not exist, and it was to be created.
14062 CX
[ENOTDIR]
A component of the path prefix is not a directory.
14063 CX
14064
[ENXIO]
The named file is a character special or block special file, and the device
associated with this special file does not exist.
14065 CX
14066
[EOVERFLOW]
The named file is a regular file and the size of the file cannot be represented
correctly in an object of type off_t.
14067 CX
14068
[EROFS]
The named file resides on a read-only file system and mode requires write
access.
14069
The freopen( ) function may fail if:
14070 CX
[EINVAL]
The value of the mode argument is not valid.
14071 CX
14072
[ELOOP]
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the path argument.
14073 CX
14074
14075
[ENAMETOOLONG]
Pathname resolution of a symbolic link produced an intermediate result
whose length exceeds {PATH_MAX}.
14076 CX
[ENOMEM]
Insufficient storage space is available.
14077 CX
14078
[ENXIO]
A request was made of a nonexistent device, or the request was outside the
capabilities of the device.
14079 CX
14080
[ETXTBSY]
The file is a pure procedure (shared text) file that is being executed and mode
requires write access.
14081
EXAMPLES
14082
Directing Standard Output to a File
14083
The following example logs all standard output to the /tmp/logfile file.
14084
14085
14086
14087
14088
14089
#include <stdio.h>
...
FILE *fp;
...
fp = freopen ("/tmp/logfile", "a+", stdout);
...
14090
14091
14092
APPLICATION USAGE
The freopen( ) function is typically used to attach the preopened streams associated with stdin,
stdout, and stderr to other files.
14093
14094
RATIONALE
None.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
429
freopen( )
System Interfaces
14095
14096
FUTURE DIRECTIONS
None.
14097
14098
14099
SEE ALSO
fclose( ), fopen( ), fdopen( ), mbsinit( ), the Base Definitions volume of IEEE Std 1003.1-2001,
<stdio.h>
14100
14101
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
14102
14103
14104
14105
Issue 5
The DESCRIPTION is updated to indicate that the orientation of the stream is cleared and the
conversion state of the stream is set to an initial conversion state by a successful call to the
freopen( ) function.
Large File Summit extensions are added.
14106
14107
14108
Issue 6
Extensions beyond the ISO C standard are marked.
The following new requirements on POSIX implementations derive from alignment with the
Single UNIX Specification:
14109
14110
14111
14112
•
In the DESCRIPTION, text is added to indicate setting of the offset maximum in the open file
description. This change is to support large files.
14113
14114
•
In the ERRORS section, the [EOVERFLOW] condition is added. This change is to support
large files.
14115
•
The [ELOOP] mandatory error condition is added.
14116
•
A second [ENAMETOOLONG] is added as an optional error condition.
14117
•
The [EINVAL], [ENOMEM], [ENXIO], and [ETXTBSY] optional error conditions are added.
The following changes are made for alignment with the ISO/IEC 9899: 1999 standard:
14118
14119
•
The freopen( ) prototype is updated.
14120
•
The DESCRIPTION is updated.
14121
14122
The wording of the mandatory [ELOOP] error condition is updated, and a second optional
[ELOOP] error condition is added.
14123
The DESCRIPTION is updated regarding failure to close, changing the ‘‘file’’ to ‘‘file descriptor’’.
430
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
14124
14125
NAME
14126
14127
SYNOPSIS
#include <math.h>
frexp( )
frexp, frexpf, frexpl — extract mantissa and exponent from a double precision number
double frexp(double num, int *exp);
float frexpf(float num, int *exp);
long double frexpl(long double num, int *exp);
14128
14129
14130
14131 DESCRIPTION
14132 CX
The functionality described on this reference page is aligned with the ISO C standard.
14133
conflict between the requirements described here and the ISO C standard is unintentional.
14134
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
14135
14136
These functions shall break a floating-point number num into a normalized fraction and an
integral power of 2. The integer exponent shall be stored in the int object pointed to by exp.
14137
14138
14139
RETURN VALUE
For finite arguments, these functions shall return the value x, such that x has a magnitude in the
interval [1⁄2,1) or 0, and num equals x times 2 raised to the power *exp.
14140 MX
If num is NaN, a NaN shall be returned, and the value of *exp is unspecified.
14141
If num is ±0, ±0 shall be returned, and the value of *exp shall be 0.
14142
If num is ±Inf, num shall be returned, and the value of *exp is unspecified.
14143
14144
ERRORS
No errors are defined.
14145
14146
EXAMPLES
None.
14147
14148
APPLICATION USAGE
None.
14149
14150
RATIONALE
None.
14151
14152
FUTURE DIRECTIONS
None.
14153
14154
SEE ALSO
isnan( ), ldexp( ), modf( ), the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>
14155
14156
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
14157
14158
14159
Issue 5
14160
14161
14162
Issue 6
The DESCRIPTION is updated to indicate how an application should check for an error. This
text was previously published in the APPLICATION USAGE section.
The frexpf( ) and frexpl( ) functions are added for alignment with the ISO/IEC 9899: 1999
standard.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
431
frexp( )
System Interfaces
14163
14164
The DESCRIPTION, RETURN VALUE, ERRORS, and APPLICATION USAGE sections are
revised to align with the ISO/IEC 9899: 1999 standard.
14165
14166
IEC 60559: 1989 standard floating-point extensions over the ISO/IEC 9899: 1999 standard are
marked.
432
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
14167
14168
NAME
14169
14170
SYNOPSIS
#include <stdio.h>
fscanf( )
fscanf, scanf, sscanf — convert formatted input
int fscanf(FILE *restrict stream, const char *restrict format, ... );
int scanf(const char *restrict format, ... );
int sscanf(const char *restrict s, const char *restrict format, ... );
14171
14172
14173
14174 DESCRIPTION
14175 CX
The functionality described on this reference page is aligned with the ISO C standard.
14176
conflict between the requirements described here and the ISO C standard is unintentional.
14177
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
14178
14179
14180
14181
14182
14183
14184
The fscanf( ) function shall read from the named input stream. The scanf( ) function shall read
from the standard input stream stdin. The sscanf( ) function shall read from the string s. Each
function reads bytes, interprets them according to a format, and stores the results in its
arguments. Each expects, as arguments, a control string format described below, and a set of
pointer arguments indicating where the converted input should be stored. The result is
undefined if there are insufficient arguments for the format. If the format is exhausted while
arguments remain, the excess arguments shall be evaluated but otherwise ignored.
14185 XSI
14186
14187
14188
14189
14190
14191
Conversions can be applied to the nth argument after the format in the argument list, rather than
to the next unused argument. In this case, the conversion specifier character % (see below) is
replaced by the sequence "%n$", where n is a decimal integer in the range [1,{NL_ARGMAX}].
This feature provides for the definition of format strings that select arguments in an order
appropriate to specific languages. In format strings containing the "%n$" form of conversion
specifications, it is unspecified whether numbered arguments in the argument list can be
referenced from the format string more than once.
14192
14193
14194
14195
14196
The format can contain either form of a conversion specification—that is, % or "%n$"—but the
two forms cannot be mixed within a single format string. The only exception to this is that %% or
%* can be mixed with the "%n$" form. When numbered argument specifications are used,
specifying the Nth argument requires that all the leading arguments, from the first to the
(N−1)th, are pointers.
14197 CX
14198
14199
14200
The fscanf( ) function in all its forms shall allow detection of a language-dependent radix
character in the input string. The radix character is defined in the program’s locale (category
LC_NUMERIC). In the POSIX locale, or in a locale where the radix character is not defined, the
radix character shall default to a period (’.’).
14201
14202
14203
14204
14205 XSI
14206
The format is a character string, beginning and ending in its initial shift state, if any, composed
of zero or more directives. Each directive is composed of one of the following: one or more
white-space characters (<space>s, <tab>s, <newline>s, <vertical-tab>s, or <form-feed>s); an
ordinary character (neither ’%’ nor a white-space character); or a conversion specification. Each
conversion specification is introduced by the character ’%’ or the character sequence "%n$",
after which the following appear in sequence:
14207
•
An optional assignment-suppressing character ’*’.
14208
•
An optional non-zero decimal integer that specifies the maximum field width.
14209
•
An option length modifier that specifies the size of the receiving object.
14210
•
A conversion specifier character that specifies the type of conversion to be applied. The valid
conversion specifiers are described below.
14211
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
433
fscanf( )
System Interfaces
14212
14213
14214
The fscanf( ) functions shall execute each directive of the format in turn. If a directive fails, as
detailed below, the function shall return. Failures are described as input failures (due to the
unavailability of input bytes) or matching failures (due to inappropriate input).
14215
14216
14217
A directive composed of one or more white-space characters shall be executed by reading input
until no more valid input can be read, or up to the first byte which is not a white-space character,
which remains unread.
14218
14219
14220
14221
14222
A directive that is an ordinary character shall be executed as follows: the next byte shall be read
from the input and compared with the byte that comprises the directive; if the comparison
shows that they are not equivalent, the directive shall fail, and the differing and subsequent
bytes shall remain unread. Similarly, if end-of-file, an encoding error, or a read error prevents a
character from being read, the directive shall fail.
14223
14224
14225
A directive that is a conversion specification defines a set of matching input sequences, as
described below for each conversion character. A conversion specification shall be executed in
the following steps.
14226
14227
Input white-space characters (as specified by isspace( )) shall be skipped, unless the conversion
specification includes a [, c, C, or n conversion specifier.
14228
14229
14230
14231
14232
14233
14234
14235
An item shall be read from the input, unless the conversion specification includes an n
conversion specifier. An input item shall be defined as the longest sequence of input bytes (up to
any specified maximum field width, which may be measured in characters or bytes dependent
on the conversion specifier) which is an initial subsequence of a matching sequence. The first
byte, if any, after the input item shall remain unread. If the length of the input item is 0, the
execution of the conversion specification shall fail; this condition is a matching failure, unless
end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is
an input failure.
14236
14237
14238
14239
14240
14241
14242 XSI
14243
14244
Except in the case of a % conversion specifier, the input item (or, in the case of a %n conversion
specification, the count of input bytes) shall be converted to a type appropriate to the conversion
character. If the input item is not a matching sequence, the execution of the conversion
specification fails; this condition is a matching failure. Unless assignment suppression was
indicated by a ’*’, the result of the conversion shall be placed in the object pointed to by the
first argument following the format argument that has not already received a conversion result if
the conversion specification is introduced by %, or in the nth argument if introduced by the
character sequence "%n$". If this object does not have an appropriate type, or if the result of the
conversion cannot be represented in the space provided, the behavior is undefined.
14245
The length modifiers and their meanings are:
14246
14247
hh
Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an
argument with type pointer to signed char or unsigned char.
14248
14249
h
Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an
argument with type pointer to short or unsigned short.
14250
14251
14252
14253
14254
l (ell)
Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an
argument with type pointer to long or unsigned long; that a following a, A, e, E, f, F, g,
or G conversion specifier applies to an argument with type pointer to double; or that a
following c, s,or [ conversion specifier applies to an argument with type pointer to
wchar_t.
14255
ll (ell-ell)
Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an
argument with type pointer to long long or unsigned long long.
14256
14257
434
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
fscanf( )
14258
14259
j
Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an
argument with type pointer to intmax_t or uintmax_t.
14260
14261
z
Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an
argument with type pointer to size_t or the corresponding signed integer type.
14262
14263
t
Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an
argument with type pointer to ptrdiff_t or the corresponding unsigned type.
14264
14265
L
Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to an
argument with type pointer to long double.
14266
14267
If a length modifier appears with any conversion specifier other than as specified above, the
behavior is undefined.
14268
The following conversion specifiers are valid:
14269
14270
14271
14272
d
Matches an optionally signed decimal integer, whose format is the same as expected for
the subject sequence of strtol( ) with the value 10 for the base argument. In the absence
of a size modifier, the application shall ensure that the corresponding argument is a
pointer to int.
14273
14274
14275
14276
i
Matches an optionally signed integer, whose format is the same as expected for the
subject sequence of strtol( ) with 0 for the base argument. In the absence of a size
modifier, the application shall ensure that the corresponding argument is a pointer to
int.
14277
14278
14279
14280
o
Matches an optionally signed octal integer, whose format is the same as expected for
the subject sequence of strtoul( ) with the value 8 for the base argument. In the absence
of a size modifier, the application shall ensure that the corresponding argument is a
pointer to unsigned.
14281
14282
14283
14284
u
Matches an optionally signed decimal integer, whose format is the same as expected for
the subject sequence of strtoul( ) with the value 10 for the base argument. In the absence
of a size modifier, the application shall ensure that the corresponding argument is a
pointer to unsigned.
14285
14286
14287
14288
x
Matches an optionally signed hexadecimal integer, whose format is the same as
expected for the subject sequence of strtoul( ) with the value 16 for the base argument. In
the absence of a size modifier, the application shall ensure that the corresponding
argument is a pointer to unsigned.
14289
14290
14291
14292
14293
a, e, f, g
Matches an optionally signed floating-point number, infinity, or NaN, whose format is
the same as expected for the subject sequence of strtod( ). In the absence of a size
modifier, the application shall ensure that the corresponding argument is a pointer to
float.
If the fprintf( ) family of functions generates character string representations for infinity
and NaN (a symbolic entity encoded in floating-point format) to support
IEEE Std 754-1985, the fscanf( ) family of functions shall recognize them as input.
14294
14295
14296
14297
14298
14299
14300
14301
14302
s
Matches a sequence of bytes that are not white-space characters. The application shall
ensure that the corresponding argument is a pointer to the initial byte of an array of
char, signed char, or unsigned char large enough to accept the sequence and a
terminating null character code, which shall be added automatically.
If an l (ell) qualifier is present, the input is a sequence of characters that begins in the
initial shift state. Each character shall be converted to a wide character as if by a call to
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
435
fscanf( )
System Interfaces
the mbrtowc( ) function, with the conversion state described by an mbstate_t object
initialized to zero before the first character is converted. The application shall ensure
that the corresponding argument is a pointer to an array of wchar_t large enough to
accept the sequence and the terminating null wide character, which shall be added
automatically.
14303
14304
14305
14306
14307
[
14308
14309
14310
14311
14312
Matches a non-empty sequence of bytes from a set of expected bytes (the scanset). The
normal skip over white-space characters shall be suppressed in this case. The
application shall ensure that the corresponding argument is a pointer to the initial byte
of an array of char, signed char, or unsigned char large enough to accept the sequence
and a terminating null byte, which shall be added automatically.
14313
14314
14315
14316
14317
14318
14319
If an l (ell) qualifier is present, the input is a sequence of characters that begins in the
initial shift state. Each character in the sequence shall be converted to a wide character
as if by a call to the mbrtowc( ) function, with the conversion state described by an
mbstate_t object initialized to zero before the first character is converted. The
application shall ensure that the corresponding argument is a pointer to an array of
wchar_t large enough to accept the sequence and the terminating null wide character,
which shall be added automatically.
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
The conversion specification includes all subsequent bytes in the format string up to
and including the matching right square bracket (’]’). The bytes between the square
brackets (the scanlist) comprise the scanset, unless the byte after the left square bracket
is a circumflex (’ˆ’), in which case the scanset contains all bytes that do not appear in
the scanlist between the circumflex and the right square bracket. If the conversion
specification begins with "[ ]" or "[ˆ]", the right square bracket is included in the
scanlist and the next right square bracket is the matching right square bracket that ends
the conversion specification; otherwise, the first right square bracket is the one that
ends the conversion specification. If a ’−’ is in the scanlist and is not the first character,
nor the second where the first character is a ’ˆ’, nor the last character, the behavior is
implementation-defined.
c
14331
14332
14333
14334
14335
Matches a sequence of bytes of the number specified by the field width (1 if no field
width is present in the conversion specification). The application shall ensure that the
corresponding argument is a pointer to the initial byte of an array of char, signed char,
or unsigned char large enough to accept the sequence. No null byte is added. The
normal skip over white-space characters shall be suppressed in this case.
If an l (ell) qualifier is present, the input shall be a sequence of characters that begins in
the initial shift state. Each character in the sequence is converted to a wide character as
if by a call to the mbrtowc( ) function, with the conversion state described by an
mbstate_t object initialized to zero before the first character is converted. The
application shall ensure that the corresponding argument is a pointer to an array of
wchar_t large enough to accept the resulting sequence of wide characters. No null wide
character is added.
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
p
Matches an implementation-defined set of sequences, which shall be the same as the set
of sequences that is produced by the %p conversion specification of the corresponding
fprintf( ) functions. The application shall ensure that the corresponding argument is a
pointer to a pointer to void. The interpretation of the input item is implementationdefined. If the input item is a value converted earlier during the same program
execution, the pointer that results shall compare equal to that value; otherwise, the
behavior of the %p conversion specification is undefined.
14350
14351
n
No input is consumed. The application shall ensure that the corresponding argument is
a pointer to the integer into which shall be written the number of bytes read from the
436
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
fscanf( )
System Interfaces
input so far by this call to the fscanf( ) functions. Execution of a %n conversion
specification shall not increment the assignment count returned at the completion of
execution of the function. No argument shall be converted, but one shall be consumed.
If the conversion specification includes an assignment-suppressing character or a field
width, the behavior is undefined.
14352
14353
14354
14355
14356
14357 XSI
C
Equivalent to lc.
14358 XSI
S
Equivalent to ls.
14359
14360
%
Matches a single ’%’ character; no conversion or assignment occurs. The complete
conversion specification shall be %%.
14361
If a conversion specification is invalid, the behavior is undefined.
14362
14363
The conversion specifiers A, E, F, G, and X are also valid and shall be equivalent to a, e, f, g, and
x, respectively.
14364
14365
14366
14367
14368
14369
If end-of-file is encountered during input, conversion shall be terminated. If end-of-file occurs
before any bytes matching the current conversion specification (except for %n) have been read
(other than leading white-space characters, where permitted), execution of the current
conversion specification shall terminate with an input failure. Otherwise, unless execution of the
current conversion specification is terminated with a matching failure, execution of the
following conversion specification (if any) shall be terminated with an input failure.
14370
14371
Reaching the end of the string in sscanf( ) shall be equivalent to encountering end-of-file for
fscanf( ).
14372
14373
14374
14375
If conversion terminates on a conflicting input, the offending input is left unread in the input.
Any trailing white space (including <newline>s) shall be left unread unless matched by a
conversion specification. The success of literal matches and suppressed assignments is only
directly determinable via the %n conversion specification.
14376 CX
14377
14378
14379
The fscanf( ) and scanf( ) functions may mark the st_atime field of the file associated with stream
for update. The st_atime field shall be marked for update by the first successful execution of
fgetc( ), fgets( ), fread( ), getc( ), getchar( ), gets( ), fscanf( ), or fscanf( ) using stream that returns data
not supplied by a prior call to ungetc( ).
14380 RETURN VALUE
14381
Upon successful completion, these functions shall return the number of successfully matched
14382
and assigned input items; this number can be zero in the event of an early matching failure. If
14383
the input ends before the first matching failure or conversion, EOF shall be returned. If a read
14384 CX
error occurs, the error indicator for the stream is set, EOF shall be returned, and errno shall be set
14385
to indicate the error.
14386
14387
14388
ERRORS
For the conditions under which the fscanf( ) functions fail and may fail, refer to fgetc( ) or
fgetwc( ).
14389
In addition, fscanf( ) may fail if:
14390 XSI
[EILSEQ]
Input byte sequence does not form a valid character.
14391 XSI
[EINVAL]
There are insufficient arguments.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
437
fscanf( )
14392
14393
System Interfaces
EXAMPLES
The call:
14394
14395
int i, n; float x; char name[50];
n = scanf("%d%f%s", &i, &x, name);
14396
with the input line:
14397
25 54.32E−1 Hamster
14398
14399
assigns to n the value 3, to i the value 25, to x the value 5.432, and name contains the string
"Hamster".
14400
The call:
14401
14402
int i; float x; char name[50];
(void) scanf("%2d%f%*d %[0123456789]", &i, &x, name);
14403
with input:
14404
56789 0123 56a72
14405
14406
assigns 56 to i, 789.0 to x, skips 0123, and places the string "56\0" in name. The next call to
getchar( ) shall return the character ’a’.
14407
Reading Data into an Array
14408
14409
The following call uses fscanf( ) to read three floating-point numbers from standard input into
the input array.
14410
float input[3]; fscanf (stdin, "%f %f %f", input, input+1, input+2);
14411
14412
14413
APPLICATION USAGE
If the application calling fscanf( ) has any objects of type wint_t or wchar_t, it must also include
the <wchar.h> header to have these objects defined.
14414
14415
14416
14417
14418
14419
14420
RATIONALE
This function is aligned with the ISO/IEC 9899: 1999 standard, and in doing so a few ‘‘obvious’’
things were not included. Specifically, the set of characters allowed in a scanset is limited to
single-byte characters. In other similar places, multi-byte characters have been permitted, but
for alignment with the ISO/IEC 9899: 1999 standard, it has not been done here. Applications
needing this could use the corresponding wide-character functions to achieve the desired
results.
14421
14422
FUTURE DIRECTIONS
None.
14423
14424
14425
SEE ALSO
getc( ), printf( ), setlocale ( ), strtod( ), strtol( ), strtoul( ), wcrtomb( ), the Base Definitions volume of
IEEE Std 1003.1-2001, Chapter 7, Locale, <langinfo.h>, <stdio.h>, <wchar.h>
14426
14427
CHANGE HISTORY
First released in Issue 1. Derived from Issue 1 of the SVID.
14428
14429
14430
Issue 5
Aligned with ISO/IEC 9899: 1990/Amendment 1: 1995 (E). Specifically, the l (ell) qualifier is
now defined for the c, s, and [ conversion specifiers.
The DESCRIPTION is updated to indicate that if infinity and NaN can be generated by the
fprintf( ) family of functions, then they are recognized by the fscanf( ) family.
14431
14432
438
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
System Interfaces
14433
14434
14435
fscanf( )
Issue 6
The Open Group Corrigenda U021/7 and U028/10 are applied. These correct several
occurrences of ‘‘characters’’ in the text which have been replaced with the term ‘‘bytes’’.
14436
The DESCRIPTION is updated to avoid use of the term ‘‘must’’ for application requirements.
14437
The following changes are made for alignment with the ISO/IEC 9899: 1999 standard:
14438
•
The prototypes for fscanf( ), scanf( ), and sscanf( ) are updated.
14439
•
The DESCRIPTION is updated.
14440
•
The hh, ll, j, t, and z length modifiers are added.
14441
•
The a, A, and F conversion characters are added.
14442
14443
The DESCRIPTION is updated to use the terms ‘‘conversion specifier’’ and ‘‘conversion
specification’’ consistently.
System Interfaces, Issue 6 — Copyright  2001, IEEE and The Open Group. All rights reserved.
439
fseek( )
System Interfaces
14444
14445
NAME
14446
14447
SYNOPSIS
#include <stdio.h>
fseek, fseeko — reposition a file-position indicator in a stream
14448
14449 CX
14450
int fseek(FILE *stream, long offset, int whence);
int fseeko(FILE *stream, off_t offset, int whence);
14451 DESCRIPTION
14452 CX
The functionality described on this reference page is aligned with the ISO C standard.
14453
conflict between the requirements described here and the ISO C standard is unintentional.
14454
volume of IEEE Std 1003.1-2001 defers to the ISO C standard.
Any
This
14455
14456
The fseek( ) function shall set the file-position indicator for the stream pointed to by stream. If a
read or write error occurs, the error indicator for the stream shall be set and fseek( ) fails.
14457
14458
14459
14460
The new position, measured in bytes from the beginning of the file, shall be obtained by adding
offset to the position specified by whence. The specified point is the beginning of the fi