The Linux Programming Interface : A Linux Und UNIX System .

Transcription

THE LINUXPROGRAMMINGINTERFACEA Linux and UNIX"System Programming HandbookMICHAEL KERRISKTECHNISCHE}IN FORMATION 3BI ft LIQTHEKUNIVERSITATSBIBLIOTHF.KHANNOVER no starchpressSan Francisco

CONTENTSINPREFACEDETAILxxxi1HISTORY AND STANDARDS11.1A Briefof UNIX and C21.2A Briefof Linux51.3HistoryHistory1.2.1The GNU1.2.2The Linux KernelProject56Standardization1.3.1101.3.2The C Programming LanguageThe First POSIX Standards1.3.3X/Open Company1.3.4SUSv3 and POSIX. 1-20011.3.5SUSv4 and POSIX. 1-2008151.3.6UNIX Standards Timeline161.3.7Implementation StandardsLinux, Standards, and the Linux1.3.8Summary2FUNDAMENTAL CONCEPTS2.1The Core2.2The Shell2.3Users and2.52.611and The Open Group1.42.410131317Standard Base1819Operating21System: The Kernel2124GroupsSingle Directory Hierarchy, Directories, Links,File I/O ModelPrograms2.7Processes2.8Memory Mappings26and Files293031,2.9Static and Shared 3ProcessCommunication and273535Synchronization3637382.14Groups and Shell Job ControlSessions, Controlling Terminals, and Controlling2.15Pseudoterminals392.16Date and Time402.17Client-Server Architecture402.18Realtime412.19The /proc File2.20Summary3SYSTEM PROGRAMMING tem394242Calls4343FunctionsThe Standard C Library; The GNU C Library [glibc]Handling Errors from System Calls and Library Functions46Notes50on3.5.13.5.2theExample Programs in This BookCommand-Line Options and ArgumentsCommon Functions and Header Files47485051

3.6PortabilityIssues 13.6.1Feature Test Macros3.6.2System61DataTypesMiscellaneous 84FILE I/O: THE UNIVERSAL I/O MODEL4.1Overview 94.2Universality of I/OOpening a File: open()724.34.3.172The open() Jlags ArgumentErrors from open()4.3.24.3.369:7477The creat() System CallReading from a File: readQWriting to a File: write()Closing a File: closeQChanging the File Offset: lseek()Operations Outside the Universal I/O Model: .74.8I/O: FURTHER DETAILS5.1Atomicity5.2File Control5.35.45.55.65.75.85.9798080818689and Race Conditions90Operations: fcnllQOpen File Status FlagsRelationship Between File Descriptors and Open FilesDuplicating File DescriptorsFile I/O at a Specified Offset: preadQ and pwriteQScatter-Gather I/O: readvQ and writevQTruncating a File: truncate() andfiruncateQ929394969899103Nonblocking I/O1035.10I/O1045.11The/dev/fd5.125.135.14onLarge FilesDirectoryCreating Temporary esses and6.2Process ID and Parent Process ID1146.3Memory Layout of a ProcessVirtual Memory Management1156.4113Programs1131186.5The Stack and Stack Frames1216.6Command-Line1226.7Environment ts in DetailArguments [argc, argv)Nonlocal Goto:125setjmp()andlongjmp()131138138

