Home > Store

Stevens: Adv. Prog. in UNIX_c

Register your product to gain access to bonus material or receive a coupon.

Stevens: Adv. Prog. in UNIX_c


  • Sorry, this book is no longer in print.
Not for Sale


  • Copyright 1992
  • Edition: 1st
  • Book
  • ISBN-10: 0-201-56317-7
  • ISBN-13: 978-0-201-56317-7

If you are an experienced C programmer with a working knowledge of UNIX, you cannot afford to be without this up-to-date tutorial on the system call interface and the most important functions found in the ANSI C library. Rich Stevens describes more than 200 system calls and functions; since he believes the best way to learn code is to read code, a brief example accompanies each description.

Building upon information presented in the first 15 chapters, the author offers chapter-long examples teaching you how to create a database library, a PostScript printer driver, a modem dialer, and a program that runs other programs under a pseudo terminal. To make your analysis and understanding of this code even easier, and to allow you to modify it, all of the code in the book is available via UUNET.

A 20-page appendix provides detailed function prototypes for all the UNIX, POSIX, and ANSI C functions that are described in the book, and lists the page on which each prototype function is described in detail. Additional tables throughout the text and a thorough index make Advanced Programming in the UNIX Environment an invaluable reference tool that all UNIX programmers - beginners to experts - will want on their bookshelves.

Advanced Programming in the UNIX Environment is applicable to all major UNIX releases, especially System V Release 4 and the latest release of 4.3BSD, including 386BSD. These real-world implementations allow you to more clearly understand the status of the current and future standards, including IEEE POSIX and XPG3.


Sample Content

Online Sample Chapter

Advanced Programming in the UNIX® Environment: UNIX File I/O

Table of Contents

(Each chapter begins with an Introduction and concludes with a Summary.)

1. Introduction.

Logging In.

Files and Directories.

Input and Output.

Programs and Processes.

ANSI C Features.

Error Handling.

User Identification.


Unix Time Values.

System Calls and Library Functions.

2. Unix Standardization and Implementations.

Unix Standardization.



X/Open XPG3.


Unix Implementations.

System V Release 4.


Relationship of Standards and Implementations.


ANSI C Limits.

POSIX Limits.

XPG3 Limits.

sysconf, pathconf, and fpathconf Functions.

FIPS 151-1 Requirements.

Summary of Limits.

Indeterminate Run-Time Limits.

Feature Test Macros.

Primitive System Data Types.

Conflicts Between Standards.

3. File I/O.

File Descriptors.

open Function.

creat Function.

close Function.

lseek Function.

read Function.

write Function.

I/O Efficiency.

File Sharing.

Atomic Operations.

dup and dup2 Functions.

fcntl Function.

ioctl Function.


4. Files and Directories.

stat, fstat, and lstat Functions.

File Types.

Set-User-ID and Set-Group-ID.

File Access Permissions.

Ownership of New Files and Directories.

access Function.

umask Function.

chmod and fchmod Functions.

Sticky Bit.

chown, fchown, and lchown Functions.

File Size.

File Truncation.


link, unlink, remove, and rename Functions.

Symbolic Links.

symlink and readlink Functions.

File Times.

utime Function.

mkdir and rmdir Functions.

Reading Directories.

chdir, fchdir, and getcwd Functions.

Special Device Files.

sync and fsync Functions.

Summary of File Access Permission Bits.

5. Standard I/O Library.

Streams and FILE Objects.

Standard Input, Standard Output, and Standard Error.


Opening a Stream.

Reading and Writing a Stream.

Line-at-a-Time I/O.

Standard I/O Efficiency.

Binary I/O.

Positioning a Stream.

Formatted I/O.

Implementation Details.

Temporary Files.

Alternatives to Standard I/O.

6. System Data Files and Information.

Password File.

Shadow Passwords.

Group File.

Supplementary Group IDs.

Other Data Files.

Login Accounting.

System Identification.

Time and Date Routines.

7. The Environment of a Unix Process.

main Function.

Process Termination.

Command-Line Arguments.

Environment List.

Memory Layout of a C Program.

Shared Libraries.

Memory Allocation.

Environment Variables.

setjmp and longjmp Functions.

getrlimit and setrlimit Functions.

8. Process Control.

Process Identifiers.

fork Function.

vfork Function.

exit Functions.

wait and waitpid Functions.

wait3 and wait4 Functions.

Race Conditions.

exec Functions.

Changing User IDs and Group IDs.

Interpreter Files.

system Function.

Process Accounting.

User Identification.

Process Times.

9. Process Relationships.

Terminal Logins.

Network Logins.

Process Groups.


Controlling Terminal.

tcgetpgrp and tcsetpgrp Functions.

Job Control.

Shell Execution of Programs.

Orphaned Process Groups.

4.3+BSD Implementation.

10. Signals.

Signal Concepts.

signal Function.

Unreliable Signals.

Interrupted System Calls.

Reentrant Functions.

