Download 1.1 What is an Operating System?

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Computer terminal wikipedia , lookup

Acorn MOS wikipedia , lookup

Commodore DOS wikipedia , lookup

Library (computing) wikipedia , lookup

MTS system architecture wikipedia , lookup

Security-focused operating system wikipedia , lookup

Copland (operating system) wikipedia , lookup

Distributed operating system wikipedia , lookup

Batch file wikipedia , lookup

Windows NT startup process wikipedia , lookup

OS 2200 wikipedia , lookup

Plan 9 from Bell Labs wikipedia , lookup

RSTS/E wikipedia , lookup

Process management (computing) wikipedia , lookup

Paging wikipedia , lookup

Burroughs MCP wikipedia , lookup

DNIX wikipedia , lookup

Spring (operating system) wikipedia , lookup

CP/M wikipedia , lookup

VS/9 wikipedia , lookup

Unix security wikipedia , lookup

Transcript
1
_________________________________________________________________________________
CS323-650 Operating Systems
Chapter 1
Introduction
1.1 What is an Operating System?
A computer system can be roughly divided into four components: the hardware, the
operating system, the application programs, and the users (Figure 1.1).
User 1
Banking system
User 2
Airline reservation
User n
…
Web browser
application programs
compiler
editors
command interpreter
operating system
computer hardware
(machine language,
microprogramming,
physical devices)
Figure 1.1 Abstract view of the components of a computer system.
We can view an operating system as a resource manager. A computer system has many
resources (hardware and software) that may be required to solve a problem: CPU time, memory
space, file storage space, I/O devices, and so on. The operating system acts as the manager of
these resources and allocates them to specific programs and users as necessary for the latter’s
tasks. Since there may be, possibly conflicting, requests for resources, the operating system must
decide which requests are allocated resources to operate the computer system efficiently and fairly.
Another different view of an operating system is as the extended machine. The function of
operating system is to present the user with the equivalent of an extended machine that is easier to
use than the underlying hardware. For example, in the case of disks, a typical abstraction would be
Computer Science, Prince of Songkla University
2
_________________________________________________________________________________
that the disks contains a collection of named files. Each file can be opened for reading or writing,
then read or written, and finally closed. Details such as whether or not recording should use modified
frequency modulation and what the current state of the motor is should not appear in the abstraction
presented to the user. The interface between the operating system and the user program is defined
by the set of “extended instructions” that the operating system provides. These extended instructions
have been traditionally know as system calls, although they can be implemented in several ways
(such as DOS interrupt) now.
CS323-650 Operating Systems
1.2 Computer System Structures
In older systems, data transfer was under the CPU control. The CPU had to execute, or at
least to monitor, the data transfer, disallowing the overlapping of CPU and I/O operations. For CPU
and I/O operations to overlap, they must have a mechanism to allow a desynchronization and
resynchonization of operation. Either of the following methods can be used; some systems use both:
 Interrupt-driven data transfer
 Direct-memory-access (DMA) data transfer
