• Nie Znaleziono Wyników

The GNU C Library Reference Manual

N/A
N/A
Protected

Academic year: 2021

Share "The GNU C Library Reference Manual"

Copied!
1103
0
0

Pełen tekst

(1)
(2)
(3)

Reference Manual

Sandra Loosemore with

Richard M. Stallman, Roland McGrath, Andrew Oram, and Ulrich Drepper

for version 2.24

(4)

Copyright c 1993–2016 Free Software Foundation, Inc.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being “Free Software Needs Free Documentation” and “GNU Lesser General Public License”, the Front-Cover texts being

“A GNU Manual”, and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled "GNU Free Documentation License".

(a) The FSF’s Back-Cover Text is: “You have the freedom to copy and modify this GNU

manual. Buying copies from the FSF supports it in developing GNU and promoting software

freedom.”

(5)

Short Contents

1 Introduction . . . . 1

2 Error Reporting . . . . 22

3 Virtual Memory Allocation And Paging . . . . 39

4 Character Handling . . . . 76

5 String and Array Utilities . . . . 86

6 Character Set Handling . . . . 127

7 Locales and Internationalization . . . . 169

8 Message Translation . . . . 188

9 Searching and Sorting . . . . 213

10 Pattern Matching . . . . 223

11 Input/Output Overview . . . . 245

12 Input/Output on Streams . . . . 250

13 Low-Level Input/Output . . . . 325

14 File System Interface . . . . 379

15 Pipes and FIFOs . . . . 426

16 Sockets . . . . 431

17 Low-Level Terminal Interface . . . . 479

18 Syslog . . . . 506

19 Mathematics . . . . 514

20 Arithmetic Functions . . . . 562

21 Date and Time . . . . 598

22 Resource Usage And Limitation . . . . 633

23 Non-Local Exits . . . . 655

24 Signal Handling . . . . 664

25 The Basic Program/System Interface . . . . 708

26 Processes . . . . 752

27 Inter-Process Communication . . . . 763

28 Job Control . . . . 765

29 System Databases and Name Service Switch . . . . 784

30 Users and Groups . . . . 794

31 System Management . . . . 824

32 System Configuration Parameters . . . . 841

33 DES Encryption and Password Handling . . . . 862

(6)

35 POSIX Threads . . . . 872

36 Internal probes . . . . 874

A C Language Facilities in the Library . . . . 881

B Summary of Library Facilities . . . . 897

C Installing the GNU C Library . . . . 1000

D Library Maintenance . . . . 1008

E Platform-specific facilities . . . . 1015

F Contributors to the GNU C Library . . . . 1017

G Free Software Needs Free Documentation . . . . 1022

H GNU Lesser General Public License . . . . 1024

I GNU Free Documentation License . . . . 1033

Concept Index . . . . 1041

Type Index . . . . 1052

Function and Macro Index . . . . 1055

Variable and Constant Macro Index . . . . 1068

Program and File Index . . . . 1078

(7)

Table of Contents

1 Introduction . . . 1

1.1 Getting Started . . . 1

1.2 Standards and Portability . . . 1

1.2.1 ISO C . . . 2

1.2.2 POSIX (The Portable Operating System Interface) . . . 2

1.2.2.1 POSIX Safety Concepts . . . 2

1.2.2.2 Unsafe Features . . . 4

1.2.2.3 Conditionally Safe Features . . . 5

1.2.2.4 Other Safety Remarks . . . 9

1.2.3 Berkeley Unix . . . 11

1.2.4 SVID (The System V Interface Description) . . . 11

1.2.5 XPG (The X/Open Portability Guide) . . . 12

1.3 Using the Library . . . 12

1.3.1 Header Files . . . 12

1.3.2 Macro Definitions of Functions . . . 13

1.3.3 Reserved Names . . . 14

1.3.4 Feature Test Macros . . . 15

1.4 Roadmap to the Manual . . . 18

2 Error Reporting . . . 22

2.1 Checking for Errors . . . 22

2.2 Error Codes . . . 23

2.3 Error Messages . . . 33

3 Virtual Memory Allocation And Paging . . . 39

3.1 Process Memory Concepts . . . 39

3.2 Allocating Storage For Program Data . . . 40

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 . . . 42

3.2.2.3 Freeing Memory Allocated with malloc . . . 43

3.2.2.4 Changing the Size of a Block . . . 44

3.2.2.5 Allocating Cleared Space . . . 45

3.2.2.6 Efficiency Considerations for malloc . . . 45

3.2.2.7 Allocating Aligned Memory Blocks . . . 46

3.2.2.8 Malloc Tunable 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 . . . 52

3.2.2.12 Summary of malloc-Related Functions . . . 53

(8)

3.2.3.1 How to install the tracing functionality . . . 54

3.2.3.2 Example program excerpts . . . 55

3.2.3.3 Some more or less clever ideas . . . 56

3.2.3.4 Interpreting the traces . . . 56

3.2.4 Obstacks . . . 58

3.2.4.1 Creating Obstacks . . . 58

3.2.4.2 Preparing for Using Obstacks . . . 59

3.2.4.3 Allocation in an Obstack . . . 60

3.2.4.4 Freeing Objects in an Obstack . . . 61

3.2.4.5 Obstack Functions and Macros . . . 61

3.2.4.6 Growing Objects . . . 62

3.2.4.7 Extra Fast Growing Objects . . . 64

3.2.4.8 Status of an Obstack . . . 65

3.2.4.9 Alignment of Data in Obstacks . . . 66

3.2.4.10 Obstack Chunks . . . 66

3.2.4.11 Summary of Obstack Functions . . . 67

3.2.5 Automatic Storage with Variable Size . . . 69

3.2.5.1 alloca Example . . . 69

3.2.5.2 Advantages of alloca . . . 70

3.2.5.3 Disadvantages of alloca . . . 70

3.2.5.4 GNU C Variable-Size Arrays . . . 70

3.3 Resizing the Data Segment . . . 71

3.4 Locking Pages . . . 72

3.4.1 Why Lock Pages . . . 72

3.4.2 Locked Memory Details . . . 72

3.4.3 Functions To Lock And Unlock Pages . . . 73

4 Character Handling . . . 76

4.1 Classification of Characters . . . 76

4.2 Case Conversion . . . 78

4.3 Character class determination for wide characters . . . 79

4.4 Notes on using the wide character classes . . . 83

4.5 Mapping of wide characters. . . 84

5 String and Array Utilities . . . 86

5.1 Representation of Strings . . . 86

5.2 String and Array Conventions . . . 87

5.3 String Length . . . 88

5.4 Copying Strings and Arrays . . . 90

5.5 Concatenating Strings . . . 95

5.6 Truncating Strings while Copying . . . 98

5.7 String/Array Comparison . . . 102

5.8 Collation Functions . . . 106

5.9 Search Functions . . . 110

5.9.1 Compatibility String Search Functions . . . 115

5.10 Finding Tokens in a String . . . 115

(9)

5.12 Trivial Encryption . . . 120

5.13 Encode Binary Data . . . 120

5.14 Argz and Envz Vectors . . . 122

5.14.1 Argz Functions . . . 122

5.14.2 Envz Functions . . . 125

6 Character Set Handling . . . 127

6.1 Introduction to Extended Characters . . . 127

6.2 Overview about Character Handling Functions . . . 131

6.3 Restartable Multibyte Conversion Functions . . . 131

6.3.1 Selecting the conversion and its properties . . . 131

6.3.2 Representing the state of the conversion . . . 132

6.3.3 Converting Single Characters . . . 133

6.3.4 Converting Multibyte and Wide Character Strings . . . 139

6.3.5 A Complete Multibyte Conversion Example . . . 143

6.4 Non-reentrant Conversion Function . . . 144

6.4.1 Non-reentrant Conversion of Single Characters . . . 144

6.4.2 Non-reentrant Conversion of Strings . . . 146

