UNIX System Programming: Introduction to System Programming, Lecture notes of Intellectual Property (IP)

using documents for lecture notes

Typology: Lecture notes

2018/2019

Uploaded on 03/10/2019

zainab-ahmed-1
zainab-ahmed-1 🇱🇾

2 documents

1 / 58

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
UNIX Lecture Notes
Chapter 1 Introduction to System Programming Stewart Weiss
Chapter 1 Introduction to System Programming
UNIX is basically a simple operating system, but you have to be a genius to understand
the simplicity. - Dennis Ritchie, 1941 - 2011.
Concepts Covered
The kernel and kernel API,
System calls and libraries,
Processes, logins and shells,
Environments, man pages,
Users, the root, and groups,
Authentication,
File system, le hierarchy,
Files and directories,
Device special les,
UNIX standards, POSIX,
System programming,
Terminals and ANSI escape sequences,
History of UNIX,
syscall, getpid, ioctl
1.1 Introduction
A modern software application typically needs to manage both private and system resources. Private
resources are its own data, such as the values of its internal data structures. System resources are
things such as les, screen displays, and network connections. An application may also be written
as a collection of cooperating threads or sub-processes that coordinate their actions with respect to
shared data. These threads and sub-processes are also system resources.
Modern operating systems prevent application software from managing system resources directly,
instead providing interfaces that these applications can use for managing such resources. For exam-
ple, when running on modern operating systems, applications cannot draw to the screen directly or
read or write les directly. To perform screen operations or le I/O they must use the interface that
the operating system denes. Although it may seem that functions from the C standard library
such as
getc()
or
fprintf()
access les directly, they do not; they make calls to system routines
that do the work on their behalf.
The interface provided by an operating system for applications to use when accessing system re-
sources is called the operating system's
application programming interface
(
API
). An API typically
consists of a collection of function, type, and constant denitions, and sometimes variable denitions
as well. The API of an operating system in eect denes the means by which an application can
utilize the services provided by that operating system.
It follows that developing a software application for any
platform
1
requires mastery of that plat-
form's API. Therefore, aside from designing the application itself, the most important task for the
application developer is to master the system level services dened in the operating system's API.
A program that uses these system level services directly is called a
system program
, and the type
of programming that uses these services is called
system programming
. System programs make re-
quests for resources and services directly from the operating system and may even access the system
1
We use the term platform to mean a specic operating system running on a specic machine architecture.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a

Partial preview of the text

Download UNIX System Programming: Introduction to System Programming and more Lecture notes Intellectual Property (IP) in PDF only on Docsity!

Chapter 1 Introduction to System Programming

Chapter 1 Introduction to System Programming

UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity. - Dennis Ritchie, 1941 - 2011.

Concepts Covered

The kernel and kernel API, System calls and libraries, Processes, logins and shells, Environments, man pages, Users, the root, and groups, Authentication, File system, le hierarchy, Files and directories,

Device special les, UNIX standards, POSIX, System programming, Terminals and ANSI escape sequences, History of UNIX, syscall, getpid, ioctl

1.1 Introduction

A modern software application typically needs to manage both private and system resources. Private resources are its own data, such as the values of its internal data structures. System resources are things such as les, screen displays, and network connections. An application may also be written as a collection of cooperating threads or sub-processes that coordinate their actions with respect to shared data. These threads and sub-processes are also system resources.

Modern operating systems prevent application software from managing system resources directly, instead providing interfaces that these applications can use for managing such resources. For exam- ple, when running on modern operating systems, applications cannot draw to the screen directly or read or write les directly. To perform screen operations or le I/O they must use the interface that the operating system denes. Although it may seem that functions from the C standard library such as getc() or fprintf() access les directly, they do not; they make calls to system routines that do the work on their behalf.

The interface provided by an operating system for applications to use when accessing system re- sources is called the operating system's application programming interface (API ). An API typically consists of a collection of function, type, and constant denitions, and sometimes variable denitions as well. The API of an operating system in eect denes the means by which an application can utilize the services provided by that operating system.