We called the interrupt-based systems. The general structure of and interrupt-based system is
depicted in Figure 1.2.
CPU
Disk
controller
Cardreader
controller
Tapedrive
controller
Memory controller
memory
Figure 1.2 Interrupt-based computer system.
Each device controller is in charge of a specific type of device (for example, disk drives,
tape drives, line printers). A device controller maintains some local buffer storage and a set of
special purpose registers. The device controller is responsible for moving data between the
peripheral device it controls and its local buffer storage.
To start an I/O, the CPU loads the appropriate registers within the device controller and then
resumes its normal operation. The device controller, in turn, examines the contents of these registers
Computer Science, Prince of Songkla University
3
_________________________________________________________________________________
to determine what action to take. For example, if it finds a read request, the controller will start the
transfer of data from the device to its local buffer. Once the transfer of data is complete, the device
controller informs the CPU that it has finished its operation. It accomplishes this communication by
causing an interrupt. When the CPU is interrupted, it stops what it is doing and transfers execution to
a fixed location. The fixed location usually contains the starting address where the service routine for
the interrupt is located. The interrupt service routine transfers data from the local buffer of the device
controller to main memory. Once this transfer is accomplished, the CPU can then resume the
interrupted computation. In this way, I/O devices and the CPU can be operated concurrently.
Usually, interrupts are disabled while an interrupt is being processed, delaying the incoming interrupt
until the operating system is done with the current one and interrupts are enabled. If they were not
thus disabled, the processing of the second interrupt while the first was being serviced would
overwrite the first’s data, and the first would be a lost interrupt. Sophisticated interrupt architectures
allow for one interrupt to be processed during another, often by a priority scheme in which request
types are assigned priorities according to their relative importance, and interrupt processing
information is stored separately for each priority. A higher-priority interrupt will be taken even if a
lower-priority interrupt is active, but interrupts at the same or lower levels are masked, or selectively
disabled, to prevent lost interrupts or unnecessary ones.
A high-speed device such as a tape, disk, or communications network, may be able to
transmit information at close to memory speeds; the CPU would need 20 microseconds to respond to
each interrupt, with interrupts arriving every 4 microseconds (for example). To solve this problem,
direct-memory access (DMA) is used for high-speed I/O devices. After setting up buffers, pointers,
and counters for the I/O device, the device controller transfers an entire block of data to or from its
own buffer storage to memory directly, with no intervention by the CPU. Only one interrupt is
generated per block, rather than the one interrupt per byte (or word) generated for low-speed
devices.
If there are no jobs to execute, no I/O devices to service, and no users to whom to respond,
and operating system will sit quietly, waiting for something to happen. Events are almost always
signaled by the occurrence of and interrupt, or a trap. A trap (or an exception) is a softwaregenerated interrupt caused either by an error (for example, division by zero or invalid memory
access), or by a specific request from a user program that an operating-system service be
performed.
A user program may disrupt the normal operation of the system by issuing illegal I/O
instructions, by accessing memory locations within the operating system itself, or by refusing to
relinquish the CPU. We must protect the operating system and all other programs and their data from
any mulfunctioning program. The approach taken is to provide hardware support to allow one to
CS323-650 Operating Systems
Computer Science, Prince of Songkla University
4
_________________________________________________________________________________
differentiate between various modes of executions. At least, we need two separate modes of
operation or (dual-mode operation) : user mode and monitor mode (also called supervisor mode or
system mode or kernel mode).
When a trap or interrupt occurs, the hardware switches from user mode to monitor mode
(that is, changes the state of the mode-bit to be 0). Thus, whenever the operating system gains
control of the computer, it is in monitor mode. The system always switches to user mode (by setting
the mode bit to 1) before passing control to a user program.
The dual mode of operation provides us with the means for protecting the operating system
from errant users, and errant users from one another. We accomplish this protection by designting
some of the machine instructions that may cause harm as privileged instructions. The hardware
allows privileged instructions to be executed only in monitor mode. If an attempt is made to execute
a privileged instruction in user mode, the hardware does not execute the instruction, but rather treats
it as an illegal instruction and traps to the operating system.
Thus, to do I/O, a user program executes a system call to request that the operating system
perform I/O on its behalf (Figure 1.3). The operating system, executing in monitor mode, checks that
the request is valid, and (if it is valid) does the I/O requested. The operating system then returns to
the user.
CS323-650 Operating Systems
case n
resident monitor
1
trap to monitor
.
.
read
perform I/O
2
.
.
3
return to user
.
system call n
.
user program
Figure 1.3 Use of a system call to perform I/O.
Computer Science, Prince of Songkla University
5
_________________________________________________________________________________
CS323-650 Operating Systems
1.3 History of Operating Systems
1.3.1
The First Generation (1945-55) Vacuum Tubes and Plugboards
All programming was done in absolute machine language, often by wiring up plugboards to
control the machine’s basic functions. No Operating Systems.
1.3.2
The Second Generation (1955-65) Transistors and Batch Systems
Batch or Simple Monitor : can run each job (i.e., a program or set of programs) at a time.
For example: FMS (the Fortran Monitor System) and IBSYS, IBM’s operating system for the 7094. The
early batch systems reading from card readers and writing to line printers or card punches. Rather
than have the CPU read directly from cards, however, the cards were first copied onto a magnetic
tape. Similarly, output was written to the tape and the contents of the tape would be printed later. The
card readers and line printers were operated off-line, not by the main computer.
1.3.3 The Third Generation (1965-1980): ICs and Multiprogramming
Multiprogramming : can run multiple jobs concurrently. Another major feature present in thirdgeneration operating systems was the ability to read jobs from cards onto the disk as soon as they
were brought to the computer room. This technique is called spooling (from Simultaneous Peripheral
Operation On Line) and was also used for output. For example: OS/360.
Timesharing : a variant of multiprogramming, in which each user has an on-line terminal i.e.
support multiple user, and works interactively. For example: CTSS, MULTICS, UNIX. To make it
possible to write programs that could run on any UNIX system, IEEE developed a standard for UNIX,
called POSIX, that most versions of UNIX now support. POSIX defines a minimal system call
interface that conformant UNIX systems must support.
Real-Time : operating system has well-defined fixed-time constraints. Processing must be done
within the defined constraints or the system will fail. Contrast this requirement to a time-sharing
system, where it is desirable (but not mandatory) to respond quickly, or to a batch system, where
there may be no time constrains at all. For example, a control device in a dedicated application.
1.3.4
The Fourth Generation (1980-Present): Personal Computers
Network Operating Systems : the users are aware of the existence of multiple computers
and can log in to remote machines and copy files from one machine to another. Each machine runs
its own local operating system and has its own local user (or users). For example : Novel Netware.
Distributed Operating Systems: appears to its users as a traditional uniprocessor system,
even through it is actually composed of multiple processors. The users should not be aware of where
Computer Science, Prince of Songkla University
6
_________________________________________________________________________________
their programs are being run or where their files are located; that should all be handled automatically
and efficiently by the operating system. For example : Amoeba, Mach, Chorus, DCE.
Note! A recent trend in computer systems is to distribute computation among several physical
processors. There are basically two schemes for building such systems. In a tightly coupled system,
the processors share memory and a clock. In these multiprocessor systems, communication usually
take place through the shared memory. In a loosely coupled system, the processors do not share
memory or a clock. Instead, each processor has its own local memory. The processor communicate
with one another through various communication lines, such as high-speed buses or telephone lines.
These systems are usually referred to as distributed system.
CS323-650 Operating Systems
1.4 Operating System Concepts
An operating system provides the environment within which programs are executed. To
construct such an environment, we partition the operating system logically into small modules and
create a well-defined interface for these programs. Obviously, not all systems have the same
structure. However, many modern operating systems share the goal of supporting the following type
of system components:
- Process Management : A process is basically a program in execution. All processes
can potentially execute concurrently, by multiplexing the CPU among them.
- I/O System Management
- Memory Management
- File Management : A major function of the operating system is to hide the peculiarities
of the disks and other I/O devices and present the programmer with a nice, clean
abstract model of device-independent files. To provide a place to keeps files, operating
system has the concept of a directory as a way of grouping files together.
In network or distributed system, Operating systems usually generalize network access as a
form of files access, with the details of networking being contained in the network interface’s device
driver. In network system, application programs can access to protocol software (such as TCP/IP) by
providing the library functions for protocol interface (such as AT&T UNIX Transport Layer Interface
(TLI), BSD UNIX socket interface, Microsoft Winsock) as shown in Figure 1.4.
application program
protocol interface
protocol software in OS
Figure 1.4
Computer Science, Prince of Songkla University
7
_________________________________________________________________________________
Command interpreter is the primary interface between a user sitting at his terminal and the
operating system. It starts out by typing the prompt, a character such as a dollar sign, which tells the
user that it is waiting to accept a command. Some operating systems, especially those on
microcomputers such as MS-DOS and Apple’s Macintosh system, include the command interpreter
in the kernel (boot disk must have MSDOS.SYS, IO.SYS, and COMMAND.COM). The command
interpreter in UNIX is called shell and is not considered to be part of the operating system.
Operating systems are frequently differentiated in the area of command interpretation, with a
user-friendly interpreter making the system more agreeable to some users. An example of are the
Macintosh interpreter, a window and menu system that is almost exclusively mouse-base, Window on
Microsoft Window, and X Window on UNIX. To write program under window, the system will provide
Graphic User Interface (GUI) or Application Program Interface (API) to the user.
CS323-650 Operating Systems
1.5 Operating System Structure
1.5.1
Monolithic Systems
There is no structure. The operating system is written as a collection of procedures, each of
which can call any of the other ones whenever it needs to. The services (system calls) provided by
the operating system are requested by putting the parameters in well-defined places, such as in
registers or on the stack, and then executing a special trap instruction known as a kernel call or
supervisor call. For example UNIX, LINUX.
(the users)
shells
compilers and interpreters
system libraries
system-call interface to the kernel
signals
file system
terminal handling
swapping
character I/) system
block I/O system
terminal drivers
disk and tape drivers
kernel interface to the hardware
terminal controllers
device controllers
terminals
disks and tapes
Figure 1.5 UNIX system structure
Computer Science, Prince of Songkla University
CPU scheduling
page replacement
demand paging
virtual memory
memory controllers
physical memory
8
_________________________________________________________________________________
CS323-650 Operating Systems
1.5.2
Layered Systems
The operating system is organized as a hierarchy of layers, each one constructed upon the
one below it. For example THE system, MULTIS, MINIX.
Layer
4
Init
User User User
….
User processes
3
Memory
File
Network
…
Server processe
manager
system server
2
Disk
Tty
Clock System Ethernet … I/O tasks (device drivers)
task
task task task task
1
Process management
Figure 1.7 MINIX system structure
1.5.3 Virtual Machines
The heart of the system, known as the virtual machine monitor (for example VM/370), runs
on the bare hardware and does the multiprogramming, providing not one, but several virtual
machines to the next layer up. However, unlike all other operating systems, these virtual machines
are not extended machine. Instead, they are exact copies of the bare hardware, including
kernel/user mode, I/O, interrupts, and everything else the real machine has. Because each virtual
machine is identical to the true hardware, each one can run any operating system that will run
directly on the bare hardware.
1.5.4
Client-Server Model
Client Client Process Terminal
Process process server server
…
Kernel
File
Memory
server server
User
mode
Kernel mode
Client obtains service by
sending messages to
server processes
A trend in modern operating systems is to move code up into higher layers even further and
remove as much as possible from the operating system, leaving a minimal kernel (micro kernel). The
usual approach is to implement most of the operating system functions in user processes. To request
a service, such as reading a block of a file, a user process (now known as the client process) sends
the request to a server process, which then does the work and sends back the answer.
Computer Science, Prince of Songkla University
9
_________________________________________________________________________________
Advantages:
- by splitting the operating system up into parts, each of which only handles one facet of
the system, such as file service, process service, terminal service, or memory service,
each part becomes small and manageable
- because all the servers run as user-mode processes, and not in kernel mode, they do
not have direct access to the hardware. As a consequence, if a bug in the file server is
triggered, the file service may crash, but this will not usually bring the whole machine
down.
- Its adaptability to use in distributed system as shown below:
Machine 1
Machine 2
Machine 3
Client
File server
Process server
Kernel
Kernel
Kernel
CS323-650 Operating Systems
network
message from client to server
For example, Amoeba.
User
Microkernel
File
server
Microkernel
Directory
server
Microkernel
Process
server
Microkernel
Network
Compare to Monolithic kernel
User
Monolithic
Kernel
Includes file,
directory and process management
1.6 System Calls
We will study only system call of MINIX operating system.
Process management
pid = fork()
Create a child process identical to the parent
pid = waitpid(pid, &statloc, opts) Wait for a child to terminate
Computer Science, Prince of Songkla University
10
_________________________________________________________________________________
s = wait(&status)
Old version of waitpid
s = execve(name, argv, envp) Replace a process core image
exit(status)
Terminate process execution and return status
size = brk(addr)
Set the size of the data segment
pid = getpid()
Return the caller’s process id
pid = getpgrp()
Return the id of the caller’s process group
pid = setid()
Create a new session and return its process group id
l = ptrace(req, pid, addr, data) Used for debugging
Signals
s = sigaction(sig, &act, &oldact) Define action to take on signals
s = sigreturn(&context)
Return from a signal
s = sigprocmask(how, &set, &old) Examine or change the signal mask
s = sigpending(set)
Get the set of blocked signals
s = sigsuspend(sigmask)
Replace the signal mask and suspend the process
s = kill(pid, sig)
Send a signal to a process
residual = alarm(seconds)
Set the alarm clock
s = pause()
Suspend the caller until the next signal
File Management
fd = creat(name, mode)
Obsolete way to create a new file
fd = mknod(name, mode, addr) Create a regular, special, or directory I-node
fd = open(file, how, …)
Opena 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
pos = lseek(fd, offset, whence) Move the file pointer
s = stat(name, &buf)
Get a file’s status information
s = fstat(fd, &buf)
Get a file’s status information
fd = dup(fd)
Allocate a new file descriptor for an open file
s = pipe(&fd[0])
Create a pipe
s = ioctl(fd, request, argp)
Perform special operations on a file
s = access(name, amode)
Check a file’s accessibility
s = rename(old, new)
Give a file’s a new name
s = fcntl(fd, cmd, …)
File locking and other operations
Directory&File System Management
s = mkdir(name, mode)
Create a new directory
CS323-650 Operating Systems
Computer Science, Prince of Songkla University
11
_________________________________________________________________________________
s = rmdir(name)
Remove an empty directory
s = link(name1, name2)
Create a new entry, name2, pointing to name1
s = unlink(name)
Remove a directory entry
s = mount(special, name, flag) Mount a file system
s = umount(special)
Unmount a file system
s = sync()
Flush all cached blocks to the disk
s = chdir(dirname)
Change the working directory
s = chroot(dirname)
Change the root directory
Protection
s = chmod(name, mode)
Change a file’s protection bits
uid = getuid()
Get the caller’s uid
gid = getgid()
Get the caller’s gid
s = setuid(uid)
Set the caller’s uid
s = setgid(gid)
Set the caller’s gid
s = chown(name, owner, group) Change a file’s owner and group
oldmask = umask(complmode) Change the mode mask
Time Management
seconds = time(&seconds)
Get the elapsed time since Jan. 1, 1970
s = stime(tp)
Set the elapsed time since Jan. 1, 1970
s = utime(file, timep)
Set a file’s “last access” time
s = times(buffer)
Get the user and system times used so far
System Calls for Process Management
 fork