6.4.3 States in Non-reentrant Functions . . . 147

6.5 Generic Charset Conversion . . . 148

6.5.1 Generic Character Set Conversion Interface . . . 149

6.5.2 A complete iconv example . . . 152

6.5.3 Some Details about other iconv Implementations . . . 154

6.5.4 The iconv Implementation in the GNU C Library . . . 155

6.5.4.1 Format of gconv-modules files . . . 156

6.5.4.2 Finding the conversion path in iconv . . . 157

6.5.4.3 iconv module data structures . . . 158

6.5.4.4 iconv module interfaces . . . 161

7 Locales and Internationalization . . . 169

7.1 What Effects a Locale Has . . . 169

7.2 Choosing a Locale . . . 170

7.3 Locale Categories . . . 170

7.4 How Programs Set the Locale . . . 171

7.5 Standard Locales . . . 173

7.6 Locale Names . . . 173

7.7 Accessing Locale Information . . . 174

7.7.1 localeconv: It is portable but . . . 175

7.7.1.1 Generic Numeric Formatting Parameters . . . 175

7.7.1.2 Printing the Currency Symbol . . . 176

7.7.1.3 Printing the Sign of a Monetary Amount . . . 178

7.7.2 Pinpoint Access to Locale Data . . . 178

7.8 A dedicated function to format numbers . . . 184

7.9 Yes-or-No Questions . . . 187

(10)

8.1 X/Open Message Catalog Handling . . . 188

8.1.1 The catgets function family . . . 188

8.1.2 Format of the message catalog files . . . 191

8.1.3 Generate Message Catalogs files . . . 193

8.1.4 How to use the catgets interface . . . 195

8.1.4.1 Not using symbolic names . . . 195

8.1.4.2 Using symbolic names . . . 195

8.1.4.3 How does to this allow to develop . . . 196

8.2 The Uniforum approach to Message Translation . . . 197

8.2.1 The gettext family of functions . . . 198

8.2.1.1 What has to be done to translate a message? . . . 198

8.2.1.2 How to determine which catalog to be used . . . 200

8.2.1.3 Additional functions for more complicated situations . . 202

8.2.1.4 How to specify the output character set gettext uses . . 206

8.2.1.5 How to use gettext in GUI programs . . . 207

8.2.1.6 User influence on gettext . . . 209

8.2.2 Programs to handle message catalogs for gettext . . . 211

9 Searching and Sorting . . . 213

9.1 Defining the Comparison Function . . . 213

9.2 Array Search Function . . . 213

9.3 Array Sort Function . . . 214

9.4 Searching and Sorting Example . . . 215

9.5 The hsearch function. . . 217

9.6 The tsearch function. . . 220

10 Pattern Matching . . . 223

10.1 Wildcard Matching . . . 223

10.2 Globbing . . . 224

10.2.1 Calling glob . . . 224

10.2.2 Flags for Globbing . . . 229

10.2.3 More Flags for Globbing . . . 230

10.3 Regular Expression Matching . . . 232

10.3.1 POSIX Regular Expression Compilation . . . 233

10.3.2 Flags for POSIX Regular Expressions . . . 234

10.3.3 Matching a Compiled POSIX Regular Expression . . . 235

10.3.4 Match Results with Subexpressions . . . 236

10.3.5 Complications in Subexpression Matching . . . 236

10.3.6 POSIX Regexp Matching Cleanup . . . 237

10.4 Shell-Style Word Expansion . . . 238

10.4.1 The Stages of Word Expansion . . . 238

10.4.2 Calling wordexp . . . 239

10.4.3 Flags for Word Expansion . . . 240

10.4.4 wordexp Example . . . 241

10.4.5 Details of Tilde Expansion . . . 242

10.4.6 Details of Variable Substitution . . . 242

(11)

11 Input/Output Overview . . . 245

11.1 Input/Output Concepts . . . 245

11.1.1 Streams and File Descriptors . . . 245

11.1.2 File Position . . . 246

11.2 File Names . . . 247

11.2.1 Directories . . . 247

11.2.2 File Name Resolution . . . 248

11.2.3 File Name Errors . . . 248

11.2.4 Portability of File Names . . . 249

12 Input/Output on Streams . . . 250

12.1 Streams . . . 250

12.2 Standard Streams . . . 250

12.3 Opening Streams . . . 251

12.4 Closing Streams . . . 255

12.5 Streams and Threads . . . 256

12.6 Streams in Internationalized Applications . . . 259

12.7 Simple Output by Characters or Lines . . . 261

12.8 Character Input . . . 264

12.9 Line-Oriented Input . . . 266

12.10 Unreading . . . 269

12.10.1 What Unreading Means . . . 269

12.10.2 Using ungetc To Do Unreading . . . 269

12.11 Block Input/Output . . . 271

12.12 Formatted Output . . . 272

12.12.1 Formatted Output Basics . . . 272

12.12.2 Output Conversion Syntax . . . 273

12.12.3 Table of Output Conversions . . . 274

12.12.4 Integer Conversions . . . 275

12.12.5 Floating-Point Conversions . . . 277

12.12.6 Other Output Conversions. . . 279

12.12.7 Formatted Output Functions . . . 280

12.12.8 Dynamically Allocating Formatted Output . . . 283

12.12.9 Variable Arguments Output Functions . . . 283

12.12.10 Parsing a Template String . . . 286

12.12.11 Example of Parsing a Template String . . . 287

12.13 Customizing printf . . . 289

12.13.1 Registering New Conversions . . . 289

12.13.2 Conversion Specifier Options . . . 290

12.13.3 Defining the Output Handler . . . 291

12.13.4 printf Extension Example . . . 292

12.13.5 Predefined printf Handlers . . . 293

12.14 Formatted Input . . . 294

12.14.1 Formatted Input Basics . . . 294

12.14.2 Input Conversion Syntax . . . 295

12.14.3 Table of Input Conversions . . . 296

12.14.4 Numeric Input Conversions . . . 298

(12)

12.14.6 Dynamically Allocating String Conversions . . . 301

12.14.7 Other Input Conversions . . . 301

12.14.8 Formatted Input Functions . . . 302

12.14.9 Variable Arguments Input Functions . . . 303

12.15 End-Of-File and Errors . . . 304

12.16 Recovering from errors . . . 305

12.17 Text and Binary Streams . . . 306

12.18 File Positioning . . . 307

12.19 Portable File-Position Functions . . . 310

12.20 Stream Buffering . . . 312

12.20.1 Buffering Concepts . . . 312

12.20.2 Flushing Buffers . . . 312

12.20.3 Controlling Which Kind of Buffering . . . 314

12.21 Other Kinds of Streams . . . 316

12.21.1 String Streams . . . 316

12.21.2 Programming Your Own Custom Streams . . . 318

12.21.2.1 Custom Streams and Cookies . . . 318

12.21.2.2 Custom Stream Hook Functions . . . 319

12.22 Formatted Messages . . . 320

12.22.1 Printing Formatted Messages . . . 320

12.22.2 Adding Severity Classes . . . 323

12.22.3 How to use fmtmsg and addseverity . . . 323

13 Low-Level Input/Output . . . 325

13.1 Opening and Closing Files . . . 325

13.2 Input and Output Primitives . . . 328

13.3 Setting the File Position of a Descriptor . . . 333

13.4 Descriptors and Streams . . . 335

13.5 Dangers of Mixing Streams and Descriptors . . . 336

13.5.1 Linked Channels . . . 337

13.5.2 Independent Channels . . . 337

13.5.3 Cleaning Streams . . . 337

13.6 Fast Scatter-Gather I/O . . . 338

13.7 Memory-mapped I/O . . . 339

13.8 Waiting for Input or Output . . . 344

13.9 Synchronizing I/O operations . . . 347

13.10 Perform I/O Operations in Parallel . . . 348