1397MEMORY ALLOCATION7.17.3Allocating MemoryHeap7.1.1Adjusting the Program Break: brk() and sbrkQ7.1.2Allocating Memory on the Heap: mallocQ and free()7.1.3Implementation of mallocQ and free()Other Methods of Allocating Memory on the Heap7.1.4Allocating Memory on the Stack: allocaQSummary7.4Exercises8USERS AND GROUPS8.1The Password8.2The Shadow Password File: /etc/shadow8.3The Group8.4Retrieving7.2on9.1Real User ID and Real Group IDEffective User ID and Effective Group ID9.7151152155PROCESS up InformationPassword Encryption and User AuthenticationSummary8.5139the157User and162166166167167168168Set-User-ID and Set-Group-ID ProgramsSaved Set-User-ID and Saved Set-Group-IDUser ID andFile-System Group170File-SystemSupplementary Group IDsRetrieving and Modifying Process Credentials9.7.1Retrieving and Modifying Real, Effective, and Saved9.7.2Retrieving and Modifying File-System IDs9.7.3Retrieving and Modifying Supplementary Group IDs9.7.4Summary of Calls for Modifying Process Credentials9.7.5Example: Displaying Process r Time10.2Time-Conversion Functions171ID172172Set IDs1721781781801 82183184185186Converting Ume t to Printable FormConverting Between time t and Broken-Down TimeConverting Between Broken-Down Time and Printable Form10.2.110.2.210.2.31871 10.6The Software Clock10.7Process Time20610.8Summary20910.9ExercisetheSystem Clock(Jiffies)204205210Contents in Detailxiii

1111.1SYSTEM LIMITS AND OPTIONS211Limits1 1.3SystemRetrieving System Limits (and Options) at Run TimeRetrieving File-Related Limits (and Options] at Run Time1 1.4Indeterminate Limits1 1.52191 1.6System OptionsSummary1 1.7Exercises2221 1.2215217 21922112SYSTEM AND PROCESS INFORMATION12.1The /proc File223System2231 2.1.1Obtaining1 2.1.2System Information UnderAccessing /proc Files12.1.3212Information AboutaProcess: /procAP/D/proc22422622612.2System Identification: unamef)12.3Summary2311 2.4Exercises23113FILE13.1Kernel1 3.213.31 3.41 3.513.613.713.813.9I/O BUFFERING233Buffering of File I/O: The Buffer CacheBuffering in the stdio LibraryControlling Kernel Buffering of File I/OSummary of I/O BufferingAdvising the Kernel About I/O PatternsDisks and Partitions14.3File14.4l-nodes14.5The Virtual File System (VFS)Journaling File 252253Systems254256259260Single Directory Hierarchy and Mount PointsMounting and Unmounting File Systems14.8.1Mounting a File System: mountQ14.8.2Unmounting a File System: umountQAdvanced Mount FeaturesMounting14.9.2Stacking MultipleMount Flags Thata261262264and 249Device14.9239ExercisesFILE SYSTEMS14.8237Summary14.114.7233Bypassing the Buffer Cache: Direct I/OMixing Library Functions and System Calls for File I/O1414.6229File SystematMountsMultipleonMount Pointsthe Same Mount PointAre Per-MountOptions27127127214.9.4Bind Mounts14.9.5Recursive Bind Mounts273Memory File System: tmpfsObtaining Information About a File System: stalvfs()Summary274A VirtualExerciseConlenlsin272276277278Detail

15FILE ATTRIBUTES15.1Retrieving File Information: stat()File g File Timestamps with utimeQ and ulimes()Changing File Timestamps with utimensat() and JutimensQFile Ownership15.3.1Ownership of New Files15.3.2Changing File Ownership: chown(),fchown(), and lchown()289File Directories15.4.3Permission-Checking AlgorithmChecking File Accessibility: accessQSet-User-ID, Set-Group-ID, and .4.415.5279Files294297297299BitsThe Process File Mode Creation Mask: umaskQChanging File Permissions: chmodQ and fchmod()Extended File30030130315.6Flags [ext2Summary15.7Exercises16EXTENDED ATTRIBUTES16.1Overview31116.2Extended AttributeImplementation DetailsSystem Calls for Manipulating Extended Attributes31316.4Summary31 816.5Exercise31 817ACCESS CONTROL LISTS17.1Overview32017.2ACLPermission-Checking Algorithm32117.3Longand Short Text Forms for ACLs32316.3Attributes)30430830931131431917.6The ACL MASK Entry and the ACL Group ClassThe gelfad and setfacl CommandsDefault ACLs and File Creation17.7ACL17.8The ACL API32917.9Summary33717.10Exercise33718DIRECTORIES AND LINKS18.1Directories and(Hard) Links33918.2Symbolic (Soft)Links3421 8.3Creating and Removing (Hard) Links: link() and unlink()Changing the Name of a File: rename()Working with Symbolic Links: symlinkQ and readlinkQCreating and Removing Directories: mkdir() and rnidirQRemoving a File or Directory: removeQ17.417.51 8.41 8.51 8.61 8.71 8.81 8.918.101 8.1118.1218.13ImplementationReadingFile TreeLimitsDirectories: opendir() and readdir()Walking: nfiwQThe Current Working Directory of a ProcessOperating Relative to a Directory File DescriptorChanging the Root Directory of a Process: chroot()Resolving a Pathname: 5367369Contents in DetailXV

