text
stringlengths 139
4.06k
| source
stringlengths 16
26
|
|---|---|
42 INTRODUCTION CHAP. 1 nice, clean abstract model of device-independent files. System calls are obviously needed to create files, remove files, read files, and write files. Before a file can be read, it must be located on the disk and opened, and after being read it should be closed, so calls are provided to do these things. To provide a place to keep files, most PC operating systems have the concept of a directory as a way of grouping files together. A student, for example, might have one directory for each course he is taking (for the programs needed for that course), another directory for his electronic mail, and still another directory for his World Wide Web home page. System calls are then needed to create and remove directories. Calls are also provided to put an existing file in a directory and to re- move a file from a directory. Directory entries may be either files or other direc- tories. This model also gives rise to a hierarchy—the file system—as shown in Fig. 1-14. Root directory Students Faculty Leo Prof.Brown Files Courses CS101 CS105 Papers Grants SOSP COST-11 Committees Prof.Green Prof.White Matty Robbert Figure 1-14. A file system for a university department. The process and file hierarchies both are organized as trees, but the similarity stops there. Process hierarchies usually are not very deep (more than three levels is unusual), whereas file hierarchies are commonly four, fiv e, or even more levels deep. Process hierarchies are typically short-lived, generally minutes at most, whereas the directory hierarchy may exist for years. Ownership and protection also differ for processes and files. Typically, only a parent process may control or even
|
OS_Page_42_Chunk42
|
SEC. 1.5 OPERATING SYSTEM CONCEPTS 43 access a child process, but mechanisms nearly always exist to allow files and direc- tories to be read by a wider group than just the owner. Every file within the directory hierarchy can be specified by giving its path name from the top of the directory hierarchy, the root directory. Such absolute path names consist of the list of directories that must be traversed from the root di- rectory to get to the file, with slashes separating the components. In Fig. 1-14, the path for file CS101 is /Faculty/Prof.Brown/Courses/CS101. The leading slash indi- cates that the path is absolute, that is, starting at the root directory. As an aside, in Windows, the backslash (\) character is used as the separator instead of the slash (/) character (for historical reasons), so the file path given above would be written as \Faculty\Prof.Brown\Courses\CS101. Throughout this book we will generally use the UNIX convention for paths. At every instant, each process has a current working directory, in which path names not beginning with a slash are looked for. For example, in Fig. 1-14, if /Faculty/Prof.Brown were the working directory, use of the path Courses/CS101 would yield the same file as the absolute path name given above. Processes can change their working directory by issuing a system call specifying the new work- ing directory. Before a file can be read or written, it must be opened, at which time the per- missions are checked. If the access is permitted, the system returns a small integer called a file descriptor to use in subsequent operations. If the access is prohibited, an error code is returned. Another important concept in UNIX is the mounted file system. Most desktop computers have one or more optical drives into which CD-ROMs, DVDs, and Blu- ray discs can be inserted. They almost always have USB ports, into which USB memory sticks (really, solid state disk drives) can be plugged, and some computers have floppy disks or external hard disks. To provide an elegant way to deal with these removable media UNIX allows the file system on the optical disc to be at- tached to the main tree. Consider the situation of Fig. 1-15(a). Before the mount call, the root file system, on the hard disk, and a second file system, on a CD- ROM, are separate and unrelated. However, the file system on the CD-ROM cannot be used, because there is no way to specify path names on it. UNIX does not allow path names to be prefixed by a drive name or number; that would be precisely the kind of device dependence that operating systems ought to eliminate. Instead, the mount system call allows the file system on the CD-ROM to be attached to the root file system wherever the program wants it to be. In Fig. 1-15(b) the file system on the CD-ROM has been mounted on directory b, thus allowing access to files /b/x and /b/y. If directory b had contained any files they would not be accessible while the CD-ROM was mounted, since /b would refer to the root directory of the CD-ROM. (Not being able to access these files is not as serious as it at first seems: file systems are nearly always mounted on empty directories.) If a system contains multiple hard disks, they can all be mounted into a single tree as well.
|
OS_Page_43_Chunk43
|
44 INTRODUCTION CHAP. 1 Root CD-ROM a b c d c d a b x y x y (a) (b) Figure 1-15. (a) Before mounting, the files on the CD-ROM are not accessible. (b) After mounting, they are part of the file hierarchy. Another important concept in UNIX is the special file. Special files are pro- vided in order to make I/O devices look like files. That way, they can be read and written using the same system calls as are used for reading and writing files. Two kinds of special files exist: block special files and character special files. Block special files are used to model devices that consist of a collection of randomly ad- dressable blocks, such as disks. By opening a block special file and reading, say, block 4, a program can directly access the fourth block on the device, without regard to the structure of the file system contained on it. Similarly, character spe- cial files are used to model printers, modems, and other devices that accept or out- put a character stream. By convention, the special files are kept in the /dev direc- tory. For example, /dev/lp might be the printer (once called the line printer). The last feature we will discuss in this overview relates to both processes and files: pipes. A pipe is a sort of pseudofile that can be used to connect two proc- esses, as shown in Fig. 1-16. If processes A and B wish to talk using a pipe, they must set it up in advance. When process A wants to send data to process B, it writes on the pipe as though it were an output file. In fact, the implementation of a pipe is very much like that of a file. Process B can read the data by reading from the pipe as though it were an input file. Thus, communication between processes in UNIX looks very much like ordinary file reads and writes. Stronger yet, the only way a process can discover that the output file it is writing on is not really a file, but a pipe, is by making a special system call. File systems are very important. We will have much more to say about them in Chap. 4 and also in Chaps. 10 and 11. Process Pipe Process A B Figure 1-16. Tw o processes connected by a pipe.
|
OS_Page_44_Chunk44
|
SEC. 1.5 OPERATING SYSTEM CONCEPTS 45 1.5.4 Input/Output All computers have physical devices for acquiring input and producing output. After all, what good would a computer be if the users could not tell it what to do and could not get the results after it did the work requested? Many kinds of input and output devices exist, including keyboards, monitors, printers, and so on. It is up to the operating system to manage these devices. Consequently, every operating system has an I/O subsystem for managing its I/O devices. Some of the I/O software is device independent, that is, applies to many or all I/O devices equally well. Other parts of it, such as device drivers, are specific to particular I/O devices. In Chap. 5 we will have a look at I/O software. 1.5.5 Protection Computers contain large amounts of information that users often want to pro- tect and keep confidential. This information may include email, business plans, tax returns, and much more. It is up to the operating system to manage the system se- curity so that files, for example, are accessible only to authorized users. As a simple example, just to get an idea of how security can work, consider UNIX. Files in UNIX are protected by assigning each one a 9-bit binary protec- tion code. The protection code consists of three 3-bit fields, one for the owner, one for other members of the owner’s group (users are divided into groups by the sys- tem administrator), and one for everyone else. Each field has a bit for read access, a bit for write access, and a bit for execute access. These 3 bits are known as the rwx bits. For example, the protection code rwxr-x--x means that the owner can read, write, or execute the file, other group members can read or execute (but not write) the file, and everyone else can execute (but not read or write) the file. For a directory, x indicates search permission. A dash means that the corresponding per- mission is absent. In addition to file protection, there are many other security issues. Protecting the system from unwanted intruders, both human and nonhuman (e.g., viruses) is one of them. We will look at various security issues in Chap. 9. 1.5.6 The Shell The operating system is the code that carries out the system calls. Editors, compilers, assemblers, linkers, utility programs, and command interpreters defi- nitely are not part of the operating system, even though they are important and use- ful. At the risk of confusing things somewhat, in this section we will look briefly at the UNIX command interpreter, the shell. Although it is not part of the operat- ing system, it makes heavy use of many operating system features and thus serves as a good example of how the system calls are used. It is also the main interface
|
OS_Page_45_Chunk45
|
46 INTRODUCTION CHAP. 1 between a user sitting at his terminal and the operating system, unless the user is using a graphical user interface. Many shells exist, including sh, csh, ksh, and bash. All of them support the functionality described below, which derives from the orig- inal shell (sh). When any user logs in, a shell is started up. The shell has the terminal as stan- dard input and standard output. It starts out by typing the prompt, a character such as a dollar sign, which tells the user that the shell is waiting to accept a com- mand. If the user now types date for example, the shell creates a child process and runs the date program as the child. While the child process is running, the shell waits for it to terminate. When the child finishes, the shell types the prompt again and tries to read the next input line. The user can specify that standard output be redirected to a file, for example, date >file Similarly, standard input can be redirected, as in sor t <file1 >file2 which invokes the sort program with input taken from file1 and output sent to file2. The output of one program can be used as the input for another program by connecting them with a pipe. Thus cat file1 file2 file3 | sort >/dev/lp invokes the cat program to concatenate three files and send the output to sort to arrange all the lines in alphabetical order. The output of sort is redirected to the file /dev/lp, typically the printer. If a user puts an ampersand after a command, the shell does not wait for it to complete. Instead it just gives a prompt immediately. Consequently, cat file1 file2 file3 | sort >/dev/lp & starts up the sort as a background job, allowing the user to continue working nor- mally while the sort is going on. The shell has a number of other interesting fea- tures, which we do not have space to discuss here. Most books on UNIX discuss the shell at some length (e.g., Kernighan and Pike, 1984; Quigley, 2004; Robbins, 2005). Most personal computers these days use a GUI. In fact, the GUI is just a pro- gram running on top of the operating system, like a shell. In Linux systems, this fact is made obvious because the user has a choice of (at least) two GUIs: Gnome and KDE or none at all (using a terminal window on X11). In Windows, it is also possible to replace the standard GUI desktop (Windows Explorer) with a different program by changing some values in the registry, although few people do this.
|
OS_Page_46_Chunk46
|
SEC. 1.5 OPERATING SYSTEM CONCEPTS 47 1.5.7 Ontogeny Recapitulates Phylogeny After Charles Darwin’s book On the Origin of the Species was published, the German zoologist Ernst Haeckel stated that ‘‘ontogeny recapitulates phylogeny.’’ By this he meant that the development of an embryo (ontogeny) repeats (i.e., reca- pitulates) the evolution of the species (phylogeny). In other words, after fertiliza- tion, a human egg goes through stages of being a fish, a pig, and so on before turn- ing into a human baby. Modern biologists regard this as a gross simplification, but it still has a kernel of truth in it. Something vaguely analogous has happened in the computer industry. Each new species (mainframe, minicomputer, personal computer, handheld, embedded computer, smart card, etc.) seems to go through the development that its ancestors did, both in hardware and in software. We often forget that much of what happens in the computer business and a lot of other fields is technology driven. The reason the ancient Romans lacked cars is not that they liked walking so much. It is be- cause they did not know how to build cars. Personal computers exist not because millions of people have a centuries-old pent-up desire to own a computer, but be- cause it is now possible to manufacture them cheaply. We often forget how much technology affects our view of systems and it is worth reflecting on this point from time to time. In particular, it frequently happens that a change in technology renders some idea obsolete and it quickly vanishes. However, another change in technology could revive it again. This is especially true when the change has to do with the relative performance of different parts of the system. For instance, when CPUs became much faster than memories, caches became important to speed up the ‘‘slow’’ memory. If new memory technology someday makes memories much faster than CPUs, caches will vanish. And if a new CPU technology makes them faster than memories again, caches will reappear. In biology, extinction is forever, but in computer science, it is sometimes only for a few years. As a consequence of this impermanence, in this book we will from time to time look at ‘‘obsolete’’ concepts, that is, ideas that are not optimal with current technology. Howev er, changes in the technology may bring back some of the so-called ‘‘obsolete concepts.’’ For this reason, it is important to understand why a concept is obsolete and what changes in the environment might bring it back again. To make this point clearer, let us consider a simple example. Early computers had hardwired instruction sets. The instructions were executed directly by hard- ware and could not be changed. Then came microprogramming (first introduced on a large scale with the IBM 360), in which an underlying interpreter carried out the ‘‘hardware instructions’’ in software. Hardwired execution became obsolete. It was not flexible enough. Then RISC computers were invented, and micropro- gramming (i.e., interpreted execution) became obsolete because direct execution was faster. Now we are seeing the resurgence of interpretation in the form of Java applets that are sent over the Internet and interpreted upon arrival. Execution speed
|
OS_Page_47_Chunk47
|
48 INTRODUCTION CHAP. 1 is not always crucial because network delays are so great that they tend to domi- nate. Thus the pendulum has already swung several cycles between direct execu- tion and interpretation and may yet swing again in the future. Large Memories Let us now examine some historical developments in hardware and how they have affected software repeatedly. The first mainframes had limited memory. A fully loaded IBM 7090 or 7094, which played king of the mountain from late 1959 until 1964, had just over 128 KB of memory. It was mostly programmed in assem- bly language and its operating system was written in assembly language to save precious memory. As time went on, compilers for languages like FORTRAN and COBOL got good enough that assembly language was pronounced dead. But when the first commercial minicomputer (the PDP-1) was released, it had only 4096 18-bit words of memory, and assembly language made a surprise comeback. Eventually, mini- computers acquired more memory and high-level languages became prevalent on them. When microcomputers hit in the early 1980s, the first ones had 4-KB memo- ries and assembly-language programming rose from the dead. Embedded com- puters often used the same CPU chips as the microcomputers (8080s, Z80s, and later 8086s) and were also programmed in assembler initially. Now their descen- dants, the personal computers, have lots of memory and are programmed in C, C++, Java, and other high-level languages. Smart cards are undergoing a similar development, although beyond a certain size, the smart cards often have a Java interpreter and execute Java programs interpretively, rather than having Java being compiled to the smart card’s machine language. Protection Hardware Early mainframes, like the IBM 7090/7094, had no protection hardware, so they just ran one program at a time. A buggy program could wipe out the operat- ing system and easily crash the machine. With the introduction of the IBM 360, a primitive form of hardware protection became available. These machines could then hold several programs in memory at the same time and let them take turns running (multiprogramming). Monoprogramming was declared obsolete. At least until the first minicomputer showed up—without protection hard- ware—so multiprogramming was not possible. Although the PDP-1 and PDP-8 had no protection hardware, eventually the PDP-11 did, and this feature led to mul- tiprogramming and eventually to UNIX. When the first microcomputers were built, they used the Intel 8080 CPU chip, which had no hardware protection, so we were back to monoprogramming—one program in memory at a time. It was not until the Intel 80286 chip that protection
|
OS_Page_48_Chunk48
|
SEC. 1.5 OPERATING SYSTEM CONCEPTS 49 hardware was added and multiprogramming became possible. Until this day, many embedded systems have no protection hardware and run just a single program. Now let us look at operating systems. The first mainframes initially had no protection hardware and no support for multiprogramming, so they ran simple op- erating systems that handled one manually loaded program at a time. Later they ac- quired the hardware and operating system support to handle multiple programs at once, and then full timesharing capabilities. When minicomputers first appeared, they also had no protection hardware and ran one manually loaded program at a time, even though multiprogramming was well established in the mainframe world by then. Gradually, they acquired protec- tion hardware and the ability to run two or more programs at once. The first microcomputers were also capable of running only one program at a time, but later acquired the ability to multiprogram. Handheld computers and smart cards went the same route. In all cases, the software development was dictated by technology. The first microcomputers, for example, had something like 4 KB of memory and no protec- tion hardware. High-level languages and multiprogramming were simply too much for such a tiny system to handle. As the microcomputers evolved into modern per- sonal computers, they acquired the necessary hardware and then the necessary soft- ware to handle more advanced features. It is likely that this development will con- tinue for years to come. Other fields may also have this wheel of reincarnation, but in the computer industry it seems to spin faster. Disks Early mainframes were largely magnetic-tape based. They would read in a pro- gram from tape, compile it, run it, and write the results back to another tape. There were no disks and no concept of a file system. That began to change when IBM introduced the first hard disk—the RAMAC (RAndoM ACcess) in 1956. It occu- pied about 4 square meters of floor space and could store 5 million 7-bit charac- ters, enough for one medium-resolution digital photo. But with an annual rental fee of $35,000, assembling enough of them to store the equivalent of a roll of film got pricey quite fast. But eventually prices came down and primitive file systems were developed. Typical of these new dev elopments was the CDC 6600, introduced in 1964 and for years by far the fastest computer in the world. Users could create so-called ‘‘permanent files’’ by giving them names and hoping that no other user had also decided that, say, ‘‘data’’ was a suitable name for a file. This was a single-level di- rectory. Eventually, mainframes developed complex hierarchical file systems, per- haps culminating in the MULTICS file system. As minicomputers came into use, they eventually also had hard disks. The standard disk on the PDP-11 when it was introduced in 1970 was the RK05 disk, with a capacity of 2.5 MB, about half of the IBM RAMAC, but it was only about
|
OS_Page_49_Chunk49
|
50 INTRODUCTION CHAP. 1 40 cm in diameter and 5 cm high. But it, too, had a single-level directory initially. When microcomputers came out, CP/M was initially the dominant operating sys- tem, and it, too, supported just one directory on the (floppy) disk. Virtual Memory Virtual memory (discussed in Chap. 3) gives the ability to run programs larger than the machine’s physical memory by rapidly moving pieces back and forth be- tween RAM and disk. It underwent a similar development, first appearing on mainframes, then moving to the minis and the micros. Virtual memory also allow- ed having a program dynamically link in a library at run time instead of having it compiled in. MULTICS was the first system to allow this. Eventually, the idea propagated down the line and is now widely used on most UNIX and Windows systems. In all these developments, we see ideas invented in one context and later thrown out when the context changes (assembly-language programming, monopro- gramming, single-level directories, etc.) only to reappear in a different context often a decade later. For this reason in this book we will sometimes look at ideas and algorithms that may seem dated on today’s gigabyte PCs, but which may soon come back on embedded computers and smart cards. 1.6 SYSTEM CALLS We hav e seen that operating systems have two main functions: providing abstractions to user programs and managing the computer’s resources. For the most part, the interaction between user programs and the operating system deals with the former; for example, creating, writing, reading, and deleting files. The re- source-management part is largely transparent to the users and done automatically. Thus, the interface between user programs and the operating system is primarily about dealing with the abstractions. To really understand what operating systems do, we must examine this interface closely. The system calls available in the inter- face vary from one operating system to another (although the underlying concepts tend to be similar). We are thus forced to make a choice between (1) vague generalities (‘‘operat- ing systems have system calls for reading files’’) and (2) some specific system (‘‘UNIX has a read system call with three parameters: one to specify the file, one to tell where the data are to be put, and one to tell how many bytes to read’’). We hav e chosen the latter approach. It’s more work that way, but it gives more insight into what operating systems really do. Although this discussion specifically refers to POSIX (International Standard 9945-1), hence also to UNIX, System V, BSD, Linux, MINIX 3, and so on, most other modern operating systems have sys- tem calls that perform the same functions, even if the details differ. Since the actual
|
OS_Page_50_Chunk50
|
SEC. 1.6 SYSTEM CALLS 51 mechanics of issuing a system call are highly machine dependent and often must be expressed in assembly code, a procedure library is provided to make it possible to make system calls from C programs and often from other languages as well. It is useful to keep the following in mind. Any single-CPU computer can ex- ecute only one instruction at a time. If a process is running a user program in user mode and needs a system service, such as reading data from a file, it has to execute a trap instruction to transfer control to the operating system. The operating system then figures out what the calling process wants by inspecting the parameters. Then it carries out the system call and returns control to the instruction following the system call. In a sense, making a system call is like making a special kind of pro- cedure call, only system calls enter the kernel and procedure calls do not. To make the system-call mechanism clearer, let us take a quick look at the read system call. As mentioned above, it has three parameters: the first one specifying the file, the second one pointing to the buffer, and the third one giving the number of bytes to read. Like nearly all system calls, it is invoked from C programs by cal- ling a library procedure with the same name as the system call: read. A call from a C program might look like this: count = read(fd, buffer, nbytes); The system call (and the library procedure) return the number of bytes actually read in count. This value is normally the same as nbytes, but may be smaller, if, for example, end-of-file is encountered while reading. If the system call cannot be carried out owing to an invalid parameter or a disk error, count is set to −1, and the error number is put in a global variable, errno. Programs should always check the results of a system call to see if an error oc- curred. System calls are performed in a series of steps. To make this concept clearer, let us examine the read call discussed above. In preparation for calling the read li- brary procedure, which actually makes the read system call, the calling program first pushes the parameters onto the stack, as shown in steps 1–3 in Fig. 1-17. C and C++ compilers push the parameters onto the stack in reverse order for historical reasons (having to do with making the first parameter to printf, the for- mat string, appear on top of the stack). The first and third parameters are called by value, but the second parameter is passed by reference, meaning that the address of the buffer (indicated by &) is passed, not the contents of the buffer. Then comes the actual call to the library procedure (step 4). This instruction is the normal proce- dure-call instruction used to call all procedures. The library procedure, possibly written in assembly language, typically puts the system-call number in a place where the operating system expects it, such as a register (step 5). Then it executes a TRAP instruction to switch from user mode to kernel mode and start execution at a fixed address within the kernel (step 6). The TRAP instruction is actually fairly similar to the procedure-call instruction in the
|
OS_Page_51_Chunk51
|
52 INTRODUCTION CHAP. 1 Return to caller 4 10 6 0 9 7 8 3 2 1 11 Dispatch Sys call handler Address 0xFFFFFFFF User space Kernel space (Operating system) Library procedure read User program calling read Trap to the kernel Put code for read in register Increment SP Call read Push fd Push &buffer Push nbytes 5 Figure 1-17. The 11 steps in making the system call read(fd, buffer, nbytes). sense that the instruction following it is taken from a distant location and the return address is saved on the stack for use later. Nevertheless, the TRAP instruction also differs from the procedure-call instruc- tion in two fundamental ways. First, as a side effect, it switches into kernel mode. The procedure call instruction does not change the mode. Second, rather than giv- ing a relative or absolute address where the procedure is located, the TRAP instruc- tion cannot jump to an arbitrary address. Depending on the architecture, either it jumps to a single fixed location or there is an 8-bit field in the instruction giving the index into a table in memory containing jump addresses, or equivalent. The kernel code that starts following the TRAP examines the system-call num- ber and then dispatches to the correct system-call handler, usually via a table of pointers to system-call handlers indexed on system-call number (step 7). At that point the system-call handler runs (step 8). Once it has completed its work, control may be returned to the user-space library procedure at the instruction following the TRAP instruction (step 9). This procedure then returns to the user program in the usual way procedure calls return (step 10). To finish the job, the user program has to clean up the stack, as it does after any procedure call (step 11). Assuming the stack grows downward, as it often
|
OS_Page_52_Chunk52
|
SEC. 1.6 SYSTEM CALLS 53 does, the compiled code increments the stack pointer exactly enough to remove the parameters pushed before the call to read. The program is now free to do whatever it wants to do next. In step 9 above, we said ‘‘may be returned to the user-space library procedure’’ for good reason. The system call may block the caller, preventing it from continu- ing. For example, if it is trying to read from the keyboard and nothing has been typed yet, the caller has to be blocked. In this case, the operating system will look around to see if some other process can be run next. Later, when the desired input is available, this process will get the attention of the system and run steps 9–11. In the following sections, we will examine some of the most heavily used POSIX system calls, or more specifically, the library procedures that make those system calls. POSIX has about 100 procedure calls. Some of the most important ones are listed in Fig. 1-18, grouped for convenience in four categories. In the text we will briefly examine each call to see what it does. To a large extent, the services offered by these calls determine most of what the operating system has to do, since the resource management on personal com- puters is minimal (at least compared to big machines with multiple users). The services include things like creating and terminating processes, creating, deleting, reading, and writing files, managing directories, and performing input and output. As an aside, it is worth pointing out that the mapping of POSIX procedure calls onto system calls is not one-to-one. The POSIX standard specifies a number of procedures that a conformant system must supply, but it does not specify wheth- er they are system calls, library calls, or something else. If a procedure can be car- ried out without invoking a system call (i.e., without trapping to the kernel), it will usually be done in user space for reasons of performance. However, most of the POSIX procedures do invoke system calls, usually with one procedure mapping di- rectly onto one system call. In a few cases, especially where several required pro- cedures are only minor variations of one another, one system call handles more than one library call. 1.6.1 System Calls for Process Management The first group of calls in Fig. 1-18 deals with process management. Fork is a good place to start the discussion. Fork is the only way to create a new process in POSIX. It creates an exact duplicate of the original process, including all the file descriptors, registers—everything. After the fork, the original process and the copy (the parent and child) go their separate ways. All the variables have identical val- ues at the time of the fork, but since the parent’s data are copied to create the child, subsequent changes in one of them do not affect the other one. (The program text, which is unchangeable, is shared between parent and child.) The fork call returns a value, which is zero in the child and equal to the child’s PID (Process IDentifier) in the parent. Using the returned PID, the two processes can see which one is the parent process and which one is the child process.
|
OS_Page_53_Chunk53
|
54 INTRODUCTION CHAP. 1 Process management Call Description pid = for k( ) Create a child process identical to the parent pid = waitpid(pid, &statloc, options) Wait for a child to terminate s = execve(name, argv, environp) Replace a process’ core image exit(status) Ter minate process execution and return status File management Call Description fd = open(file, how, ...) Open a file for reading, writing, or both s = close(fd) Close an open file n = read(fd, buffer, nbytes) Read data from a file into a buffer n = write(fd, buffer, nbytes) Write data from a buffer into a file position = lseek(fd, offset, whence) Move the file pointer s = stat(name, &buf) Get a file’s status infor mation Director y- and file-system management Call Description s = mkdir(name, mode) Create a new director y s = rmdir(name) Remove an empty directory s = link(name1, name2) Create a new entr y, name2, pointing to name1 s = unlink(name) Remove a director y entr y s = mount(special, name, flag) Mount a file system s = umount(special) Unmount a file system Miscellaneous Call Description s = chdir(dir name) Change the wor king director y s = chmod(name, mode) Change a file’s protection bits s = kill(pid, signal) Send a signal to a process seconds = time(&seconds) Get the elapsed time since Jan. 1, 1970 Figure 1-18. Some of the major POSIX system calls. The return code s is −1 if an error has occurred. The return codes are as follows: pid is a process id, fd is a file descriptor, n is a byte count, position is an offset within the file, and seconds is the elapsed time. The parameters are explained in the text. In most cases, after a fork, the child will need to execute different code from the parent. Consider the case of the shell. It reads a command from the terminal, forks off a child process, waits for the child to execute the command, and then reads the next command when the child terminates. To wait for the child to finish,
|
OS_Page_54_Chunk54
|
SEC. 1.6 SYSTEM CALLS 55 the parent executes a waitpid system call, which just waits until the child terminates (any child if more than one exists). Waitpid can wait for a specific child, or for any old child by setting the first parameter to −1. When waitpid completes, the address pointed to by the second parameter, statloc, will be set to the child process’ exit status (normal or abnormal termination and exit value). Various options are also provided, specified by the third parameter. For example, returning immediately if no child has already exited. Now consider how fork is used by the shell. When a command is typed, the shell forks off a new process. This child process must execute the user command. It does this by using the execve system call, which causes its entire core image to be replaced by the file named in its first parameter. (Actually, the system call itself is exec, but several library procedures call it with different parameters and slightly different names. We will treat these as system calls here.) A highly simplified shell illustrating the use of fork, waitpid, and execve is shown in Fig. 1-19. #define TRUE 1 while (TRUE) { /* repeat forever */ type prompt( ); /* display prompt on the screen */ read command(command, parameters); /* read input from terminal */ if (for k( ) != 0) { /* fork off child process */ /* Parent code. */ waitpid(−1, &status, 0); /* wait for child to exit */ } else { /* Child code. */ execve(command, parameters, 0); /* execute command */ } } Figure 1-19. A stripped-down shell. Throughout this book, TRUE is assumed to be defined as 1. In the most general case, execve has three parameters: the name of the file to be executed, a pointer to the argument array, and a pointer to the environment array. These will be described shortly. Various library routines, including execl, execv, execle, and execve, are provided to allow the parameters to be omitted or specified in various ways. Throughout this book we will use the name exec to represent the system call invoked by all of these. Let us consider the case of a command such as cp file1 file2 used to copy file1 to file2. After the shell has forked, the child process locates and executes the file cp and passes to it the names of the source and target files.
|
OS_Page_55_Chunk55
|
56 INTRODUCTION CHAP. 1 The main program of cp (and main program of most other C programs) con- tains the declaration main(argc, argv, envp) where argc is a count of the number of items on the command line, including the program name. For the example above, argc is 3. The second parameter, argv, is a pointer to an array. Element i of that array is a pointer to the ith string on the command line. In our example, argv[0] would point to the string ‘‘cp’’, argv[1] would point to the string ‘‘file1’’, and argv[2] would point to the string ‘‘file2’’. The third parameter of main, envp, is a pointer to the environment, an array of strings containing assignments of the form name = value used to pass information such as the terminal type and home directory name to programs. There are library procedures that programs can call to get the environment variables, which are often used to customize how a user wants to perform certain tasks (e.g., the default print- er to use). In Fig. 1-19, no environment is passed to the child, so the third parame- ter of execve is a zero. If exec seems complicated, do not despair; it is (semantically) the most com- plex of all the POSIX system calls. All the other ones are much simpler. As an ex- ample of a simple one, consider exit, which processes should use when they are finished executing. It has one parameter, the exit status (0 to 255), which is re- turned to the parent via statloc in the waitpid system call. Processes in UNIX have their memory divided up into three segments: the text segment (i.e., the program code), the data segment (i.e., the variables), and the stack segment. The data segment grows upward and the stack grows downward, as shown in Fig. 1-20. Between them is a gap of unused address space. The stack grows into the gap automatically, as needed, but expansion of the data segment is done explicitly by using a system call, br k, which specifies the new address where the data segment is to end. This call, however, is not defined by the POSIX stan- dard, since programmers are encouraged to use the malloc library procedure for dynamically allocating storage, and the underlying implementation of malloc was not thought to be a suitable subject for standardization since few programmers use it directly and it is doubtful that anyone even notices that br k is not in POSIX. 1.6.2 System Calls for File Management Many system calls relate to the file system. In this section we will look at calls that operate on individual files; in the next one we will examine those that involve directories or the file system as a whole. To read or write a file, it must first be opened. This call specifies the file name to be opened, either as an absolute path name or relative to the working directory, as well as a code of O RDONLY, O WRONLY, or O RDWR, meaning open for reading, writing, or both. To create a new file, the O CREAT parameter is used.
|
OS_Page_56_Chunk56
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.