13.10.1 Asynchronous Read and Write Operations . . . 351

13.10.2 Getting the Status of AIO Operations . . . 355

13.10.3 Getting into a Consistent State . . . 356

13.10.4 Cancellation of AIO Operations . . . 358

13.10.5 How to optimize the AIO implementation . . . 360

13.11 Control Operations on Files . . . 361

13.12 Duplicating Descriptors . . . 362

13.13 File Descriptor Flags . . . 363

13.14 File Status Flags . . . 365

13.14.1 File Access Modes . . . 365

(13)

13.14.3 I/O Operating Modes . . . 368

13.14.4 Getting and Setting File Status Flags . . . 369

13.15 File Locks. . . 370

13.16 Open File Description Locks . . . 373

13.17 Open File Description Locks Example . . . 376

13.18 Interrupt-Driven Input . . . 377

13.19 Generic I/O Control operations . . . 378

14 File System Interface . . . 379

14.1 Working Directory . . . 379

14.2 Accessing Directories . . . 381

14.2.1 Format of a Directory Entry . . . 381

14.2.2 Opening a Directory Stream . . . 383

14.2.3 Reading and Closing a Directory Stream . . . 384

14.2.4 Simple Program to List a Directory . . . 386

14.2.5 Random Access in a Directory Stream . . . 387

14.2.6 Scanning the Content of a Directory . . . 387

14.2.7 Simple Program to List a Directory, Mark II . . . 389

14.3 Working with Directory Trees . . . 390

14.4 Hard Links . . . 394

14.5 Symbolic Links . . . 395

14.6 Deleting Files . . . 398

14.7 Renaming Files . . . 399

14.8 Creating Directories . . . 400

14.9 File Attributes . . . 401

14.9.1 The meaning of the File Attributes . . . 401

14.9.2 Reading the Attributes of a File . . . 405

14.9.3 Testing the Type of a File . . . 406

14.9.4 File Owner . . . 408

14.9.5 The Mode Bits for Access Permission . . . 410

14.9.6 How Your Access to a File is Decided . . . 411

14.9.7 Assigning File Permissions . . . 412

14.9.8 Testing Permission to Access a File . . . 414

14.9.9 File Times . . . 415

14.9.10 File Size . . . 417

14.9.11 Storage Allocation . . . 420

14.10 Making Special Files . . . 421

14.11 Temporary Files . . . 422

15 Pipes and FIFOs . . . 426

15.1 Creating a Pipe . . . 426

15.2 Pipe to a Subprocess . . . 428

15.3 FIFO Special Files . . . 429

15.4 Atomicity of Pipe I/O . . . 430

(14)

16.1 Socket Concepts . . . 431

16.2 Communication Styles . . . 432

16.3 Socket Addresses . . . 433

16.3.1 Address Formats . . . 433

16.3.2 Setting the Address of a Socket . . . 435

16.3.3 Reading the Address of a Socket . . . 435

16.4 Interface Naming . . . 436

16.5 The Local Namespace . . . 437

16.5.1 Local Namespace Concepts . . . 437

16.5.2 Details of Local Namespace . . . 437

16.5.3 Example of Local-Namespace Sockets . . . 438

16.6 The Internet Namespace . . . 439

16.6.1 Internet Socket Address Formats . . . 440

16.6.2 Host Addresses . . . 441

16.6.2.1 Internet Host Addresses . . . 441

16.6.2.2 Host Address Data Type . . . 442

16.6.2.3 Host Address Functions . . . 443

16.6.2.4 Host Names . . . 445

16.6.3 Internet Ports . . . 449

16.6.4 The Services Database . . . 450

16.6.5 Byte Order Conversion . . . 451

16.6.6 Protocols Database . . . 452

16.6.7 Internet Socket Example. . . 454

16.7 Other Namespaces . . . 455

16.8 Opening and Closing Sockets . . . 455

16.8.1 Creating a Socket . . . 455

16.8.2 Closing a Socket . . . 456

16.8.3 Socket Pairs . . . 457

16.9 Using Sockets with Connections . . . 457

16.9.1 Making a Connection . . . 458

16.9.2 Listening for Connections . . . 459

16.9.3 Accepting Connections . . . 459

16.9.4 Who is Connected to Me? . . . 461

16.9.5 Transferring Data . . . 461

16.9.5.1 Sending Data . . . 461

16.9.5.2 Receiving Data . . . 462

16.9.5.3 Socket Data Options . . . 463

16.9.6 Byte Stream Socket Example . . . 463

16.9.7 Byte Stream Connection Server Example . . . 464

16.9.8 Out-of-Band Data . . . 466

16.10 Datagram Socket Operations . . . 469

16.10.1 Sending Datagrams. . . 469

16.10.2 Receiving Datagrams . . . 470

16.10.3 Datagram Socket Example . . . 471

16.10.4 Example of Reading Datagrams . . . 472

16.11 The inetd Daemon . . . 473

16.11.1 inetd Servers . . . 473

(15)

16.12 Socket Options . . . 474

16.12.1 Socket Option Functions . . . 474

16.12.2 Socket-Level Options . . . 475

16.13 Networks Database . . . 477

17 Low-Level Terminal Interface . . . 479

17.1 Identifying Terminals . . . 479

17.2 I/O Queues . . . 480

17.3 Two Styles of Input: Canonical or Not . . . 480

17.4 Terminal Modes . . . 481

17.4.1 Terminal Mode Data Types. . . 481

17.4.2 Terminal Mode Functions. . . 482

17.4.3 Setting Terminal Modes Properly . . . 483

17.4.4 Input Modes . . . 484

17.4.5 Output Modes . . . 486

17.4.6 Control Modes . . . 487

17.4.7 Local Modes . . . 488

17.4.8 Line Speed . . . 491

17.4.9 Special Characters . . . 492

17.4.9.1 Characters for Input Editing . . . 492

17.4.9.2 Characters that Cause Signals . . . 494

17.4.9.3 Special Characters for Flow Control . . . 495

17.4.9.4 Other Special Characters . . . 496

17.4.10 Noncanonical Input . . . 496

17.5 BSD Terminal Modes . . . 498

17.6 Line Control Functions . . . 499

17.7 Noncanonical Mode Example . . . 501

17.8 Pseudo-Terminals . . . 502

17.8.1 Allocating Pseudo-Terminals . . . 502

17.8.2 Opening a Pseudo-Terminal Pair . . . 504

18 Syslog . . . 506

18.1 Overview of Syslog . . . 506

18.2 Submitting Syslog Messages . . . 507

18.2.1 openlog . . . 507

18.2.2 syslog, vsyslog . . . 509

18.2.3 closelog . . . 511

18.2.4 setlogmask . . . 512

18.2.5 Syslog Example . . . 512

(16)

19.1 Predefined Mathematical Constants . . . 514

19.2 Trigonometric Functions . . . 515

19.3 Inverse Trigonometric Functions . . . 517

19.4 Exponentiation and Logarithms . . . 518

19.5 Hyperbolic Functions . . . 523

19.6 Special Functions . . . 525

19.7 Known Maximum Errors in Math Functions . . . 528

19.8 Pseudo-Random Numbers . . . 552

19.8.1 ISO C Random Number Functions . . . 553

19.8.2 BSD Random Number Functions . . . 554

19.8.3 SVID Random Number Function . . . 556

19.9 Is Fast Code or Small Code preferred? . . . 561

20 Arithmetic Functions . . . 562

20.1 Integers . . . 562

20.2 Integer Division . . . 563

20.3 Floating Point Numbers . . . 565

20.4 Floating-Point Number Classification Functions . . . 566

20.5 Errors in Floating-Point Calculations . . . 568

20.5.1 FP Exceptions . . . 568

20.5.2 Infinity and NaN . . . 569

20.5.3 Examining the FPU status word . . . 570

20.5.4 Error Reporting by Mathematical Functions . . . 572

