The header files and library facilities that make up theGNU library are asuperset of those specified by theISOC standard.. 1.3.1 Header Files Libraries for use by C programs really consi
Trang 1Application Fundamentals
For GNU C Libraries version 2.3.x
by Sandra Loosemore
with Richard M Stallman, Roland McGrath,
Andrew Oram, and Ulrich Drepper
Trang 2Published by:
Copyright © 1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation
Permission is granted to copy, distribute and/or modify this document under theterms of the GNUFree Documentation License, Version 1.2, or any later versionpublished by the Free Software Foundation; with the Invariant Sections being “FreeSoftware and Free Manuals”, the “GNU Free Documentation License”," and the
“GNULesser General Public License”, with the Front Cover Texts being “A GNUManual”, and with the Back Cover Texts as in (a) below A copy of the license isincluded in the section entitled “GNUFree Documentation License”
(a) The Back Cover Text is: You are free to copy and modify this GNU Manual.Buying copies fromGNUPress supports theFSFin developingGNUand promotingsoftware freedom
Cover art by Etienne Suvasa Cover design by Jonathan Richard Printed in USA
Trang 3Short Contents
1 Introduction . 1
2 Error Reporting . 17
3 Virtual Memory Allocation and Paging . 39
4 Character Handling . 79
5 String and Array Utilities . 89
6 Character-Set Handling . 133
7 Locales and Internationalization . 181
8 Mathematics . 203
9 Arithmetic Functions . 243
10 Date and Time . 277
11 Message Translation . 315
12 Searching and Sorting . 343
13 Pattern Matching . 355
14 The Basic Program/System Interface . 379
15 Input/Output Overview . 429
16 Debugging Support . 435
17 Input/Output on Streams . 439
A Summary of Library Facilities . 521
B Contributors to the GNU C Library . 587
C Free Software Needs Free Documentation . 591
D GNU Lesser General Public License . 593
E GNU Free Documentation License . 603
Concept Index . 611
Type Index . 617
Function and Macro Index . 619
Variable and Constant Macro Index . 629
Program and File Index . 635
Trang 5Table of Contents
1 Introduction 1
1.1 Getting Started 1
1.2 Standards and Portability 1
1.2.1 ISOC 2
1.2.2 POSIX(The Portable Operating System Interface) 2
1.2.3 Berkeley Unix 3
1.2.4 SVID(The System V Interface Description) 3
1.2.5 XPG(The X/Open Portability Guide) 4
1.3 Using the Library 4
1.3.1 Header Files 4
1.3.2 Macro Definitions of Functions 5
1.3.3 Reserved Names 6
1.3.4 Feature-Test Macros 8
1.4 Road Map to the Manual 12
2 Error Reporting 17
2.1 Checking for Errors 17
2.2 Error Codes 18
2.3 Error Messages 32
3 Virtual Memory Allocation and Paging 39
3.1 Process Memory Concepts 39
3.2 Allocating Storage for Program Data 41
3.2.1 Memory Allocation in C Programs 41
3.2.1.1 Dynamic Memory Allocation 41
3.2.2 Unconstrained Allocation 42
3.2.2.1 Basic Memory Allocation 42
3.2.2.2 Examples of malloc 43
3.2.2.3 Freeing Memory Allocated with malloc 44
3.2.2.4 Changing the Size of a Block 45
3.2.2.5 Allocating Cleared Space 46
3.2.2.6 Efficiency Considerations for malloc 46
3.2.2.7 Allocating Aligned Memory Blocks 47
3.2.2.8 mallocTunable Parameters 47
3.2.2.9 Heap Consistency Checking 48
3.2.2.10 Memory Allocation Hooks 50
3.2.2.11 Statistics for Memory Allocation with malloc 53
3.2.2.12 Summary of malloc-Related Functions 54
3.2.3 Allocation Debugging 55
3.2.3.1 How to Install the Tracing Functionality 56
Trang 63.2.3.2 Example Program Excerpts 56
3.2.3.3 Some More or Less Clever Ideas 57
3.2.3.4 Interpreting the Traces 58
3.2.4 Obstacks 59
3.2.4.1 Creating Obstacks 60
3.2.4.2 Preparing for Using Obstacks 60
3.2.4.3 Allocation in an Obstack 61
3.2.4.4 Freeing Objects in an Obstack 63
3.2.4.5 Obstack Functions and Macros 63
3.2.4.6 Growing Objects 64
3.2.4.7 Extra-Fast Growing Objects 66
3.2.4.8 Status of an Obstack 67
3.2.4.9 Alignment of Data in Obstacks 68
3.2.4.10 Obstack Chunks 69
3.2.4.11 Summary of Obstack Functions 69
3.2.5 Automatic Storage with Variable Size 71
3.2.5.1 allocaExample 72
3.2.5.2 Advantages of alloca 72
3.2.5.3 Disadvantages of alloca 73
3.2.5.4 GNUC Variable-Size Arrays 73
3.3 Resizing the Data Segment 74
3.4 Locking Pages 74
3.4.1 Why Lock Pages? 75
3.4.2 Locked-Memory Details 75
3.4.3 Functions to Lock and Unlock Pages 76
4 Character Handling 79
4.1 Classification of Characters 79
4.2 Case Conversion 81
4.3 Character Class Determination for Wide Characters 82
4.4 Notes on Using the Wide-Character Classes 86
4.5 Mapping of Wide Characters 87
Trang 75 String and Array Utilities 89
5.1 Representation of Strings 89
5.2 String and Array Conventions 91
5.3 String Length 91
5.4 Copying and Concatenation 93
5.5 String/Array Comparison 105
5.6 Collation Functions 109
5.7 Search Functions 114
5.7.1 Compatibility String Search Functions 119
5.8 Finding Tokens in a String 119
5.9 strfry .124
5.10 Trivial Encryption 124
5.11 Encode Binary Data 125
5.12 Argz and Envz Vectors 127
5.12.1 Argz Functions .127
5.12.2 Envz Functions 130
6 Character-Set Handling 133
6.1 Introduction to Extended Characters 133
6.2 Overview About Character-Handling Functions 137
6.3 Restartable Multibyte Conversion Functions 137
6.3.1 Selecting the Conversion and Its Properties 138
6.3.2 Representing the State of the Conversion 139
6.3.3 Converting Single Characters 140
6.3.4 Converting Multibyte- and Wide-Character Strings 147
6.3.5 A Complete Multibyte Conversion Example 150
6.4 Nonreentrant Conversion Function 152
6.4.1 Nonreentrant Conversion of Single Characters 153
6.4.2 Nonreentrant Conversion of Strings 154
6.4.3 States in Nonreentrant Functions 155
6.5 Generic Charset Conversion 157
6.5.1 Generic Character-Set Conversion Interface 157
6.5.2 A Complete iconv Example 161
6.5.3 Some Details About Other iconv Implementations 163
6.5.4 The iconv Implementation in theGNUC Library 165
6.5.4.1 Format of ‘gconv-modules’ Files 166
6.5.4.2 Finding the Conversion Path in iconv 167
6.5.4.3 iconvModule Data Structures 168
6.5.4.4 iconvModule Interfaces 171
Trang 87 Locales and Internationalization 181
7.1 What Effects a Locale Has 181
7.2 Choosing a Locale 182
7.3 Categories of Activities That Locales Affect 182
7.4 How Programs Set the Locale .183
7.5 Standard Locales 185
7.6 Accessing Locale Information 186
7.6.1 localeconv: “It is portable, but ” 186
7.6.1.1 Generic Numeric Formatting Parameters 187
7.6.1.2 Printing the Currency Symbol 188
7.6.1.3 Printing the Sign of a Monetary Amount 190
7.6.2 Pinpoint Access to Locale Data 191
7.7 A Dedicated Function to Format Numbers 197
7.8 Yes-or-No Questions 200
8 Mathematics 203
8.1 Predefined Mathematical Constants 203
8.2 Trigonometric Functions 204
8.3 Inverse Trigonometric Functions 206
8.4 Exponentiation and Logarithms 207
8.5 Hyperbolic Functions 212
8.6 Special Functions 214
8.7 Known Maximum Errors in Math Functions 216
8.8 Pseudorandom Numbers 234
8.8.1 ISO C Random-Number Functions 235
8.8.2 BSD Random-Number Functions 235
8.8.3 SVID Random-Number Functions 237
8.9 Is Fast Code or Small Code Preferred? 242
9 Arithmetic Functions 243
9.1 Integers 243
9.2 Integer Division 244
9.3 Floating-Point Numbers 246
9.4 Floating-Point Number Classification Functions 247
9.5 Errors in Floating-Point Calculations 249
9.5.1 FP Exceptions 249
9.5.2 Infinity and NaN 250
9.5.3 Examining the FPU Status Word 252
9.5.4 Error Reporting by Mathematical Functions 253
9.6 Rounding Modes 254
9.7 Floating-Point Control Functions 256
9.8 Arithmetic Functions 258
9.8.1 Absolute Value 258
9.8.2 Normalization Functions 259
9.8.3 Rounding Functions 260
Trang 99.8.4 Remainder Functions 262
9.8.5 Setting and Modifying Single Bits of FP Values 263
9.8.6 Floating-Point Comparison Functions 264
9.8.7 Miscellaneous FP Arithmetic Functions 265
9.9 Complex Numbers 266
9.10 Projections, Conjugates and Decomposing of Complex Numbers 267
9.11 Parsing of Numbers 268
9.11.1 Parsing of Integers 268
9.11.2 Parsing of Floats 273
9.12 Old-fashioned System V Number-to-String Functions .275
10 Date and Time 277
10.1 Time Basics 277
10.2 Elapsed Time 277
10.3 Processor andCPUTime 279
10.3.1 CPUTime Inquiry 280
10.3.2 Processor Time Inquiry 281
10.4 Calendar Time 282
10.4.1 Simple Calendar Time 282
10.4.2 High-Resolution Calendar 283
10.4.3 Broken-Down Time 285
10.4.4 High-Accuracy Clock 288
10.4.5 Formatting Calendar Time 291
10.4.6 Convert Textual Time and Date Information Back 297
10.4.6.1 Interpret String According to Given Format 297
10.4.6.2 A More User-Friendly Way to Parse Times and Dates 303
10.4.7 Specifying the Time Zone with TZ 306
10.4.8 Functions and Variables for Time Zones 308
10.4.9 Time Functions Example 309
10.5 Setting an Alarm 310
10.6 Sleeping 312
Trang 1011 Message Translation 315
11.1 X/Open Message Catalog Handling 315
11.1.1 The catgets Function Family 316
11.1.2 Format of the Message Catalog Files 319
11.1.3 Generate Message Catalogs Files 321
11.1.4 How to Use the catgets Interface 322
11.1.4.1 Not Using Symbolic Names 322
11.1.4.2 Using Symbolic Names 323
11.1.4.3 Using Symbolic Version Numbers 324
11.2 The Uniforum Approach to Message Translation 325
11.2.1 The gettext Family of Functions 326
11.2.1.1 What Has to Be Done to Translate a Message? 326
11.2.1.2 How to Determine Which Catalog to Use 328
11.2.1.3 Additional Functions for More Complicated Situations 330
11.2.1.4 How to Specify the Output Character Set That gettextUses 335
11.2.1.5 How to Use gettext inGUIPrograms 336
11.2.1.6 User Influence on gettext 338
11.2.2 Programs to Handle Message Catalogs for gettext 341
12 Searching and Sorting 343
12.1 Defining the Comparison Function 343
12.2 Array Search Function 343
12.3 Array Sort Function 344
12.4 Searching and Sorting Example 345
12.5 The hsearch Function 348
12.6 The tsearch Function 351
13 Pattern Matching 355
13.1 Wildcard Matching 355
13.2 Globbing 357
13.2.1 Calling glob 357
13.2.2 Flags for Globbing 361
13.2.3 More Flags for Globbing 362
13.3 Regular Expression Matching 364
13.3.1 POSIXRegular Expression Compilation 365
13.3.2 Flags forPOSIXRegular Expressions 367
13.3.3 Matching a CompiledPOSIXRegular Expression 367
13.3.4 Match Results with Subexpressions 368
13.3.5 Complications in Subexpression Matching .369
13.3.6 POSIXRegexp Matching Clean-Up 369
Trang 1113.4 Shell-Style Word Expansion 370
13.4.1 The Stages of Word Expansion 371
13.4.2 Calling wordexp 371
13.4.3 Flags for Word Expansion 373
13.4.4 wordexpExample 374
13.4.5 Details of Tilde Expansion 375
13.4.6 Details of Variable Substitution 375
14 The Basic Program/System Interface 379
14.1 Program Arguments 379
14.1.1 Program Argument Syntax Conventions 380
14.1.2 Parsing Program Arguments 381
14.2 Parsing Program Options Using getopt 381
14.2.1 Using the getopt Function 381
14.2.2 Example of Parsing Arguments with getopt 382
14.2.3 Parsing Long Options with getopt_long 385
14.2.4 Example of Parsing Long Options with getopt_long 386
14.3 Parsing Program Options with Argp 389
14.3.1 The argp_parse Function 389
14.3.2 Argp Global Variables 390
14.3.3 Specifying Argp Parsers 391
14.3.4 Specifying Options in an Argp Parser 392
14.3.4.1 Flags for Argp Options 393
14.3.5 Argp Parser Functions 394
14.3.5.1 Special Keys for Argp Parser Functions 395
14.3.5.2 Functions for Use in Argp Parsers 397
14.3.5.3 Argp Parsing State 399
14.3.6 Combining Multiple Argp Parsers 400
14.3.7 Flags for argp_parse 401
14.3.8 Customizing Argp Help Output 402
14.3.8.1 Special Keys for Argp Help Filter Functions 403
14.3.9 The argp_help Function 403
14.3.10 Flags for the argp_help Function 404
14.3.11 Argp Examples 405
14.3.11.1 A Minimal Program Using Argp 405
14.3.11.2 A Program Using Argp with Only Default Options 406
14.3.11.3 A Program Using Argp with User Options 407
14.3.11.4 A Program Using Multiple Combined Argp Parsers 411
14.3.12 Argp User Customization .415
14.3.12.1 Parsing of Suboptions 416
14.3.13 Parsing of Suboptions Example 416
Trang 1214.4 Environment Variables 418
14.4.1 Environment Access .419
14.4.2 Standard Environment Variables 421
14.5 System Calls 423
14.6 Program Termination 425
14.6.1 Normal Termination 425
14.6.2 Exit Status 425
14.6.3 Clean-Ups on Exit 426
14.6.4 Aborting a Program 427
14.6.5 Termination Internals 428
15 Input/Output Overview 429
15.1 Input/Output Concepts 429
15.1.1 Streams and File Descriptors 429
15.1.2 File Position 430
15.2 File Names 431
15.2.1 Directories 431
15.2.2 File-Name Resolution 432
15.2.3 File-Name Errors 433
15.2.4 Portability of File Names 434
16 Debugging Support 435
16.1 Backtraces .435
17 Input/Output on Streams 439
17.1 Streams 439
17.2 Standard Streams 439
17.3 Opening Streams 440
17.4 Closing Streams 444
17.5 Streams and Threads 445
17.6 Streams in Internationalized Applications 448
17.7 Simple Output by Characters or Lines 450
17.8 Character Input 453
17.9 Line-Oriented Input 455
17.10 Unreading 458
17.10.1 What Unreading Means 458
17.10.2 Using ungetc to Do Unreading 458
17.11 Block Input/Output 459
17.12 Formatted Output 460
17.12.1 Formatted Output Basics 461
17.12.2 Output Conversion Syntax 462
17.12.3 Table of Output Conversions 463
17.12.4 Integer Conversions 465
17.12.5 Floating-Point Conversions 467
17.12.6 Other Output Conversions 469
Trang 1317.12.7 Formatted Output Functions 470
17.12.8 Dynamically Allocating Formatted Output 473
17.12.9 Variable Arguments Output Functions 474
17.12.10 Parsing a Template String 476
17.12.11 Example of Parsing a Template String 478
17.13 Customizing printf 480
17.13.1 Registering New Conversions 480
17.13.2 Conversion Specifier Options 481
17.13.3 Defining the Output Handler 482
17.13.4 printfExtension Example 483
17.13.5 Predefined printf Handlers 485
17.14 Formatted Input 486
17.14.1 Formatted Input Basics 486
17.14.2 Input Conversion Syntax 488
17.14.3 Table of Input Conversions 489
17.14.4 Numeric Input Conversions 490
17.14.5 String Input Conversions 492
17.14.6 Dynamically Allocating String Conversions 494
17.14.7 Other Input Conversions 494
17.14.8 Formatted Input Functions 495
17.14.9 Variable Arguments Input Functions 496
17.15 End-of-File and Errors 497
17.16 Recovering from Errors 498
17.17 Text and Binary Streams 499
17.18 File Positioning 500
17.19 Portable File-Position Functions 502
17.20 Stream Buffering 504
17.20.1 Buffering Concepts 505
17.20.2 Flushing Buffers 505
17.20.3 Controlling Which Kind of Buffering 506
17.21 Other Kinds of Streams 509
17.21.1 String Streams 509
17.21.2 Obstack Streams 511
17.21.3 Programming Your Own Custom Streams 512
17.21.3.1 Custom Streams and Cookies 512
17.21.3.2 Custom Stream Hook Functions 513
17.22 Formatted Messages 514
17.22.1 Printing Formatted Messages 515
17.22.2 Adding Severity Classes 518
17.22.3 How to Use fmtmsg and addseverity 518
Appendix A Summary of Library Facilities 521
Appendix B Contributors to the GNU C Library 587
Trang 14Appendix C Free Software Needs Free Documentation
591
Appendix D GNU Lesser General Public License 593
D.0.1 Preamble 593
D.0.2 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 595
D.0.3 How to Apply These Terms to Your New Libraries 602
Appendix E GNU Free Documentation License 603
E.0.1 ADDENDUM: How to Use This License for Your Documents 609
Concept Index 611
Type Index 617
Function and Macro Index 619
Variable and Constant Macro Index 629
Program and File Index 635
Trang 171 Introduction
The C language provides no built-in facilities for performing such common erations as input/output, memory management, string manipulation and the like.Instead, these facilities are defined in a standard library, which you compile andlink with your programs
op-The GNUC Library, described in this document, defines all of the library tions that are specified by theISOC standard, as well as additional features specific
func-toPOSIX and other derivatives of the Unix operating system, and extensions cific to theGNUsystem
spe-The purpose of this manual is to tell you how to use the facilities of the GNUlibrary We have mentioned which features belong to which standards to help youidentify things that are potentially nonportable But the emphasis in this manual isnot on strict portability
1.1 Getting Started
This manual is written with the assumption that you are at least somewhat miliar with the C programming language and basic programming concepts Specif-ically, familiarity with ISOstandard C (seeSection 1.2.1 [ISOC], page 2), ratherthan “traditional” pre-ISOC dialects, is assumed
fa-The GNU C Library includes several header files, each of which provides initions and declarations for a group of related facilities; this information is used
def-by the C compiler when processing your program For example, the header file
‘stdio.h’ declares facilities for performing input and output, and the header file
‘string.h’ declares string-processing utilities The organization of this manualgenerally follows the same division as the header files
If you are reading this manual for the first time, you should read all of the troductory material and skim the remaining chapters There are a lot of functions
in-in the GNU C Library and it is not realistic to expect that you will be able to member exactly how to use each and every one of them It is more important tobecome generally familiar with the kinds of facilities that the library provides, sothat when you are writing your programs you can recognize when to make use oflibrary functions, and where in this manual you can find more specific informationabout them
re-1.2 Standards and Portability
This section discusses the various standards and other sources that the GNU CLibrary is based upon These sources include theISOC andPOSIXstandards, andthe System V and Berkeley Unix implementations
The primary focus of this manual is to tell you how to make effective use oftheGNU library facilities But if you are concerned about making your programscompatible with these standards, or portable to operating systems other thanGNU,
Trang 18this can affect how you use the library This section gives you an overview of thesestandards, so that you will know what they are when they are mentioned in otherparts of the manual.
SeeAppendix A [Summary of Library Facilities], page 521, for an alphabeticallist of the functions and other symbols provided by the library This list also stateswhich standards each function or symbol comes from
1.2.1 ISO C
The GNU C Library is compatible with the C standard adopted by the ican National Standards Institute (ANSI)as American National Standard X3.159-1989—"ANSIC" and later by the International Standardization Organization (ISO)
Amer-asISO/IEC9899:1990, "Programming languages—C" In this manual, we refer tothe standard as ISOC since this is the more general standard with respect to rati-fication The header files and library facilities that make up theGNU library are asuperset of those specified by theISOC standard
If you are concerned about strict adherence to theISOC standard, you should usethe ‘-ansi’ option when you compile your programs with theGNUC Compiler.This tells the compiler to define onlyISOstandard features from the library headerfiles, unless you explicitly ask for additional features SeeSection 1.3.4 [Feature-Test Macros], page 8, for information on how to do this
Being able to restrict the library to include onlyISOC features is important cause ISOC puts limitations on what names can be defined by the library imple-mentation, and the GNU extensions don’t fit these limitations See Section 1.3.3[Reserved Names], page 6, for more information about these restrictions
be-This manual does not attempt to give you complete details on the differencesbetween ISOC and older dialects It gives advice on how to write programs towork portably under multiple C dialects, but does not aim for completeness
1.2.2 POSIX (The Portable Operating System Interface)
The GNU library is also compatible with the ISO POSIX family of standards,known more formally as the Portable Operating System Interface for ComputerEnvironments (ISO/IEC9945) They were also published asANSI/IEEE Std 1003.POSIXis derived mostly from various versions of the Unix operating system.The library facilities specified by the POSIX standards are a superset of thoserequired byISOC;POSIXspecifies additional features forISOC functions, as well
as specifying new additional functions In general, the additional requirements andfunctionality defined by the POSIX standards are aimed at providing lower-levelsupport for a particular kind of operating system environment, rather than generalprogramming language support that can run in many diverse operating system en-vironments
The GNU C Library implements all of the functions specified inISO/IEC1:1996, thePOSIXSystem Application Program Interface, commonly referred to asPOSIX.1 The primary extensions to the ISOC facilities specified by this standard
Trang 199945-include file-system interface primitives1, device-specific terminal control tions2and process control functions.3
func-Some facilities fromISO/IEC9945-2:1993, thePOSIXShell and Utilities standard(POSIX.2) are also implemented in theGNUlibrary These include utilities for deal-ing with regular expressions and other pattern-matching facilities (seeChapter 13[Pattern Matching], page 355)
1.2.3 Berkeley Unix
The GNU C Library defines facilities from some versions of Unix that are notformally standardized, specifically from the 4.2 BSD, 4.3 BSD and 4.4 BSD Unixsystems (also known as Berkeley Unix) and from SunOS(a popular 4.2BSDderiva-tive that includes some Unix System V functionality) These systems support most
of theISOC andPOSIXfacilities, and 4.4BSDand newer releases of SunOSin factsupport them all
TheBSDfacilities include symbolic links4, the select function5, theBSDnal functions6and sockets.7
sig-1.2.4 SVID (The System V Interface Description)
The System V Interface Description (SVID) is a document describing the AT&TUnix System V operating system It is to some extent a superset of the POSIXstandard
The GNU C Library defines most of the facilities required by theSVIDthat arenot also required by theISOC or POSIXstandards, for compatibility with System
V Unix and other Unix systems (such as SunOS) that include these facilities ever, many of the more obscure and less generally useful facilities required by theSVIDare not included (In fact, Unix System V itself does not provide them all.)The supported facilities from System V include the methods for inter-processcommunication and shared memory, the hsearch and drand48 families of func-tions, fmtmsg and several of the mathematical functions
How-1
See Sandra Loosemore et al., “File-System Interface”, GNU C Library: Systems & Network cations (Boston: GNU Press, 2004), available online at http:// www.gnu.org/ manual/ manual.html.
Appli-2 Ibid., “Low-Level Terminal Interface”.
Trang 201.2.5 XPG (The X/Open Portability Guide)
The X/Open Portability Guide8is a more general standard thanPOSIX X/Openowns the Unix copyright and theXPGspecifies the requirements for systems thatare intended to be Unix systems
TheGNUC Library complies with the X/Open Portability Guide, Issue 4.2, withall extensions common toXSI (X/Open System Interface) compliant systems andalso all X/Open Unix extensions
The additions on top ofPOSIXare mainly derived from functionality available inSystem V andBSD systems, though some of the really bad mistakes in System Vsystems were corrected Since fulfilling theXPGstandard with the Unix extensions
is a precondition for getting the Unix brand, chances are good that the functionality
is available on commercial systems
1.3 Using the Library
This section describes some of the practical issues involved in using theGNUCLibrary
1.3.1 Header Files
Libraries for use by C programs really consist of two parts: header files thatdefine types and macros and declare variables and functions, and the actual library
or archive that contains the definitions of the variables and functions
(Recall that in C, a declaration merely provides information that a function orvariable exists and gives its type For a function declaration, information about thetypes of its arguments might be provided as well The purpose of declarations is
to allow the compiler to correctly process references to the declared variables andfunctions A definition, on the other hand, actually allocates storage for a variable
or says what a function does.)
In order to use the facilities in the GNUC Library, you should be sure that yourprogram source files include the appropriate header files This is so that the com-piler has declarations of these facilities available and can correctly process refer-ences to them Once your program has been compiled, the linker resolves thesereferences to the actual definitions provided in the archive file
Header files are included into a program source file by the ‘#include’ cessor directive The C language supports two forms of this directive; the first,
prepro-#include " header"
is typically used to include a header file header that you write yourself; this wouldcontain definitions and declarations describing the interfaces between the differentparts of your particular application By contrast,
8
X/Open Company, X/Open Portability Guide, Issue 4 (Reading, UK: X/Open Company, Ltd., 1992).
Trang 21#include <file.h>
is typically used to include a header file ‘file.h’ that contains definitions anddeclarations for a standard library This file would normally be installed in a stan-dard place by your system administrator You should use this second form for the
C library header files
Typically, ‘#include’ directives are placed at the top of the C source file, fore any other code.9 If you begin your source files with some comments explainingwhat the code in the file does (a good idea), put the ‘#include’ directives im-mediately afterward, following the feature-test macro definition (seeSection 1.3.4[Feature-Test Macros], page 8)
be-TheGNUC Library provides several header files, each of which contains the typeand macro definitions and variable and function declarations for a group of relatedfacilities This means that your programs may need to include several header files,depending on exactly which facilities you are using
Some library header files include other library header files automatically ever, as a matter of programming style, you should not rely on this; it is better toexplicitly include all the header files required for the library facilities you are using.TheGNUC Library header files have been written in such a way that it doesn’t mat-ter if a header file is accidentally included more than once; including a header file
How-a second time hHow-as no effect Likewise, if your progrHow-am needs to include multipleheader files, the order in which they are included doesn’t matter
Compatibility Note: Inclusion of standard header files in any order and anynumber of times works in anyISOC implementation However, this has tradition-ally not been the case in many older C implementations
Strictly speaking, you don’t have to include a header file to use a function itdeclares; you could declare the function explicitly yourself, according to the spec-ifications in this manual But it is usually better to include the header file because
it may define types and macros that are not otherwise available and because it maydefine more efficient macro replacements for some functions It is also a sure way
to have the correct declaration
1.3.2 Macro Definitions of Functions
If we describe something as a function in this manual, it may have a macrodefinition as well This normally has no effect on how your program runs—themacro definition does the same thing as the function would In particular, macroequivalents for library functions evaluate arguments exactly once, in the same waythat a function call would The main reason for these macro definitions is thatsometimes they can produce an in-line expansion that is considerably faster than anactual function call
9 For more information about the use of header files and ‘#include’ directives, see Richard M Stallman and the GCC Developer Community, “Header Files” in The GNU C Preprocessor Man- ual (2003), http:// gcc.gnu.org/ onlinedocs/ gcc-3.3.2/ cpp/
Trang 22Taking the address of a library function works even if it is also defined as amacro This is because, in this context, the name of the function isn’t followed bythe left parenthesis that is syntactically necessary to recognize a macro call.You might occasionally want to avoid using the macro definition of a function—perhaps to make your program easier to debug There are two ways you can dothis:
1 You can avoid a macro definition in a specific use by enclosing the name ofthe function in parentheses This works because the name of the function doesnot appear in a syntactic context where it is recognizable as a macro call
2 You can suppress any macro definition for a whole source file by using the
‘#undef’ preprocessor directive, unless otherwise stated explicitly in the scription of that facility
de-For example, suppose the header file ‘stdlib.h’ declares a function named
extern int abs (int);
and also provides a macro definition for abs Then, in:
#include <stdlib.h>
int f (int *i) { return abs (++*i); }
the reference to abs might refer to either a macro or a function On the other hand,
in each of the following examples, the reference is to a function and not a macro:
#include <stdlib.h>
int g (int *i) { return (abs) (++*i); }
#undef abs
int h (int *i) { return abs (++*i); }
Since macro definitions that double for a function behave in exactly the same way
as the actual function version, there is usually no need for any of these methods Infact, removing macro definitions usually just makes your program slower
1.3.3 Reserved Names
The names of all library types, macros, variables and functions that come fromthe ISOC standard are reserved unconditionally; your program may not redefinethese names All other library names are reserved if your program explicitly in-cludes the header file that defines or declares them There are several reasons forthese restrictions:
• Other people reading your code could get very confused if, for example, youwere using a function named exit to do something completely different fromwhat the standard exit function does Preventing this situation helps to makeyour programs easier to understand and contributes to modularity and main-tainability
Trang 23• It avoids the possibility of a user accidentally redefining a library function that
is called by other library functions If redefinition were allowed, those otherfunctions would not work properly
• It allows the compiler to do whatever special optimizations it pleases on calls
to these functions, without the possibility that they may have been redefined
by the user Some library facilities, such as those for dealing with variadicarguments10 and nonlocal exits11, actually require a considerable amount ofcooperation on the part of the C compiler, and with respect to the implemen-tation, it might be easier for the compiler to treat these as built-in parts of thelanguage
In addition to the names documented in this manual, reserved names include allexternal identifiers (global functions and variables) that begin with an underscore(‘_’) and all identifiers regardless of use that begin with either two underscores or
an underscore followed by a capital letter This is so that the library and headerfiles can define functions, variables, and macros for internal purposes without risk
of conflict with names in user programs
Some additional classes of identifier names are reserved for future extensions tothe C language or thePOSIX.1 environment While using these names for your ownpurposes right now might not cause a problem, there is the possibility of conflictwith future versions of the C orPOSIXstandards, so you should avoid using them:
• Names beginning with a capital ‘E’ followed by a digit or uppercase lettermay be used for additional error-code names (seeChapter 2 [Error Reporting],page 17)
• Names that begin with either ‘is’ or ‘to’ followed by a lowercase letter may
be used for additional character testing and conversion functions (see ter 4 [Character Handling], page 79)
Chap-• Names that begin with ‘LC_’ followed by an uppercase letter may be usedfor additional macros specifying locale attributes (seeChapter 7 [Locales andInternationalization], page 181)
• Names of all existing mathematics functions (seeChapter 8 [Mathematics],page 203) suffixed with ‘f’ or ‘l’ are reserved for corresponding functionsthat operate on float and long double arguments, respectively
• Names that begin with ‘SIG’ followed by an uppercase letter are reserved foradditional signal names.12
• Names that begin with ‘SIG_’ followed by an uppercase letter are reservedfor additional signal actions.13
• Names beginning with ‘str’, ‘mem’, or ‘wcs’ followed by a lowercase letterare reserved for additional string and array functions (see Chapter 5 [Stringand Array Utilities], page 89)
Trang 24• Names that end with ‘_t’ are reserved for additional type names.
In addition, some individual header files reserve names beyond those that theyactually define You only need to worry about these restrictions if your programincludes that particular header file
• The header file ‘dirent.h’ reserves names prefixed with ‘d_’
• The header file ‘fcntl.h’ reserves names prefixed with ‘l_’, ‘F_’, ‘O_’,and ‘S_’
• The header file ‘grp.h’ reserves names prefixed with ‘gr_’
• The header file ‘limits.h’ reserves names suffixed with ‘_MAX’
• The header file ‘pwd.h’ reserves names prefixed with ‘pw_’
• The header file ‘signal.h’ reserves names prefixed with ‘sa_’ and ‘SA_’
• The header file ‘sys/stat.h’ reserves names prefixed with ‘st_’ and ‘S_’
• The header file ‘sys/times.h’ reserves names prefixed with ‘tms_’
• The header file ‘termios.h’ reserves names prefixed with ‘c_’, ‘V’, ‘I’,
‘O’, and ‘TC’; and names prefixed with ‘B’ followed by a digit
1.3.4 Feature-Test Macros
The exact set of features available when you compile a source file is controlled
by which feature-test macros you define
If you compile your programs using ‘gcc -ansi’, you get only the ISOC brary features, unless you explicitly request additional features by defining one ormore of the feature macros.14
li-You should define these macros by using ‘#define’ preprocessor directives
at the top of your source code files These directives must come before any
#includeof a system header file It is best to make them the very first thing
in the file, preceded only by comments You could also use the ‘-D’ option toGCC, but it is better if you make the source files indicate their own meaning in aself-contained way
This system exists to allow the library to conform to multiple standards though the different standards are often described as supersets of each other, theyare usually incompatible because larger standards require functions with names thatsmaller ones reserve to the user program This is not mere pedantry—it has been aproblem in practice For instance, some non-GNUprograms define functions namedgetlinethat have nothing to do with this library’s getline They would not
Al-be compilable if all features were enabled indiscriminately
14
See Richard M Stallman and the GCC Developer Community, “Invoking GCC” in Using GCC: The GNU Compiler Collection Reference Manual (Boston, MA: GNU Press, October 2003), http:// gcc.gnu.org/ onlinedocs/ gcc-3.3.2/ gcc/ , for more information about options.
Trang 25This should not be used to verify that a program conforms to a limited standard.
It is insufficient for this purpose, as it will not protect you from including headerfiles outside the standard, or relying on semantics undefined within the standard
If you define this macro to a value greater than or equal to 1, then the ity from the 1990 edition of thePOSIX.1 standard (IEEEStandard 1003.1-1990)
Greater values for _POSIX_C_SOURCE will enable future extensions ThePOSIXstandards process will define these values as necessary, and the GNUCLibrary should support them some time after they become standardized The
1996 edition of POSIX.1 (ISO/IEC 9945-1: 1996) states that if you define _
functionality from the 1996 edition is made available
Due to the nature of some of the conflicts between 4.3 BSDandPOSIX.1, youneed to use a special BSD compatibility library when linking programs com-piled for BSD compatibility This is because some functions must be defined
in two different ways, one in the normal C library, and one in the ity library If your program defines _BSD_SOURCE, you must give the option
compatibil-‘-lbsd-compat’ to the compiler or linker when linking the program, to tell
it to find functions in this special compatibility library before looking for them
in the normal C library
Trang 26XOPEN SOURCE EXTENDED
If you define this macro, functionality described in the X/Open PortabilityGuide15is included This is a superset of thePOSIX.1 and POSIX.2 functional-ity and in fact _POSIX_SOURCE and _POSIX_C_SOURCE are automaticallydefined
As the unification of all Unices, functionality only available inBSDandSVIDisalso included
If the macro _XOPEN_SOURCE_EXTENDED is also defined, even more tionality is available The extra functions will make all functions available thatare necessary for the X/Open Unix brand
func-If the macro _XOPEN_SOURCE has the value 500, this includes all functionalitydescribed so far plus some new definitions from the Single Unix Specification,version 2
Macro
LARGEFILE SOURCE
If this macro is defined, some extra functions are available that rectify a fewshortcomings in all previous standards Specifically, the functions fseekoand ftello are available Without these functions, the difference between theISOC interface (fseek, ftell) and the low-levelPOSIX interface (lseek)would lead to problems
This macro was introduced as part of the Large File Support extension (LFS)
Macro
LARGEFILE64 SOURCE
If you define this macro, an additional set of functions is made available thatenables 32-bit systems to use files of sizes beyond the usual limit of 2GB Thisinterface is not available if the system does not support files that large Onsystems where the natural file size limit is greater than 2GB (i.e., on 64-bitsystems), the new functions are identical to the replaced functions
The new functionality is made available by a new set of types and functions thatreplace the existing ones The names of these new objects contain 64 to indicatethe intention, e.g., off_t vs off64_t and fseeko vs fseeko64
This macro was introduced as part of the Large File Support extension (LFS) It
is a transition interface for the period when 64-bit offsets are not generally used(see _FILE_OFFSET_BITS)
15
X/Open Company, X/Open Portability Guide, Issue 4, Version 2 (Reading, UK: X/Open Company, Ltd., 1994).
Trang 27FILE OFFSET BITS
This macro determines which file-system interface will be used, one ing the other Whereas _LARGEFILE64_SOURCE makes the 64-bit interfaceavailable as an additional interface, _FILE_OFFSET_BITS allows the 64-bitinterface to replace the old interface
replac-If _FILE_OFFSET_BITS is undefined, or if it is defined to the value 32,nothing changes The 32-bit interface is used and types like off_t have a size
of 32 bits on 32-bit systems
If the macro is defined to the value 64, the large file interface replaces the oldinterface The functions are not made available under different names (as theyare with _LARGEFILE64_SOURCE); instead, the old function names now ref-erence the new functions, e.g., a call to fseeko now indeed calls fseeko64.This macro should only be selected if the system provides mechanisms for han-dling large files On 64-bit systems this macro has no effect since the *64functions are identical to the normal functions
This macro was introduced as part of the Large File Support extension (LFS)
If you want to get the full effect of _GNU_SOURCE but make theBSDdefinitionstake precedence over thePOSIXdefinitions, use this sequence of definitions:
is the delay in the standardization of the thread safe C library interface
Unlike on some other systems, no special version of the C library must be usedfor linking There is only one version—but while compiling this, it must havebeen specified to compile as thread safe
Trang 28We recommend you use _GNU_SOURCE in new programs If you don’t specifythe ‘-ansi’ option to GCCand do not define any of these macros explicitly, theeffect is the same as defining _POSIX_C_SOURCE to 2 and _POSIX_SOURCE,
When you define a feature-test macro to request a larger class of features, it
is harmless to define, in addition, a feature-test macro for a subset of those tures For example, if you define _POSIX_C_SOURCE, then defining _POSIX_SOURCEas well has no effect Likewise, if you define _GNU_SOURCE, definingeither _POSIX_SOURCE, _POSIX_C_SOURCE, or _SVID_SOURCE as well has
fea-no effect
Note, however, that the features of _BSD_SOURCE are not a subset of any ofthe other feature-test macros supported This is because it definesBSDfeatures thattake precedence over thePOSIXfeatures that are requested by the other macros Forthis reason, defining _BSD_SOURCE in addition to the other feature-test macrosdoes have an effect—it causes theBSDfeatures to take priority over the conflictingPOSIXfeatures
1.4 Road Map to the Manual
Here is an overview of the contents of the remaining chapters of this manual.The following chapters are found in the first volume, Sandra Loosemore et al.,GNU C Library: Application Fundamentals(Boston: GNU Press, 2004), availableonline at http:// www.gnu.org/ manual/ manual.html
• “Error Reporting” describes how errors detected by the library are reported
• “Virtual Memory Allocation and Paging” describes theGNUlibrary’s facilitiesfor managing and using virtual and real memory, including dynamic allocation
of virtual memory If you do not know in advance how much memory yourprogram needs, you can allocate it dynamically instead, and manipulate it viapointers
• “Character Handling” contains information about character-classificationfunctions (such as isspace) and functions for performing case conversion
• “String and Array Utilities” has descriptions of functions for manipulatingstrings (null-terminated character arrays) and general byte arrays, includingoperations such as copying and comparison
• “Character-Set Handling” contains information about manipulating charactersand strings using character sets larger than will fit in the usual char data type
• “Locales and Internationalization” describes how selecting a particular try or language affects the behavior of the library For example, the localeaffects collation sequences for strings and how monetary values are formatted
coun-• “Mathematics” contains information about the math library functions Theseinclude things like random-number generators and remainder functions on in-tegers as well as the usual trigonometric and exponential functions on floating-point numbers
Trang 29• “Arithmetic Functions” describes functions for simple arithmetic, analysis offloating-point values, and reading numbers from strings.
• “Date and Time” describes functions for measuring both calendar time andCPUtime, as well as functions for setting alarms and timers
• “Message Translation” describes how to write programs that are capable ofdelivering messages in whatever language the user selects without filling thesource code with sets of translations
• “Searching and Sorting” contains information about functions for searchingand sorting arrays You can use these functions on any kind of array by pro-viding an appropriate comparison function
• “Pattern Matching” presents functions for matching regular expressions andshell file-name patterns, and for expanding words as the shell does
• “The Basic Program/System Interface” tells how your programs can accesstheir command-line arguments and environment variables
• “Input/Output Overview” gives an overall look at the input and output ties in the library, and contains information about basic concepts such as filenames
facili-• “Debugging Support” describes functions provided by the library to make thedebugging process easier, whether or not a dedicated debugger program isbeing used
• “Input/Output on Streams” describes I/O operations involving streams (orFILE * objects) These are the normal C library functions from ‘stdio.h’
• “Summary of Library Facilities” gives a summary of all the functions, ables, and macros in the library, with complete data types and function proto-types, and says what standard or system each is derived from This section isalso found in the second volume, for convenient reference
vari-The following chapters are found in the second volume, Sandra Loosemore etal., GNU C Library: System & Network Applications (Boston: GNU Press, 2004),available online at http:// www.gnu.org/ manual/ manual.html
• “Low-Level Input/Output” contains information about I/O operations on filedescriptors File descriptors are a lower-level mechanism specific to the Unixfamily of operating systems
• “File-System Interface” has descriptions of operations on entire files, such
as functions for deleting and renaming them and for creating new directories.This chapter also contains information about how you can access the attributes
of a file, such as its owner and file-protection modes
related processes (such as between a parent and child), while FIFOs allowcommunication between processes sharing a common file-system on the samemachine
• “Sockets” describes a more complicated interprocess-communication anism that allows processes running on different machines to communicate
Trang 30mech-over a network This chapter also contains information about Internet addressing and how to use the system network databases.
host-• “Low-Level Terminal Interface” describes how you can change the attributes
of a terminal device If you want to disable echo of characters typed by theuser, for example, read this chapter
• “Processes” contains information about how to start new processes and runprograms
• “Job Control” describes functions for manipulating process groups and thecontrolling terminal This material is probably only of interest if you are writ-ing a shell or other program that handles job control specially
• “System Databases and Name-Service Switch” describes the services that areavailable for looking up names in the system databases, how to determinewhich service is used for which database, and how these services are imple-mented so that contributors can design their own services
• “Users and Groups” tells you how to access the system user- and databases
group-• “System Management” describes functions for controlling and getting mation about the hardware and software configuration your program is exe-cuting under
infor-• “System Configuration Parameters” tells you how you can get informationabout various operating system limits Most of these parameters are providedfor compatibility withPOSIX.
• “DES Encryption and Password Handling” discusses the legal and technicalissues related to password encryption and security, as well as the functionsnecessary to implement effective encryption
• “Resource Usage and Limitation” tells you how to monitor the memory andother resource usage totals of processes, and how to regulate this usage It alsocovers prioritization and scheduling
• “Syslog” describes facilities for issuing and logging messages of system ministration interest
ad-• “Nonlocal Exits” contains descriptions of the setjmp and longjmp tions These functions provide a facility for goto-like jumps that can jumpfrom one function to another
func-• “Signal Handling” tells you all about signals—what they are, how to establish
a handler that is called when a particular kind of signal is delivered, and how
to prevent signals from arriving during critical sections of your program
• “POSIXThreads” describes the pthreads (POSIXthreads) library This libraryprovides support functions for multithreaded programs: thread primitives, syn-chronization objects, etc It also implementsPOSIX1003.1b semaphores
• “C Language Facilities in the Library” contains information about library port for standard parts of the C language, including things like the sizeofoperator and the symbolic constant NULL, how to write functions acceptingvariable numbers of arguments, and constants describing the ranges and other
Trang 31sup-properties of the numerical types There is also a simple debugging nism that allows you to put assertions in your code and have diagnostic mes-sages printed if the tests fail.
mecha-• “Installing the GNU C Library” provides a detailed reference for installing,compiling and configuring theGNUC Library Configuration and optimizationcommand-line options are covered here
• “Library Maintenance” explains how to port and enhance theGNUC Libraryand how to report any bugs you might find
If you already know the name of the facility you are interested in, you can look
it up in Appendix A [Summary of Library Facilities], page 521 This gives you
a summary of its syntax and a pointer to where you can find a more detailed scription This appendix is particularly useful if you just want to verify the orderand type of arguments to a function, for example It also tells you what standard orsystem each function, variable, or macro is derived from
Trang 33de-2 Error Reporting
Many functions in the GNU C Library detect and report error conditions, andsometimes your programs need to check for these error conditions For example,when you open an input file, you should verify that the file was actually openedcorrectly, and print an error message or take other appropriate action if the call tothe library function failed
This chapter describes how the error-reporting facility works Your programshould include the header file ‘errno.h’ to use this facility
2.1 Checking for Errors
Most library functions return a special value to indicate that they have failed Thespecial value is typically -1, a null pointer, or a constant such as EOF that is definedfor that purpose But this return value tells you only that an error has occurred Tofind out what kind of error it was, you need to look at the error code stored in thevariable errno This variable is declared in the header file ‘errno.h’
Variable
volatile interrno
The variable errno contains the system error number You can change thevalue of errno
Since errno is declared volatile, it might be changed asynchronously by
a signal handler.1However, a properly written signal handler saves and restoresthe value of errno, so you generally do not need to worry about this possibilityexcept when writing signal handlers
The initial value of errno at program start-up is zero Many library functionsare guaranteed to set it to certain nonzero values when they encounter certainkinds of errors These error conditions are listed for each function These func-tions do not change errno when they succeed; thus, the value of errno after
a successful call is not necessarily zero, and you should not use errno to termine whether a call failed The proper way to do that is documented for eachfunction If the call failed, you can examine errno
de-Many library functions can set errno to a nonzero value as a result of ing other library functions that might fail You should assume that any libraryfunction might alter errno when the function returns an error
call-Portability Note: ISOC specifies errno as a "modifiable lvalue" rather than
as a variable, permitting it to be implemented as a macro For example, itsexpansion might involve a function call, like *_errno () In fact, that is what
it is on the GNU system itself The GNU library, on non-GNU systems, doeswhatever is right for the particular system
There are a few library functions, like sqrt and atan, that return a perfectlylegitimate value in case of an error, but also set errno For these functions, if
1
See Loosemore et al., “Defining Handlers” (see chap 1, n 1).
Trang 34you want to check to see whether an error occurred, the recommended method
is to set errno to zero before calling the function, and then check its valueafterward
All the error codes have symbolic names; they are macros defined in
‘errno.h’ The names start with ‘E’ and an uppercase letter or digit; you shouldconsider names of this form to be reserved names (see Section 1.3.3 [ReservedNames], page 6)
The error code values are all positive integers and are all distinct, with one tion: EWOULDBLOCK and EAGAIN are the same Since the values are distinct, youcan use them as labels in a switch statement; just do not use both EWOULDBLOCKand EAGAIN Your program should not make any other assumptions about the spe-cific values of these symbolic constants
excep-The value of errno doesn’t necessarily have to correspond to any of thesemacros, since some library functions might return other error codes of their ownfor other situations The only values that are guaranteed to be meaningful for aparticular library function are the ones that this manual lists for that function
On non-GNUsystems, almost any system call can return EFAULT if it is given
an invalid pointer as an argument Since this could only happen as a result of a bug
in your program, and since it will not happen on theGNUsystem, we have savedspace by not mentioning EFAULT in the descriptions of individual functions
In some Unix systems, many system calls can also return EFAULT if given as
an argument a pointer into the stack, and the kernel for some obscure reason fails
in its attempt to extend the stack If this ever happens, you should probably tryusing statically or dynamically allocated memory instead of stack memory on thatsystem
2.2 Error Codes
The error code macros are defined in the header file ‘errno.h’ All of themexpand into integer constant values Some of these error codes cannot occur on theGNUsystem, but they can occur using theGNUlibrary on other systems
Macro
This means no process matches the specified processID.
Trang 35intEINTR
This indicates an interrupted function call; an asynchronous signal occurred andprevented completion of the call When this happens, you should try the callagain
You can choose to have functions resume after a signal that is handled, ratherthan failing with EINTR.2
is missing or not correctly attached to the computer
Macro
intE2BIG
This means that the argument list is too long; it is used when the argumentspassed to a new program being executed with one of the exec functions3 oc-cupy too much memory space This condition never arises in theGNUsystem
There are no child processes This error happens on operations that are supposed
to manipulate child processes when there are not any processes to manipulate
Macro
This means a deadlock was avoided; allocating a system resource would haveresulted in a deadlock situation The system does not guarantee that it will noticeall such situations This error means you got lucky and the system noticed; itmight just hang.5
Trang 36intEBUSY
This means that a resource is busy; a system resource that cannot be shared
is already in use For example, if you try to delete a file that is the root of acurrently mounted file system, you get this error
Trang 37intENFILE
There are too many distinct file openings in the entire system Note that anynumber of linked channels count as just one file opening.9 This error neveroccurs in theGNUsystem
Trang 38This indicates a broken pipe; there is no process reading from the other end
of a pipe Every library function that returns this error code also generates aSIGPIPEsignal; this signal terminates the program if not handled or blocked.Thus, your program will never actually see EPIPE unless it has handled orblocked SIGPIPE
This error can happen in a few different situations:
• An operation that would block was attempted on an object that has blocking mode selected Trying the same operation again will block untilsome external condition makes it possible to read, write, or connect (what-ever the operation) You can use select to find out when the operationwill be possible.11
non-Portability Note: In many older Unix systems, this condition was cated by EWOULDBLOCK, which was a distinct error code different fromEAGAIN To make your program portable, you should check for both codesand treat them the same
indi-• A temporary resource shortage made an operation impossible fork canreturn this error It indicates that the shortage is expected to pass, so yourprogram can try the call again later and it may succeed It is probably
a good idea to delay for a few seconds before trying it again, to allowtime for other processes to release scarce resources Such shortages areusually fairly serious and affect the whole system, so usually an interactiveprogram should report the error to the user and return to its command loop
Trang 39to indicate that the operation has begun and will take some time Attempts tomanipulate the object before the call completes return EALREADY You can usethe select function to find out when the pending operation has completed.13
Trang 40The operation you requested is not supported Some socket functions don’tmake sense for all types of sockets, and others may not be implemented for allcommunications protocols In theGNUsystem, this error can happen for manycalls when the object does not support the particular operation; it is a genericindication that the server knows nothing to do for that call
Macro
The kernel’s buffers for I/O operations are all in use In GNU, this error isalways synonymous with ENOMEM; you may get one or the other from networkoperations