18.14Parsing Pathname Strings: dimame() and RING FILE EVENTS19.1Overview37619.2The moiz/y APIinotijy Events37619.337537819.4Reading inotijy19.5Queue Limits and /proc FilesAn Older System for Monitoring File GNALS: FUNDAMENTAL CONCEPTS20.1Concepts and Overview20.2Signal Types and Default ActionsChanging Signal Dispositions: signalQIntroduction to Signal HandlersSending Signals: kill()Checking for the Existence of a ProcessOther Ways of Sending Signals: raiseQ and hillpgQDisplaying Signal DescriptionsSignal SetsThe Signal Mask (Blocking Signal Delivery)Pending SignalsSignals Are Not QueuedChanging Signal Dispositions: sigactionQWafting for a Signal: es41921SIGNALS: SIGNAL HANDLERS21.1Designing Signal Handlers21.1.1Signals Are Not Queued21.1.2Reentrant and421422(Revisited)Async-Signal-Safe Functions21.1.321.2Global Variables and the sig atomic t Data TypeOther Methods of Terminating a Signal Handler21.2.1Performing a Nonlocal Goto from a Signal Handler21.2.2Terminating a Process Abnormally: abort()Signal on an Alternate Stack: sigaltstackQ21.3Handling21.421.5The SA SIGINF0 FlagInterruption and Restarting of21.6Summary21.7Exercise22SIGNALS: ADVANCED 9433434437SystemCalls442445446447Dump FilesSpecial Cases for448Interruptible451andDelivery, Disposition, and HandlingUninterruptible Process Sleep StatesHardware-Generated SignalsSynchronousContents in DetailandAsynchronous Signal450452Generation452

22.6Timing and Order of Signal 922.1022.1122.1222.1322.14Portability ohignalf)Signals22.8.1Sending Realtime Signals22.8.2Handling Realtime SignalsWaiting for a Signal Using a Mask: sigsuspendQSynchronously Waiting for a SignalFetching Signals via a File DescriptorInterprocess Communication with SignalsEarlier Signal APIs (System V and es47823TIMERS AND SLEEPING23.1Interval Timers47923.2Scheduling48523.323.4Accuracy of TimersSetting Timeouts on Blocking OperationsSuspendingandExecution for23.4.123.4.223.5POSIX Clocks23.5.1486Fixed Interval(Sleeping)Low-Resolution Sleeping: sleepQHigh-Resolution Sleeping: nanosleep()a23.5.323.5.4POSIX Interval 98499Timer: time.r dekte()Notification via a Signal499Timer Overruns503a49923.6.723.7488Retrieving the Current Value of a Timer: timer gettime()Deleting23.6.5487495Creating a Timer: timer create()Arming and Disarming a Timer: timer settime()23.6.2487491Retrieving the Value of a Clock: dock gettime()Setting the Value of a Clock: clock settime()Obtaining the Clock ID of a Specific Process or ThreadImproved High-Resolution Sleeping: cloch nanosleep()23.5.223.6479Notification via a ThreadTimers That Notify via File Descriptors: The limerjd API504507Summary-51123.9Exercises51224PROCESS CREATION24.1Overview of fork(), exit(), waitQ, and execve()Creating a New Process: fork()24.224.2.124.324.424.5513FileSharing Between Parent24.2.2Memory Semantics offork()The vforkQ System CallRace Conditions After fork()Avoiding Race Conditions by513515and .7Summary25PROCESS TERMINATION25.1Terminating25.2Details of Process Termination53325.3Exit Handlers53325.4Interactions Between forty), stdio Buffers, and )531Contents in DetailXVfi