20.6 Rounding Modes . . . 573

20.7 Floating-Point Control Functions . . . 574

20.8 Arithmetic Functions . . . 576

20.8.1 Absolute Value . . . 577

20.8.2 Normalization Functions . . . 577

20.8.3 Rounding Functions . . . 579

20.8.4 Remainder Functions . . . 581

20.8.5 Setting and modifying single bits of FP values . . . 582

20.8.6 Floating-Point Comparison Functions . . . 584

20.8.7 Miscellaneous FP arithmetic functions . . . 585

20.9 Complex Numbers . . . 586

20.10 Projections, Conjugates, and Decomposing of Complex Numbers . . . 587

20.11 Parsing of Numbers . . . 588

20.11.1 Parsing of Integers . . . 588

20.11.2 Parsing of Floats . . . 593

20.12 Old-fashioned System V number-to-string functions . . . 595

(17)

21.1 Time Basics . . . 598

21.2 Elapsed Time . . . 598

21.3 Processor And CPU Time . . . 600

21.3.1 CPU Time Inquiry . . . 600

21.3.2 Processor Time Inquiry . . . 601

21.4 Calendar Time . . . 602

21.4.1 Simple Calendar Time . . . 602

21.4.2 High-Resolution Calendar . . . 603

21.4.3 Broken-down Time . . . 605

21.4.4 High Accuracy Clock . . . 608

21.4.5 Formatting Calendar Time . . . 611

21.4.6 Convert textual time and date information back . . . 617

21.4.6.1 Interpret string according to given format . . . 617

21.4.6.2 A More User-friendly Way to Parse Times and Dates . . 622

21.4.7 Specifying the Time Zone with TZ . . . 625

21.4.8 Functions and Variables for Time Zones . . . 627

21.4.9 Time Functions Example . . . 628

21.5 Setting an Alarm . . . 628

21.6 Sleeping . . . 631

22 Resource Usage And Limitation . . . 633

22.1 Resource Usage . . . 633

22.2 Limiting Resource Usage . . . 635

22.3 Process CPU Priority And Scheduling . . . 639

22.3.1 Absolute Priority . . . 640

22.3.1.1 Using Absolute Priority . . . 640

22.3.2 Realtime Scheduling . . . 641

22.3.3 Basic Scheduling Functions . . . 642

22.3.4 Traditional Scheduling . . . 645

22.3.4.1 Introduction To Traditional Scheduling . . . 646

22.3.4.2 Functions For Traditional Scheduling . . . 647

22.3.5 Limiting execution to certain CPUs . . . 648

22.4 Querying memory available resources . . . 651

22.4.1 Overview about traditional Unix memory handling . . . 651

22.4.2 How to get information about the memory subsystem? . . 651

22.5 Learn about the processors available . . . 653

23 Non-Local Exits . . . 655

23.1 Introduction to Non-Local Exits . . . 655

23.2 Details of Non-Local Exits. . . 656

23.3 Non-Local Exits and Signals . . . 657

23.4 Complete Context Control. . . 658

(18)

24.1 Basic Concepts of Signals. . . 664

24.1.1 Some Kinds of Signals . . . 664

24.1.2 Concepts of Signal Generation . . . 664

24.1.3 How Signals Are Delivered . . . 665

24.2 Standard Signals . . . 666

24.2.1 Program Error Signals . . . 666

24.2.2 Termination Signals . . . 669

24.2.3 Alarm Signals . . . 670

24.2.4 Asynchronous I/O Signals . . . 670

24.2.5 Job Control Signals. . . 671

24.2.6 Operation Error Signals . . . 672

24.2.7 Miscellaneous Signals . . . 673

24.2.8 Signal Messages . . . 674

24.3 Specifying Signal Actions . . . 674

24.3.1 Basic Signal Handling . . . 675

24.3.2 Advanced Signal Handling . . . 677

24.3.3 Interaction of signal and sigaction . . . 678

24.3.4 sigaction Function Example . . . 678

24.3.5 Flags for sigaction . . . 679

24.3.6 Initial Signal Actions . . . 680

24.4 Defining Signal Handlers . . . 681

24.4.1 Signal Handlers that Return . . . 681

24.4.2 Handlers That Terminate the Process . . . 682

24.4.3 Nonlocal Control Transfer in Handlers . . . 683

24.4.4 Signals Arriving While a Handler Runs . . . 684

24.4.5 Signals Close Together Merge into One . . . 684

24.4.6 Signal Handling and Nonreentrant Functions . . . 687

24.4.7 Atomic Data Access and Signal Handling . . . 688

24.4.7.1 Problems with Non-Atomic Access . . . 689

24.4.7.2 Atomic Types . . . 689

24.4.7.3 Atomic Usage Patterns . . . 690

24.5 Primitives Interrupted by Signals . . . 690

24.6 Generating Signals . . . 691

24.6.1 Signaling Yourself . . . 691

24.6.2 Signaling Another Process . . . 692

24.6.3 Permission for using kill . . . 693

24.6.4 Using kill for Communication . . . 694

24.7 Blocking Signals . . . 695

24.7.1 Why Blocking Signals is Useful . . . 695

24.7.2 Signal Sets . . . 696

24.7.3 Process Signal Mask . . . 697

24.7.4 Blocking to Test for Delivery of a Signal . . . 698

24.7.5 Blocking Signals for a Handler . . . 699

24.7.6 Checking for Pending Signals . . . 700

24.7.7 Remembering a Signal to Act On Later . . . 701

24.8 Waiting for a Signal . . . 702

24.8.1 Using pause . . . 702

(19)

24.8.3 Using sigsuspend . . . 703

24.9 Using a Separate Signal Stack . . . 704

24.10 BSD Signal Handling . . . 706

25 The Basic Program/System Interface . . . 708

25.1 Program Arguments . . . 708

25.1.1 Program Argument Syntax Conventions . . . 709

25.1.2 Parsing Program Arguments . . . 709

25.2 Parsing program options using getopt . . . 710

25.2.1 Using the getopt function . . . 710

25.2.2 Example of Parsing Arguments with getopt . . . 711

25.2.3 Parsing Long Options with getopt_long . . . 713

25.2.4 Example of Parsing Long Options with getopt_long . . . . 715

25.3 Parsing Program Options with Argp . . . 717

25.3.1 The argp_parse Function . . . 717

25.3.2 Argp Global Variables . . . 718

25.3.3 Specifying Argp Parsers . . . 718

25.3.4 Specifying Options in an Argp Parser . . . 719

25.3.4.1 Flags for Argp Options . . . 720

25.3.5 Argp Parser Functions . . . 721

25.3.5.1 Special Keys for Argp Parser Functions . . . 722

25.3.5.2 Argp Parsing State . . . 724

25.3.5.3 Functions For Use in Argp Parsers . . . 725

25.3.6 Combining Multiple Argp Parsers . . . 727

25.3.7 Flags for argp_parse . . . 727

25.3.8 Customizing Argp Help Output . . . 728

25.3.8.1 Special Keys for Argp Help Filter Functions . . . 729

25.3.9 The argp_help Function . . . 729

25.3.10 Flags for the argp_help Function . . . 729

25.3.11 Argp Examples . . . 730

25.3.11.1 A Minimal Program Using Argp . . . 731

25.3.11.2 A Program Using Argp with Only Default Options . . 731

25.3.11.3 A Program Using Argp with User Options . . . 732

25.3.11.4 A Program Using Multiple Combined Argp Parsers . . 735

25.3.12 Argp User Customization . . . 738

25.3.12.1 Parsing of Suboptions . . . 739

25.3.13 Parsing of Suboptions Example . . . 740

25.4 Environment Variables . . . 741

25.4.1 Environment Access . . . 742

25.4.2 Standard Environment Variables . . . 744

25.5 Auxiliary Vector . . . 745

