You are previewing The Linux Programming Interface.
O'Reilly logo
The Linux Programming Interface

Book Description

The Linux Programming Interface describes the Linux API (application programming interface)—the system calls, library functions, and other low-level interfaces that are used, directly or indirectly, by every program that runs on Linux.

Table of Contents

  1. Praise for The Linux Programming Interface
  2. Dedication
  3. Preface
    1.  
      1.  
        1. Subject
        2. Intended audience
        3. Linux and UNIX
        4. Usage and organization
        5. Example programs
        6. Exercises
        7. Standards and portability
        8. Linux kernel and C library versions
        9. Using the programming interface from other languages
        10. About the author
        11. Acknowledgements
        12. Permissions
        13. Web site and source code of example programs
        14. Feedback
  4. 1. History and Standards
    1. A Brief History of UNIX and C
      1.  
        1. UNIX First through Sixth editions
        2. The birth of BSD and System V
    2. A Brief History of Linux
      1. The GNU Project
      2. The Linux Kernel
        1. An aside: the BSDs
        2. Linux kernel version numbers
        3. Ports to other hardware architectures
        4. Linux distributions
    3. Standardization
      1. The C Programming Language
      2. The First POSIX Standards
        1. POSIX.1 and POSIX.2
        2. FIPS 151-1 and FIPS 151-2
      3. X/Open Company and The Open Group
      4. SUSv3 and POSIX.1-2001
        1. POSIX conformance, XSI conformance, and the XSI extension
        2. Unspecified and weakly specified
        3. LEGACY features
      5. SUSv4 and POSIX.1-2008
      6. UNIX Standards Timeline
      7. Implementation Standards
      8. Linux, Standards, and the Linux Standard Base
    4. Summary
      1.  
        1. Further information
  5. 2. Fundamental Concepts
    1. The Core Operating System: The Kernel
      1.  
        1. Tasks performed by the kernel
        2. Kernel mode and user mode
        3. Process versus kernel views of the system
        4. Further information
    2. The Shell
    3. Users and Groups
      1.  
        1. Users
        2. Groups
        3. Superuser
    4. Single Directory Hierarchy, Directories, Links, and Files
      1.  
        1. File types
        2. Directories and links
        3. Symbolic links
        4. Filenames
        5. Pathnames
        6. Current working directory
        7. File ownership and permissions
    5. File I/O Model
      1.  
        1. File descriptors
        2. The stdio library
    6. Programs
      1.  
        1. Filters
        2. Command-line arguments
    7. Processes
      1.  
        1. Process memory layout
        2. Process creation and program execution
        3. Process ID and parent process ID
        4. Process termination and termination status
        5. Process user and group identifiers (credentials)
        6. Privileged processes
        7. Capabilities
        8. The init process
        9. Daemon processes
        10. Environment list
        11. Resource limits
    8. Memory Mappings
    9. Static and Shared Libraries
      1.  
        1. Static libraries
        2. Shared libraries
    10. Interprocess Communication and Synchronization
    11. Signals
    12. Threads
    13. Process Groups and Shell Job Control
    14. Sessions, Controlling Terminals, and Controlling Processes
    15. Pseudoterminals
    16. Date and Time
    17. Client-Server Architecture
    18. Realtime
    19. The /proc File System
    20. Summary
  6. 3. System Programming Concepts
    1. System Calls
    2. Library Functions
    3. The Standard C Library; The GNU C Library (glibc)
      1.  
        1. Determining the version of glibc on the system
    4. Handling Errors from System Calls and Library Functions
      1.  
        1. Handling system call errors
        2. Handling errors from library functions
    5. Notes on the Example Programs in This Book
      1. Command-Line Options and Arguments
      2. Common Functions and Header Files
        1. Common header file
        2. Error-diagnostic functions
        3. Functions for parsing numeric command-line arguments
    6. Portability Issues
      1. Feature Test Macros
        1. _POSIX_C_SOURCE, _XOPEN_SOURCE, and POSIX.1/SUS
        2. Feature test macros in function prototypes and source code examples
      2. System Data Types
        1. Printing system data type values
      3. Miscellaneous Portability Issues
        1. Initializing and using structures
        2. Using macros that may not be present on all implementations
        3. Variation in required header files across implementations
    7. Summary
    8. Exercise
  7. 4. File I/O: The Universal I/O Model
    1. Overview
    2. Universality of I/O
    3. Opening a File: open()
      1.  
        1. File descriptor number returned by open()
      2. The open() flags Argument
      3. Errors from open()
      4. The creat() System Call
    4. Reading from a File: read()
    5. Writing to a File: write()
    6. Closing a File: close()
    7. Changing the File Offset: lseek()
      1.  
        1. File holes
        2. Example program
    8. Operations Outside the Universal I/O Model: ioctl()
    9. Summary
    10. Exercises
  8. 5. File I/O: Further Details
    1. Atomicity and Race Conditions
      1.  
        1. Creating a file exclusively
        2. Appending data to a file
    2. File Control Operations: fcntl()
    3. Open File Status Flags
    4. Relationship Between File Descriptors and Open Files
    5. Duplicating File Descriptors
    6. File I/O at a Specified Offset: pread() and pwrite()
    7. Scatter-Gather I/O: readv() and writev()
      1.  
        1. Scatter input
        2. Gather output
        3. Performing scatter-gather I/O at a specified offset
    8. Truncating a File: truncate() and ftruncate()
    9. Nonblocking I/O
    10. I/O on Large Files
      1.  
        1. The transitional LFS API
        2. The _FILE_OFFSET_BITS macro
        3. Passing off_t values to printf()
    11. The /dev/fd Directory
    12. Creating Temporary Files
    13. Summary
    14. Exercises
  9. 6. Processes
    1. Processes and Programs
    2. Process ID and Parent Process ID
    3. Memory Layout of a Process
    4. Virtual Memory Management
    5. The Stack and Stack Frames
    6. Command-Line Arguments (argc, argv)
    7. Environment List
      1. Accessing the environment from a program
        1. Modifying the environment
        2. Example program
    8. Performing a Nonlocal Goto: setjmp() and long jmp()
      1.  
        1. Example program
        2. Restrictions on the use of setjmp()
        3. Abusing longjmp()
        4. Problems with optimizing compilers
        5. Avoid setjmp() and long jmp() where possible
    9. Summary
      1.  
        1. Further information
    10. Exercises
  10. 7. Memory Allocation
    1. Allocating Memory on the Heap
      1. Adjusting the Program Break: brk() and sbrk()
      2. Allocating Memory on the Heap: malloc() and free()
        1. Example program
        2. To free() or not to free()?
      3. Implementation of malloc() and free()
        1. Tools and libraries for malloc debugging
        2. Controlling and monitoring the malloc package
      4. Other Methods of Allocating Memory on the Heap
        1. Allocating memory with calloc() and realloc()
        2. Allocating aligned memory: memalign() and posix_memalign()
    2. Allocating Memory on the Stack: alloca()
    3. Summary
    4. Exercises
  11. 8. Users and Groups
    1. The Password File: /etc/passwd
    2. The Shadow Password File: /etc/shadow
    3. The Group File: /etc/group
    4. Retrieving User and Group Information
      1.  
        1. Retrieving records from the password file
        2. Retrieving records from the group file
        3. Example program
        4. Scanning all records in the password and group files
        5. Retrieving records from the shadow password file
    5. Password Encryption and User Authentication
      1.  
        1. Example program
    6. Summary
    7. Exercises
  12. 9. Process Credentials
    1. Real User ID and Real Group ID
    2. Effective User ID and Effective Group ID
    3. Set-User-ID and Set-Group-ID Programs
    4. Saved Set-User-ID and Saved Set-Group-ID
    5. File-System User ID and File-System Group ID
    6. Supplementary Group IDs
    7. Retrieving and Modifying Process Credentials
      1. Retrieving and Modifying Real, Effective, and Saved Set IDs
        1. Retrieving real and effective IDs
        2. Modifying effective IDs
        3. Modifying real and effective IDs
        4. Retrieving real, effective, and saved set IDs
        5. Modifying real, effective, and saved set IDs
      2. Retrieving and Modifying File-System IDs
      3. Retrieving and Modifying Supplementary Group IDs
      4. Summary of Calls for Modifying Process Credentials
      5. Example: Displaying Process Credentials
    8. Summary
    9. Exercises
  13. 10. Time
    1. Calendar Time
    2. Time-Conversion Functions
      1. Converting time_t to Printable Form
      2. Converting Between time_t and Broken-Down Time
      3. Converting Between Broken-Down Time and Printable Form
        1. Converting from broken-down time to printable form
        2. Converting from printable form to broken-down time
    3. Timezones
      1.  
        1. Timezone definitions
        2. Specifying the timezone for a program
    4. Locales
      1.  
        1. Locale definitions
        2. Specifying the locale for a program
    5. Updating the System Clock
    6. The Software Clock (Jiffies)
    7. Process Time
      1.  
        1. Example program
    8. Summary
      1.  
        1. Further information
    9. Exercise
  14. 11. System Limits and Options
    1. System Limits
      1.  
        1. Runtime invariant values (possibly indeterminate)
        2. Pathname variable values
        3. Runtime increasable values
        4. Summary of selected SUSv3 limits
        5. Determining limits and options from the shell: getconf
    2. Retrieving System Limits (and Options) at Run Time
    3. Retrieving File-Related Limits (and Options) at Run Time
    4. Indeterminate Limits
    5. System Options
    6. Summary
      1.  
        1. Further information
    7. Exercises
  15. 12. System and Process Information
    1. The /proc File System
      1. Obtaining Information About a Process: /proc/PID
        1. The /proc/PID/fd directory
        2. Threads: the /proc/PID/task directory
      2. System Information Under /proc
      3. Accessing /proc Files
        1. Accessing files in /proc/PID
        2. Example program
    2. System Identification: uname()
    3. Summary
      1.  
        1. Further information
    4. Exercises
  16. 13. File I/O Buffering
    1. Kernel Buffering of File I/O: The Buffer Cache
      1.  
        1. Effect of buffer size on I/O system call performance
    2. Buffering in the stdio Library
      1.  
        1. Setting the buffering mode of a stdio stream
        2. Flushing a stdio buffer
    3. Controlling Kernel Buffering of File I/O
      1.  
        1. Synchronized I/O data integrity and synchronized I/O file integrity
        2. System calls for controlling kernel buffering of file I/O
        3. Making all writes synchronous: O_SYNC
        4. Performance impact of O_SYNC
        5. The O_DSYNC and O_RSYNC flags
    4. Summary of I/O Buffering
    5. Advising the Kernel About I/O Patterns
    6. Bypassing the Buffer Cache: Direct I/O
      1.  
        1. Alignment restrictions for direct I/O
        2. Example program
    7. Mixing Library Functions and System Calls for File I/O
    8. Summary
      1.  
        1. Further information
    9. Exercises
  17. 14. File Systems
    1. Device Special Files (Devices)
      1.  
        1. Device IDs
    2. Disks and Partitions
      1.  
        1. Disk drives
        2. Disk partitions
    3. File Systems
      1.  
        1. The ext2 file system
        2. File-system structure
    4. I-nodes
      1.  
        1. I-nodes and data block pointers in ext2
    5. The Virtual File System (VFS)
    6. Journaling File Systems
    7. Single Directory Hierarchy and Mount Points
    8. Mounting and Unmounting File Systems
      1. Mounting a File System: mount()
        1. Example program
      2. Unmounting a File System: umount() and umount2()
    9. Advanced Mount Features
      1. Mounting a File System at Multiple Mount Points
      2. Stacking Multiple Mounts on the Same Mount Point
      3. Mount Flags That Are Per-Mount Options
      4. Bind Mounts
      5. Recursive Bind Mounts
    10. A Virtual Memory File System: tmpfs
    11. Obtaining Information About a File System: statvfs()
    12. Summary
      1.  
        1. Further information
    13. Exercise
  18. 15. File Attributes
    1. Retrieving File Information: stat()
      1.  
        1. Device IDs and i-node number
        2. File ownership
        3. Link count
        4. File type and permissions
        5. File size, blocks allocated, and optimal I/O block size
        6. File timestamps
        7. Example program
    2. File Timestamps
      1.  
        1. Nanosecond timestamps
      2. Changing File Timestamps with utime() and utimes()
      3. Changing File Timestamps with utimensat() and futimens()
    3. File Ownership
      1. Ownership of New Files
      2. Changing File Ownership: chown(), fchown(), and lchown()
    4. File Permissions
      1. Permissions on Regular Files
      2. Permissions on Directories
      3. Permission-Checking Algorithm
        1. Permission checking for privileged processes
      4. Checking File Accessibility: access()
      5. Set-User-ID, Set-Group-ID, and Sticky Bits
      6. The Process File Mode Creation Mask: umask()
      7. Changing File Permissions: chmod() and fchmod()
    5. I-node Flags (ext2 Extended File Attributes)
    6. Summary
    7. Exercises
  19. 16. Extended Attributes
    1. Overview
      1.  
        1. EA namespaces
        2. Creating and viewing EAs from the shell
    2. Extended Attribute Implementation Details
      1.  
        1. Restrictions on user extended attributes
        2. Implementation limits
    3. System Calls for Manipulating Extended Attributes
      1.  
        1. Creating and modifying EAs
        2. Retrieving the value of an EA
        3. Removing an EA
        4. Retrieving the names of all EAs associated with a file
        5. Example program
    4. Summary
    5. Exercise
  20. 17. Access Control Lists
    1. Overview
      1.  
        1. ACL entries
        2. Minimal and extended ACLs
    2. ACL Permission-Checking Algorithm
    3. Long and Short Text Forms for ACLs
    4. The ACL_MASK Entry and the ACL Group Class
    5. The getfacl and setfacl Commands
    6. Default ACLs and File Creation
    7. ACL Implementation Limits
    8. The ACL API
      1.  
        1. Overview
        2. Fetching a file’s ACL into memory
        3. Retrieving entries from an in-memory ACL
        4. Retrieving and modifying attributes in an ACL entry
        5. Creating and deleting ACL entries
        6. Updating a file’s ACL
        7. Converting an ACL between in-memory and text form
        8. Other functions in the ACL API
        9. Example program
    9. Summary
      1.  
        1. Further information
    10. Exercise
  21. 18. Directories and Links
    1. Directories and (Hard) Links
    2. Symbolic (Soft) Links
      1.  
        1. Interpretation of symbolic links by system calls
        2. File permissions and ownership for symbolic links
    3. Creating and Removing (Hard) Links: link() and unlink()
      1.  
        1. An open file is deleted only when all file descriptors are closed
    4. Changing the Name of a File: rename()
    5. Working with Symbolic Links: symlink() and readlink()
    6. Creating and Removing Directories: mkdir() and rmdir()
    7. Removing a File or Directory: remove()
    8. Reading Directories: opendir() and readdir()
      1.  
        1. Directory streams and file descriptors
        2. Example program
        3. The readdir_r() function
    9. File Tree Walking: nftw()
      1.  
        1. Example program
        2. The nftw() FTW_ACTIONRETVAL flag
    10. The Current Working Directory of a Process
      1.  
        1. Retrieving the current working directory
        2. Changing the current working directory
    11. Operating Relative to a Directory File Descriptor
    12. Changing the Root Directory of a Process: chroot()
    13. Resolving a Pathname: realpath()
    14. Parsing Pathname Strings: dirname() and basename()
    15. Summary
    16. Exercises
  22. 19. Monitoring File Events
    1. Overview
    2. The inotify API
    3. inotify Events
    4. Reading inotify Events
      1.  
        1. Example program
    5. Queue Limits and /proc Files
    6. An Older System for Monitoring File Events: dnotify
    7. Summary
    8. Exercise
  23. 20. Signals: Fundamental Concepts
    1. Concepts and Overview
    2. Signal Types and Default Actions
    3. Changing Signal Dispositions: signal()
    4. Introduction to Signal Handlers
    5. Sending Signals: kill()
    6. Checking for the Existence of a Process
    7. Other Ways of Sending Signals: raise() and killpg()
    8. Displaying Signal Descriptions
    9. Signal Sets
      1.  
        1. Example program
    10. The Signal Mask (Blocking Signal Delivery)
    11. Pending Signals
    12. Signals Are Not Queued
    13. Changing Signal Dispositions: sigaction()
    14. Waiting for a Signal: pause()
    15. Summary
      1.  
        1. Further information
    16. Exercises
  24. 21. Signals: Signal Handlers
    1. Designing Signal Handlers
      1. Signals Are Not Queued (Revisited)
      2. Reentrant and Async-Signal-Safe Functions
        1. Reentrant and nonreentrant functions
        2. Example program
        3. Standard async-signal-safe functions
        4. Use of errno inside signal handlers
        5. Use of unsafe functions in example programs in this book
      3. Global Variables and the sig_atomic_t Data Type
    2. Other Methods of Terminating a Signal Handler
      1. Performing a Nonlocal Goto from a Signal Handler
        1. Example program
      2. Terminating a Process Abnormally: abort()
    3. Handling a Signal on an Alternate Stack: sigaltstack()
    4. The SA_SIGINFO Flag
      1.  
        1. The siginfo_t structure
        2. The ucontext argument
    5. Interruption and Restarting of System Calls
      1.  
        1. System calls (and library functions) for which SA_RESTART is effective
        2. Modifying the SA_RESTART flag for a signal
        3. Unhandled stop signals can generate EINTR for some Linux system calls
    6. Summary
      1.  
        1. Further information
    7. Exercise
  25. 22. Signals: Advanced Features
    1. Core Dump Files
      1.  
        1. Circumstances in which core dump files are not produced
        2. Naming the core dump file: /proc/sys/kernel/core_pattern
    2. Special Cases for Delivery, Disposition, and Handling
      1.  
        1. SIGKILL and SIGSTOP
        2. SIGCONT and stop signals
        3. Don’t change the disposition of ignored terminal-generated signals
    3. Interruptible and Uninterruptible Process Sleep States
    4. Hardware-Generated Signals
    5. Synchronous and Asynchronous Signal Generation
    6. Timing and Order of Signal Delivery
      1.  
        1. When is a signal delivered?
        2. Order of delivery of multiple unblocked signals
    7. Implementation and Portability of signal()
      1.  
        1. Some glibc details
        2. sigaction() is the preferred API for establishing a signal handler
    8. Realtime Signals
      1.  
        1. Limits on the number of queued realtime signals
        2. Using realtime signals
      2. Sending Realtime Signals
      3. Handling Realtime Signals
    9. Waiting for a Signal Using a Mask: sigsuspend()
      1.  
        1. Example program
    10. Synchronously Waiting for a Signal
    11. Fetching Signals via a File Descriptor
    12. Interprocess Communication with Signals
    13. Earlier Signal APIs (System V and BSD)
      1.  
        1. The System V signal API
        2. The BSD signal API
    14. Summary
      1.  
        1. Further information
    15. Exercises
  26. 23. Timers and Sleeping
    1. Interval Timers
      1.  
        1. Example program
        2. A simpler timer interface: alarm()
        3. Interactions between setitimer() and alarm()
    2. Scheduling and Accuracy of Timers
      1.  
        1. High-resolution timers
    3. Setting Timeouts on Blocking Operations
    4. Suspending Execution for a Fixed Interval (Sleeping)
      1. Low-Resolution Sleeping: sleep()
      2. High-Resolution Sleeping: nanosleep()
    5. POSIX Clocks
      1. Retrieving the Value of a Clock: clock_gettime()
      2. Setting the Value of a Clock: clock_settime()
      3. Obtaining the Clock ID of a Specific Process or Thread
      4. Improved High-Resolution Sleeping: clock_nanosleep()
    6. POSIX Interval Timers
      1. Creating a Timer: timer_create()
      2. Arming and Disarming a Timer: timer_settime()
      3. Retrieving the Current Value of a Timer: timer_gettime()
      4. Deleting a Timer: timer_delete()
      5. Notification via a Signal
      6. Timer Overruns
      7. Notification via a Thread
    7. Timers That Notify via File Descriptors: The timerfd API
      1.  
        1. Interactions of timerfd with fork() and exec()
        2. Reading from the timerfd file descriptor
        3. Example program
    8. Summary
      1.  
        1. Further information
    9. Exercises
  27. 24. Process Creation
    1. Overview of fork(), exit(), wait(), and execve()
    2. Creating a New Process: fork()
      1. File Sharing Between Parent and Child
      2. Memory Semantics of fork()
        1. Controlling a process’s memory footprint
    3. The vfork() System Call
    4. Race Conditions After fork()
    5. Avoiding Race Conditions by Synchronizing with Signals
    6. Summary
      1.  
        1. Further information
    7. Exercises
  28. 25. Process Termination
    1. Terminating a Process: _exit() and exit()
    2. Details of Process Termination
    3. Exit Handlers
      1.  
        1. Registering exit handlers
        2. Example program
    4. Interactions Between fork(), stdio Buffers, and _exit()
    5. Summary
      1.  
        1. Further information
    6. Exercise
  29. 26. Monitoring Child Processes
    1. Waiting on a Child Process
      1. The wait() System Call
      2. The waitpid() System Call
      3. The Wait Status Value
        1. Example program
      4. Process Termination from a Signal Handler
      5. The waitid() System Call
      6. The wait3() and wait4() System Calls
    2. Orphans and Zombies
    3. The SIGCHLD Signal
      1. Establishing a Handler for SIGCHLD
        1. Design issues for SIGCHLD handlers
        2. Example program
      2. Delivery of SIGCHLD for Stopped Children
      3. Ignoring Dead Child Processes
        1. Deviations from SUSv3 in older Linux kernels
        2. The sigaction()SA_NOCLDWAIT flag
        3. The System V SIGCLD signal
    4. Summary
      1.  
        1. Further information
    5. Exercises
  30. 27. Program Execution
    1. Executing a New Program: execve()
      1.  
        1. Example program
    2. The exec() Library Functions
      1. The PATH Environment Variable
      2. Specifying Program Arguments as a List
      3. Passing the Caller’s Environment to the New Program
      4. Executing a File Referred to by a Descriptor: fexecve()
    3. Interpreter Scripts
      1.  
        1. Execution of interpreter scripts
        2. Using the script optional-arg
        3. Executing scripts with execlp() and execvp()
    4. File Descriptors and exec()
      1.  
        1. The close-on-exec flag (FD_CLOEXEC)
    5. Signals and exec()
    6. Executing a Shell Command: system()
      1.  
        1. Example program
        2. Avoid using system() in set-user-ID and set-group-ID programs
    7. Implementing system()
      1.  
        1. A simple implementation of system()
        2. Treating signals correctly inside system()
        3. An improved system() implementation
        4. Further details on system()
    8. Summary
      1.  
        1. Further information
    9. Exercises
  31. 28. Process Creation and Program Execution in More Detail
    1. Process Accounting
      1.  
        1. Enabling and disabling process accounting
        2. Process accounting records
        3. Example program
        4. Process accounting Version 3 file format
    2. The clone() System Call
      1.  
        1. Example program
      2. The clone() flags Argument
        1. Sharing file descriptor tables: CLONE_FILES
        2. Sharing file system-related information: CLONE_FS
        3. Sharing signal dispositions: CLONE_SIGHAND
        4. Sharing the parent’s virtual memory: CLONE_VM
        5. Thread groups: CLONE_THREAD
        6. Threading library support: CLONE_PARENT_SETTID, CLONE_CHILD_SETTID, and CLONE_CHILD_CLEARTID
        7. Thread-local storage: CLONE_SETTLS
        8. Sharing System V semaphore undo values: CLONE_SYSVSEM
        9. Per-process mount namespaces: CLONE_NEWNS
        10. Making the child’s parent the same as the caller’s: CLONE_PARENT
        11. Making the child’s PID the same as the parent’s PID: CLONE_PID (obsolete)
        12. Process tracing: CLONE_PTRACE and CLONE_UNTRACED
        13. Suspending the parent until the child exits or execs: CLONE_VFORK
        14. New clone() flags to support containers
        15. Use of clone() flags
      3. Extensions to waitpid() for Cloned Children
    3. Speed of Process Creation
    4. Effect of exec() and fork() on Process Attributes
    5. Summary
      1.  
        1. Further information
    6. Exercise
  32. 29. Threads: Introduction
    1. Overview
    2. Background Details of the Pthreads API
      1.  
        1. Pthreads data types
        2. Threads and errno
        3. Return value from Pthreads functions
        4. Compiling Pthreads programs
    3. Thread Creation
    4. Thread Termination
    5. Thread IDs
    6. Joining with a Terminated Thread
      1.  
        1. Example program
    7. Detaching a Thread
    8. Thread Attributes
    9. Threads Versus Processes
    10. Summary
      1.  
        1. Further information
    11. Exercises
  33. 30. Threads: Thread Synchronization
    1. Protecting Accesses to Shared Variables: Mutexes
      1. Statically Allocated Mutexes
      2. Locking and Unlocking a Mutex
        1. Example program
        2. pthread_mutex_trylock() and pthread_mutex_timedlock()
      3. Performance of Mutexes
      4. Mutex Deadlocks
      5. Dynamically Initializing a Mutex
      6. Mutex Attributes
      7. Mutex Types
    2. Signaling Changes of State: Condition Variables
      1. Statically Allocated Condition Variables
      2. Signaling and Waiting on Condition Variables
        1. Using a condition variable in the producer-consumer example
      3. Testing a Condition Variable’s Predicate
      4. Example Program: Joining Any Terminated Thread
      5. Dynamically Allocated Condition Variables
    3. Summary
      1.  
        1. Further information
    4. Exercises
  34. 31. Threads: Thread Safety and Per-Thread Storage
    1. Thread Safety (and Reentrancy Revisited)
      1.  
        1. Non-thread-safe functions
        2. Reentrant and nonreentrant functions
    2. One-Time Initialization
    3. Thread-Specific Data
      1. Thread-Specific Data from the Library Function’s Perspective
      2. Overview of the Thread-Specific Data API
      3. Details of the Thread-Specific Data API
      4. Employing the Thread-Specific Data API
      5. Thread-Specific Data Implementation Limits
    4. Thread-Local Storage
    5. Summary
      1.  
        1. Further information
    6. Exercises
  35. 32. Threads: Thread Cancellation
    1. Canceling a Thread
    2. Cancellation State and Type
    3. Cancellation Points
      1.  
        1. Example program
    4. Testing for Thread Cancellation
    5. Cleanup Handlers
      1.  
        1. Example program
    6. Asynchronous Cancelability
    7. Summary
      1.  
        1. Further information
  36. 33. Threads: Further Details
    1. Thread Stacks
    2. Threads and Signals
      1. How the UNIX Signal Model Maps to Threads
      2. Manipulating the Thread Signal Mask
      3. Sending a Signal to a Thread
      4. Dealing with Asynchronous Signals Sanely
    3. Threads and Process Control
      1.  
        1. Threads and exec()
        2. Threads and fork()
        3. Threads and exit()
    4. Thread Implementation Models
      1.  
        1. Many-to-one (M:1) implementations (user-level threads)
        2. One-to-one (1:1) implementations (kernel-level threads)
        3. Many-to-many (M:N) implementations (two-level model)
    5. Linux Implementations of POSIX Threads
      1. LinuxThreads
        1. LinuxThreads deviations from specified behavior
        2. Other problems with LinuxThreads
      2. NPTL
        1. NPTL standards conformance
      3. Which Threading Implementation?
        1. Discovering the threading implementation
        2. Selecting the threading implementation used by a program
    6. Advanced Features of the Pthreads API
    7. Summary
      1.  
        1. Further information
    8. Exercises
  37. 34. Process Groups, Sessions, and Job Control
    1. Overview
    2. Process Groups
      1.  
        1. Using setpgid() in a job-control shell
        2. Other (obsolete) interfaces for retrieving and modifying process group IDs
    3. Sessions
    4. Controlling Terminals and Controlling Processes
      1.  
        1. Removing a process’s association with the controlling terminal
        2. Establishing a controlling terminal on BSD
        3. Obtaining a pathname that refers to the controlling terminal: ctermid()
    5. Foreground and Background Process Groups
    6. The SIGHUP Signal
      1. Handling of SIGHUP by the Shell
      2. SIGHUP and Termination of the Controlling Process
    7. Job Control
      1. Using Job Control Within the Shell
      2. Implementing Job Control
        1. The SIGTTIN and SIGTTOU signals
        2. Example program: demonstrating the operation of job control
      3. Handling Job-Control Signals
        1. Example program
        2. Dealing with ignored job-control and terminal-generated signals
      4. Orphaned Process Groups (and SIGHUP Revisited)
        1. Example program
        2. Orphaned process groups and the SIGTSTP, SIGTTIN, and SIGTTOU signals
    8. Summary
      1.  
        1. Further information
    9. Exercises
  38. 35. Process Priorities and Scheduling
    1. Process Priorities (Nice Values)
      1.  
        1. Effect of the nice value
        2. Retrieving and modifying priorities
    2. Overview of Realtime Process Scheduling
      1.  
        1. POSIX realtime versus hard realtime
      2. The SCHED_RR Policy
      3. The SCHED_FIFO Policy
      4. The SCHED_BATCH and SCHED_IDLE Policies
    3. Realtime Process Scheduling API
      1. Realtime Priority Ranges
      2. Modifying and Retrieving Policies and Priorities
        1. Modifying scheduling policies and priorities
        2. Privileges and resource limits affecting changes to scheduling parameters
        3. Retrieving scheduling policies and priorities
        4. Preventing realtime processes from locking up the system
        5. Preventing child processes from inheriting privileged scheduling policies
      3. Relinquishing the CPU
      4. The SCHED_RR Time Slice
    4. CPU Affinity
    5. Summary
      1.  
        1. Further information
    6. Exercises
  39. 36. Process Resources
    1. Process Resource Usage
    2. Process Resource Limits
      1.  
        1. Example program
        2. Unrepresentable limit values
    3. Details of Specific Resource Limits
      1.  
        1. RLIMIT_AS
        2. RLIMIT_CORE
        3. RLIMIT_CPU
        4. RLIMIT_DATA
        5. RLIMIT_FSIZE
        6. RLIMIT_MEMLOCK
        7. RLIMIT_MSGQUEUE
        8. RLIMIT_NICE
        9. RLIMIT_NOFILE
        10. RLIMIT_NPROC
        11. RLIMIT_RSS
        12. RLIMIT_RTPRIO
        13. RLIMIT_RTTIME
        14. RLIMIT_SIGPENDING
        15. RLIMIT_STACK
    4. Summary
    5. Exercises
  40. 37. Daemons
    1. Overview
    2. Creating a Daemon
    3. Guidelines for Writing Daemons
    4. Using SIGHUP to Reinitialize a Daemon
    5. Logging Messages and Errors Using syslog
      1.  
        1. Overview
        2. The syslog API
        3. Establishing a connection to the system log
        4. Logging a message
        5. Closing the log
        6. Filtering log messages
        7. The /etc/syslog.conf File
    6. Summary
      1.  
        1. Further information
    7. Exercise
  41. 38. Writing Secure Privileged Programs
    1. Is a Set-User-ID or Set-Group-ID Program Required?
    2. Operate with Least Privilege
      1.  
        1. Hold privileges only while they are required
        2. Drop privileges permanently when they will never again be required
        3. General points on changing process credentials
    3. Be Careful When Executing a Program
      1.  
        1. Drop privileges permanently before execing another program
        2. Avoid executing a shell (or other interpreter) with privileges
        3. Close all unnecessary file descriptors before an exec()
    4. Avoid Exposing Sensitive Information
    5. Confine the Process
      1.  
        1. Consider using capabilities
        2. Consider using a chroot jail
    6. Beware of Signals and Race Conditions
    7. Pitfalls When Performing File Operations and File I/O
    8. Don’t Trust Inputs or the Environment
      1.  
        1. Don’t trust the environment list
        2. Handle untrusted user inputs defensively
        3. Avoid unreliable assumptions about the process’s run-time environment
    9. Beware of Buffer Overruns
    10. Beware of Denial-of-Service Attacks
    11. Check Return Statuses and Fail Safely
    12. Summary
      1.  
        1. Further information
    13. Exercises
  42. 39. Capabilities
    1. Rationale for Capabilities
    2. The Linux Capabilities
    3. Process and File Capabilities
      1. Process Capabilities
      2. File Capabilities
      3. Purpose of the Process Permitted and Effective Capability Sets
      4. Purpose of the File Permitted and Effective Capability Sets
      5. Purpose of the Process and File Inheritable Sets
      6. Assigning and Viewing File Capabilities from the Shell
    4. The Modern Capabilities Implementation
    5. Transformation of Process Capabilities During exec()
      1. Capability Bounding Set
      2. Preserving root Semantics
    6. Effect on Process Capabilities of Changing User IDs
    7. Changing Process Capabilities Programmatically
      1.  
        1. The libcap API
        2. Example program
    8. Creating Capabilities-Only Environments
      1.  
        1. SECBIT_KEEP_CAPS and the prctl() PR_SET_KEEPCAPS operation
    9. Discovering the Capabilities Required by a Program
    10. Older Kernels and Systems Without File Capabilities
      1.  
        1. The CAP_SETPCAP capability
        2. The capability bounding set
        3. Using capabilities within a program on a system without file capabilities
    11. Summary
    12. Exercise
  43. 40. Login Accounting
    1. Overview of the utmp and wtmp Files
    2. The utmpx API
    3. The utmpx Structure
    4. Retrieving Information from the utmp and wtmp Files
      1.  
        1. Example program
    5. Retrieving the Login Name: getlogin()
    6. Updating the utmp and wtmp Files for a Login Session
      1.  
        1. Example program
    7. The lastlog File
    8. Summary
      1.  
        1. Further information
    9. Exercises
  44. 41. Fundamentals of Shared Libraries
    1. Object Libraries
      1.  
        1. An aside: including debugger information when compiling a program
    2. Static Libraries
      1.  
        1. Creating and maintaining a static library
        2. Using a static library
    3. Overview of Shared Libraries
    4. Creating and Using Shared Libraries—A First Pass
      1. Creating a Shared Library
      2. Position-Independent Code
      3. Using a Shared Library
        1. The LD_LIBRARY_PATH environment variable
        2. Static linking and dynamic linking contrasted
      4. The Shared Library Soname
    5. Useful Tools for Working with Shared Libraries
      1.  
        1. The ldd command
        2. The objdump and readelf commands
        3. The nm command
    6. Shared Library Versions and Naming Conventions
      1.  
        1. Real names, sonames, and linker names
        2. Creating a shared library using standard conventions
    7. Installing Shared Libraries
      1.  
        1. ldconfig
    8. Compatible Versus Incompatible Libraries
    9. Upgrading Shared Libraries
    10. Specifying Library Search Directories in an Object File
      1.  
        1. Using the -rpath linker option when building a shared library
        2. The ELF DT_RPATH and DT_RUNPATH entries
        3. Using $ORIGIN in rpath
    11. Finding Shared Libraries at Run Time
    12. Run-Time Symbol Resolution
    13. Using a Static Library Instead of a Shared Library
    14. Summary
      1.  
        1. Further information
    15. Exercise
  45. 42. Advanced Features of Shared Libraries
    1. Dynamically Loaded Libraries
      1. Opening a Shared Library: dlopen()
      2. Diagnosing Errors: dlerror()
      3. Obtaining the Address of a Symbol: dlsym()
        1. Using library pseudohandles with dlsym()
        2. Example program
      4. Closing a Shared Library: dlclose()
      5. Obtaining Information About Loaded Symbols: dladdr()
      6. Accessing Symbols in the Main Program
    2. Controlling Symbol Visibility
    3. Linker Version Scripts
      1. Controlling Symbol Visibility with Version Scripts
      2. Symbol Versioning
    4. Initialization and Finalization Functions
      1.  
        1. The _init() and _fini() functions
    5. Preloading Shared Libraries
    6. Monitoring the Dynamic Linker: LD_DEBUG
    7. Summary
      1.  
        1. Further information
    8. Exercises
  46. 43. Interprocess Communication Overview
    1. A Taxonomy of IPC Facilities
    2. Communication Facilities
      1.  
        1. Data transfer
        2. Shared memory
    3. Synchronization Facilities
    4. Comparing IPC Facilities
      1.  
        1. IPC object identification and handles for open objects
        2. Functionality
        3. Network communication
        4. Portability
        5. System V IPC design issues
        6. Accessibility
        7. Persistence
        8. Performance
    5. Summary
    6. Exercises
  47. 44. Pipes and FIFOs
    1. Overview
      1.  
        1. A pipe is a byte stream
        2. Reading from a pipe
        3. Pipes are unidirectional
        4. Writes of up to PIPE_BUF bytes are guaranteed to be atomic
        5. Pipes have a limited capacity
    2. Creating and Using Pipes
      1.  
        1. Pipes allow communication between related processes
        2. Closing unused pipe file descriptors
        3. Example program
    3. Pipes as a Method of Process Synchronization
    4. Using Pipes to Connect Filters
      1.  
        1. Example program
    5. Talking to a Shell Command via a Pipe: popen()
      1.  
        1. Example program
    6. Pipes and stdio Buffering
    7. FIFOs
      1.  
        1. Using FIFOs and tee(1) to create a dual pipeline
    8. A Client-Server Application Using FIFOs
      1.  
        1. Application overview
        2. Server program
        3. Client program
    9. Nonblocking I/O
      1.  
        1. Nonblocking read() and write()
    10. Semantics of read() and write() on Pipes and FIFOs
    11. Summary
      1.  
        1. Further information
    12. Exercises
  48. 45. Introduction to System V IPC
    1. API Overview
      1.  
        1. Creating and opening a System V IPC object
        2. IPC object deletion and object persistence
    2. IPC Keys
      1.  
        1. Generating a unique key with IPC_PRIVATE
        2. Generating a unique key with ftok()
    3. Associated Data Structure and Object Permissions
    4. IPC Identifiers and Client-Server Applications
    5. Algorithm Employed by System V IPC get Calls
    6. The ipcs and ipcrm Commands
    7. Obtaining a List of All IPC Objects
    8. IPC Limits
    9. Summary
      1.  
        1. Further information
    10. Exercises
  49. 46. System V Message Queues
    1. Creating or Opening a Message Queue
    2. Exchanging Messages
      1. Sending Messages
      2. Receiving Messages
        1. Example program
    3. Message Queue Control Operations
    4. Message Queue Associated Data Structure
    5. Message Queue Limits
    6. Displaying All Message Queues on the System
    7. Client-Server Programming with Message Queues
      1.  
        1. Using a single message queue for server and clients
        2. Using one message queue per client
    8. A File-Server Application Using Message Queues
      1.  
        1. Common header file
        2. Server program
        3. Client program
    9. Disadvantages of System V Message Queues
    10. Summary
    11. Exercises
  50. 47. System V Semaphores
    1. Overview
    2. Creating or Opening a Semaphore Set
    3. Semaphore Control Operations
      1.  
        1. Generic control operations
        2. Retrieving and initializing semaphore values
        3. Retrieving per-semaphore information
    4. Semaphore Associated Data Structure
      1.  
        1. Monitoring a semaphore set
        2. Initializing all semaphores in a set
    5. Semaphore Initialization
    6. Semaphore Operations
      1.  
        1. Example program
    7. Handling of Multiple Blocked Semaphore Operations
    8. Semaphore Undo Values
      1.  
        1. Example of the effect of SEM_UNDO
        2. Limitations of SEM_UNDO
    9. Implementing a Binary Semaphores Protocol
    10. Semaphore Limits
    11. Disadvantages of System V Semaphores
    12. Summary
      1.  
        1. Further information
    13. Exercises
  51. 48. System V Shared Memory
    1. Overview
    2. Creating or Opening a Shared Memory Segment
    3. Using Shared Memory
    4. Example: Transferring Data via Shared Memory
    5. Location of Shared Memory in Virtual Memory
    6. Storing Pointers in Shared Memory
    7. Shared Memory Control Operations
      1.  
        1. Generic control operations
        2. Locking and unlocking shared memory
    8. Shared Memory Associated Data Structure
    9. Shared Memory Limits
    10. Summary
      1.  
        1. Further information
    11. Exercises
  52. 49. Memory Mappings
    1. Overview
    2. Creating a Mapping: mmap()
      1.  
        1. Memory protection in more detail
        2. Alignment restrictions specified in standards for offset and addr
        3. Example program
    3. Unmapping a Mapped Region: munmap()
    4. File Mappings
      1. Private File Mappings
      2. Shared File Mappings
        1. Memory-mapped I/O
        2. IPC using a shared file mapping
        3. Example program
      3. Boundary Cases
      4. Memory Protection and File Access Mode Interactions
    5. Synchronizing a Mapped Region: msync()
    6. Additional mmap() Flags
    7. Anonymous Mappings
      1.  
        1. MAP_ANONYMOUS and /dev/zero
        2. MAP_PRIVATE anonymous mappings
        3. MAP_SHARED anonymous mappings
        4. Example program
    8. Remapping a Mapped Region: mremap()
    9. MAP_NORESERVE and Swap Space Overcommitting
      1.  
        1. The OOM killer
    10. The MAP_FIXED Flag
    11. Nonlinear Mappings: remap_file_pages()
    12. Summary
      1.  
        1. Further information
    13. Exercises
  53. 50. Virtual Memory Operations
    1. Changing Memory Protection: mprotect()
    2. Memory Locking: mlock() and mlockall()
      1.  
        1. The RLIMIT_MEMLOCK resource limit
        2. Locking and unlocking memory regions
        3. Details of the semantics of memory locking
        4. Locking and unlocking all of a process’s memory
    3. Determining Memory Residence: mincore()
    4. Advising Future Memory Usage Patterns: madvise()
    5. Summary
    6. Exercises
  54. 51. Introduction to POSIX IPC
    1. API Overview
      1.  
        1. IPC object names
        2. Creating or opening an IPC object
        3. Closing an IPC object
        4. IPC object permissions
        5. IPC object deletion and object persistence
        6. Listing and removing POSIX IPC objects via the command line
        7. Compiling programs that use POSIX IPC on Linux
    2. Comparison of System V IPC and POSIX IPC
    3. Summary
  55. 52. POSIX Message Queues
    1. Overview
    2. Opening, Closing, and Unlinking a Message Queue
      1.  
        1. Opening a message queue
        2. Effect of fork(), exec(), and process termination on message queue descriptors
        3. Closing a message queue
        4. Removing a message queue
    3. Relationship Between Descriptors and Message Queues
    4. Message Queue Attributes
      1.  
        1. Setting message queue attributes during queue creation
        2. Retrieving message queue attributes
        3. Modifying message queue attributes
    5. Exchanging Messages
      1. Sending Messages
      2. Receiving Messages
      3. Sending and Receiving Messages with a Timeout
    6. Message Notification
      1. Receiving Notification via a Signal
      2. Receiving Notification via a Thread
    7. Linux-Specific Features
      1.  
        1. Displaying and deleting message queue objects via the command line
        2. Obtaining information about a message queue
        3. Using message queues with alternative I/O models
    8. Message Queue Limits
    9. Comparison of POSIX and System V Message Queues
    10. Summary
      1.  
        1. Further information
    11. Exercises
  56. 53. POSIX Semaphores
    1. Overview
    2. Named Semaphores
      1. Opening a Named Semaphore
        1. Example program
      2. Closing a Semaphore
      3. Removing a Named Semaphore
    3. Semaphore Operations
      1. Waiting on a Semaphore
      2. Posting a Semaphore
      3. Retrieving the Current Value of a Semaphore
        1. Example
    4. Unnamed Semaphores
      1.  
        1. Unnamed versus named semaphores
      2. Initializing an Unnamed Semaphore
        1. Example program
      3. Destroying an Unnamed Semaphore
    5. Comparisons with Other Synchronization Techniques
      1.  
        1. POSIX semaphores versus System V semaphores
        2. POSIX semaphores versus Pthreads mutexes
    6. Semaphore Limits
    7. Summary
      1.  
        1. Further information
    8. Exercises
  57. 54. POSIX Shared Memory
    1. Overview
    2. Creating Shared Memory Objects
      1.  
        1. Example program
    3. Using Shared Memory Objects
    4. Removing Shared Memory Objects
    5. Comparisons Between Shared Memory APIs
    6. Summary
    7. Exercise
  58. 55. File Locking
    1. Overview
      1.  
        1. Mixing locking and stdio functions
        2. Advisory and mandatory locking
    2. File Locking with flock()
      1. Semantics of Lock Inheritance and Release
      2. Limitations of flock()
    3. Record Locking with fcntl()
      1.  
        1. The flock structure
        2. The cmd argument
        3. Details of lock acquisition and release
      2. Deadlock
      3. Example: An Interactive Locking Program
      4. Example: A Library of Locking Functions
      5. Lock Limits and Performance
      6. Semantics of Lock Inheritance and Release
      7. Lock Starvation and Priority of Queued Lock Requests
    4. Mandatory Locking
      1.  
        1. Effect of mandatory locking on file I/O operations
        2. Mandatory locking caveats
    5. The /proc/locks File
    6. Running Just One Instance of a Program
    7. Older Locking Techniques
      1.  
        1. open(file, O_CREAT | O_EXCL,...) plus unlink(file)
        2. link(file, lockfile) plus unlink(lockfile)
        3. open(file, O_CREAT | O_TRUNC | O_WRONLY, 0) plus unlink(file)
    8. Summary
      1.  
        1. Further information
    9. Exercises
  59. 56. Sockets: Introduction
    1. Overview
      1.  
        1. Communication domains
        2. Socket types
        3. Socket system calls
    2. Creating a Socket: socket()
    3. Binding a Socket to an Address: bind()
    4. Generic Socket Address Structures: struct sockaddr
    5. Stream Sockets
      1.  
        1. Active and passive sockets
      2. Listening for Incoming Connections: listen()
      3. Accepting a Connection: accept()
      4. Connecting to a Peer Socket: connect()
      5. I/O on Stream Sockets
      6. Connection Termination: close()
    6. Datagram Sockets
      1. Exchanging Datagrams: recvfrom() and sendto()
      2. Using connect() with Datagram Sockets
    7. Summary
      1.  
        1. Further information
  60. 57. Sockets: UNIX Domain
    1. UNIX Domain Socket Addresses: struct sockaddr_un
    2. Stream Sockets in the UNIX Domain
    3. Datagram Sockets in the UNIX Domain
      1.  
        1. Maximum datagram size for UNIX domain datagram sockets
        2. Example program
    4. UNIX Domain Socket Permissions
    5. Creating a Connected Socket Pair: socketpair()
    6. The Linux Abstract Socket Namespace
    7. Summary
      1.  
        1. Further information
    8. Exercises
  61. 58. Sockets: Fundamentals of TCP/IP Networks
    1. Internets
    2. Networking Protocols and Layers
      1.  
        1. Encapsulation
    3. The Data-Link Layer
    4. The Network Layer: IP
      1.  
        1. IP transmits datagrams
        2. IP is connectionless and unreliable
        3. IP may fragment datagrams
    5. IP Addresses
      1.  
        1. IPv4 addresses
        2. IPv6 addresses
    6. The Transport Layer
      1. Port Numbers
        1. Well-known, registered, and privileged ports
        2. Ephemeral ports
      2. User Datagram Protocol (UDP)
        1. Selecting a UDP datagram size to avoid IP fragmentation
      3. Transmission Control Protocol (TCP)
        1. Connection establishment
        2. Packaging of data in segments
        3. Acknowledgements, retransmissions, and timeouts
        4. Sequencing
        5. Flow control
        6. Congestion control: slow-start and congestion-avoidance algorithms
    7. Requests for Comments (RFCs)
    8. Summary
      1.  
        1. Further information
  62. 59. Sockets: Internet Domains
    1. Internet Domain Sockets
    2. Network Byte Order
    3. Data Representation
    4. Internet Socket Addresses
      1.  
        1. IPv4 socket addresses: struct sockaddr_in
        2. IPv6 socket addresses: struct sockaddr_in6
        3. The sockaddr_storage structure
    5. Overview of Host and Service Conversion Functions
      1.  
        1. Converting IPv4 addresses between binary and human-readable forms
        2. Converting IPv4 and IPv6 addresses between binary and human-readable forms
        3. Converting host and service names to and from binary form (obsolete)
        4. Converting host and service names to and from binary form (modern)
    6. The inet_pton() and inet_ntop() Functions
    7. Client-Server Example (Datagram Sockets)
    8. Domain Name System (DNS)
      1.  
        1. Recursive and iterative resolution requests
        2. Top-level domains
    9. The /etc/services File
    10. Protocol-Independent Host and Service Conversion
      1. The getaddrinfo() Function
        1. The hints argument
      2. Freeing addrinfo Lists: freeaddrinfo()
      3. Diagnosing Errors: gai_strerror()
      4. The getnameinfo() Function
    11. Client-Server Example (Stream Sockets)
      1.  
        1. Common header file
        2. Server program
        3. Client program
    12. An Internet Domain Sockets Library
    13. Obsolete APIs for Host and Service Conversions
      1. The inet_aton() and inet_ntoa() Functions
      2. The gethostbyname() and gethostbyaddr() Functions
      3. The getservbyname() and getservbyport() Functions
    14. UNIX Versus Internet Domain Sockets
    15. Further Information
    16. Summary
    17. Exercises
  63. 60. Sockets: Server Design
    1. Iterative and Concurrent Servers
    2. An Iterative UDP echo Server
    3. A Concurrent TCP echo Server
    4. Other Concurrent Server Designs
      1.  
        1. Preforked and prethreaded servers
        2. Handling multiple clients from a single process
        3. Using server farms
    5. The inetd (Internet Superserver) Daemon
      1.  
        1. Operation of the inetd daemon
        2. The /etc/inetd.conf file
        3. Example: invoking a TCP echo service via inetd
    6. Summary
      1.  
        1. Further information
    7. Exercises
  64. 61. Sockets: Advanced Topics
    1. Partial Reads and Writes on Stream Sockets
    2. The shutdown() System Call
      1.  
        1. Example program
    3. Socket-Specific I/O System Calls: recv() and send()
    4. The sendfile() System Call
      1.  
        1. The TCP_CORK socket option
    5. Retrieving Socket Addresses
    6. A Closer Look at TCP
      1. Format of a TCP Segment
      2. TCP Sequence Numbers and Acknowledgements
      3. TCP State Machine and State Transition Diagram
      4. TCP Connection Establishment
      5. TCP Connection Termination
      6. Calling shutdown() on a TCP Socket
      7. The TIME_WAIT State
    7. Monitoring Sockets: netstat
    8. Using tcpdump to Monitor TCP Traffic
    9. Socket Options
    10. The SO_REUSEADDR Socket Option
    11. Inheritance of Flags and Options Across accept()
    12. TCP Versus UDP
    13. Advanced Features
      1. Out-of-Band Data
      2. The sendmsg() and recvmsg() System Calls
      3. Passing File Descriptors
      4. Receiving Sender Credentials
      5. Sequenced-Packet Sockets
      6. SCTP and DCCP Transport-Layer Protocols
    14. Summary
      1.  
        1. Further information
    15. Exercises
  65. 62. Terminals
    1. Overview
    2. Retrieving and Modifying Terminal Attributes
    3. The stty Command
    4. Terminal Special Characters
      1.  
        1. CR
        2. DISCARD
        3. EOF
        4. EOL and EOL2
        5. ERASE
        6. INTR
        7. KILL
        8. LNEXT
        9. NL
        10. QUIT
        11. REPRINT
        12. START and STOP
        13. SUSP
        14. WERASE
        15. Other terminal special characters
        16. Example program
    5. Terminal Flags
      1.  
        1. BRKINT
        2. ECHO
        3. ECHOCTL
        4. ECHOE
        5. ECHOK and ECHOKE
        6. ICANON
        7. IEXTEN
        8. IMAXBEL
        9. IUTF8
        10. NOFLSH
        11. OPOST
        12. PARENB, IGNPAR, INPCK, PARMRK, and PARODD
        13. Example program
    6. Terminal I/O Modes
      1. Canonical Mode
      2. Noncanonical Mode
        1. MIN == 0, TIME == 0 (polling read)
        2. MIN > 0, TIME == 0 (blocking read)
        3. MIN == 0, TIME > 0 (read with timeout)
        4. MIN > 0, TIME > 0 (read with interbyte timeout)
        5. Portably modifying and restoring MIN and TIME
      3. Cooked, Cbreak, and Raw Modes
        1. Example: setting raw and cbreak mode
    7. Terminal Line Speed (Bit Rate)
    8. Terminal Line Control
    9. Terminal Window Size
    10. Terminal Identification
    11. Summary
      1.  
        1. Further information
    12. Exercises
  66. 63. Alternative I/O Models
    1. Overview
      1.  
        1. Which technique?
      2. Level-Triggered and Edge-Triggered Notification
      3. Employing Nonblocking I/O with Alternative I/O Models
    2. I/O Multiplexing
      1. The select() System Call
        1. File descriptor sets
        2. The timeout argument
        3. Return value from select()
        4. Example program
      2. The poll() System Call
        1. The pollfd array
        2. The timeout argument
        3. Return value from poll()
        4. Example program
      3. When Is a File Descriptor Ready?
        1. Regular files
        2. Terminals and pseudoterminals
        3. Pipes and FIFOs
        4. Sockets
      4. Comparison of select() and poll()
        1. Implementation details
        2. API differences
        3. Portability
        4. Performance
      5. Problems with select() and poll()
    3. Signal-Driven I/O
      1.  
        1. Example program
        2. Establish the signal handler before enabling signal-driven I/O
        3. Setting the file descriptor owner
      2. When Is “I/O Possible” Signaled?
        1. Terminals and pseudoterminals
        2. Pipes and FIFOs
        3. Sockets
        4. inotify file descriptors
      3. Refining the Use of Signal-Driven I/O
        1. Handling signal-queue overflow
        2. Using signal-driven I/O with multithreaded applications
    4. The epoll API
      1. Creating an epoll Instance: epoll_create()
      2. Modifying the epoll Interest List: epoll_ctl()
        1. The max_user_watches limit
      3. Waiting for Events: epoll_wait()
        1. epoll events
        2. The EPOLLONESHOT flag
        3. Example program
      4. A Closer Look at epoll Semantics
      5. Performance of epoll Versus I/O Multiplexing
      6. Edge-Triggered Notification
        1. Preventing file-descriptor starvation when using edge-triggered notification
    5. Waiting on Signals and File Descriptors
      1. The pselect() System Call
        1. The ppoll() and epoll_pwait() system calls
      2. The Self-Pipe Trick
    6. Summary
      1.  
        1. Further information
    7. Exercises
  67. 64. Pseudoterminals
    1. Overview
      1.  
        1. The pseudoterminal master and slave devices
        2. How programs use pseudoterminals
        3. Applications of pseudoterminals
        4. System V (UNIX 98) and BSD pseudoterminals
    2. UNIX 98 Pseudoterminals
      1. Opening an Unused Master: posix_openpt()
        1. Limits on the number of UNIX 98 pseudoterminals
      2. Changing Slave Ownership and Permissions: grantpt()
      3. Unlocking the Slave: unlockpt()
      4. Obtaining the Name of the Slave: ptsname()
    3. Opening a Master: ptyMasterOpen()
    4. Connecting Processes with a Pseudoterminal: ptyFork()
    5. Pseudoterminal I/O
      1.  
        1. Packet mode
    6. Implementing script(1)
    7. Terminal Attributes and Window Size
    8. BSD Pseudoterminals
    9. Summary
    10. Exercises
  68. A. Tracing System Calls
  69. B. Parsing Command-Line Options
    1. Example program
    2. GNU-specific behavior
    3. GNU extensions
  70. C. Casting the NULL Pointer
  71. D. Kernel Configuration
  72. E. Further Sources of Information
    1. Manual pages
    2. GNU info documents
    3. The GNU C library (glibc) manual
    4. Books
    5. Source code of existing applications
    6. The Linux Documentation Project
    7. The GNU project
    8. Newsgroups
    9. Linux kernel mailing list
    10. Web sites
    11. The kernel source code
  73. F. Solutions to Selected Exercises
    1. Chapter 5
    2. Chapter 6
    3. Chapter 8
    4. Chapter 9
    5. Chapter 10
    6. Chapter 12
    7. Chapter 13
    8. Chapter 15
    9. Chapter 18
    10. Chapter 20
    11. Chapter 22
    12. Chapter 23
    13. Chapter 24
    14. Chapter 25
    15. Chapter 26
    16. Chapter 27
    17. Chapter 29
    18. Chapter 31
    19. Chapter 33
    20. Chapter 34
    21. Chapter 35
    22. Chapter 36
    23. Chapter 37
    24. Chapter 38
    25. Chapter 44
    26. Chapter 45
    27. Chapter 46
    28. Chapter 47
    29. Chapter 48
    30. Chapter 49
    31. Chapter 50
    32. Chapter 52
    33. Chapter 53
    34. Chapter 55
    35. Chapter 57
    36. Chapter 59
    37. Chapter 60
    38. Chapter 61
    39. Chapter 62
    40. Chapter 63
    41. Chapter 64
  74. Bibliography
  75. G. Updates
  76. Index
  77. Colophon
  78. Copyright