53825.5Summary25.6Exercise26MONITORING CHILD PROCESSES26.1Waiting539541Child Process54154126.1.2The wait() System CallThe xuaitpidQ System Call26.1.3The Wait Status Value26.1.4Process Termination fromon a26.1.1544545aSignalHandler26.2The waitidQ System CallThe wait3() and wait4() System Calls26.1.6Orphans and Delivery of26.3.3IgnoringSICCHLDaHandler 549Dead Child GRAM EXECUTION27.1Executing a New Program: execve()The execQ Library Functions27.227.2.1The PATH Environment Variable27.2.2Specifying Program Arguments563563567568as aList27.2.3570Passing the Caller's Environment to the New Program27.2.4Executing a File Referred to by a Descriptor: fexecve()Interpreter ScriptsFile Descriptors and execf)Signals and exec()Executing a Shell Command: systemQ57058227.8Implementing system()Summary27.9Exercises58928PROCESS CREATION AND PROGRAM EXECUTION IN27.327.427.527.627.7572575578579588591MORE DETAIL28.1Process28.2The cloneQ System CallThe clone() flags Argument28.2.1591Accounting28.2.2571Extensions towaitpid() for Cloned Childrenof Process Creation59860360928.3Speed28.4Effect of execQ and JorkQ28.5Summary61628.6Exercise61629THREADS: INTRODUCTION29.1Overview61729.262029.3Background Details of the Pthreads APIThread Creation29.4Thread Termination62329.5Thread IDs62429.6Joining withDetaching a29.7XVifiaon610Process AttributesTerminated ThreadThreadContents in Detail612617622625627

29.8Thread Attributes62829.9Threads Versus ADS: THREAD SYNCHRONIZATION30.1Protecting Accesses to Shared Variables: Mutexes30.1.1Statically Allocated Mutexes30.263163163530.1.2Locking and Unlocking30.1.3Performance of Mutexes30.1.4Mutex Deadlocks30.1.5Dynamically Initializing30.1.6Mutex Attributes64030.1.7Mutex Types640Mutexa635638639Mutexa639Signaling Changes of State: Condition Variables30.2.1Statically Allocated Condition ple Program: Joining Any Terminated ThreadDynamically Allocated Condition Variables30.2.5aand642WaitingonCondition Variables643Condition Variable's THREADS: THREAD SAFETY AND PER-THREAD STORAGE31.1Thread31.2One-Time Initialization31.3Thread-Specific Data31.3.1Thread-SpecificSafety (and Reentrancy Revisited)31.3.2655658659Data from theLibraryFunction'sOverview of the Thread-Specific Data API31.3.3Details of the Thread-Specific Data APIEmploying the Thread-Specific Data nLimitsPerspective66066066166366831.4Thread-Local Storage31.5Summary31.6669Exercises67032THREADS: THREAD CANCELLATION32.1Canceling32.232.3Cancellation State and TypeCancellation Points32.4Testing for Thread Cancellation67532.567632.7Cleanup HandlersAsynchronous 3THREADS: FURTHER DETAILS33.1Thread Stacks33.2Threads and681681Signals68233.2.1How the UNIX33.2.2Manipulating the33.2.3Sending a Signal to a ThreadDealing with Asynchronous Signals Sanely33.2.4671SignalModelThreadMaps to ThreadsSignal Mask682684684685Contenls in DetailXIX