25.5.1 Definition of getauxval . . . 746

25.6 System Calls . . . 746

25.7 Program Termination . . . 747

25.7.1 Normal Termination . . . 748

25.7.2 Exit Status . . . 748

25.7.3 Cleanups on Exit . . . 749

(20)

25.7.5 Termination Internals . . . 750

26 Processes . . . 752

26.1 Running a Command . . . 752

26.2 Process Creation Concepts . . . 753

26.3 Process Identification . . . 753

26.4 Creating a Process . . . 754

26.5 Executing a File. . . 755

26.6 Process Completion . . . 758

26.7 Process Completion Status . . . 760

26.8 BSD Process Wait Function . . . 761

26.9 Process Creation Example . . . 762

27 Inter-Process Communication . . . 763

27.1 Semaphores . . . 763

27.1.1 System V Semaphores . . . 763

27.1.2 POSIX Semaphores . . . 763

28 Job Control . . . 765

28.1 Concepts of Job Control . . . 765

28.2 Job Control is Optional . . . 766

28.3 Controlling Terminal of a Process. . . 766

28.4 Access to the Controlling Terminal . . . 766

28.5 Orphaned Process Groups . . . 767

28.6 Implementing a Job Control Shell . . . 767

28.6.1 Data Structures for the Shell . . . 768

28.6.2 Initializing the Shell . . . 769

28.6.3 Launching Jobs . . . 770

28.6.4 Foreground and Background . . . 774

28.6.5 Stopped and Terminated Jobs . . . 775

28.6.6 Continuing Stopped Jobs . . . 778

28.6.7 The Missing Pieces . . . 779

28.7 Functions for Job Control . . . 780

28.7.1 Identifying the Controlling Terminal . . . 780

28.7.2 Process Group Functions . . . 780

28.7.3 Functions for Controlling Terminal Access . . . 782

29 System Databases and Name Service Switch . . 784

29.1 NSS Basics . . . 784

29.2 The NSS Configuration File . . . 785

29.2.1 Services in the NSS configuration File. . . 785

29.2.2 Actions in the NSS configuration . . . 786

29.2.3 Notes on the NSS Configuration File . . . 787

29.3 NSS Module Internals . . . 788

29.3.1 The Naming Scheme of the NSS Modules . . . 788

(21)

29.4 Extending NSS . . . 790

29.4.1 Adding another Service to NSS . . . 791

29.4.2 Internals of the NSS Module Functions . . . 791

30 Users and Groups . . . 794

30.1 User and Group IDs . . . 794

30.2 The Persona of a Process . . . 794

30.3 Why Change the Persona of a Process? . . . 795

30.4 How an Application Can Change Persona . . . 795

30.5 Reading the Persona of a Process . . . 796

30.6 Setting the User ID . . . 797

30.7 Setting the Group IDs . . . 798

30.8 Enabling and Disabling Setuid Access . . . 800

30.9 Setuid Program Example . . . 801

30.10 Tips for Writing Setuid Programs . . . 803

30.11 Identifying Who Logged In . . . 804

30.12 The User Accounting Database . . . 805

30.12.1 Manipulating the User Accounting Database . . . 805

30.12.2 XPG User Accounting Database Functions . . . 810

30.12.3 Logging In and Out . . . 812

30.13 User Database . . . 813

30.13.1 The Data Structure that Describes a User . . . 813

30.13.2 Looking Up One User . . . 814

30.13.3 Scanning the List of All Users . . . 815

30.13.4 Writing a User Entry . . . 816

30.14 Group Database . . . 817

30.14.1 The Data Structure for a Group . . . 817

30.14.2 Looking Up One Group . . . 817

30.14.3 Scanning the List of All Groups . . . 818

30.15 User and Group Database Example . . . 820

30.16 Netgroup Database . . . 821

30.16.1 Netgroup Data . . . 821

30.16.2 Looking up one Netgroup. . . 821

30.16.3 Testing for Netgroup Membership . . . 822

31 System Management . . . 824

31.1 Host Identification . . . 824

31.2 Platform Type Identification . . . 826

31.3 Controlling and Querying Mounts . . . 827

31.3.1 Mount Information . . . 828

31.3.1.1 The fstab file . . . 828

31.3.1.2 The mtab file . . . 831

31.3.1.3 Other (Non-libc) Sources of Mount Information . . . . 834

31.3.2 Mount, Unmount, Remount . . . 834

31.4 System Parameters . . . 838

(22)

32.1 General Capacity Limits. . . 841 32.2 Overall System Options . . . 842 32.3 Which Version of POSIX is Supported . . . 843 32.4 Using sysconf . . . 844 32.4.1 Definition of sysconf . . . 844 32.4.2 Constants for sysconf Parameters . . . 844 32.4.3 Examples of sysconf . . . 851 32.5 Minimum Values for General Capacity Limits . . . 852 32.6 Limits on File System Capacity . . . 853 32.7 Optional Features in File Support . . . 854 32.8 Minimum Values for File System Limits . . . 855 32.9 Using pathconf . . . 856 32.10 Utility Program Capacity Limits . . . 858 32.11 Minimum Values for Utility Limits . . . 858 32.12 String-Valued Parameters . . . 859

33 DES Encryption and Password Handling . . 862

33.1 Legal Problems . . . 862 33.2 Reading Passwords . . . 863 33.3 Encrypting Passwords . . . 864 33.4 DES Encryption . . . 866

34 Debugging support . . . 869

34.1 Backtraces . . . 869

35 POSIX Threads . . . 872

35.1 Thread-specific Data . . . 872 35.2 Non-POSIX Extensions . . . 872 35.2.1 Setting Process-wide defaults for thread attributes . . . 872

36 Internal probes . . . 874

36.1 Memory Allocation Probes . . . 874 36.2 Mathematical Function Probes . . . 877 36.3 Non-local Goto Probes . . . 879

Appendix A C Language

Facilities in the Library . . . 881

A.1 Explicitly Checking Internal Consistency . . . 881

A.2 Variadic Functions . . . 882

A.2.1 Why Variadic Functions are Used . . . 882

A.2.2 How Variadic Functions are Defined and Used . . . 883

A.2.2.1 Syntax for Variable Arguments . . . 883

A.2.2.2 Receiving the Argument Values . . . 884

A.2.2.3 How Many Arguments Were Supplied . . . 884

(23)

A.2.2.5 Argument Access Macros . . . 885 A.2.3 Example of a Variadic Function . . . 887 A.3 Null Pointer Constant . . . 887 A.4 Important Data Types . . . 888 A.5 Data Type Measurements . . . 888 A.5.1 Computing the Width of an Integer Data Type . . . 889 A.5.2 Range of an Integer Type . . . 889 A.5.3 Floating Type Macros . . . 891 A.5.3.1 Floating Point Representation Concepts . . . 891 A.5.3.2 Floating Point Parameters . . . 892 A.5.3.3 IEEE Floating Point . . . 895 A.5.4 Structure Field Offset Measurement . . . 895

Appendix B Summary of Library Facilities . . . 897

Appendix C Installing the GNU C Library . . 1000

C.1 Configuring and compiling the GNU C Library . . . 1000 C.2 Installing the C Library . . . 1004 C.3 Recommended Tools for Compilation . . . 1005 C.4 Specific advice for GNU/Linux systems . . . 1006 C.5 Reporting Bugs . . . 1007

Appendix D Library Maintenance . . . 1008

D.1 Adding New Functions . . . 1008 D.1.1 Platform-specific types, macros and functions . . . 1009 D.2 Porting the GNU C Library. . . 1010 D.2.1 Layout of the sysdeps Directory Hierarchy . . . 1012 D.2.2 Porting the GNU C Library to Unix Systems . . . 1014

Appendix E Platform-specific facilities . . . 1015

E.1 PowerPC-specific Facilities . . . 1015

Appendix F Contributors to the

GNU C Library . . . 1017