It follows that developing a software application for any platform^1 requires mastery of that plat- form's API. Therefore, aside from designing the application itself, the most important task for the application developer is to master the system level services dened in the operating system's API. A program that uses these system level services directly is called a system program, and the type of programming that uses these services is called system programming. System programs make re- quests for resources and services directly from the operating system and may even access the system (^1) We use the term platform to mean a specic operating system running on a specic machine architecture.

Chapter 1 Introduction to System Programming

Figure 1.1: Simple I/O model used by beginning programmer.

resources directly. System programs can sometimes be written to extend the functionality of the operating system itself and provide functions that higher level applications can use.

These lecture notes specically concern system programming using the API of the UNIX operating system. They do not require any prior programming experience with UNIX. They also include tutorial information for those readers who have little experience with UNIX as a user, but this material can be skipped by the experienced UNIX users.

In the remainder of these notes, a distinction will be made between the user's view of UNIX and the programmer's view of UNIX. The user's view of UNIX is limited to a subset of commands that can be entered at the command-line and parts of the le system. Some commands and les are not available to all users, as will be explained later. The programmer's view includes the programming language features of the kernel API, the functions, types, and constants in all of the libraries, the various header les, and the various les used by the system. Familiarity with basic C programming is assumed.

1.2 A Programming Illusion

A beginning programmer typically writes programs that follow the simple I/O model depicted in Figure 1.1: the program gets its input from the keyboard or a disk le, and writes its output to the display screen or to a le on disk. Such programs are called console applications. because the keyboard and display screen are part of the console device. Listings 1.1 and 1.2 contain examples of such a program, one using the C Standard I/O Library, and the other, the C++ stream library. Both get input from the keyboard and send output to the display device, which is some sort of a console window on a monitor.

The comment in Listing1.1 states that the program copies from stdin to stdout. In UNIX^2 , every process has access to abstractions called the standard input device and the standard output device. When a process is created and loaded into memory, UNIX automatically creates the standard input and standard output devices for it, opens them, and makes them ready for reading and writing respectively^3. In C (and C++), stdin and stdout are variables dened in the <stdio.h>

(^2) In fact, every POSIX-compliant operating system must provide both a standard input and standard output stream. (^3) It also creates a standard error device that defaults to the same device as standard output.

Chapter 1 Introduction to System Programming

Figure 1.2: Connecting multiple users to a UNIX system.

shortly.) Programs that use the model of I/O described above do not have to be concerned with the complexities of connecting to monitors and keyboards, because the operating system hides that complexity, presenting a simplied interface for dealing with I/O. To understand how the operating system achieves this, one must rst understand several cornerstone concepts of the UNIX operating system: les, processes, users and groups, privileges and protections, and environments.

1.3 Cornerstones of UNIX

From its beginning, UNIX was designed around a small set of clever ideas, as Ritchie and Thompson [2] put it:

The success of UNIX lies not so much in new inventions but rather in the full exploita- tion of a carefully selected set of fertile ideas, and especially in showing that they can be keys to the implementation of a small yet powerful operating system.

Those fertile ideas included the design of its le system, its process concept, the concept of privileged and unprivileged programs, the concepts of user and groups, a programmable shell, environments, and device independent input and output. In this section we describe each of these briey.

Chapter 1 Introduction to System Programming

1.3.1 Files and the File Hierarchy

Most people who have used computers know what a le is, but as an exercise, try explaining what a le is to your oldest living relative. You may know what it is, but knowing how to dene it is another matter. In UNIX, the traditional denition of a le was that it is the smallest unit of external storage. "External storage" has always meant non-volatile storage, not in primary memory, but on media such as magnetic, optical, and electronic disks, tapes and so on. (Internal storage is on memory chips.) The contemporary denition of a le in UNIX is that it is an object that can be written to, or read from, or both. There is no requirement that it must reside on external storage. We will use this denition of a le in the remainder of these notes. UNIX organizes les into a tree-like hierarchy that most people erroneously call the le system. It is more accurately called the le hierarchy, because a le system is something slightly dierent. The internal nodes of the hierarchy are called directories. Directories are special types of les that, from the user perspective, appear to contain other les, although they do not contain les any more than a table of contents in a book contains the chapters of the book themselves. To be precise, a directory is a le that contains directory entries. A directory entry is an object that associates a lename to a le^5. Filenames are not the same things as les. The root of the UNIX le system is a directory known in the UNIX world as the root directory, however it is not named "root" in the le system; it is named "/". When you need to refer to this directory, you call it "root", not "slash". More will be said about les, lenames, and the le hierarchy in Section 1.8.