The only way in which a new process is created by Unix is for an existing process to execute the
fork system call. For example, a simple shell
while (1) {
/* repeat forever */
read_command(command, parameters); /* read input from terminal */
if (fork() != 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 */
}
}
CS323-650 Operating Systems
Computer Science, Prince of Songkla University
12
_________________________________________________________________________________
CS323-650 Operating Systems
We will discuss more in chapter2.
Note! To see the different between parent and child process use command, man fork.
 exit
A process terminates by calling the exit system call. This system call never returns to the caller.
When exit is called, an integer exit status is passed by the process to the kernel. This exit status is
then available to the parent process of the exiting process through the wait system call.
 exec
The only way in which a program is executed by Unix is for an existing process to issue the exec
system call. The exec system call replaces the current process with the new program. The process
ID does not change.
There are six different versions of the exec function.
int execlp(char *filename, char *arg0, char *arg1, …, char *argn, (char *) 0);
int execl(char *pathname, char *arg0, char *arg1, …, char *argn, (char *) 0);
int execle(char *pathname, char *arg0, char *arg1, …, char *argn, (char *) 0, char **envp);
int execvp(char *filename, char **argv);
int execv(char *pathname, char **argv);
int execve(char *pathname, char **argv, char **envp);
The exec functions return to the caller only if an error occurs. Otherwise control passes to the start of
the new program. The relationship between these six functions is shown below:
Computer Science, Prince of Songkla University
13
_________________________________________________________________________________
CS323-650 Operating Systems
execlp(file,arg,…,0)
create argv
execvp(file,argv)
execl(path,arg,…,0)
execle(path,arg,…,0,envp)
create argv
execv(path,arv)
convert file
to path
create argv
system call
execve(path,argv,envp)
add
envp
หมายเหตุ
1. ถ้ าใช้ execlp หรื อ execvp และตรง file มี / แสดงว่าเป็ น path อยูแ่ ล้ ว จะไม่มีการ convert file
to path
2. ในกรณีที่มีการ convert file to path จะใช้ PATH ใน environment list แต่ถ้าไม่มี PATH หรื อว่าง
ให้ PATH=”:/bin:/usr/bin”
3. argv และ envp ต้ องสิ ้นสุดด้ วย NULL pointer เพราะไม่มี argc
4. ถ้ าไม่กาหนด envp จะใช้ environment list ที่ผา่ นมาทาง main (หรื อ environ)
Argument List
Whenever a program is executed, a variable-length argument list is passed to the process.
The argument list is an array of pointers to character strings. There is an upper bound on the size of
the argument list, often 5120 bytes or 10240 bytes.
Typically a program is executed when a command line is entered on a terminal. For
example, if we enter the line
ls –l *.*
to a Unix shell, the program echo is executed and is passed three argument strings:
ls, -l, and *.*.
A C program is passed its argument list by the C start-up function as arguments to the main
function. The main function is declared as
main (argc, argv)
int argc;
char *argv[];
{
}
Computer Science, Prince of Songkla University
14
_________________________________________________________________________________
For the ls example shown above the picture is
CS323-650 Operating Systems
argv
argv[0]
argv[1]
argv[2]
ls\0
-l\0
*.*\0
argc = 3
Environment List
Whenever a program is executed, it is also passed a variable-length list of environment
variables. But, since a count of the number of elements in this array of pointers is not provided, it
must be terminated by a NULL pointer. These are accessible to the program as an optional thrid
argument
main (argc, argv, envp)
int argc;
char *argv[];
char *envp[];
{
}
The environment strings are usually of the form
variable=string
The following C program prints the values of all environment strings
main(argc, argv, envp)
int argc;
char *argv[];
char *envp[];
{
int i;
for (i = 0; envp[i] != (char *) 0; i++)
printf(“%s\n”, envp[i]);
exit(0);
}
Computer Science, Prince of Songkla University
15
_________________________________________________________________________________
Note! The C start-up function provides an external variable named environ that can also be used to
access the environment list. (put declared in C as extern char **environ;)
To obtain the value of a specific variable from the list, using the function getenv provided by
the C library. For example, the following program prints the value of the environment variable HOME,
if it is defined.
CS323-650 Operating Systems
main()
{
char *ptr, *getenv();
if ((ptr = getenv(“HOME”)) == (char *) 0)
printf(“HOME is not defined\n”);
else
printf(“HOME=%s\n”,ptr);
exit(0);
}
System Calls for Signaling
Read text book and appendix.
System Calls for File Management
File Sharing
There are three kernel tables used to access a file, which is shown below:
Computer Science, Prince of Songkla University
16
_________________________________________________________________________________
parent process
table entry
CS323-650 Operating Systems
fd 0:
fd 1:
…
fd i:
child process
table entry
fd 0:
fd 1:
file table
i-node table
current file
position
i-node ptr
i-node information
…
fd i:
other process
table entry
fd 0:
fd 1:
fd 2:
i-node information
current
position
i-node ptr
…
…
…
…
fd j:
Since the i-node table does not keep the file’s current position, an i-node entry for a file can be
shared by any number of processes. A common operation that must be handled is if two or more
processes are reading the same file at some point in time- the file position of one process must be
independent of the other. If the files’s position were kept in the i-node table, processes could not
share an i-node table entry.
Note! A file table entry can only have more than one process table entry pointing to it from a fork
operation. But dup copy fd (in the same process) to the same file table. File descriptor on Unix
0 is standard input (e.g. freadf(stdin,…)
1 is standard output (e.g. fprintf(stdout,…)
2 is standard error (e.g. fprintf(stderr,…);
Computer Science, Prince of Songkla University
17
_________________________________________________________________________________
 dup
An existing file descriptor is duplicated by
int dup(int filedes);
It is guaranteed that the new file descriptor returned by dup is the lowest numbered available file
descriptor.
For redirection, e.g. cat file1 > file2, the DUP system call is helpful by executing the
following statements,
fd = dup(1);
nfd = creat(“file2”,O_CREAT);
close(1);
dup(nfd);
close(nfd);
which uses the DUP system call to allocate a new file descriptor, fd, and arrange for it to correspond
to the same file as standard output. Then standard output can be closed and a new file opened and
used. When it is time to restore the original situation, file descriptor 1 can be closed,
close(1);
and then
dup(fd);
executed to assign the lowest file descriptor, namely, 1, to the same file as fd. Finally, fd can be
closed,
close(fd);
and we are back where we started.
CS323-650 Operating Systems
Computer Science, Prince of Songkla University
18
_________________________________________________________________________________
For example,
#include <fcntl.h>
main()
{
int fd,nfd;
CS323-650 Operating Systems
fd = dup(1);
printf(“fd = %d\n”,fd);
/* write to standard output */
nfd = creat(“file2”,O_CREAT);
close(1);
dup(nfd);
close(nfd);
printf(“nfd = %d\n”,nfd);
/* now write to file2 */
printf(“hello test\n”);
/* write to file2 */
close(1);
dup(fd);
close(fd);
}
Pipes
A pipes provides a one-way flow of data. A pipe is created by the pipe system call,
int pipe(int *filedes);
Two file descriptors are return- fd[0] which is open for read, and fd[1] which is open for writing. A
diagram of what a pipe looks like in a single process is shown below,
user process
read fd[0]
write fd[1]
kernel
pipe
flow of data
A pipe has a finite size, always at least 4096 bytes. The rule for reading and writing a pipe in normal
condition, read empty pipe wait until data come, write full pipe wait until have room to write.
Computer Science, Prince of Songkla University
19
_________________________________________________________________________________
When a user types
cat file1 file2 | sort
The shell creates a pipe and arranges for standard output of the first process to write to the pipe, so
standard input of the second process can read from it. The pipe system call creates a pipe and
returns two file descriptors, one for writing and one for reading. The call is
pipe(&fd[0]);
where fd is an array of two integers and fd[0] is the file descriptor for reading and fd[1] is the one for
writing. The following skeleton creates two processes, with the output of the first one piped into the
second one.
CS323-650 Operating Systems
#define STD_INPUT 0
/* file descriptor for standard input */
#define STD_OUTPUT 1
/* file descriptor for standard output */
pipeline(process1, process2)
char *process1, process2;/ pointers to program names */
{
int fd[2];
pipe(&fd[0]);
/* create a pipe */
if (fork() != 0) {
/* The parent process executes these statements. */
close(fd[0]);
/* process 1 does not need to read from pipe */
close(STD_OUTPUT);
/* prepare for new standard output */
dup(fd[1]);
/* set standard output to fd[1] */
close(fd[1]);
/* this file descriptor not needed any more */
execl(process1, process1, 0);
} else {
/* The child process executes these statements. */
close(fd[1]);
/* process 2 does not need to write to pipe */
close(STD_INPUT);
/* prepare for new standard input */
dup(fd[0]);
/* set standard input to fd[0] */
close(fd[0]);
/* this file descriptor not needed any more */
execl(process2, process2, 0);
}
}
Computer Science, Prince of Songkla University
20
_________________________________________________________________________________
System Calls for Directory Management
See text book.
System Calls for Protection
See text book.
System Calls for Time Management
See text book.
CS323-650 Operating Systems
How MINIX loads into memory (Bootstrapping MINIX)?
When the computer is turned on, the hardware reads the first sector of the first track of the
boot disk into memory and executes the code it finds there. The details vary depending upon
whether the boot disk is a diskette or a hard disk. On a diskette this sector contains the bootstrap
program. It is very small, since it has to fit in one sector. The MINIX boothstrap loads a larger
program, boot (see source code for booting and installing MINIX in src/boot), which then loads the
operating system itself.
load
bootblock
boot program
In contrast, hard disks require an intermediate step. A hard disk is divided into partitions,
and the first sector of a hard disk contains a small program and the disk’s partition table. Collectively
these are called the master boot record. The program part is executed to read the partition table and
to select the active partition. The active partition has a bootstrap on its first sector, which is then
loaded and executed to find and start a copy of boot in the partition, exactly as is done when booting
from a diskette.
master boot record & partition table
partition 1 bootblock
partition 2 bootblock
boot program for partition 1
boot program for
partition 2
Computer Science, Prince of Songkla University
21
_________________________________________________________________________________
In either case, boot looks for a multipart file on the diskette or partition and loads the
individual parts into memory at the proper locations as follow (for PC):
Limit of memory
Memory
available for
user programs
2383 K
src/tools/init
Init
2372 K
src/inet/inet (optional)
Inet task
2198 K (Depends on number of buffers
/src/fs/fs
File system
include in file system)
1077 K
src/mm/mm
Memory manager
1024 K
Read only memory
And I/O adapter
Memory
(unavailable to Minix)
640 K
Memory
available for
user programs
129 K (Depends on number of I/O tasks)
Ethernet task
Printer task
src/kernel/kernel
Terminal task
Memory task
Clock task
Disk task
Kernel
2 K Start of kernel
Unused
Interupt vectors
1K
0
Note! All of the tasks in layer 2 and all the code in layer 1 are linked together into a single binary
program called the kernel. For more information see pp. 100 in text book.
CS323-650 Operating Systems
Computer Science, Prince of Songkla University