Appendix G Free Software Needs

Free Documentation . . . 1022

Appendix H GNU Lesser General

Public License . . . 1024

(24)

Appendix I GNU Free

Documentation License . . . 1033

Concept Index . . . 1041

Type Index . . . 1052

Function and Macro Index . . . 1055

Variable and Constant Macro Index . . . 1068

Program and File Index . . . 1078

(25)

1 Introduction

The C language provides no built-in facilities for performing such common operations as input/output, memory management, string manipulation, and the like. Instead, these fa- cilities are defined in a standard library, which you compile and link with your programs.

The GNU C Library, described in this document, defines all of the library functions that are specified by the ISO C standard, as well as additional features specific to POSIX and other derivatives of the Unix operating system, and extensions specific to GNU systems.

The purpose of this manual is to tell you how to use the facilities of the GNU C Library.

We have mentioned which features belong to which standards to help you identify things that are potentially non-portable to other systems. But the emphasis in this manual is not on strict portability.

1.1 Getting Started

This manual is written with the assumption that you are at least somewhat familiar with the C programming language and basic programming concepts. Specifically, familiarity with ISO standard C (see Section 1.2.1 [ISO C], page 2), rather than “traditional” pre-ISO C dialects, is assumed.

The GNU C Library includes several header files, each of which provides definitions and declarations for a group of related facilities; this information is used by the C compiler when processing your program. For example, the header file stdio.h declares facilities for performing input and output, and the header file string.h declares string processing utilities. The organization of this manual generally follows the same division as the header files.

If you are reading this manual for the first time, you should read all of the introductory material and skim the remaining chapters. There are a lot of functions in the GNU C Library and it’s not realistic to expect that you will be able to remember exactly how to use each and every one of them. It’s more important to become generally familiar with the kinds of facilities that the library provides, so that when you are writing your programs you can recognize when to make use of library functions, and where in this manual you can find more specific information about them.

1.2 Standards and Portability

This section discusses the various standards and other sources that the GNU C Library is based upon. These sources include the ISO C and POSIX standards, and the System V and Berkeley Unix implementations.

The primary focus of this manual is to tell you how to make effective use of the GNU C Library facilities. But if you are concerned about making your programs compatible with these standards, or portable to operating systems other than GNU, this can affect how you use the library. This section gives you an overview of these standards, so that you will know what they are when they are mentioned in other parts of the manual.

See Appendix B [Summary of Library Facilities], page 897, for an alphabetical list of the

functions and other symbols provided by the library. This list also states which standards

each function or symbol comes from.

(26)

1.2.1 ISO C

The GNU C Library is compatible with the C standard adopted by the American Na- tional Standards Institute (ANSI): American National Standard X3.159-1989—“ANSI C”

and later by the International Standardization Organization (ISO): ISO/IEC 9899:1990,

“Programming languages—C”. We here refer to the standard as ISO C since this is the more general standard in respect of ratification. The header files and library facilities that make up the GNU C Library are a superset of those specified by the ISO C standard.

If you are concerned about strict adherence to the ISO C standard, you should use the

‘-ansi’ option when you compile your programs with the GNU C compiler. This tells the compiler to define only ISO standard features from the library header files, unless you explicitly ask for additional features. See Section 1.3.4 [Feature Test Macros], page 15, for information on how to do this.

Being able to restrict the library to include only ISO C features is important because ISO C puts limitations on what names can be defined by the library implementation, and the GNU extensions don’t fit these limitations. See Section 1.3.3 [Reserved Names], page 14, for more information about these restrictions.

This manual does not attempt to give you complete details on the differences between ISO C and older dialects. It gives advice on how to write programs to work portably under multiple C dialects, but does not aim for completeness.

1.2.2 POSIX (The Portable Operating System Interface)

The GNU C Library is also compatible with the ISO POSIX family of standards, known more formally as the Portable Operating System Interface for Computer Environments (ISO/IEC 9945). They were also published as ANSI/IEEE Std 1003. POSIX is derived mostly from various versions of the Unix operating system.

The library facilities specified by the POSIX standards are a superset of those required by ISO C; POSIX specifies additional features for ISO C functions, as well as specifying new additional functions. In general, the additional requirements and functionality defined by the POSIX standards are aimed at providing lower-level support for a particular kind of operating system environment, rather than general programming language support which can run in many diverse operating system environments.

The GNU C Library implements all of the functions specified in ISO/IEC 9945-1:1996, the POSIX System Application Program Interface, commonly referred to as POSIX.1. The primary extensions to the ISO C facilities specified by this standard include file system interface primitives (see Chapter 14 [File System Interface], page 379), device-specific ter- minal control functions (see Chapter 17 [Low-Level Terminal Interface], page 479), and process control functions (see Chapter 26 [Processes], page 752).

Some facilities from ISO/IEC 9945-2:1993, the POSIX Shell and Utilities standard (POSIX.2) are also implemented in the GNU C Library. These include utilities for deal- ing with regular expressions and other pattern matching facilities (see Chapter 10 [Pattern Matching], page 223).

1.2.2.1 POSIX Safety Concepts

This manual documents various safety properties of GNU C Library functions, in lines that

follow their prototypes and look like:

(27)

Preliminary: | MT-Safe | AS-Safe | AC-Safe |

The properties are assessed according to the criteria set forth in the POSIX standard for such safety contexts as Thread-, Async-Signal- and Async-Cancel- -Safety. Intuitive defi- nitions of these properties, attempting to capture the meaning of the standard definitions, follow.

• MT-Safe or Thread-Safe functions are safe to call in the presence of other threads. MT, in MT-Safe, stands for Multi Thread.

Being MT-Safe does not imply a function is atomic, nor that it uses any of the memory synchronization mechanisms POSIX exposes to users. It is even possible that calling MT-Safe functions in sequence does not yield an MT-Safe combination. For example, having a thread call two MT-Safe functions one right after the other does not guaran- tee behavior equivalent to atomic execution of a combination of both functions, since concurrent calls in other threads may interfere in a destructive way.

Whole-program optimizations that could inline functions across library interfaces may expose unsafe reordering, and so performing inlining across the GNU C Library inter- face is not recommended. The documented MT-Safety status is not guaranteed under whole-program optimization. However, functions defined in user-visible headers are designed to be safe for inlining.

• AS-Safe or Async-Signal-Safe functions are safe to call from asynchronous signal han- dlers. AS, in AS-Safe, stands for Asynchronous Signal.

Many functions that are AS-Safe may set errno, or modify the floating-point environ- ment, because their doing so does not make them unsuitable for use in signal handlers.

However, programs could misbehave should asynchronous signal handlers modify this thread-local state, and the signal handling machinery cannot be counted on to pre- serve it. Therefore, signal handlers that call functions that may set errno or modify the floating-point environment must save their original values, and restore them before returning.

• AC-Safe or Async-Cancel-Safe functions are safe to call when asynchronous cancellation is enabled. AC in AC-Safe stands for Asynchronous Cancellation.

The POSIX standard defines only three functions to be AC-Safe, namely pthread_

cancel, pthread_setcancelstate, and pthread_setcanceltype. At present the GNU C Library provides no guarantees beyond these three functions, but does docu- ment which functions are presently AC-Safe. This documentation is provided for use by the GNU C Library developers.

Just like signal handlers, cancellation cleanup routines must configure the floating point environment they require. The routines cannot assume a floating point environment, particularly when asynchronous cancellation is enabled. If the configuration of the floating point environment cannot be performed atomically then it is also possible that the environment encountered is internally inconsistent.

• MT-Unsafe, AS-Unsafe, AC-Unsafe functions are not safe to call within the safety con- texts described above. Calling them within such contexts invokes undefined behavior.

Functions not explicitly documented as safe in a safety context should be regarded as Unsafe.

• Preliminary safety properties are documented, indicating these properties may not be