SIGCLD Semantics.

Reliable Signal Terminology and Semantics.

kill and raise Functions.

alarm and pause Functions.

Signal Sets.

sigprocmask Function.

sigpending Function.

sigaction Function.

sigsetjmp and siglongjmp Functions.

sigsuspend Function.

abort Function.

system Function.

sleep Function.

Job-Control Signals.

Additional Features.

11. Terminal I/O.


Special Input Characters.

Getting and Setting Terminal Attributes.

Terminal Option Flags.

stty Command.

Baud Rate Functions.

Line Control Functions.

Terminal Identification.

Canonical Mode.

Noncanonical Mode.

Terminal Window Size.

termcap, terminfo, and curses.

12. Advanced I/O

Nonblocking I/O.

Record Locking.


I/O Multiplexing.

select Function.

poll Function.

Asynchronous I/O.

System V Release 4.


readv and writev Functions.

readn and writen Functions.

Memory Mapped I/O.

13. Daemon Processes.

Daemon Characteristics.

Coding Rules.

Error Logging.

SVR4 Streams log Driver.

4.3+BSD syslog Facility.

Client-Server Model.

14. Interprocess Communication.


popen and pclose Functions.



System V IPC.

Identifiers and Keys.

Permission Structure.

Configuration Limits.

Advantages and Disadvantages.

Message Queues.


Shared Memory.

Client-Server Properties.

15. Advanced Interprocess Communication.

Stream Pipes.

Passing File Descriptors.

System V Release 4.



An Open Server, Version 1.

Client-Server Connection Functions.

System V Release 4.


An Open Server, Version 2.

16. A Database Library.


The Library.

Implementation Overview.

Centralized or Decentralized?


Source Code.


17. Communicating with a PostScript Printer.

PostScript Communication Dynamics.

Printer Spooling.



18. A Modem Dialer.


Program Design.

Data Files.

Server Design.

Server Source Code.

Client Design.

Client Source Code.

19. Pseudo Terminals.


Opening Pseudo-Terminal Devices.

System V Release 4.


pty_fork Function.

pty Program.

Using the pty Program.

Advanced Features.

Appendix A. Function Prototypes.

Appendix B. Miscellaneous Source Code.

Our Header File.

Standard Error Routines.

Appendix C. Solutions to Selected Exercises.


Index. 0201563177T04062001



This book describes the programming interface to the Unix system - the system call interface and many of the functions provided in the standard C library. It is intended for anyone writing programs that run under Unix.