1.3.2 Processes

A program is an executable le, and a process is an instance of a running program. When a program is run on a computer, it is given various resources such as a primary memory space, both physical and logical, secondary storage space, mappings of various kinds^6 , and privileges, such as the right to read or write certain les or devices. As a result, at any instant of time, associated to a process is the collection of all resources allocated to the running program, as well as any other properties and settings that characterize that process, such as the values of the processor's registers. Thus, although the idea of a process sounds like an abstract idea, it is, in fact, a very concrete thing. UNIX assigns to each process a unique number called its process-id or pid. For example, at a given instant of time, several people might all be running the Gnu C compiler, gcc. Each separate execution instance of gcc is a process with its own unique pid. The ps command can be used to display which processes are running, and various options to it control what it outputs. At the programming level, the function getpid() returns the process-id of the process that invokes it. The program in Listing 1.3 does nothing other than printing its own process-id, but it illustrates how to use it. Shortly we will see that getpid() is an example of a system call.

Listing 1.3: A program using getpid().

#i n c l u d e #i n c l u d e i n t main ( ) (^5) In practice a directory entry is an object with two components: the name of a le and a pointer to a structure that contains the attributes of that le. (^6) For example, a map of how its logical addresses map to physical addresses, and a map of where the pieces of its logical address space reside on secondary storage.

Chapter 1 Introduction to System Programming

with the superuser's privileges. Processes running with user privileges are called user processes. At the programming level, the function getuid() returns the real user-id of the process that calls it, and the getgid() function returns the real group-id of the process that calls it.

1.3.4 Privileged and Non-Privileged Instructions

In order to prevent ordinary user processes from accessing hardware and performing other operations that may corrupt the state of the computer system, UNIX requires that the processor support two modes of operation, known as privileged and unprivileged mode^11. Privileged instructions are those that can alter system resources, directly or indirectly. Examples of privileged instructions include:

ˆ acquiring more memory;

ˆ changing the system time;

ˆ raising the priority of the running process;

ˆ reading from or writing to the disk;

ˆ entering privileged mode.

Only the operating system is allowed to execute privileged instructions. User processes can execute only the unprivileged instructions. The security and reliability of the operating system depend upon this separation of powers.

1.3.5 Environments

When a program is run in UNIX, one of the steps that the operating system takes prior to running the program is to make available to that program an array of name-value pairs called the environment. Each name-value pair is a string of the form

name=value

where value is a NULL-terminated C string. The name is called an environment variable and the pair name=value is called an environment string. The variables by convention contain only uppercase letters, digits, and underscores, but this is not required^12. The only requirement is that the name does not contain the = character. For example, LOGNAME is an environment variable that stores the user-name of the current user, and COLUMNS is a variable that stores the number of columns in the current console window^13. Even though it is a number, it is stored as a string.

When a user logs into a UNIX system, the operating system creates the environment for the user, based on various les in the system. From that point forward, whenever a new program runs, it is given a copy of that environment. This will be explained in greater depth later.

(^11) These modes are also known as supervisor mode and user mode. (^12) Environment variable names used by the utilities in the Shell and Utilities volume of POSIX.1-2008 consist solely of uppercase letters, digits, and the underscore ( '_' ) and do not begin with a digit. (^13) If the user denes a value for COLUMNS in a start-up script, then terminal windows will have that many columns. If the user does not dene it, or sets it to the NULL string, the size of terminal windows is determined by the operating system software.