counted on in future releases of the GNU C Library.

(28)

Such preliminary properties are the result of an assessment of the properties of our current implementation, rather than of what is mandated and permitted by current and future standards.

Although we strive to abide by the standards, in some cases our implementation is safe even when the standard does not demand safety, and in other cases our implementation does not meet the standard safety requirements. The latter are most likely bugs; the former, when marked as Preliminary, should not be counted on: future standards may require changes that are not compatible with the additional safety properties afforded by the current implementation.

Furthermore, the POSIX standard does not offer a detailed definition of safety. We assume that, by “safe to call”, POSIX means that, as long as the program does not invoke undefined behavior, the “safe to call” function behaves as specified, and does not cause other functions to deviate from their specified behavior. We have chosen to use its loose definitions of safety, not because they are the best definitions to use, but because choosing them harmonizes this manual with POSIX.

Please keep in mind that these are preliminary definitions and annotations, and certain aspects of the definitions are still under discussion and might be subject to clarification or change.

Over time, we envision evolving the preliminary safety notes into stable commitments, as stable as those of our interfaces. As we do, we will remove the Preliminary keyword from safety notes. As long as the keyword remains, however, they are not to be regarded as a promise of future behavior.

Other keywords that appear in safety notes are defined in subsequent sections.

1.2.2.2 Unsafe Features

Functions that are unsafe to call in certain contexts are annotated with keywords that document their features that make them unsafe to call. AS-Unsafe features in this sec- tion indicate the functions are never safe to call when asynchronous signals are enabled.

AC-Unsafe features indicate they are never safe to call when asynchronous cancellation is enabled. There are no MT-Unsafe marks in this section.

• lock

Functions marked with lock as an AS-Unsafe feature may be interrupted by a signal while holding a non-recursive lock. If the signal handler calls another such function that takes the same lock, the result is a deadlock.

Functions annotated with lock as an AC-Unsafe feature may, if cancelled asynchronously, fail to release a lock that would have been released if their execution had not been interrupted by asynchronous thread cancellation. Once a lock is left taken, attempts to take that lock will block indefinitely.

• corrupt

Functions marked with corrupt as an AS-Unsafe feature may corrupt data structures and misbehave when they interrupt, or are interrupted by, another such function.

Unlike functions marked with lock, these take recursive locks to avoid MT-Safety

problems, but this is not enough to stop a signal handler from observing a partially-

updated data structure. Further corruption may arise from the interrupted function’s

failure to notice updates made by signal handlers.

(29)

Functions marked with corrupt as an AC-Unsafe feature may leave data structures in a corrupt, partially updated state. Subsequent uses of the data structure may misbehave.

• heap

Functions marked with heap may call heap memory management functions from the malloc/free family of functions and are only as safe as those functions. This note is thus equivalent to:

| AS-Unsafe lock | AC-Unsafe lock fd mem |

• dlopen

Functions marked with dlopen use the dynamic loader to load shared libraries into the current execution image. This involves opening files, mapping them into memory, allocating additional memory, resolving symbols, applying relocations and more, all of this while holding internal dynamic loader locks.

The locks are enough for these functions to be AS- and AC-Unsafe, but other issues may arise. At present this is a placeholder for all potential safety issues raised by dlopen.

• plugin

Functions annotated with plugin may run code from plugins that may be external to the GNU C Library. Such plugin functions are assumed to be MT-Safe, AS-Unsafe and AC-Unsafe. Examples of such plugins are stack unwinding libraries, name service switch (NSS) and character set conversion (iconv) back-ends.

Although the plugins mentioned as examples are all brought in by means of dlopen, the plugin keyword does not imply any direct involvement of the dynamic loader or the libdl interfaces, those are covered by dlopen. For example, if one function loads a module and finds the addresses of some of its functions, while another just calls those already-resolved functions, the former will be marked with dlopen, whereas the latter will get the plugin. When a single function takes all of these actions, then it gets both marks.

• i18n

Functions marked with i18n may call internationalization functions of the gettext family and will be only as safe as those functions. This note is thus equivalent to:

| MT-Safe env | AS-Unsafe corrupt heap dlopen | AC-Unsafe corrupt |

• timer

Functions marked with timer use the alarm function or similar to set a time-out for a system call or a long-running operation. In a multi-threaded program, there is a risk that the time-out signal will be delivered to a different thread, thus failing to interrupt the intended thread. Besides being MT-Unsafe, such functions are always AS-Unsafe, because calling them in signal handlers may interfere with timers set in the interrupted code, and AC-Unsafe, because there is no safe way to guarantee an earlier timer will be reset in case of asynchronous cancellation.

1.2.2.3 Conditionally Safe Features

For some features that make functions unsafe to call in certain contexts, there are known ways to avoid the safety problem other than refraining from calling the function altogether.

The keywords that follow refer to such features, and each of their definitions indicate how

(30)

the whole program needs to be constrained in order to remove the safety problem indicated by the keyword. Only when all the reasons that make a function unsafe are observed and addressed, by applying the documented constraints, does the function become safe to call in a context.

• init

Functions marked with init as an MT-Unsafe feature perform MT-Unsafe initialization when they are first called.

Calling such a function at least once in single-threaded mode removes this specific cause for the function to be regarded as MT-Unsafe. If no other cause for that remains, the function can then be safely called after other threads are started.

Functions marked with init as an AS- or AC-Unsafe feature use the internal libc_

once machinery or similar to initialize internal data structures.

If a signal handler interrupts such an initializer, and calls any function that also per- forms libc_once initialization, it will deadlock if the thread library has been loaded.

Furthermore, if an initializer is partially complete before it is canceled or interrupted by a signal whose handler requires the same initialization, some or all of the initializa- tion may be performed more than once, leaking resources or even resulting in corrupt internal data.

Applications that need to call functions marked with init as an AS- or AC-Unsafe feature should ensure the initialization is performed before configuring signal handlers or enabling cancellation, so that the AS- and AC-Safety issues related with libc_once do not arise.

• race

Functions annotated with race as an MT-Safety issue operate on objects in ways that may cause data races or similar forms of destructive interference out of concurrent execution. In some cases, the objects are passed to the functions by users; in others, they are used by the functions to return values to users; in others, they are not even exposed to users.

We consider access to objects passed as (indirect) arguments to functions to be data race free. The assurance of data race free objects is the caller’s responsibility. We will not mark a function as MT-Unsafe or AS-Unsafe if it misbehaves when users fail to take the measures required by POSIX to avoid data races when dealing with such objects. As a general rule, if a function is documented as reading from an object passed (by reference) to it, or modifying it, users ought to use memory synchronization primitives to avoid data races just as they would should they perform the accesses themselves rather than by calling the library function. FILE streams are the exception to the general rule, in that POSIX mandates the library to guard against data races in many functions that manipulate objects of this specific opaque type. We regard this as a convenience provided to users, rather than as a general requirement whose expectations should extend to other types.

In order to remind users that guarding certain arguments is their responsibility, we will

annotate functions that take objects of certain types as arguments. We draw the line

for objects passed by users as follows: objects whose types are exposed to users, and

that users are expected to access directly, such as memory buffers, strings, and various

(31)

user-visible struct types, do not give reason for functions to be annotated with race.

It would be noisy and redundant with the general requirement, and not many would be surprised by the library’s lack of internal guards when accessing objects that can be accessed directly by users.

As for objects that are opaque or opaque-like, in that they are to be manipulated only by passing them to library functions (e.g., FILE, DIR, obstack, iconv_t), there might be additional expectations as to internal coordination of access by the library. We will annotate, with race followed by a colon and the argument name, functions that take such objects but that do not take care of synchronizing access to them by default. For example, FILE stream unlocked functions will be annotated, but those that perform implicit locking on FILE streams by default will not, even though the implicit locking may be disabled on a per-stream basis.