Like most operating systems, Unix provides numerous services to the programs that are running - open a file, read a file, start a new program, allocate a region of memory, get the current time-of-day, and so on. This has been termed the system call interface. Additionally, the standard C library provides numerous functions that are used by almost every C program (format a variable's value for output, compare two strings, etc.).

The system call interface and the library routines have traditionally been described in Sections 2 and 3 of the Unix Programmer's Manual. This book is not a duplication of these sections. Examples and rationale are missing from the Unix Programmer's Manual, and that's what this book provides.

Unix Standards

The proliferation of different versions of Unix during the 1980s has been tempered by the various international standards that were started during the late 1980s. These include the ANSI standard for the C programming language, the IEEE POSIX family (still being developed), and the X/Open portability guide.

This book also describes these standards. But instead of just describing the standards by themselves, we describe them in relation to popular implementations of the standards - System V Release 4 and the forthcoming 4.4BSD. This provides a real-world description, which is often lacking from the standard itself and from books that describe only the standard.

Organization of the Book

This book is divided into six parts:

  • 1. An overview and introduction to basic Unix programming concepts and terminology (Chapter 1), with a discussion of the various Unix standardization efforts and different Unix implementations (Chapter 2).
  • 2. I/O - unbuffered I/O (Chapter 3), properties of files and directories (Chapter 4), the standard I/O library (Chapter 5), and the standard system data files (Chapter 6).
  • 3. Processes - the environment of a Unix process (Chapter 7), process control (Chapter 8), the relationships between different processes (Chapter 9), and signals (Chapter 10).
  • 4. More I/O - terminal I/O (Chapter 11), advanced I/O (Chapter 12), and daemon processes (Chapter 13).
  • 5. IPC - Interprocess communication (Chapters 14 and 15).
  • 6. Examples - a database library (Chapter 16), communicating with a PostScript printer (Chapter 17), a modem dialing program (Chapter 18), and using pseudo terminals (Chapter 19).
A reading familiarity with C would be beneficial as would some experience using Unix. No prior programming experience with Unix is assumed. This text is intended for programmers familiar with Unix and programmers familiar with some other operating system who wish to learn the details of the services provided by most Unix systems.

Examples in the Text

This book contains many examples - approximately 10,000 lines of source code. All the examples are in the C programming language. Furthermore, these examples are in ANSI C. You should have a copy of the Unix Programmer's Manual for your system handy while reading this book, since reference is made to it for some of the more esoteric and implementation-dependent features.

Almost every function and system call is demonstrated with a small, complete program. This lets us see the arguments and return values and is often easier to comprehend than the use of the function in a much larger program. But since some of the small programs are contrived examples, a few bigger examples are also included (Chapters 16, 17, 18, and 19). These larger examples demonstrate the programming techniques in larger, real-world examples.

All the examples have been included in the text directly from their source files. A machine-readable copy of all the examples is available via anonymous FTP from the Internet host ftp.uu.net in the file published/books/stevens.advprog.tar.Z. Obtaining the source code allows you to modify the programs from this text and experiment with them on your system.

Systems Used to Test the Examples

Unfortunately all operating systems are moving targets. Unix is no exception. The following diagram shows the recent evolution of the various versions of System V and 4.xBSD.
                                                    4.3+BSD          4.3BSD       4.3BSD Tahoe    4.3BSD Reno      4.4BSD?            |                |  BSD Net 1    | BSD Net 2 |  |          | |    |       |   |  |   |   |    | |   |   | |  | |          +-+----+-------+---+--+---+---+----+-+---+---+-+--+-+            1986   1987    1988 + 1989 +  1990 + 1991    1992              |      |       |  +      +    |  +           SVR3.0 SVR3.1  SVR3.2+      +  SVR4 +                              XPG3  ANSI C POSIX.1 

4.xBSD are the various systems from the Computer Systems Research Group at the University of California at Berkeley. This group also distributes the BSD Net 1 and BSD Net 2 releases - publicly available source code from the 4.xBSD systems. SVRx refers to System V Release x from AT&T. XPG3 is the X/Open Portability Guide, Issue 3, and ANSI C is the ANSI standard for the C programming language. POSIX.1 is the IEEE and ISO standard for the interface to a Unix-like system. We'll have more to say about these different standards and the various versions of Unix in Sections 2.2 and 2.3.

In this text we use the term 4.3+BSD to refer to the Unix system from Berkeley that is somewhere between the BSD Net 2 release and 4.4BSD.

At the time of this writing, 4.4BSD was not released, so the system could not be called 4.4BSD. Nevertheless a simple name was needed to refer to this system and 4.3+BSD is used throughout the text.

Most of the examples in this text have been run on four different versions of Unix:

  • 1. Unix System V/386 Release 4.0 Version 2.0 ("vanilla SVR4") from U.H. Corp. (UHC), on an Intel 80386 processor.
  • 2. 4.3+BSD at the Computer Systems Research Group, Computer Science Division, University of California at Berkeley, on a Hewlett Packard workstation.
  • 3. BSD/386 (a derivative of the BSD Net 2 release) from Berkeley Software Design, Inc., on an Intel 80386 processor. This system is almost identical to what we call 4.3+BSD.
  • 4. SunOS 4.1.1 and 4.1.2 (systems with a strong Berkeley heritage but many System V features) from Sun Microsystems, on a SPARCstation SLC.
Numerous timing tests are provided in the text and the systems used for the test are identified.


Once again I am indebted to my family for their love, support, and many lost weekends over the past year and a half. Writing a book is, in many ways, a family affair. Thank you Sally, Bill, Ellen, and David.

I am especially grateful to Brian Kernighan for his help in the book. His numerous thorough reviews of the entire manuscript and his gentle prodding for better prose hopefully show in the final result. Steve Rago was also a great resource, both in reviewing the entire manuscript and answering many questions about the details and history of System V. My thanks to the other technical reviewers used by Addison-Wesley, who provided valuable comments on various portions of the manuscript: Maury Bach, Mark Ellis, Jeff Gitlin, Peter Honeyman, John Linderman, Doug McIlroy, Evi Nemeth, Craig Partridge, Dave Presotto, Gary Wilson, and Gary Wright.

Keith Bostic and Kirk McKusick at the U.C. Berkeley CSRG provided an account that was used to test the examples on the latest BSD system. (Many thanks to Peter Salus too.) Sam Nataros and Joachim Sacksen at UHC provided the copy of SVR4 used to test the examples. Trent Hein helped obtain the alpha and beta copies of BSD/386.

Other friends have helped in many small, but significant ways over the past few years: Paul Lucchina, Joe Godsil, Jim Hogue, Ed Tankus, and Gary Wright. My editor at Addison-Wesley, John Wait, has been a great friend through it all. He never complained when the due date slipped and the page count kept increasing. A special thanks to the National Optical Astronomy Observatories (NOAO), especially Sidney Wolff, Richard Wolff, and Steve Grandi, for providing computer time.

Real Unix books are written using troff and this book follows that time-honored tradition. Camera-ready copy of the book was produced by the author using the groff package written by James Clark. Many thanks to James Clark for providing this excellent system and for his rapid response to bug fixes. Perhaps someday I will really understand troff footer traps.

I welcome electronic mail from any readers with comments, suggestions, or bug fixes: rstevens@kohala.com.

W. Richard Stevens
Tucson, Arizona
April 1992



Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020