Chapter 1 Introduction to System Programming

The printenv command displays the values of all environment variables as does the env command. Within a program the getenv() function can be used to retrieve a particular environment string, as in

char* username = getenv("LOGNAME"); printf("The user's user-name is %s\n, username);

The operating system also makes available to every running program an external global variable

extern char **environ;

which is a pointer to the start of the array of the name-value pairs in the running program's environment. Programs can read and modify these variables if they choose. For example, a program that needs to know how many columns are in the current terminal window will query the COLUMNS variable, whereas other programs may just ignore it.

1.3.6 Shells

The kernel provides services to processes, not to users; users interact with UNIX through a command- line interface called a shell. The word "shell" is the UNIX term for a particular type of command- line-interpreter. Command-line interpreters have been in operating systems since they were rst created. DOS uses a command-line-interpreter, as is the Command window of Microsoft Windows, which is simply a DOS emulator. The way that DOS and the Command window are used is similar to the way that UNIX is used^14 : you type a command and press the Enter key, and the com- mand is executed, after which the prompt reappears. The program that displays the prompt, reads the input you type, runs the appropriate programs in response and re-displays the prompt is the command-line-interpreter, which in UNIX is called a shell.

In UNIX, a shell is much more than a command-line-interpreter. It can do more than just read simple commands and execute them. A shell is also programming language interpreter; it allows the user to dene variables, evaluate expressions, use conditional control-of-ow statements such as while- and if-statements, and make calls to other programs. A sequence of shell commands can be saved into a le and executed as a program by typing the name of the le. Such a sequence of shell commands is called a shell script. When a shell script is run, the operating system starts up a shell process to read the instructions and execute them.

1.3.7 Online Documentation: The Man Pages

Shortly after Ritchie and Thompson wrote the rst version of UNIX, at the insistence of their manager, Doug McIlroy, in 1971, they wrote the UNIX Programmer's Manual. This manual was initially a single volume, but in short course it was extended into a set of seven volumes, organized by topic. It existed in both printed form and as formatted les for display on an ordinary character display device. Over time it grew in size. Every UNIX distribution comes with this set of manual pages, called manpages for short. Appendix B.4 contains a brief description of the structure of the manpages, and Chapter 2 provides more detail about how to use them. (^14) This is not a coincidence. Long before Microsoft wrote MS-DOS, they wrote a version of UNIX for the PC called Xenix, whose rights they sold to Santa Cruz Operations in 1987

Chapter 1 Introduction to System Programming

The kernel has full access to all of the hardware attached to the computer. User programs do not; they interact with the hardware indirectly through the kernel. The kernel maintains various system resources in order to provide these services to user programs. These system resources include many dierent data structures that keep track of I/O, memory, and device usage for example. In Section 1.4.1 this is explained in more detail.

Summarizing, if a user process needs data from the disk for example, it has to "ask" the kernel to get it. If a user process needs to write to the display, it has to "ask" the kernel to do this too. All processes gain access to devices and resources through the kernel. The kernel uses its resources to provide these services to user processes.

1.4.1 System Resources

The kernel provides many services to user programs, including

ˆ process scheduling and management,

ˆ I/O handling,

ˆ physical and virtual memory management,

ˆ device management,

ˆ le management,

ˆ signaling and inter-process communication,

ˆ multi-threading,

ˆ multi-tasking,

ˆ real-time signaling and scheduling, and

ˆ networking services.

Network services include protocols such as HTTP, NIS, NFS, X.25, SSH, SFTP, TCP/IP, and Java. Exactly which protocols are supported is not important; what is important is for you to understand that the kernel provides the means by which a user program can make requests for these services.

There are two dierent methods by which a program can make requests for services from the kernel:

ˆ by making a system call to a function (i.e., entry point) built directly into the kernel, or

ˆ by calling a higher-level library routine that makes use of this call.

Do not confuse either of these with a system program. The term "system program" refers to a separate program that is bundled with the kernel, that interfaces to it to achieve its functionality, and that provides higher level services to users. We can browse through the /bin or /usr/bin directories of a UNIX installation to nd many dierent system programs. Many UNIX commands are implemented by system programs.

Chapter 1 Introduction to System Programming

1.4.2 System Calls

An ordinary function call is a jump to and return from a subroutine that is part of the code linked into the program making the call, regardless of whether the subroutine is statically or dynamically linked into the code. A system call is like a conventional function call in that it causes a jump to a subroutine followed by a return to the caller. But it is signicantly dierent because it is a call to a function that is a part of the UNIX kernel.

The code that is executed during the call is actually kernel code. Since the kernel code accesses hardware and contains privileged instructions, kernel code must be run in privileged mode. Because the kernel alone runs in privileged mode, it is also commonly called kernel mode or superuser mode. Therefore, during a system call, the process that made the call is run in kernel mode. Unlike an ordinary function call, a system call requires a change in the execution mode of the processor; this is usually implemented by a trap instruction. The trap is typically invoked with special parameters that specify which system call to run. The method of implementing this is system dependent. In all cases, the point at which a user process begins to execute kernel code is a perilous point, and great care must be taken by operating system designers and the programmers who code the system call interfaces to make sure that it cannot be booby-trapped by malicious programmers trying to get their programs to run in kernel mode.

Programs do not usually invoke system calls directly. The C library provides wrappers for almost all system calls, and these usually have the same name as the call itself. A wrapper for a function f is a function that does little more than invoking f, usually rearranging or pre-processing its arguments, checking error conditions, and collecting its return value and possibly supplying it in a dierent form to the caller. Wrappers for system calls also have to trap into kernel mode before the call and restore user mode after the call. A wrapper is thin if it does almost nothing but pass through the arguments and the return values. Often, for example, the GNU C library wrapper function is very thin, doing little work other than copying arguments to the right registers before invoking the system call, and then setting the value of a global error variable^16 appropriately after the system call has returned.

Sometimes a wrapper is not so thin, as when the library function has to decide which of several alternative functions to invoke, depending upon what is available in the kernel. For example. there is a system call named truncate(), which can crop a le to a specied length, discarding the data after that length. The original truncate() function could only handle lengths that could t into a 32-bit integer, and when le systems were able to support very large les, a newer version named truncate64() was developed. The latter function can handle lengths representable in 64 bits in size. The wrapper for truncate() decides which one is provided by the kernel and calls it appropriately.

There may be system calls that do not have wrappers in the library, and for these, the programmer has no other choice but to invoke the system call with a special function named syscall(), passing the system call's identication number and arguments. Every system call has a unique number associated to it. Generally speaking, for a system call named foo, its number is dened by a macro named either __NR_foo or SYS_foo. The macro denitions are included by including the header le <sys/syscall.h> in the code. They may not be in that le itself; they may be another le, such as <asm/unistd_32.h> or <asm/unistd_64.h>. An example of a system call without a wrapper is

(^16) To be precise, the variable is named errno and it has thread local storage, which means each thread has its own unique copy and the lifetime of this variable is the entire lifetime of the thread.

Chapter 1 Introduction to System Programming

the kernel, as depicted in Figure 1.3. UNIX also contains libraries for various specialized tasks, such as asynchronous input and output, shared memory, terminal control, login and logout management, and so on. Using any of these libraries requires that the library's header le be included in the code with the appropriate #include directive (e.g. #include <termios.h>), and sometimes, that the library be linked explicitly because it is not in a standard place. Manpages for functions that are part of system libraries are contained in Volume 3 of the UNIX Manual Pages.

1.5 UNIX and Related Standards

1.5.1 The Problem

The very rst version of UNIX was written by Ken Thompson and Dennis Ritchie in 1969 while they were working for AT&T Bell Labs. Their edgling operating system turned out to be full of very novel ideas, and they presented these ideas in a seminal paper at the ACM Symposium on Operating Systems at IBM Yorktown Heights in 1973. In January 1974, the University of California at Berkeley (UCB) acquired Version 4 from Bell Labs and embarked on a mission to add modern features to UNIX. Later that year, AT&T began licensing UNIX to universities. From 1974 to 1979, UCB and AT&T worked on independent copies of UNIX. By 1978, the various versions of UNIX had most of the features that are found in it today, but not all in one system. But in 1979, AT&T did something that changed the playing eld; they staked proprietary rights to their own brand of UNIX, selling it commercially. In essence, they trademarked UNIX and made it expensive to own it.

BSD code was released under a much more generous license than AT&T's source and did not require a license fee or a requirement to be distributed with source unlike the GPL that the GNU Project and Linux use today. The result was that much BSD source code was incorporated into various commercial UNIX variants. By the time that 4.3BSD was written, almost none of the original AT&T source code was left in it. FreeBSD/NetBSD/OpenBSD were all forks of 4.3BSD having none of the original AT&T source code, and no right to the UNIX trademark, but much of their code found its way into commercial UNIX operating systems. In short, two major versions of UNIX came into existence  those based on BSD and those based on the AT&T version.

In 1991, the picture was further complicated by the creation of Linux. Linux was developed from scratch unlike BSD and it used the existing GNU Project which was a clean-room implementation of much of the UNIX user-space. It is a lot less like the AT&T UNIX than BSD is. In 1993, AT&T divested itself of UNIX, selling it to Novell, which one year later sold the trademark to an industry consortium known as X/Open.

There are now dozens of dierent UNIX distributions, each with its own dierent behavior. There are systems such as Solaris and UnixWare that are based on SVR4, the AT&T version released in 1989, and FreeBSD and OpenBSD based on the UC Berkeley distributions. Systems such as Linux are hybrids, as are AIX, IRIX, and HP-UX. It is natural to ask what makes a system UNIX. The answer is that over the course of the past thirty years or so, standards have been developed in order to dene UNIX. Operating systems can be branded as conforming to one standard or another.

1.5.2 The Solution: Standards

One widely accepted UNIX standard is the POSIX standard. Technically, POSIX does not dene UNIX in particular; it is more general than that. POSIX, which stands for Portable Operating

Chapter 1 Introduction to System Programming

System Interface, is a family of standards known formally as IEEE 1003. It is also published by the International Standards Organization (ISO) as ISO/IEC 9945:2003 ; these are one and the same doc- ument. The most recent version of POSIX is IEEE Std 1003.1-2008, also known as POSIX.1-2008. The POSIX.1-2008 standard consolidates the major standards preceding it, including POSIX.1, and the Single UNIX Specication (SUS ). The spirit of POSIX is to dene a UNIX system, as is stated in the Introduction to the specication (http://pubs.opengroup.org/onlinepubs/9699919799/):

The intended audience for POSIX.1-2008 is all persons concerned with an industry-wide standard operating system based on the UNIX system. This includes at least four groups of people:

Persons buying hardware and software systems Persons managing companies that are deciding on future corporate computing directions Persons implementing operating systems, and especially Persons developing applications where portability is an objective

The Single UNIX Specication was derived from an earlier standard written in 1994 known as the X/Open System Interface which itself was developed around a UNIX portability guide called the Spec 1170 Initiative, so called because it contained a description of exactly 1,170 distinct system calls, headers, commands, and utilities covered in the spec. The number of standardized elements has grown since then, as UNIX has grown.

The Single UNIX Specication was revised in 1997, 2001, and 2003 by The Open Group, which was formed in 1996 as a merger of X/Open and the Open Software Foundation (OSF ), both industry consortia. The Open Group owns the UNIX trademark. It uses the Single UNIX Specication to dene the interfaces an implementation must support to call itself a UNIX system.

What, then, does this standard standardize? It standardizes a number of things, including the collection of all system calls, the system libraries, and those utility programs such as grep, awk, and sed that make UNIX feel like UNIX. The collection of system calls is what denes the UNIX kernel. The system calls and system libraries together constitute the UNIX application programming interface. They are the programmer's view of the kernel. The utility programs are the part of the interface that the UNIX user sees.

From the Introduction again:

POSIX.1-2008 is simultaneously IEEE Std 1003.1—-2008 and The Open Group Technical Standard Base Specications, Issue 7. POSIX.1-2008 denes a standard operating system interface and environment, including a command interpreter (or shell), and common utility programs to support applica- tions portability at the source code level. POSIX.1-2008 is intended to be used by both application developers and system implementers [sic] and comprises four major components (each in an associated volume):

ˆ General terms, concepts, and interfaces common to all volumes of this standard, including utility conventions and C-language header denitions, are included in the Base Denitions volume.

Chapter 1 Introduction to System Programming

contains all of the library functions of the ISO C language. For example, every UNIX distribution includes libraries such as the C Standard I/O Library, the C math library, and the C string library.

The C Standard Library provided for Linux as well as several other UNIX distributions is the GNU C library, called GNU libc, or glibc. GNU often extends the C library, and not everything in it conforms to the ISO standard, nor to POSIX. What all of this amounts to is that the version of the C library on one system is not necessarily the same as that found on another system.

This is one reason why it is important to know the standard and know what it denes and what it does not dene. In general, the C standard describes what is required, what is prohibited, and what is allowed within certain limits. Specically, it describes

ˆ the representation of C programs

ˆ the syntax and constraints of the C language

ˆ the semantic rules for interpreting C programs

ˆ the representation of input data to be processed by C programs

ˆ the representation of output data produced by C programs

ˆ the restrictions and limits imposed by a conforming implementation of C

Not all compilers and C runtime libraries comply with the standard, and this complicates program- ming in C. The GNU compiler has command line options that let you compile according to various standards. For example, if you want your program to be compiled against the ANSI standard, you would use the command

$ gcc -ansi

or

$ gcc -std=c

To use the current ISO C11 standard, either of these works:

$ gcc -std=c $ gcc -std=iso9899:

Understanding how to write programs for UNIX requires knowing which features are part of C and which are there because they are part of UNIX. In other words, you will need to understand what the C libraries do and what the underlying UNIX system denes. Having a good grasp of the C standard will make this easier.

Chapter 1 Introduction to System Programming

1.7 Learning System Programming by Example

The number of system calls and library functions is so large that mere mortals cannot remember them all. Trying to learn all of the intricacies and details of the UNIX API by reading through reference manuals and user documentation would be a painstaking task. Fortunately, people often learn well by example. Rather than studying the reference manuals and documentation, we can learn the API little by little by writing programs that use it. One starts out simple, and over time adds complexity.

Bruce Molay [1] uses an excellent strategy for learning how to write system programs and discover the UNIX API:

  1. Pick an existing program that uses the API, such as a shell command;
  2. Using the system man pages and other information available online, investigate the system calls and kernel data structures that this program most likely uses in its implementation; and
  3. Write a new version of the program, iteratively improving it until it behaves just like the actual command.

By repeating this procedure over and over, one can familiarize oneself with the relevant portions of the API as well as the resources needed to learn about it. When it is time to write a full-edged application, the portions of it that must communicate with the kernel should be relatively easy to write. We will partly follow this same paradigm in this sequence of notes on UNIX.

1.8 The UNIX File Hierarchy

The typical UNIX le hierarchy has several directories just under the root. Figure 1.4 shows part of a typical, but hypothetical, le hierarchy. The following directories should be present in most UNIX systems, but they are not all required. The only required directories are /dev and /tmp.

Directory Purpose bin The repository for all essential binary executables including those shell commands that must be available when the computer is running in "single-user mode" (something like safe mode in Windows.) boot Static les of the boot loader dev The directory containing essential device les, which will be explained later. etc Where almost all host conguration les are stored. It is something like the registry le of Windows. home The directory where all user home directories are located, but not always. lib Essential shared libraries and kernel modules media Mount point for removable media mnt Mount point for mounting a le system temporarily opt Add-on application software packages sbin Essential system binaries srv Data for services provided by this system tmp Temporary les

Chapter 1 Introduction to System Programming

ple, /home/fac/sweiss is the absolute pathname to the directory sweiss in Figure 1.4, as is /home//fac///sweiss. The extra slashes are ignored. Observe that UNIX (actually POSIX) uses slashes, not backslashes, in pathnames: /usr/local, not \usr\local.

If a pathname does not begin with "/" it is called a relative pathname. When a process must resolve a relative pathname so that it can access the le, the pathname is assumed to start in the current working directory. In fact, the denition of the current working directory, also called the present working directory, is that it is the directory that a process uses to resolve pathnames that do not begin with a "/". For example, if the current working directory is /home/fac, then the pathname sweiss/testdata refers to a le whose absolute pathname is /home/fac/sweiss/testdata. The convention is to use pwd as a shorthand for the current working directory.

The environment variable PWD contains the absolute pathname of the current working directory. The command pwd prints the value of the PWD.

1.8.1.1 Working with Directories

This section may be skipped if you have experience working with directories at the user level. You do not need to know many commands in order to do most directory-related tasks in UNIX. This is a list of the basic commands. The principal tasks are navigation and displaying and altering their contents. The tables that follow give the command name and the simplest usage of it. They do not describe the various options or details of the command's usage.

Command Explanation pwd print the path of the current working directory (pwd) ls [] [] ... list the contents of the pwd, or , ... if supplied cd [

] change pwd to HOME directory, or if it is supplied mkdir [] ... create new directories (and ...) in the pwd; rmdir [] ... remove the EMPTY directory (and ...) rm -r remove all contents of and itself. Dangerous!! mv see the explanation in Section 1.8.

Notes

  1. The "p" in "pwd" stands for print, but it does not print on a printer. In UNIX, "printing" means displaying on the screen^20.
  2. mkdir is the only way to create a directory
  3. You cannot use rmdir to delete a directory if it is not empty.
  4. You can delete multiple directories and their contents with rm -r, but this is not reversible, so be careful.
  5. Commands that create and delete les are technically modifying directories, but these will be covered separately. (^20) That is why the C instruction printf sends output to the display device, not the printer. In FORTRAN, by contrast, the print instruction sent output to the printer.

Chapter 1 Introduction to System Programming

"Changing directories" and "being in a directory" are imprecise phrases. When you cd to a directory named dir, you may think of yourself as being in dir, but this is not true. What is true is that the dir directory is now your current working directory and that every process that you run from the shell process in which you changed directory, including the shell process, will use this dir directory by default when it is trying to resolve relative pathnames.

There are two special entries that are dened in every directory

. The directory itself

.. The parent directory of the directory, or itself if it is /

Thus, "cd .." changes the pwd to the parent of the current pwd, "cd ../.." changes it to the grandparent and "cd ." has no eect. Before reading further, you should experiment with these commands and make sure that you understand how they work.

1.8.2 Files and Filenames

Unlike other operating systems, UNIX distinguishes between only ve types of non-directory les:

ˆ regular les

ˆ device les (character or block)

ˆ FIFOs

ˆ sockets

ˆ symbolic links

Device les and FIFOs will be described in depth in Chapter 4, sockets in Chapter 9, and symbolic links below. That leaves regular les, which are dened quite simply: a regular le is a sequence of bytes with no particular structure.

1.8.2.1 Filenames

Files and lenames, as noted earlier, are dierent things. A lename, which is technically called a le link, or just a link, is just a string that names a le^21. A le may have many lenames. Filenames are practically unlimited in size, unless you think 255 characters is not big enough. The maximum number of bytes in a lename is contained in the system-dependent constant NAME_MAX. Filenames can contain any characters except "/" and the null character. They can have spaces and new lines, but if they do, you will usually need to put quotes around the name to use it as an argument to commands. UNIX is case-sensitive, so "References" and "references" are two dierent lenames.

Unlike DOS, Windows, and Apple operating systems, lename extensions are not used by the op- erating system for any purpose, although application-level software such as compilers and word

(^21) A lename is sometimes referred to as a "pathname component".