33.3Threads and Process Control33.4Thread33.5LinuxImplementation ModelsImplementations of POSIX33.5.1LinuxThreads33.5.2NPTL33.5.3Which 3.6Advanced Features of the Pthreads API69633.7Summary69633.8Exercises69734PROCESS 434.4Controlling Terminals and Controlling ProcessesForeground and Background Process GroupsThe SIGHUP Signal34.6.1Handling of SIGHUP by the Shell34.6.2SIGHUP and Termination of the Controlling70634.534.634.7SESSIONS,AND JOB CONTROLGroups699708709710ProcessJob Control71271434.7.134.7.3Using Job Control Within the ShellImplementing Job ControlHandling Job-Control Signals34.7.4Orphaned34.7.2Process 3034.9Exercises73135PROCESS PRIORITIES AND SCHEDULING73335.1Process Priorities(Nice Values)SchedulingThe SCHED RR PolicyThe SCH D FIF0 Policy73335.2Overview of Realtime Process737The SCHED BATCH and SCHED IDLE PoliciesRealtime Process Scheduling .3.3Priority RangesModifying and Retrieving PoliciesRelinquishing the CPU35.3.4The SCHE0 RR Time Slice35.3.2740740and ses75136PROCESS RESOURCES36.1Process Resource36.2Process Resource LimitsDetails of Specific Resource .1Overview37.2Creating nb in Detail768

37.3Guidelines for37.4Using37.5Logging Messages and Errors Using 37.5.2Ihesyslog AP\777The /etc/syslog.conf File37.5.337.6WritingSICHUP to Reinitialize781Summary782Exercise78238WRITING SECURE PRIVILEGED PROGRAMS38.1IsSet-User-ID78378438.4Set-Group-ID Program Required?Operate with Least PrivilegeBe Careful When Executing a ProgramAvoid Exposing Sensitive Information38.5Confine the Process78938.6Beware of38.7Pitfalls38.879138.10Don't Trust Inputs or the EnvironmentBeware of Buffer OverrunsBeware of Denial-of-Service Attacks38.11Check Return Statuses and 1Rationale for39.2The Linux Capabilities39.3Process and File38.238.338.9aorSignals and Race ConditionsWhen Performing File Operations and7847877887 0File I/O790792793Safely79579 cess CapabilitiesFile Capabilities39.3.239.3.3Purpose of the Process Permitted and Effective Capability Sets39.3.4Purpose of the File Permitted and Effective Capability Sets39.3.5Purpose of the Process and File Inheritable Sets39.3.6Assigning and Viewing File Capabilities from the ShellThe Modern Capabilities ImplementationTransformation of Process Capabilities During exec()39.5.1Capability Bounding Set39.5.2Preserving root SemanticsEffect on Process Capabilities of Changing User IDsChanging Process Capabilities ProgrammaticallyCreating Capabilities-Only EnvironmentsDiscovering the Capabilities Required by a ProgramOlder Kernels and Systems Without File CapabilitiesSummary39.12Exercise81640LOGIN ACCOUNTING40.1Overview of40.2Thewim 4816817818Retrieving Information from the utmp and wtmp Filesthe799817the utmp and wtmp FilesThe utmpx Structu reRetrieving798Name:getlogin()the utmp and wtmp Files fora81 8821825Login Session825Conlenis in DetailXXl