In either case, we will not regard as MT-Unsafe functions that may access user-supplied objects in unsafe ways should users fail to ensure the accesses are well defined. The notion prevails that users are expected to safeguard against data races any user-supplied objects that the library accesses on their behalf.

This user responsibility does not apply, however, to objects controlled by the library itself, such as internal objects and static buffers used to return values from certain calls. When the library doesn’t guard them against concurrent uses, these cases are regarded as MT-Unsafe and AS-Unsafe (although the race mark under AS-Unsafe will be omitted as redundant with the one under MT-Unsafe). As in the case of user- exposed objects, the mark may be followed by a colon and an identifier. The identifier groups all functions that operate on a certain unguarded object; users may avoid the MT-Safety issues related with unguarded concurrent access to such internal objects by creating a non-recursive mutex related with the identifier, and always holding the mutex when calling any function marked as racy on that identifier, as they would have to should the identifier be an object under user control. The non-recursive mutex avoids the MT-Safety issue, but it trades one AS-Safety issue for another, so use in asynchronous signals remains undefined.

When the identifier relates to a static buffer used to hold return values, the mutex must be held for as long as the buffer remains in use by the caller. Many functions that return pointers to static buffers offer reentrant variants that store return values in caller-supplied buffers instead. In some cases, such as tmpname, the variant is chosen not by calling an alternate entry point, but by passing a non-NULL pointer to the buffer in which the returned values are to be stored. These variants are generally preferable in multi-threaded programs, although some of them are not MT-Safe because of other internal buffers, also documented with race notes.

• const

Functions marked with const as an MT-Safety issue non-atomically modify internal

objects that are better regarded as constant, because a substantial portion of the

GNU C Library accesses them without synchronization. Unlike race, that causes both

readers and writers of internal objects to be regarded as MT-Unsafe and AS-Unsafe, this

mark is applied to writers only. Writers remain equally MT- and AS-Unsafe to call, but

the then-mandatory constness of objects they modify enables readers to be regarded as

MT-Safe and AS-Safe (as long as no other reasons for them to be unsafe remain), since

the lack of synchronization is not a problem when the objects are effectively constant.

(32)

The identifier that follows the const mark will appear by itself as a safety note in readers. Programs that wish to work around this safety issue, so as to call writers, may use a non-recursve rwlock associated with the identifier, and guard all calls to functions marked with const followed by the identifier with a write lock, and all calls to functions marked with the identifier by itself with a read lock. The non-recursive locking removes the MT-Safety problem, but it trades one AS-Safety problem for another, so use in asynchronous signals remains undefined.

• sig

Functions marked with sig as a MT-Safety issue (that implies an identical AS-Safety is- sue, omitted for brevity) may temporarily install a signal handler for internal purposes, which may interfere with other uses of the signal, identified after a colon.

This safety problem can be worked around by ensuring that no other uses of the signal will take place for the duration of the call. Holding a non-recursive mutex while calling all functions that use the same temporary signal; blocking that signal before the call and resetting its handler afterwards is recommended.

There is no safe way to guarantee the original signal handler is restored in case of asynchronous cancellation, therefore so-marked functions are also AC-Unsafe.

Besides the measures recommended to work around the MT- and AS-Safety problem, in order to avert the cancellation problem, disabling asynchronous cancellation and installing a cleanup handler to restore the signal to the desired state and to release the mutex are recommended.

• term

Functions marked with term as an MT-Safety issue may change the terminal settings in the recommended way, namely: call tcgetattr, modify some flags, and then call tcsetattr; this creates a window in which changes made by other threads are lost.

Thus, functions marked with term are MT-Unsafe. The same window enables changes made by asynchronous signals to be lost. These functions are also AS-Unsafe, but the corresponding mark is omitted as redundant.

It is thus advisable for applications using the terminal to avoid concurrent and reen- trant interactions with it, by not using it in signal handlers or blocking signals that might use it, and holding a lock while calling these functions and interacting with the terminal. This lock should also be used for mutual exclusion with functions marked with race:tcattr(fd), where fd is a file descriptor for the controlling terminal. The caller may use a single mutex for simplicity, or use one mutex per terminal, even if referenced by different file descriptors.

Functions marked with term as an AC-Safety issue are supposed to restore terminal settings to their original state, after temporarily changing them, but they may fail to do so if cancelled.

Besides the measures recommended to work around the MT- and AS-Safety problem,

in order to avert the cancellation problem, disabling asynchronous cancellation and

installing a cleanup handler to restore the terminal settings to the original state and

to release the mutex are recommended.

(33)

1.2.2.4 Other Safety Remarks

Additional keywords may be attached to functions, indicating features that do not make a function unsafe to call, but that may need to be taken into account in certain classes of programs:

• locale

Functions annotated with locale as an MT-Safety issue read from the locale object without any form of synchronization. Functions annotated with locale called concur- rently with locale changes may behave in ways that do not correspond to any of the locales active during their execution, but an unpredictable mix thereof.

We do not mark these functions as MT- or AS-Unsafe, however, because functions that modify the locale object are marked with const:locale and regarded as unsafe.

Being unsafe, the latter are not to be called when multiple threads are running or asyn- chronous signals are enabled, and so the locale can be considered effectively constant in these contexts, which makes the former safe.

• env

Functions marked with env as an MT-Safety issue access the environment with getenv or similar, without any guards to ensure safety in the presence of concurrent modifica- tions.

We do not mark these functions as MT- or AS-Unsafe, however, because functions that modify the environment are all marked with const:env and regarded as unsafe.

Being unsafe, the latter are not to be called when multiple threads are running or asynchronous signals are enabled, and so the environment can be considered effectively constant in these contexts, which makes the former safe.

• hostid

The function marked with hostid as an MT-Safety issue reads from the system-wide data structures that hold the “host ID” of the machine. These data structures cannot generally be modified atomically. Since it is expected that the “host ID” will not nor- mally change, the function that reads from it (gethostid) is regarded as safe, whereas the function that modifies it (sethostid) is marked with const:hostid, indicating it may require special care if it is to be called. In this specific case, the special care amounts to system-wide (not merely intra-process) coordination.

• sigintr

Functions marked with sigintr as an MT-Safety issue access the _sigintr internal data structure without any guards to ensure safety in the presence of concurrent mod- ifications.

We do not mark these functions as MT- or AS-Unsafe, however, because functions that modify the this data structure are all marked with const:sigintr and regarded as unsafe. Being unsafe, the latter are not to be called when multiple threads are run- ning or asynchronous signals are enabled, and so the data structure can be considered effectively constant in these contexts, which makes the former safe.

• fd

Functions annotated with fd as an AC-Safety issue may leak file descriptors if asyn-

chronous thread cancellation interrupts their execution.

Cytaty

Powiązane dokumenty

BOINC1 - Berkeley Open Infrastructure for Network Computing jest znane szerokim gronom internautów z projektu SETI@Home2, w którym każdy kto posiada komputer i dostęp do

The children in both of these age groups were able to correctly differentiate generic and non-generic properties 64% of the time (with 60% within the group of 5-year-olds and

(i) Copy the tree diagram and add the four missing probability values on the branches that refer to playing with a stick.. During a trip to the park, one of the dogs is chosen

If you convey a covered work, knowingly relying on a patent license, and the Corre- sponding Source of the work is not available for anyone to copy, free of charge and under the

The Hepburn system reflects their pronunciation, but does not convey any information about the original shape of the Japanese text, even if it has been written without

Foss Lviv 2011 193 business owners!) can quickly learn these tools and can benefit from them for their daily, non programming computer-related needs.. Promoting

* t, const double epsabs, const double epsrel, const size_t limit, gsl_integration_workspace * workspace, double * result, double * abserr) This function computes the integral of

The discussion is Sections 3.9 and 3.10 does prove, at least in the situations we are interested in, that, for a square-free Darboux polynomial at a Darboux point, there exists,