40.7The lastlog S OF SHARED LIBRARIES41.1Object41.2Static Libraries41.3Overview of41.4833834Shared LibrariesCreating and Using Shared Libraries—A First Pass41.4.1Creating a Shared Library 41.641.741.8837Position-Independent Code41.4.3Using a Shared Library41.4.4The Shared Library SonameUseful Tools for Working with Shared LibrariesShared Library Versions and Naming ConventionsInstalling Shared LibrariesCompatible Versus Incompatible Libraries41.9Upgrading41.10Specifying Library Search Directories in an ObjectFinding Shared Libraries at Run TimeRun-Time Symbol ResolutionUsing a Static Library Instead of a Shared Library41.1141.1241.13838839840843844847850Shared D FEATURES OF SHARED LIBRARIES42.1Dynamically42.342.442.542.6Loaded LibrariesInitialization and Finalization FunctionsPreloading Shared Libraries42.742.8ExercisestheDynamicLinker: LD 874876INTERPROCESS COMMUNICATION OVERVIEW43.1A43.2Communication Facilities43.3Synchronization FacilitiesComparing IPC FacilitiesTaxonomy8598754343.4854857Opening a Shared Library: dlopen()42.1.2Diagnosing Errors: dlerrorf)42.1.3Obtaining the Address of a Symbol: dlsymQ42.1.4Closing a Shared Library: dlclose(j42.1.5Obtaining Information About Loaded Symbols: dladdr()42.1.6Accessing Symbols in the Main ProgramControlling Symbol VisibilityLinker Version Scripts42.3.1Controlling Symbol Visibility with Version Scripts42.3.2Symbol 1.4.241.5833Librariesof IPC es887XXliConlenls in Delail

44PIPES AND FIFOS44.1Overview88944.2Creating and Using PipesPipes as a Method of Process SynchronizationUsing Pipes to Connect FiltersTalking to a Shell Command via a Pipe: Os44.8A Client-Server44.9Nonblocking I/O44.10Semantics of read() and writeQ44.1 1Summary91 844.12Exercises91945INTRODUCTION TO SYSTEM V IPC45.1API Overview92245.2IPC92545.345.445.545.645.7and stdioBuffering906906Application UsingFIFOs909915onPipes andFIFOsKeysAssociated Data Structure and Object PermissionsIPC Identifiers and Client-Server ApplicationsAlgorithm Employed by System V IPC getThe ipcs and ipcrm CommandsObtaining List of All IPC ObjectsCallsa91792192792993193493545.8IPC Limits93545.9Summary93645.10Exercises93646SYSTEM V MESSAGE QUEUES46.1Creating937Opening MessageExchanging Messages46.2.1Sending Messages46.2.2Receiving MessagesMessage Queue Control OperationsMessage Queue Associated Data StructureMessage Queue LimitsDisplaying All Message Queues on the System93895346.9Client-Server Programming with Message QueuesA File-Server Application Using Message QueuesDisadvantages of System V Message Queues46.10Summary96246.11Exercises96347SYSTEM V SEMAPHORES47.1Overview96647.2CreatingOpening a Semaphore SetSemaphore Control rAssociated Data Structure969Semaphore InitializationSemaphore OperationsHandling of Multiple Blocked Semaphore Operations97547.8Semaphore Undo Values98647.9Implementing47.547.647.7aBinary SemaphoresProtocol978986988Contents in DetailXXIU

47.1047.1 1Semaphore LimitsDisadvantages of System47.12Summary99347.13Exercises99448SYSTEM V SHARED MEMORY48.1Overview"848.2Creating or Opening a Shared Memory SegmentUsing Shared xample: Transferring Data via Shared MemoryLocation of Shared Memory in Virtual MemoryStoring Pointers in Shared MemoryShared Memory Control OperationsShared Memory Associated Data StructureShared Memory LimitsSummary48.11Exercises101649MEMORY .12Mapping: mmap()Unmapping a Mapped Region: munmapQFile Mappings49.4.1Private File Mappings49.4.2Shared File Mappings49.4.3Boundary Cases49.4.4Memory Protection and File AccessSynchronizing a Mapped Region: msync()Additional mmapQ FlagsAnonymous MappingsRemapping a Mapped Region: mremapQMAP N0RE5ERVE and Swap Space 4102410251029Mode InteractionsThe MAPJIXED FlagNonlinear Mappings: remapJile 49.13Exercises104450VIRTUAL MEMORY OPERATIONS50.1Changing Memory50.250.350.450.5Protection:mprotectQMemory Locking: mlock() and mlockallQDetermining Memory Residence: mincore()Advising Future Memory Usage Patterns: madvisef)Summary50.6Exercises51INTRODUCTION TO POSIX IPC51.1API 051105410561056of System V IPC and POSIX IPCConienls in Detail1057105810611062

52POSIX MESSAGE QUEUES52.1Overview52.252.10Opening, Closing, and Unlinking a Message QueueRelationship Between Descriptors and Message QueuesMessage Queue AttributesExchanging Messages52.5.1Sending Messages52.5.2Receiving Messages52.5.3Sending and Receiving Messages with a TimeoutMessage Notification52.6.1Receiving Notification via a Signal52.6.2Receiving Notification via a ThreadLinux-Specific FeaturesMessage Queue LimitsComparison of POSIX and System V Message QueuesSummary1 8752.11Exercises1 8753POSIX zingDestroyingComparisons withSemaphore phores53.2.1Opening a Named Semaphore53.2.2Closing a Semaphore53.2.3Removing a Named SemaphoreSemaphore Operations53.3.1Waiting on a Semaphore53.3.2Posting a Semaphore53.3.3Retrieving the Current Value of a SemaphoreOther SynchronizationTechniques 04110511 554POSIX SHARED MEMORY54.1Overview110854.2110954.6Creating Shared Memory ObjectsUsing Shared Memory ObjectsRemoving Shared Memory ObjectsComparisons Between Shared MemorySummary54.7Exercise54.354.454.555FILE 51116111655.1Locking110711171 ' I7with JlockQSemantics of Lock Inheritance and ReleaseLimitations of JlockQ111911221123ContentsinDetailXXV

3.311241128An InteractiveALocking Program1129Library of Locking Functions55.3.5Lock Limits and PerformanceSemantics of Lock Inheritance and Release55.3.6Lock Starvation and55.3.455.4with fcnll()55.3.1Mandatory LockingPriorityof Queued Lock113311351136Requests1 137113755.5The /proc/locks File55.6Running55.7Older Locking55.8Summary114 55.9Exercises114756SOCKETS: INTRODUCTION56.1Overview56.2115356.3Creating a Socket: socket()Binding a Socket to an Address: bind()56.4Generic Socket Address Structures: struct sockaddr115456.5Stream Sockets1155aProgram1142Techniques11441149 56.5.156.5.256.5.3Connecting56.5.4I/ODatagramonto a Peer Socket: connectQStream Sockets1157115811591159Exchanging Datagrams: reaifrom() and sendtoQUsing connecLQ with Datagram Sockets56.6.211561159Connection Termination: close.()Sockets56.6.111501 153Listening for Incoming Connections: lislen()Accepting a Connection: accept()56.5.556.61140Just One Instance of1160116256.7Summary57SOCKETS: UNIX DOMAIN57.157.2UNIX Domain Socket Addresses: struct sockaddr unStream Sockets in the UNIX Domain57.3Datagram57.4UNIX Domain Socket Permissions117457.5Connected Socket Pair: socketpair()The Linux Abstract Socket KETS: FUNDAMENTALS OF58.1Internets58.2Networking58.358.4The Data-Link LayerThe Network Layer: IP58.5IP Addresses58.6The Transport Layer57.6Creating58.8XXVi116511651167Sockets in the UNIX Domain1171aTCP/IP1175NETWORKS11791179Protocols 358.71162NumbersDatagram Protocol (UDP)Transmission Control Protocol (TCP)Requests for Comments (RFCs)SummaryContents in Detail118811881189119011931195

59SOCKETS: INTERNET DOMAINS59.1Internet Domain Sockets119759.2Network Byte Order119859.3DataRepresentation119959.4Internet Socket Addresses120259.5119759.6Overview of Host and Service Conversion FunctionsThe inet pton() and inet ntop() Functions120659.7Client-Server1 20759.8Domain Name System (DNS)The /etc/services File1209Protocol-Independent Host and Service Conversion59.10.1The getaddrinfo() Function59.10.2Freeing addrinfo Lists: freeaddrinfoQ59.10.3Diagnosing Errors: gai strerror()The getnameinfoQ Function59.10.4Client-Server Example (Stream Sockets)An Internet Domain Sockets Library121359.959.1059.1159.1259.131204Example (Datagram Sockets]1212121312171217121812191225Obsolete APIs for Host and Service Conversions59.13.11230The inet aton() and inel nioa() FunctionsThe gethostbyname() and gethostbyaddrQ ubyporlQ12301231Functions123459.14UNIX Versus Internet Domain Sockets59.15Further KETS: SERVER DESIGN60.1Iterative and Concurrent Servers60.2An Iterative UDP echo Server124060.3A Concurrent TCP echo Server124360.4124560.5Other Concurrent Server DesignsThe inetd (Internet Superserver) Daemon60.6Summary125260.7Exercises125261SOCKETS: ADVANCED TOPICS61.1Partial Reads and Writes61.2The shutdovmO61.3Socket-Specific I/O System Calls: recvQThe sendftleO System Call61.461.561.61235SystemonCall12541256and send()125912601263at TCP126661.6.1Format of61.6.2TCP61.6.3TCP State Machine61.6.4TCP Connection Establishment127061.6.5TCP Connection Termination127261.6.6Calling shutdownQ127361.6.7The TIME WAIT StateSockets: netstataTCPSequenceSegment1266Numbers andAcknowledgementsand State Transition Diagramon a61.8Using tcpdump to Monitor TCP TrafficSocket Options61.111253Retrieving Socket AddressesA Closer Look12391247Stream SocketsMonitoring61.101239 61.761.91235TCP SocketThe S0 REU5EADDR Socket OptionInheritance of Flags and Options Across1268126912741275127612781 279acceptQ1281Contents in DetailXXVil

61.12TCP Versus UDP128261.13Advanced Features128361.13.2Out-of-Band DataThe sendmsg() and recvmsgO System Calls61.13.3Passing61.13.4Receiving Sender Credentials61.13.5Sequenced-Packet SocketsSCTP and DCCP ng and Modifying Terminal AttributesThe stty CommandTerminal Special CharactersTerminal FlagsTerminal I/O 1Canonical Mode130762.6.2Noncanonical Mode130762.6.3Cooked, Cbreak, and Raw Modes130962.7Terminal Line62.8Terminal Line Control131762.9Terminal Window Size131962.10Terminal 2363ALTERNATIVE63.1Overview63.3MODELSandWhen Is "I/O Possible" Signaled?Refining the Use of Signal-Driven I/OThe epoll 13521355epoll Instance: epoll create()Modifying the epoll Interest List: epoll dl()Waiting for Events: epoll xvait()A Closer Look at epoll SemanticsPerformance of epoll Versus I/O ge-Triggered Notification63.1.2Employing Nonblocking I/O with Alternative I/OI/O Multiplexing63.2.1The seleclf) System Call63.2.2The poll() System Call63.2.3When Is a File Descriptor Ready?63.2.4Comparison ofselectQ andpollQ63.2.5Problems with selectf) and poll()Signal-Driven I/O63.3.163.4I/OLevel-Triggered63.1.163.2Speed (Bit Rate)anEdge-Triggered NotificationSignals and File DescriptorsThepselectQ System CallThe Self-Pipe Trick1356135613581363136

THELINUX PROGRAMMING INTERFACE ALinuxand UNIX" System ProgrammingHandbook MICHAELKERRISK TECHNISCHE INFORMATION3BIftLIQTHEK} UNIVERSITATSBIBLIOTHF.K HANNOVER nostarch press SanFrancisco. CONTENTS IN DETAIL PREFACE xxxi 1 HISTORYAND STANDARDS 1 1.1 ABrief History of UNIXandC 2 1.2 ABrief History of Linux 5File Size: 919KBPage Count: 20