Bca 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 147

Patliputra University, Patna

1
Dear Students,

We, at CIMAGE, are dedicated to provide the best of education and to bring
an overall positive growth in our students. No wonder, that’s the reason, our
students have been Toppers in the University Examinations; and after
successful completion of the course, they have been provided with the best
placements or have been selected in top ranking institutes for further studies.
I am happy that CIMAGE have been pioneer in setting milestone in the
segment of higher education, for others to be followed.

The publication of ‘CIMAGE Courseware’ is also one of the several innovative initiatives taken by our
college. This textbook is unique in several ways. It has been written in simple language, so that
students could understand even the complex and tough topics very easily. Every chapter has been
divided into three sections, ‘The Objective’, ‘The Chapter itself’ & ‘The Summary’ part. The
‘Objective’ section will help the students to understand about the ‘Objective and Purpose’ of the
chapter. It will also help them in understanding, how to use the knowledge, studied in the chapter.
The second section is ‘The Chapter’ itself, which has the relevant study material, prescribed by the
university. In this section some practical examples have also been cited to clarify concept. The third
section is the ‘Summary of the chapter’. It has been written using Hindi & English both the
languages. Hence it will help the student from Hindi medium background also to understand the
concept Properly, Deeply and Completely. At the end of the chapters, relevant Projects,
Assignments and Questions have also been given, to make the students well prepared in the studied
chapter.

I am confident that this book will serve the purpose of providing a Clear and Concise guide-line to
the students. However, there is ‘No limit’ of acquiring the knowledge, hence I advice the students to
read other text & reference books as well, as it will help them in gaining more knowledge in the
subject. At CIMAGE Library, a number of Reference Books, Video Lectures, Journals, Research
Papers are there to serve this purpose.

I suggest the students, not to ‘Mug-up’, but to ‘Understand’ the subject properly. You should attend
the classes seriously and if something is not well understood by you; Do not hesitate in asking
questions from your teachers. I also suggest students to discuss the topic and subjects in a group,
as group study has its own advantages. Group Study makes the study easy and interesting, at the
same time, it also makes you aware of the different prospective and dimensions.

You Know, at CIMAGE, we have one more innovative system for you, i.e. ‘Teacher – Student Doubt
Clearing Session’. If you have any doubts in any chapter, you may meet the respective teachers
individually and get your doubts cleared. Every teacher has been assigned a special time table for it.
You are advised to get benefited with it.

At last, but not the least, I thank all the faculty members of CIMAGE for their valuable contribution in
preparing the courseware.

If you have any suggestions or concerns, you may mail me at info.cimage@gmail.com. Go ahead;
Study Well, Give your Best & Keep adding glory to the rich legacy of CIMAGE.

Thank You.

Neeraj Agrawal
Director,
CIMAGE Group of Institutions.

1
TABLE OF CONTENTS

PART–I : OPERATING SYSTEM

Chapter–I : OPERATING SYSTEM BASICS 1-16

Chapter–II : PROCESS MANAGEMENT 17-66

Chapter–III : DISK OPERATING SYSTEM (DOS) 67-79

PART–II: BUSINESS APPLICATION - FOXPRO

Chapter–I : INTRODUCTION TO DATABASE & FOXPRO 80-88

Chapter–II : CREATING & DISPLAYING DATABASE 89-96

Chapter–III : EDITING A DATABASE 97-104

Chapter–IV : SORTING & INDEXING A DATABASE 105-113

Chapter–V : PERFORMING QUERIES 114-119

Chapter–VI : FOXPRO'S RATIONAL POWER 120-126

Chapter–VII: MEMO FIELD & FILE UTILITIES 127-131

Chapter–VIII: MEMORY VARIABLES & FUNCTIONS 132-142

1
PART-I

OPERATING SYSTEM

2
Chapter-1

OPERATING SYSTEM BASICS

Objectives
 Unit Operating System Operating System
Operating System components generations

 Unit Computers Operating System


Unit

What is an Operating System?


An operating system (OS) is a program that controls the execution of an
application program and acts as an interface between the user and computer
hardware. The purpose of an OS is to provide an environment in which a
user can execute programs in a convenient and efficient manner.

The operating system must provide certain services to programs and to the
users of those programs in order to make the programming task easier,
these services will differ from one OS to another.

Functions of an Operating System

Modern Operating systems generally have following three major goals.


Operating systems generally accomplish these goals by running processes in
low privilege and providing service calls that invoke the operating system
kernel in high-privilege state.

To hide details of hardware

An abstraction is software that hides lower level details and provides a set of
higher-level functions. An operating system transforms the physical world of
devices, instructions, memory, and time into virtual world that is the result
of abstractions built by the operating system. There are several reasons for
abstraction.

1
First, the code needed to control peripheral devices is not standardized.
Operating systems provide subroutines called device drivers that perform
operations on behalf of programs for example, input/output operations.

Second, the operating system introduces new functions as it abstracts the


hardware. For instance, operating system introduces the file abstraction so
that programs do not have to deal with disks.

Third, the operating system transforms the computer hardware into multiple
virtual computers, each belonging to a different program. Each program that
is running is called a process. Each process views the hardware through the
lens of abstraction.

Fourth, the operating system can enforce security through abstraction.

Resources Management

An operating system as resource manager, controls how processes(the


active agents) may access resources (passive entities). One can view
Operating Systems from two points of views: Resource
manager and Extended machines. Form Resource manager point of view
Operating Systems manage the different parts of the system efficiently and
from extended machines point of view Operating Systems provide a virtual
machine to users that is more convenient to use. The structurally Operating
Systems can be design as a monolithic system, a hierarchy of layers, a
virtual machine system, a micro-kernel, or using the client-server model.
The basic concepts of Operating Systems are processes, memory
management, I/O management, the file systems, and security.

Provide a effective user interface

The user interacts with the operating systems through the user interface and
usually interested in the look and feel of the operating system. The most
important components of the user interface are the command interpreter,
the file system, on-line help, and application integration. The recent trend
has been toward increasingly integrated graphical user interfaces that
encompass the activities of multiple processes on networks of computers.

2
Evolution of Operating System

Operating system and computer architecture have had a great deal of


influence on each other. To facilitate the use of the hardware, OS's were
developed. As operating systems were designed and used, it became
obvious that changes in the design of the hardware could simplify them.

Early Systems

In the earliest days of electronic digital computing, everything was done on


the bare hardware. Very few computers existed and those that did exist
were experimental in nature. The researchers who were making the first
computers were also the programmers and the users. They worked directly
on the "bare hardware". There was no operating system. The experimenters
wrote their programs in assembly language and a running program had
complete control of the entire computer. Debugging consisted of a
combination of fixing both the software and hardware, rewriting the object
code and changing the actual computer itself.

The lack of any operating system meant that only one person could use a
computer at a time. Even in the research lab, there were many researchers
competing for limited computing time. The first solution was a reservation
system, with researchers signing up for specific time slots.

The high cost of early computers meant that it was essential that the rare
computers be used as efficiently as possible. The reservation system was not
particularly efficient. If a researcher finished work early, the computer sat
idle until the next time slot. If the researcher's time ran out, the researcher
might have to pack up his or her work in an incomplete state at an awkward
moment to make room for the next researcher. Even when things were
going well, a lot of the time the computer actually sat idle while the
researcher studied the results (or studied memory of a crashed program to
figure out what went wrong).

The solution to this problem was to have programmers prepare their work
off-line on some input medium (often on punched cards, paper tape, or
magnetic tape) and then hand the work to a computer operator. The
computer operator would load up jobs in the order received (with priority
overrides based on politics and other factors). Each job still ran one at a
time with complete control of the computer, but as soon as a job finished,
the operator would transfer the results to some output medium (punched

3
tape, paper tape, magnetic tape, or printed paper) and deliver the results to
the appropriate programmer. If the program ran to completion, the result
would be some end data. If the program crashed, memory would be
transferred to some output medium for the programmer to study (because
some of the early business computing systems used magnetic core memory,
these became known as "core dumps")

Soon after the first successes with digital computer experiments, computers
moved out of the lab and into practical use. The first practical application of
these experimental digital computers was the generation of artillery tables
for the British and American armies. Much of the early research in computers
was paid for by the British and American militaries. Business and scientific
applications followed.

As computer use increased, programmers noticed that they were duplicating


the same efforts.

Every programmer was writing his or her own routines for I/O, such as
reading input from a magnetic tape or writing output to a line printer. It
made sense to write a common device driver for each input or output device
and then have every programmer share the same device drivers rather than
each programmer writing his or her own. Some programmers resisted the
use of common device drivers in the belief that they could write "more
efficient" or faster or ""better" device drivers of their own.

Additionally each programmer was writing his or her own routines for fairly
common and repeated functionality, such as mathematics or string
functions. Again, it made sense to share the work instead of everyone
repeatedly "reinventing the wheel". These shared functions would be
organized into libraries and could be inserted into programs as needed. In
the spirit of cooperation among early researchers, these library functions
were published and distributed for free, an early example of the power of the
open source approach to software development.

Simple Batch Systems

When punched cards were used for user jobs, processing of a job involved
physical actions by the system operator, e.g., loading a deck of cards into
the card reader, pressing switches on the computer's console to initiate a
job, etc. These actions wasted a lot of central processing unit (CPU) time.

4
Operating System
User Program Area
Figure 1.1: Simple Batch System

To speed up processing, jobs with similar needs were batched together and
were run as a group. Batch processing (BP) was implemented by locating a
component of the BP system, called the batch monitor or supervisor,
permanently in one part of computer's memory. The remaining memory was
used to process a user job - the current job in the batch as shown in the
figure 1.1 above.

The delay between job submission and completion was considerable in batch
processed system as a number of programs were put in a batch and the
entire batch had to be processed before the results were printed. Further
card reading and printing were slow as they used slower mechanical units
compared to CPU which was electronic. The speed mismatch was of the
order of 1000. To alleviate this problem programs were spooled. Spool is an
acronym for simultaneous peripheral operation on-line. In essence the idea
was to use a cheaper processor known as peripheral processing unit (PPU) to
read programs and data from cards store them on a disk. The faster CPU
read programs/data from the disk processed them and wrote the results
back on the disk. The cheaper processor then read the results from the disk
and printed them.

Multi Programmed Batch Systems

Even though disks are faster than card reader/ printer they are still two
orders of magnitude slower than CPU. It is thus useful to have several
programs ready to run waiting in the main memory of CPU. When one
program needs input/output (I/O) from disk it is suspended and another
program whose data is already in main memory (as shown in the figure 1.2
below) is taken up for execution. This is called multiprogramming.

Operating System
Program 1
Program 2
Program 3
Program 4
Figure 1.2: Multi Programmed Batch Systems

5
Multiprogramming (MP) increases CPU utilization by organizing jobs such
that the CPU always has a job to execute. Multiprogramming is the first
instance where the operating system must make decisions for the user.

The MP arrangement ensures concurrent operation of the CPU and the I/O
subsystem. It ensures that the CPU is allocated to a program only when it is
not performing an I/O operation.

Time Sharing Systems

Multiprogramming features were superimposed on BP to ensure good


utilization of CPU but from the point of view of a user the service was poor
as the response time, i.e., the time elapsed between submitting a job and
getting the results was unacceptably high. Development of interactive
terminals changed the scenario. Computation became an on-line activity. A
user could provide inputs to a computation from a terminal and could also
examine the output of the computation on the same terminal. Hence, the
response time needed to be drastically reduced. This was achieved by
storing programs of several users in memory and providing each user a slice
of time on CPU to process his/her program.

Distributed Systems

A recent trend in computer system is to distribute computation among


several processors. In the loosely coupled systems the processors do not
share memory or a clock. Instead, each processor has its own local memory.
The processors communicate with one another using communication
network.

The processors in a distributed system may vary in size and function, and
referred by a number of different names, such as sites, nodes, computers
and so on depending on the context. The major reasons for building
distributed systems are:

Resource sharing: If a number of different sites are connected to one


another, then a user at one site may be able to use the resources available
at the other.

Computation speed up: If a particular computation can be partitioned into


a number of sub computations that can run concurrently, then a distributed

6
system may allow a user to distribute computation among the various sites
to run them concurrently.

Reliability: If one site fails in a distributed system, the remaining sites can
potentially continue operations.

Communication: There are many instances in which programs need to


exchange data with one another. Distributed data base system is an
example of this.

Real-time Operating System

The advent of timesharing provided good response times to computer users.


However, timesharing could not satisfy the requirements of some
applications. Real-time (RT) operating systems were developed to meet the
response requirements of such applications.

There are two flavors of real-time systems. A hard real-time system


guarantees that critical tasks complete at a specified time. A less restrictive
type of real time system is soft real-time system, where a critical real-time
task gets priority over other tasks, and retains that priority until it
completes. The several areas in which this type is useful are multimedia,
virtual reality, and advance scientific projects such as undersea
exploration and planetary rovers. Because of the expanded uses for soft
real-time functionality, it is finding its way into most current operating
systems, including major versions of Unix and Windows NT OS.

A real-time operating system is one, which helps to fulfill the worst-case


response time requirements of an application. An RT OS provides the
following facilities for this purpose:

1. Multitasking within an application.

2. Ability to define the priorities of tasks.

3. Priority driven or deadline oriented scheduling.

4. Programmer defined interrupts.

A task is a sub-computation in an application program, which can be


executed concurrently with other sub-computations in the program, except
at specific places in its execution called synchronization points. Multi-tasking,
which permits the existence of many tasks within the application program,

7
provides the possibility of overlapping the CPU and I/O activities of the
application with one another. This helps in reducing its elapsed time. The
ability to specify priorities for the tasks provides additional controls to a
designer while structuring an application to meet its response-time
requirements.

Real time operating systems (RTOS) are specifically designed to respond to


events that happen in real time. This can include computer systems that run
factory floors, computer systems for emergency room or intensive care unit
equipment (or even the entire ICU), computer systems for air traffic control,
or embedded systems. RTOSs are grouped according to the response time
that is acceptable (seconds, milliseconds, microseconds) and according to
whether or not they involve systems where failure can result in loss of life.
Examples of real-time operating systems include QNX, Jaluna-1, ChorusOS,
LynxOS, Windows CE .NET, and VxWorks AE, etc.

Operating System Components

Even though, not all systems have the same structure many modern
operating systems share the same goal of supporting the following types of
system components.

Process Management

The operating system manages many kinds of activities ranging from user
programs to system programs like printer spooler, name servers, file server
etc. Each of these activities is encapsulated in a process. A process includes
the complete execution context (code, data, PC, registers, OS resources in
use etc.).

It is important to note that a process is not a program. A process is only


ONE instant of a program in execution. There are many processes can be
running the same program. The five major activities of an operating system
in regard to process management are
1. Creation and deletion of user and system processes.
2. Suspension and resumption of processes.
3. A mechanism for process synchronization.
4. A mechanism for process communication.
5. A mechanism for deadlock handling.

8
Main-Memory Management

Primary-Memory or Main-Memory is a large array of words or bytes. Each


word or byte has its own address. Main-memory provides storage that can
be access directly by the CPU. That is to say for a program to be executed, it
must in the main memory.

The major activities of an operating in regard to memory-management are:

1. Keep track of which part of memory are currently being used and by
whom.

2. Decide which processes are loaded into memory when memory space
becomes available.

3. Allocate and de-allocate memory space as needed.

File Management

A file is a collection of related information defined by its creator. Computer


can store files on the disk (secondary storage), which provides long term
storage. Some examples of storage media are magnetic tape, magnetic disk
and optical disk. Each of these media has its own properties like speed,
capacity, data transfer rate and access methods.

A file system normally organized into directories to ease their use. These
directories may contain files and other directions.

The five main major activities of an operating system in regard to file


management are -

The creation and deletion of files.

The creation and deletion of directions.

The support of primitives for manipulating files and directions.

The mapping of files onto secondary storage.

The backup of files on stable storage media.

9
I/O System Management

I/O subsystem hides the peculiarities of specific hardware devices from the
user. Only the device driver knows the peculiarities of the specific device to
whom it is assigned.

Secondary-Storage Management

Generally speaking, systems have several levels of storage, including


primary storage, secondary storage and cache storage. Instructions and
data must be placed in primary storage or cache to be referenced by a
running program. Because main memory is too small to accommodate all
data and programs, and its data are lost when power is lost, the computer
system must provide secondary storage to back up main memory.
Secondary storage consists of tapes, disks, and other media designed to
hold information that will eventually be accessed in primary storage
(primary, secondary, cache) is ordinarily divided into bytes or words
consisting of a fixed number of bytes. Each location in storage has an
address; the set of all addresses available to a program is called an address
space.

The three major activities of an operating system in regard to secondary


storage management are:

Managing the free space available on the secondary-storage device.

Allocation of storage space when new files have to be written.

Scheduling the requests for memory access.

Networking

A distributed system is a collection of processors that do not share memory,


peripheral devices, or a clock. The processors communicate with one another
through communication lines called network. The communication-network
design must consider routing and connection strategies, and the problems of
contention and security.

Protection System

If a computer system has multiple users and allows the concurrent execution
of multiple processes, then various processes must be protected from one
another's activities. Protection refers to mechanism for controlling the access

10
of programs, processes, or users to the resources defined by a computer
system.

Command Interpreter System

A command interpreter is an interface of the operating system with the user.


The user gives commands with are executed by operating system (usually
by turning them into system calls). The main function of a command
interpreter is to get and execute the next user specified command.
Command-Interpreter is usually not part of the kernel, since multiple
command interpreters (shell, in UNIX terminology) may be supported by an
operating system, and they do not really need to run in kernel mode. There
are two main advantages of separating the command interpreter from the
kernel.

If we want to change the way the command interpreter looks, i.e., I want to
change the interface of command interpreter, I am able to do that if the
command interpreter is separate from the kernel. I cannot change the code
of the kernel so I cannot modify the interface.

If the command interpreter is a part of the kernel, it is possible for a


malicious process to gain access to certain part of the kernel that it should
not have. To avoid this scenario it is advantageous to have the command
interpreter separate from kernel.

Operating System Services

Following are the five services provided by operating systems for the
convenience of the users.

Program Execution

The purpose of a computer system is to allow the user to execute programs.


So the operating system provides an environment where the user can
conveniently run programs. The user does not have to worry about the
memory allocation or multitasking or anything. These things are taken care
of by the operating systems.

Running a program involves the allocating and de-allocating memory, CPU


scheduling in case of multi-process. These functions cannot be given to the
user-level programs. So user-level programs cannot help the user to run
programs independently without the help from operating systems.

11
I/O Operations

Each program requires an input and produces output. This involves the use
of I/O. The operating systems hides from the user the details of underlying
hardware for the I/O. All the users see that the I/O has been performed
without any details. So the operating system, by providing I/O, makes it
convenient for the users to run programs.

For efficiently and protection users cannot control I/O so this service cannot
be provided by user-level programs.

File System Manipulation

The output of a program may need to be written into new files or input taken
from some files. The operating system provides this service. The user does
not have to worry about secondary storage management. User gives a
command for reading or writing to a file and sees his/her task accomplished.
Thus operating system makes it easier for user programs to accomplish their
task.

This service involves secondary storage management. The speed of I/O that
depends on secondary storage management is critical to the speed of many
programs and hence I think it is best relegated to the operating systems to
manage it than giving individual users the control of it. It is not difficult for
the user-level programs to provide these services but for above mentioned
reasons it is best if this service is left with operating system.

Communications

There are instances where processes need to communicate with each other
to exchange information. It may be between processes running on the same
computer or running on the different computers. By providing this service
the operating system relieves the user from the worry of passing messages
between processes. In case where the messages need to be passed to
processes on the other computers through a network, it can be done by the
user programs. The user program may be customized to the specifications of
the hardware through which the message transits and provides the service
interface to the operating system.

12
Error Detection

An error in one part of the system may cause malfunctioning of the complete
system. To avoid such a situation the operating system constantly monitors
the system for detecting the errors. This relieves the user from the worry of
errors propagating to various part of the system and causing malfunctioning.

This service cannot be allowed to be handled by user programs because it


involves monitoring and in cases altering area of memory or de-allocation of
memory for a faulty process, or may be relinquishing the CPU of a process
that goes into an infinite loop. These tasks are too critical to be handed over
to the user programs. A user program if given these privileges can interfere
with the correct (normal) operation of the operating systems.

Operating Systems for Different Computers

Operating systems can be grouped according to functionality: operating


systems for Supercomputers, Computer Clusters, Mainframes, Servers,
Workstations, Desktops, Handheld Devices, Real Time Systems, or
Embedded Systems.

OS for Supercomputers:

Supercomputers are the fastest computers, very expensive and are


employed for specialized applications that require immense amounts of
mathematical calculations, for example, weather forecasting, animated
graphics, fluid dynamic calculations, nuclear energy research, and petroleum
exploration. Out of many operating systems used for supercomputing UNIX
and Linux are the most dominant ones.

Computer Clusters Operating Systems:

A computer cluster is a group of computers that work together closely so


that in many respects they can be viewed as though they are a single
computer. The components of a cluster are commonly, connected to each
other through fast local area networks. Besides many open source operating
systems, and two versions of Windows 2003 Server, Linux is popularly used
for Computer clusters.

13
Mainframe Operating Systems:

Mainframes used to be the primary form of computer. Mainframes are large


centralized computers and at one time they provided the bulk of business
computing through time sharing. Mainframes are still useful for some large
scale tasks, such as centralized billing systems, inventory systems, database
operations, etc.

Minicomputers were smaller, less expensive versions of mainframes for


businesses that couldn't afford true mainframes. The chief difference
between a supercomputer and a mainframe is that a supercomputer
channels all its power into executing a few programs as fast as possible,
whereas a mainframe uses its power to execute many programs
concurrently. Besides various versions of operating systems by IBM for its
early System/360, to newest Z series operating system z/OS, Unix and Linux
are also used as mainframe operating systems.

Servers Operating Systems:

Servers are computers or groups of computers that provides services to


other computers, connected via network. Based on the requirements, there
are various versions of server operating systems from different vendors,
starting with Microsoft's Servers from Windows NT to Windows 2003, OS/2
servers, UNIX servers, Mac OS servers, and various flavors of Linux.

Workstation Operating Systems:

Workstations are more powerful versions of personal computers. Like


desktop computers, often only one person uses a particular workstation, and
run a more powerful version of a desktop operating system. Most of the
times workstations are used as clients in a network environment. The
popular workstation operating systems are Windows NT Workstation,
Windows 2000 Professional, OS/2 Clients, Mac OS, UNIX, Linux, etc

Desktop Operating Systems:

A personal computer (PC) is a microcomputer whose price, size, and


capabilities make it useful for individuals, also known as Desktop computers
or home computers.

Desktop operating systems are used for personal computers, for example
DOS, Windows 9x, Windows XP, Macintosh OS, Linux, etc.

14
Embedded Operating Systems:

Embedded systems are combinations of processors and special software that


are inside of another device, such as the electronic ignition system on cars.
Examples of embedded operating systems are Embedded Linux, Windows
CE, Windows XP Embedded, Free DOS, Free RTOS, etc.

Operating Systems for Handheld Computers:

Handheld operating systems are much smaller and less capable than
desktop operating systems, so that they can fit into the limited memory of
handheld devices. The operating systems include Palm OS, Windows CE,
EPOC, and many Linux versions such as Qt Palmtop, and Pocket Linux, etc.

QUESTIONS
1. What is an operating system?
2. What are the objectives of an operating system?
3. Describe in brief, the function of an operating system.
4. Explain the evolution of operating system in brief.
5. Write a note on Batch OS. Discuss how it is differ from Multi Programmed Batch
Systems.
6. What is difference between multi-programming and timesharing operating systems?
7. What are the typical features of an operating system provides?
8. Explain the functions of operating system as file manager.
9. What are different services provided by an operating system?
10. Write Note on :
a. Mainframe Operating Systems
b. Embedded Operating Systems
c. Servers Operating Systems
d. Desktop Operating Systems
11. Discuss the various components of OS?
12. Explain the Memory Management and File Management in brief.
13. Write Note on -
a. Secondary-Storage Management
b. Command Interpreter System
14. Explain the five services provided by the operating system.

15
Summary
Operating System system program applications program

Users, computer hardware

operating system hardware details

users

16
Chapter-2
PROCESS MANAGEMENT

Objectives
 Unit Proces PCB components, Process State model

 Unit Scheduling conditions scheduling


algorithm
 Deadlock, conditions for deadlock, deadlock avoid unit

What is a Process?

The notion of process is central to the understanding of operating systems.


The term process is used somewhat interchangeably with 'task' or 'job'.
There are quite a few definitions presented in the literature, for instance\

· A program in Execution.

· An asynchronous activity.

· The entity to which processors are assigned.

· The 'dispatchable' unit.

And many more, but the definition "Program in Execution" seem to be most
frequently used. And this is a concept we will use in the present study of
operating systems.

Process is not the same as program. A process is more than a program code.
A process is an 'active' entity as oppose to program which considered being
a 'passive' entity. As we all know that a program is an algorithm expressed
in some programming language. Being a passive, a program is only a part of
process. Process, on the other hand, includes:

17
· Current value of Program Counter (PC)

· Contents of the processors registers

· Value of the variables

· The process stack, which typically contains temporary data such as


subroutine parameter, return address, and temporary variables.

· A data section that contains global variables.

· A process is the unit of work in a system.

In Process model, all software on the computer is organized into a number


of sequential processes. A process includes PC, registers, and variables.
Conceptually, each process has its own virtual CPU. In reality, the CPU
switches back and forth among processes.

Process Creation

In general-purpose systems, some way is needed to create processes as


needed during operation. There are four principal events led to processes
creation.

· System initialization.

· Execution of a process Creation System call by a running process.

· A user request to create a new process.

· Initialization of a batch job.

Foreground processes interact with users. Background processes that stay in


background sleeping but suddenly springing to life to handle activity such as
email, webpage, printing, and so on. Background processes are called
daemons. This call creates an exact clone of the calling process.

Following are some reasons for creation of a process

1. User logs on.

2. User starts a program.

18
3. Operating systems creates process to provide service, e.g., to manage
printer.

4. Some program starts another process.

Creation of a process involves following steps:

1. Assign a unique process identifier to the new process, followed by


making new entry in to the process table regarding this process.

2. Allocate space for the process: this operating involves finding how much
space is needed by the process and allocating space to the parts of the
process such as user program, user data, stack and process attributes.
The requirement of the space can be taken by default based on the type
of the process, or from the parent process if the process is spawned by
another process.

3. Initialize Process Control Block: the PCB contains various attributes


required to execute and control a process, such as process
identification, processor status information and control information. This
can be initialized to standard default values plus attributes that have
been requested for this process.

4. Set the appropriate linkages: the operating system maintains various


queues related to a process in the form of linked lists, the newly created
process should be attached to one of such queues.

5. Create or expand other data structures: depending on the


implementation, an operating system may need to create some data
structures for this process, for example to maintain accounting file for
billing or performance assessment.

Process Termination

A process terminates when it finishes executing its last statement. Its


resources are returned to the system, it is purged from any system lists or
tables, and its process control block (PCB) is erased i.e., the PCB's
memory space is returned to a free memory pool. The new process
terminates the existing process, usually due to following reasons:

Normal Exit-Most processes terminates because they have done their job.
This call is exit in UNIX.

19
Error Exit-When process discovers a fatal error. For example, a user tries to
compile a program that does not exist.

Fatal Error-An error caused by process due to a bug in program for


example, executing an illegal instruction, referring non-existing memory or
dividing by zero.

Killed by another Process-A process executes a system call telling the


Operating Systems to terminate some other process.

Process States

A process goes through a series of discrete process states during its lifetime.
Depending on the implementation, the operating systems may differ in the
number of states a process goes though. The state of a process is defined in
part by the current activity of that process. Each process may be in one of
the following states:

• New. The process is being created.

• Running. Instructions are being executed.

• Waiting. The process is waiting for some event to occur (such as an I/O

completion or reception of a signal).

• Ready. The process is waiting to be assigned to a processor.

• Terminated. The process has finished execution.

Five State Process Model

Following are the states of a five state process model.

20
 New State -The process being created.
 Terminated State -The process has finished execution.
 Blocked (waiting) State - When a process blocks, it does so because
logically it cannot continue, typically because it is waiting for input that
is not yet available. Formally, a process is said to be blocked if it is
waiting for some event to happen (such as an I/O completion) before
it can proceed. In this state a process is unable to run until some
external event happens.
 Running State - A process is said to be running if it currently has the
CPU, which is, actually using the CPU at that particular instant.
 Ready State - A process is said to be ready if it use a CPU if one
were available. It is run-able but temporarily stopped to let another
process run.

Swapping
Many of the operating systems follow the above shown process model.
However the operating systems which does not employ virtual memory, the
processor will be idle most of the times considering the difference between
speed of I/O and processor. There will be many processes waiting for I/O in
the memory, and exhausting the memory. If there is no ready process to
run; new processes cannot be created as there is no memory available to
accommodate new process. Thus the processor has to wait till any of the
waiting processes become ready after completion of an I/O operation.

This problem can be solved by adding to more states in the above process
model by using swapping technique. Swapping involves moving part or all of
a process from main memory to disk. When none of the processes in main
memory is in the ready state, the operating system swaps one of the
blocked processes out onto disk in to a suspend queue. This is a queue of
existing processes that have been temporarily shifted out of main memory,
or suspended. The operating system then either creates new process or
brings a swapped process from the disk which has become ready.

21
Seven State Process Model

The following figure shows the seven state process model in which uses
above described swapping technique.

Apart from the transitions we have seen in five states model, following are
the new transitions which occur in the above seven state model.

Blocked to Blocked / Suspend: If there are now ready processes in the main
memory, at least one blocked process is swapped out to make room for
another process that is not blocked.

Blocked / Suspend to Blocked: If a process is terminated making space in


the main memory, and if there is any high priority process which is blocked
but suspended, anticipating that it will become free very soon, the process is
brought in to the main memory.

Blocked / Suspend to Ready / Suspend: A process is moved from Blocked /


Suspend to Ready / Suspend, if the event occurs on which the process was
waiting, as there is no space in the main memory.

Ready / Suspend to Ready: If there are no ready processes in the main


memory, operating system has to bring one in main memory to continue the
execution. Sometimes this transition takes place even there are ready

22
processes in main memory but having lower priority than one of the
processes in Ready / Suspend state. So the high priority process is brought
in the main memory.

Ready to Ready / Suspend: Normally the blocked processes are suspended


by the operating system but sometimes to make large block free, a ready
process may be suspended. In this case normally the low priority processes
are suspended.

New to Ready / Suspend: When a new process is created, it should be added


to the Ready state. But sometimes sufficient memory may not be available
to allocate to the newly created process. In this case, the new process is
sifted to Ready / Suspend.

Process Structure

The location of the process depends on memory management scheme being


used. In the simplest case, a process is maintained in the secondary
memory, and to manage this process, at least small part of this process is
maintained in the main memory. To execute the process, the entire process
or part of it is brought in the main memory, and for that the operating
system need to know the location of the process.

Process identification
Processor state information
Process control information
User Stack
Private user address space
(program, data)
Shared address space
Figure 3.3: Process Image

The obvious contents of a process are User Program to be executed, and


the User Data which is associated with that program. Apart from these there
are two major parts of a process; System Stack, which is used to store
parameters and calling addresses for procedure and system calls,
and Process Control Block, this is nothing but collection of process attributes
needed by operating system to control a process. The collection of user

23
program, data, system stack, and process control block is called as Process
Image as shown in the figure 3.3 above.

Process Control Block

Each process is represented in the operating system by a process control


block (PCB)—also called a task control block. A PCB is shown in Figure 3.3. It
contains many pieces of information associated with a specific process,
including these:

• Process state-The state may be new, ready, running, waiting, halted, and
so on.

• Program counter- The counter indicates the address of the next


instruction to be executed for this process.

• CPU registers-The registers vary in number and type, depending on the


computer architecture. They include accumulators, index registers, stack
pointers, and general-purpose registers, plus any condition-code
information. Along with the program counter, this state information must be
saved when an interrupt occurs, to allow the process to be continued
correctly afterward.

• CPU-scheduling information-This information includes a process


priority, pointers to scheduling queues, and any other scheduling
parameters.

24
• Memory-management information- This information may include such
information as the value of the base and limit registers, the page tables, or
the segment tables, depending on the memory system used by the
operating system.

• Accounting information-This information includes the amount of CPU


and real time used, time limits, account members, job or process numbers,
and so on.

• I/O status information- This information includes the list of I/O devices
allocated to the process, a list of open files, and so on. In brief, the PCB
simply serves as the repository for any information that may vary from
process to process.

Context Switching

To give each process on a multi programmed machine a fair share of the


CPU, a hardware clock generates interrupts periodically. This allows the
operating system to schedule all processes in main memory (using
scheduling algorithm) to run on the CPU at equal intervals. Each time a clock
interrupt occurs, the interrupt handler checks how much time the current
running process has used. If it has used up its entire time slice, then the
CPU scheduling algorithm (in kernel) picks a different process to run. Each
switch of the CPU from one process to another is called a context switch.

A context is the contents of a CPU's registers and program counter at any


point in time. Context switching can be described as the kernel (i.e., the
core of the operating system) performing the following activities with regard
to processes on the CPU: (1) suspending the progression of one process and
storing the CPU's state (i.e., the context) for that process somewhere in
memory, (2) retrieving the context of the next process from memory and
restoring it in the CPU's registers and (3) returning to the location indicated
by the program counter (i.e., returning to the line of code at which the
process was interrupted) in order to resume the process. The figure bellow
depicts the process of context switch from process P0 to process P1.

25
Switching the CPU to another process requires performing a state save of
the current process and a state restore of a different process. This task is
known as a context switch. When a context switch occurs, the kernel saves
the context of the old process in its PCB and loads the saved context of the
new process scheduled to run. Context-switch time is pure overhead,
because the system does no useful work while switching. Its speed varies
from machine to machine, depending on the memory speed, the number of
registers that must be copied, and the existence of special instructions (such
as a single instruction to load or store all registers). Typical speeds are a few
milliseconds. Context-switch times are highly dependent on hardware
support. For instance, some processors (such as the Sun Ultras ARC) provide
multiple sets of registers. A context switch here simply requires changing the
pointer to the current register set. Of course, if there are more active
processes than there are register sets, the system resorts to copying
register data to and from memory, as before. Also, the more complex the
operating system, the more work must be done during a context switch
space is preserved, and what amount of work is needed to preserve it,
depend on the memory-management method of the operating system.

26
A context switch is sometimes described as the kernel suspending execution
of one process on the CPU and resuming execution of some other process
that had previously been suspended.
A context switch occurs due to interrupts, trap (error due to the current
instruction) or a system call as described below:
Clock interrupt: when a process has executed its current time quantum
which was allocated to it, the process must be switched from running state
to ready state, and another process must be dispatched for execution.
I/O interrupt: whenever any I/O related event occurs, the OS is interrupted,
the OS has to determine the reason of it and take necessary action for that
event. Thus the current process is switched to ready state and the interrupt
routine is loaded to do the action for the interrupt event (e.g. after an I/O
interrupt the OS moves all the processes which were blocked on the event,
from blocked state to ready state, and blocked/suspended to
ready/suspended state). After completion of the interrupt related actions, it is
expected that the process which was switched, should be brought for
execution, but that does not happen. At this point the scheduler again decides
which process is to be scheduled for execution from all the ready processes
afresh. This is important as it will schedule any high priority process present
in the ready queue added during the interrupt handling period.
Memory fault: when virtual memory technique is used for memory
management, many a times it happens that a process refers to a memory
address which is not present in the main memory, and needs to be brought
in. As the memory block transfer takes time, another process should be
given chance for execution and the current process should be blocked. Thus
the OS blocks the current process, issues an I/O request to get the memory
block in the memory and switches the current process to blocked state, and
loads another process for execution.
Trap: if the instruction being executed has any error or exception,
depending on the criticalness of the error / exception and design of
operating system, it may either move the process to exit state, or may
execute the current process after a possible recovery.
System call: many a times a process has to invoke a system call for a
privileged job, for this the current process is blocked and the respective
operating system's system call code is executed. Thus the context of the
current process is switched to the system call code.

27
CPU Scheduler

Whenever the CPU becomes idle, it is the job of the CPU Scheduler (a.k.a.
the short-term scheduler) to select another process from the ready queue to
run next. The storage structure for the ready queue and the algorithm used
to select the next process are not necessarily a FIFO queue. There are
several alternatives to choose from, as well as numerous adjustable
parameters for each algorithm, which is the basic subject of this entire unit.

Preemptive Scheduling

CPU scheduling decisions take place under one of four conditions:

1. When a process switches from the running state to the waiting state, such
as for an I/O request or invocation of the wait( ) system call.

2. When a process switches from the running state to the ready state, for
example in response to an interrupt.

3. When a process switches from the waiting state to the ready state, say at
completion of I/O or a return from wait ( ).

4. When a process terminates.

For conditions 1 and 4 there is no choice - A new process must be selected.


For conditions 2 and 3 there is a choice - To either continue running the
current process, or select a different one. If scheduling takes place only
under conditions 1 and 4, the system is said to be non-preemptive,
or cooperative. Under these conditions, once a process starts running it
keeps running, until it either voluntarily blocks or until it finishes. Otherwise
the system is said to be preemptive. Windows used non-preemptive
scheduling up to Windows 3.x, and started using pre-emptive scheduling
with Win95. Macs used non-preemptive prior to OSX, and pre-emptive since
then. Note that pre-emptive scheduling is only possible on hardware that
supports a timer interrupt. It is to be noted that pre-emptive scheduling can
cause problems when two processes share data, because one process may
get interrupted in the middle of updating shared data structures.

Preemption can also be a problem if the kernel is busy implementing a


system call (e.g. updating critical kernel data structures) when the
preemption occurs. Most modern UNIXes deal with this problem by making
the process wait until the system call has either completed or blocked before

28
allowing the preemption Unfortunately this solution is problematic for real-
time systems, as real-time response can no longer be guaranteed. Some
critical sections of code protect themselves from concurrency problems by
disabling interrupts before entering the critical section and re-enabling
interrupts on exiting the section. Needless to say, this should only be done
in rare situations, and only on very short pieces of code that will finish
quickly, (usually just a few machine instructions).

Dispatcher

The dispatcher is the module that gives control of the CPU to the process
selected by the scheduler. This function involves:· Switching
context. · Switching to user mode. · Jumping to the proper location in the
newly loaded program.

The dispatcher needs to be as fast as possible, as it is run on every context


switch. The time consumed by the dispatcher is known as dispatch latency.

Scheduling Criteria

There are several different criteria to consider when trying to select the
"best" scheduling algorithm for a particular situation and environment,
including:·

CPU utilization – Ideally the CPU would be busy 100% of the time, so as to
waste 0 CPU cycles. On a real system CPU usage should range from 40%
(lightly loaded) to 90% (heavily loaded.)·

Throughput – Number of processes completed per unit time. May range


from 10 / second to 1 / hour depending on the specific processes.·

Turnaround time – Time required for a particular process to complete,


from submission time to completion. (Wall clock time.)·

Waiting time – How much time processes spend in the ready queue waiting
their turn to get on the CPU.

Scheduling Algorithms

The following subsections will explain several common scheduling strategies,


looking at only a single CPU burst each for a small number of processes.
Obviously real systems have to deal with a lot more simultaneous processes
executing their CPU-I/O burst cycles.

29
First-Come First-Serve Scheduling, FCFS

FCFS is very simple - Just a FIFO queue, like customers waiting in line at the
bank or the post office or at a copying machine. Unfortunately, however,
FCFS can yield some very long average wait times, particularly if the first
process to get there takes a long time. For example, consider the following
three processes:

Process Burst Time


P1 24
P2 3
P3 3
In the first Gantt chart below, process P1 arrives first. The average waiting
time for the three processes is (0 + 24 + 27) / 3 = 17.0 ms. In the second
Gantt chart below, the same three processes have an average wait time of
(0 + 3 + 6) / 3 = 3.0 ms. The total run time for the three bursts is the
same, but in the second case two of the three finish much quicker, and the
other process is only delayed by a short amount.

FCFS can also block the system in a busy dynamic system in another way,
known as the convoy effect. When one CPU intensive process blocks the
CPU, a number of I/O intensive processes can get backed up behind it,
leaving the I/O devices idle. When the CPU hog finally relinquishes the CPU,
then the I/O processes pass through the CPU quickly, leaving the CPU idle
while everyone queues up for I/O, and then the cycle repeats itself when the
CPU intensive process gets back to the ready queue.

Shortest-Job-First Scheduling, SJF

The idea behind the SJF algorithm is to pick the quickest fastest little job
that needs to be done, get it out of the way first, and then pick the next
smallest fastest job to do next. (Technically this algorithm picks a process
based on the next shortest CPU burst, not the overall process time.). For
example, the Gantt chart below is based upon the following CPU burst times,
(and the assumption that all jobs arrive at the same time.)

30
Process Burst Time
P1 6

P2 8
P3 7
P4 3

In the case above the average wait time is (0 + 3 + 9 + 16) / 4 = 7.0 ms,
(as opposed to 10.25 ms for FCFS for the same processes.)

SJF can be either preemptive or non-preemptive. Preemption occurs when a


new process arrives in the ready queue that has a predicted burst time
shorter than the time remaining in the process whose burst is currently on
the CPU. Preemptive SJF is sometimes referred to as shortest remaining
time first scheduling. For example, the following Gantt chart is based upon
the following data:

Process Arrival Time Burst Time

P1 0 8

P2 1 4

P3 2 9

p4 3 5

The average wait time in this case is ( (5 – 3) + (10 – 1) + (17 – 2)) / 4 =


26 / 4 = 6.5 ms. (As opposed to 7.75 ms for non-preemptive SJF or 8.75 for
FCFS.)

Priority Scheduling

The SJF algorithm is a special case of the general priority scheduling


algorithm. A priority is associated with each process, and the CPU is
allocated to the process with the highest priority. Equal-priority processes
are scheduled in FCFS order.

31
An SJF algorithm is simply a priority algorithm where the priority (p) is the
inverse of the (predicted) next CPU burst. The larger the CPU burst, the
lower the priority, and vice versa.

Priorities are generally indicated by some fixed range of numbers, such as 0


to 7 or 0 to 4095. However, there is no general agreement on whether 0 is
the highest or lowest priority. Some systems use low numbers to represent
low priority; others use low numbers for high priority. We use as low
numbers represent high priority.

As an example, consider the following set of processes, assumed to have


arrived at time 0, in the order , with the length of the CPU burst

given in milliseconds:

Burst Waiting Turnaround


Process Time Priority Time Time

10 3 6 16

1 1 0 1

2 4 16 18

1 5 18 19

5 2 1 6

Average - - 8.2 12

Using priority scheduling, we would schedule these processes according to


the following chart:

Priorities can be defined either internally or externally.

Internally defined priorities use some measurable quantity or quantities to


compute the priority of a process. For example, time limits, memory

32
requirements, the number of open files, and the ratio of average I/O burst to
average CPU burst have been used in computing priorities.

External priorities are set by criteria outside the OS, such as the importance
of the process, the type and amount of funds being paid for computer use,
the department sponsoring the work, and other, often political, factors.

Priority scheduling can be either pre-emptive or non preemptive. When a


process arrives at the ready queue, its priority is compared with the priority
of the currently running process.

A pre-emptive priority scheduling algorithm will preempt the CPU if the


priority of the newly arrived process is higher than the priority of the
currently running process.

A non preemptive priority scheduling algorithm will simply put the new
process at the head of the ready queue.

A major problem with priority scheduling algorithms is indefinite blocking,


or starvation. A process that is ready to run but waiting for the CPU can be
considered blocked.

A priority scheduling algorithm can leave some low priority processes waiting
indefinitely.

In a heavily loaded computer system, a steady stream of higher-priority


processes can prevent a low-priority process from ever getting the CPU.

It is often convenient to group processes into priority classes and use


priority scheduling among the classes but round-robin scheduling within
each class. Figure 5.9 shows a system with four priority classes.

The scheduling algorithm is as follows: as long as there are runnable


processes in priority class 4, just run each one for one quantum, round-robin
fashion, and never bother with lower priority classes, if priority class 4 is
empty, then run the class 3 processes round robin. If classes 4 and 3 are
both empty, then run class 2 round robin, and so on. If priorities are not
adjusted occasionally, lower priority classes may all starve to death.

33
Figure 5.9: A scheduling algorithm with four priority classes.

A solution to the problem of indefinite blockage of low-priority processes


is aging. Aging is a technique of gradually increasing the priority
of processes that wait in the system for a long time.

For example, if priorities range from 127 (low) to 0 (high), we could increase
the priority of a waiting process by 1 every 15 minutes.

Eventually, even a process with an initial priority of 127 would have the
highest priority in the system and would be executed.

Figure 5.10: An example to Priority-based Scheduling.

Round-Robin Scheduling

The round-robin (RR) scheduling algorithm is designed especially for time-


sharing systems. It is similar to FCFS scheduling, but pre-emption is added
to switch between processes.

34
A small unit of time, called a time quantum or time slice, is defined. A time
quantum is generally from 10 to 100 milliseconds. The ready queue is
treated as a circular queue.

To implement RR scheduling,

we keep the ready queue as a FIFO queue of processes.

New processes are added to the tail of the ready queue.

The CPU scheduler picks the first process from the ready queue, sets a timer
to interrupt after 1 time quantum, and dispatches the process.

The process may have a CPU burst of less than 1 time quantum.

In this case, the process itself will release the CPU voluntarily.

The scheduler will then proceed to the next process in the ready queue.

Otherwise, if the CPU burst of the currently running process is longer than 1
time quantum,

The timer will go off and will cause an interrupt to the OS.

A context switch will be executed, and the process will be put at the tail of
the ready queue.

The CPU scheduler will then select the next process in the ready queue.

Figure 5.11: Round-robin scheduling. (a) The list of runnable


processes. (b) The list of runnable processes after B uses up its
quantum.

The average waiting time under the RR policy is often long. Consider the
following set of processes that arrive at time 0, with the length of the CPU
burst given in milliseconds: (a time quantum of 4 milliseconds)

35
Burst Waiting Turnaround
Process Time Time Time

24 6 30

3 4 7

3 7 10

Average - 5.66 15.66


Using round-robin scheduling, we would schedule these processes according
to the following chart:

In the RR scheduling algorithm, no process is allocated the CPU for more


than 1 time quantum in a row (unless it is the only runnable process).

If a process's CPU burst exceeds 1 time quantum, that process


is preempted and is put back in the ready queue. The RR scheduling
algorithm is thus pre-emptive.

Multilevel Queue Scheduling

When processes can be readily categorized, then multiple separate queues


can be established, each implementing whatever scheduling algorithm is
most appropriate for that type of job, and/or with different parametric
adjustments. Scheduling must also be done between queues, that is
scheduling one queue to get time relative to other queues. Two common
options are strict priority (no job in a lower priority queue runs until all
higher priority queues are empty) and round-robin (each queue gets a time
slice in turn, possibly of different sizes.)

Note that under this algorithm jobs cannot switch from queue to queue -
Once they are assigned a queue that is their queue until they finish.

36
Multilevel Feedback-Queue Scheduling

Multilevel feedback queue scheduling is similar to the ordinary multilevel


queue scheduling described above, except jobs may be moved from one
queue to another for a variety of reasons:

· If the characteristics of a job change between CPU-intensive and I/O


intensive, then it may be appropriate to switch a job from one queue to
another. · Aging can also be incorporated, so that a job that has waited for
a long time can get bumped up into a higher priority queue for a while.

Multilevel Feedback Queue Scheduling

Multilevel feedback queue scheduling is the most flexible, because it can be


tuned for any situation. But it is also the most complex to implement
because of all the adjustable parameters. Some of the parameters which
define one of these systems include:· The number of queues.· The
scheduling algorithm for each queue.· The methods used to upgrade or
demote processes from one queue to another. (Which may be
different)? The method used to determine which queue a process enters
initially.

37
Deadlock

A deadlock is a situation when a process in the system has acquired some


resources and waiting for more resources which are acquired by some other
process which in turn is waiting for the resources acquired by this process.
Hence, none of them can proceed and OS can’t do any work.

In a multiprogramming environment, several processes may compete for a


finite number of resources.

A process requests resources; and if the resources are not available at that
time, the process enters a waiting state. Sometimes, a waiting process is
never again able to change state, because the resources it has requested are
held by other waiting processes.

Deadlock is defined as the permanent blocking of a set of processes


that compete for system resources.

38
Necessary Conditions

Figure: An example to Deadlock.

A deadlock situation can arise if the following four conditions hold


simultaneously in a system:

Mutual exclusion. At least one resource must be held in a non-sharable


mode;

That is, only one process at a time can use the resource.

If another process requests that resource, the requesting process must be


delayed until the resource has been released.

Hold and wait. A process must be holding at least one resource and waiting
to acquire additional resources that are currently being held by other
processes.

No preemption. Resources cannot be preempted; that is, a resource can be


released only voluntarily by the process holding it, after that process has
completed its task.

Circular wait. A set of waiting processes must exist such


that

is waiting for a resource held by ,

39
is waiting for a resource held by ,

is waiting for a resource held by ,

is waiting for a resource held by .

There must be a circular chain of two or more processes, each of which is


waiting for a resource held by the next member of the chain.

We emphasize that all four conditions must hold for a deadlock to occur.

Resource-Allocation Graph

Deadlocks can be described more precisely in terms of a directed


graph called a system resource-allocation graph.

This graph consists of a set of vertices and a set of edges .

The set of vertices is partitioned into two different types of nodes: s

and s.

A directed edge from process to resource type is denoted

by ; it signifies that process has requested an instance of

resource type and is currently waiting for that resource (request edge).

A directed edge from resource type to process is denoted

by ; it signifies that an instance of resource type has been

allocated to process (assignment edge).

Pictorially, each process is represented as a circle and each resource

type as a rectangle.

40
Figure: Resource allocation graphs. (a) Holding a resource. (b)
Requesting a resource. (c) Deadlock.

An arc from a resource node (square) to a process node (circle) means that
the resource has previously been requested by, granted to, and is currently
held by that process.

Since resource type may have more than one instance, each such

instance is represented as a dot within the rectangle.

Figure 7.5: Left: Resource-allocation graph. Middle: Resource-


allocation graph with a deadlock. Right: Resource-allocation graph with
a cycle but no deadlock

The resource-allocation graph shown in Fig. 7.5left depicts the following


situation. The sets , , and :

41
Given the definition of a resource-allocation graph, it can be shown that, if
the graph contains no cycles, then no process in the system is deadlocked. If
the graph does contain a cycle, then a deadlock may exist.
A cycle in the graph is a necessary but not a sufficient condition for the
existence of deadlock with resource types of several instances. A knot must
exist; a cycle with no non-cycle outgoing path from any involved node

Suppose that process requests an instance of resource type . Since

no resource instance is currently available, a request edge is is

added to the graph.


At this point, two minimal cycles exist in the system.
Now consider the resource-allocation graph in Fig. 7.5right.
In this case, we also have a cycle. However, there is no deadlock.

Observe that process may release its instance of resource type .

That resource can then be allocated to , breaking the cycle.

In summary, if a resource-allocation graph does not have a cycle, then the


system is not in a deadlocked state. If there is a cycle, then the system may
or may not be in a deadlocked state.
An example of resource allocation graphs;

42
Figure: Resource Allocation Graphs. Lower; either or could

relinquish (release) a resource allowing or (which are currently


blocked) to continue.
Another example of how resource graphs can be used; three processes,
, , and , and three resources , , and (see Fig. 7.7);.

Figure: An example of how deadlock occurs and how it can be avoided.

Methods for Handling Deadlocks

Generally speaking, we can deal with the deadlock problem in one of


three ways:

We can use a protocol to prevent or avoid deadlocks, ensuring that the


system will never enter a deadlock state.

43
To ensure that deadlocks never occur, the system can use either a deadlock-
prevention or a deadlock-avoidance scheme.

Deadlock prevention provides a set of methods for ensuring that at least one
of the necessary conditions (Section 7.2.1) cannot hold.

Design a system in such a way that the possibility of deadlock is excluded a


priori (compile-time/statically, by design).

Deadlock avoidance requires that the OS be given in advance additional


information concerning which resources a process will request and use
during its lifetime. With this additional knowledge, it can decide for each
request whether or not the process should wait.

Make a decision dynamically checking whether the request will, if granted,


potentially lead to a deadlock or not. (run-time/dynamically, before it
happens).

We can allow the system to enter a deadlock state, detect it, and recover.

If a system does not employ either a deadlock-prevention or a deadlock-


avoidance algorithm, then a deadlock situation may arise.

In this environment, the system can provide an algorithm that examines


the state of the system to determine whether a deadlock has occurred and
an algorithm to recover from the deadlock.

Let deadlocks occur, detect them, and take action (run-time/dynamically,


after it happens)

We can ignore (The Ostrich Algorithm; maybe if you ignore it, it will ignore
you) the problem altogether and pretend that deadlocks never occur in the
system.

If a system neither ensures that a deadlock will never occur nor provides a
mechanism for deadlock detection and recovery, then we may arrive at a
situation where the system is in a deadlocked state yet has no way of
recognizing what has happened.

Eventually, the system will stop functioning and will need to be restarted
manually.

44
In many systems, deadlocks occur infrequently (say, once per year); thus,
this method is cheaper than the prevention, avoidance, or detection and
recovery methods.

Most OSs potentially suffers from deadlocks that are not even detected.
Process table slots are finite resources. If a fork fails because the table is
full, a reasonable approach for the program doing the fork is to wait a
random time and try again.

The maximum number of open files is similarly restricted by the size of the i-
node table, so a similar problem occurs when it fills up. Swap space on the
disk is another limited resource. In fact, almost every table in the OS
represents a finite resource.

The third solution is the one used by most OSs, including UNIX and
Windows; it is then up to the application developer to write programs that
handle deadlocks.

If deadlocks could be eliminated for free, there would not be much


discussion. The problem is that the price is high, mostly in terms of putting
inconvenient restrictions on processes.

Thus we are faced with an unpleasant trade-off between convenience and


correctness. Under these conditions, general solutions are hard to find.

Deadlock Prevention

Having seen that deadlock avoidance is essentially impossible, because it


requires information about future requests, which is not known, how do real
systems avoid deadlock?

If we can ensure that at least one of the four following conditions is never
satisfied, then deadlocks will be structurally impossible.

The various approaches to deadlock prevention are summarized in Fig. 7.8.

45
Figure: Summary of approaches, to deadlock prevention.

Mutual Exclusion

Attacking the Mutual Exclusion Condition; can a given resource be assigned


to more than one process at once? Systems with only simultaneously shared
resources cannot deadlock!

The mutual-exclusion condition must hold for non sharable resources (i.e., a
printer).

Shareable resources, in contrast, do not require mutually exclusive access


and thus cannot be involved in a deadlock (i.e. read-only files). A process
never needs to wait for a shareable resource.

In general, however, we cannot prevent deadlocks by denying the mutual-


exclusion condition, because some resources are intrinsically non-sharable.

Hold and Wait

Attacking the Hold and Wait Condition; can a process hold a resource and
ask for another? Can we require processes to request all resources at once?
Most processes do not statically know about the resources they need.

To ensure that the hold-and-wait condition never occurs in the system, we


must guarantee that, whenever a process requests a resource, it does not
hold any other resources.

One protocol that can be used requires each process to request and be
allocated all its resources before it begins execution.

An alternative protocol allows a process to request resources only when it


has none. A process may request some resources and use them. Before it

46
can request any additional resources, however, it must release all the
resources that it is currently allocated.

To illustrate the difference between these two protocols, we consider a


process that copies data from a DVD drive to a file on disk, sorts the file,
and then prints the results to a printer.

Both these protocols have two main disadvantages.

First, resource utilization may be low, since resources may be allocated but
unused for a long period.

Second, starvation is possible. A process that needs several popular


resources may have to wait indefinitely, because at least one of the
resources that it needs is always allocated to some other process.

No Preemption

Attacking the No Preemption Condition; can resources be preempted? If a


process' requests (holding certain resources) is denied, that process must
release its unused resources and request them again, together with the
additional resource.

The third necessary condition for deadlocks is that there be no preemption of


resources that have already been allocated.

To ensure that this condition does not hold, we can use the following
protocol.

If a process is holding some resources and requests another resource that


cannot be immediately allocated to it (that is, the process must wait), then
all resources currently being held are preempted.

The preempted resources are added to the list of resources for which the
process is waiting. The process will be restarted only when it can regain its
old resources, as well as the new ones that it is requesting.

47
Circular Wait

Attacking the Circular Wait Condition; Can circular waits exist? Order
resources by an index: ; requires that resources are always

requested in order.

One way to ensure that this condition never holds is to impose a total
ordering of all resource types and to require that each process requests
resources in an increasing order of enumeration.

Assign to each resource type a unique integer number, which allows us to


compare two resources and to determine whether one precedes another in
our ordering.

Each process can request resources only in an increasing order


of enumeration.

If these two protocols are used, then the circular-wait condition cannot hold.

Recovery from Deadlock

When a detection algorithm determines that a deadlock exists, several


alternatives are available.

One possibility is to inform the operator that a deadlock has occurred and to
let the operator deal with the deadlock manually.

Another possibility is to let the system recover from the deadlock


automatically.

There are two options for breaking a deadlock.

One is simply to abort one or more processes to break the circular.

Resource Preemption

To eliminate deadlocks using resource preemption, we successively preempt


some resources from processes and give these resources to other processes
until the deadlock cycle is broken.

In some cases it may be possible to temporarily take a resource away from


its current owner and give it to another process. Highly dependent on the

48
nature of the resource. Recovering this way is frequently difficult or
impossible.

Selecting a victim. Which resources and which processes are to be


preempted? As in process termination, we must determine the order of
preemption to minimize cost.

Rollback. If we preempt a resource from a process, what should be done


with that process? Clearly, it cannot continue with its normal execution; it is
missing some needed resource.

Check pointing; means that its state is written to a file so that it can be
restarted later.

The checkpoint contains not only the memory image, but also the resource
state, that is, which resources are currently assigned to the process.

When a deadlock is detected, it is easy to see which resources are needed.


To do the recovery, a process that owns a needed resource is rolled back to
a point in time before it acquired some other resource by starting one of its
earlier checkpoints.

Since, in general, it is difficult to determine what a safe state is, the simplest
solution is a total rollback: Abort the process and then restart it.

Although it is more effective to roll back the process only as far as necessary
to break the deadlock, this method requires the system to keep more
information about the state of all running processes.

Starvation. How do we ensure that starvation will not occur? That is, how
can we guarantee that resources will not always be preempted from the
same process?

Solutions to deadlock

There are several ways to address the problem of deadlock in an operating


system.

 Just ignore it and hope it doesn't happen


 Detection and recovery - if it happens, take action

49
 Dynamic avoidance by careful resource allocation. Check to see if a
resource can be granted, and if granting it will cause deadlock, don't
grant it.
 Prevention - change the rules

Ignore deadlock

The text refers to this as the Ostrich Algorithm. Just hope that deadlock
doesn't happen. In general, this is a reasonable strategy. Deadlock is
unlikely to occur very often; a system can run for years without deadlock
occurring. If the operating system has a deadlock prevention or detection
system in place, this will have a negative impact on performance (slow the
system down) because whenever a process or thread requests a resource,
the system will have to check whether granting this request could cause a
potential deadlock situation.

If deadlock does occur, it may be necessary to bring the system down, or at


least manually kill a number of processes, but even that is not an extreme
solution in most situations.

Deadlock detection and recovery

As we saw above, if there is only one instance of each resource, it is possible


to detect deadlock by constructing a resource allocation/request graph and
checking for cycles. Graph theorists have developed a number of algorithms
to detect cycles in a graph. The book discusses one of these. It uses only
one data structure L a list of nodes.

A cycle detection algorithm

For each node N in the graph

Initialize L to the empty list and designate all edges as unmarked

Add the current node to L and check to see if it appears twice. If it does,
there is a cycle in the graph.

From the given node, check to see if there are any unmarked outgoing
edges. If yes, go to the next step, if no, skip the next step

50
Pick an unmarked edge, mark it, then follow it to the new current node and
go to step 3.

We have reached a dead end. Go back to the previous node and make that
the current node. If the current node is the starting Node and there are no
unmarked edges, there are no cycles in the graph. Otherwise, go to step 3.

Let's work through an example with five processes and five resources. Here
is the resource request/allocation graph.

The algorithm needs to search each node; let's start at node P1. We add P1
to L and follow the only edge to R1, marking that edge. R1 is now the
current node so we add that to L, checking to confirm that it is not already in
L. We then follow the unmarked edge to P2, marking the edge, and making
P2 the current node. We add P2 to L, checking to make sure that it is not
already in L, and follow the edge to R2. This makes R2 the current node, so
we add it to L, checking to make sure that it is not already there. We are
now at a dead end so we back up, making P2 the current node again. There
are no more unmarked edges from P2 so we back up yet again, making R1
the current node. There are no more unmarked edges from R1 so we back
up yet again, making P1 the current node. Since there are no more
unmarked edges from P1 and since this was our starting point, we are
through with this node (and all of the nodes visited so far).

We move to the next unvisited node P3, and initialize L to empty. We first
follow the unmarked edge to R1, putting R1 on L. Continuing, we make P2
the current node and then R2. Since we are at a dead end, we repeatedly
back up until P3 becomes the current node again.

L now contains P3, R1, P2, and R2. P3 is the current node, and it has
another unmarked edge to R3. We make R3 the current node, add it to L,
follow its edge to P4. We repeat this process, visiting R4, then P5, then R5,
then P3. When we visit P3 again we note that it is already on L, so we have
detected a cycle, meaning that there is a deadlock situation.

Once deadlock has been detected, it is not clear what the system should do
to correct the situation. There are three strategies.

Preemption – we can take an already allocated resource away from a


process and give it to another process. This can present problems. Suppose

51
the resource is a printer and a print job is half completed. It is often difficult
to restart such a job without completely starting over.

Rollback – In situations where deadlock is a real possibility, the system can


periodically make a record of the state of each process and when deadlock
occurs, roll everything back to the last checkpoint, and restart, but allocating
resources differently so that deadlock does not occur. This means that all
work done after the checkpoint is lost and will have to be redone.

Kill one or more processes – this is the simplest and crudest, but it works.

Deadlock avoidance

The above solution allowed deadlock to happen, then detected that deadlock
had occurred and tried to fix the problem after the fact. Another solution is
to avoid deadlock by only granting resources if granting them cannot result
in a deadlock situation later. However, this works only if the system knows
what requests for resources a process will be making in the future, and this
is an unrealistic assumption. The text describes the bankers algorithm but
then points out that it is essentially impossible to implement because of this
assumption.

Deadlock Prevention

The difference between deadlock avoidance and deadlock prevention is a


little subtle. Deadlock avoidance refers to a strategy where whenever a
resource is requested, it is only granted if it cannot result in deadlock.
Deadlock prevention strategies involve changing the rules so that processes
will not make requests that could result in deadlock.

Here is a simple example of such a strategy. Suppose every possible


resource is numbered (easy enough in theory, but often hard in practice),
and processes must make their requests in order; that is, they cannot
request a resource with a number lower than any of the resources that they
have been granted so far. Deadlock cannot occur in this situation.

As an example, consider the dining philosophers problem. Suppose each


chopstick is numbered, and philosophers always have to pick up the lower
numbered chopstick before the higher numbered chopstick. Philosopher five
picks up chopstick 4, philosopher 4 picks up chopstick 3, philosopher 3 picks
up chopstick 2, philosopher 2 picks up chopstick 1. Philosopher 1 is hungry,

52
and without this assumption, would pick up chopstick 5, thus causing
deadlock. However, if the lower number rule is in effect, he/she has to pick
up chopstick 1 first, and it is already in use, so he/she is blocked.
Philosopher 5 picks up chopstick 5, eats, and puts both down, allows
philosopher 4 to eat. Eventually everyone gets to eat.

An alternative strategy is to require all processes to request all of their


resources at once, and either all are granted or none are granted. Like the
above strategy, this is conceptually easy but often hard to implement in
practice because it assumes that a process knows what resources it will need
in advance.

Livelock

There is a variant of deadlock called livelock. This is a situation in which two


or more processes continuously change their state in response to changes in
the other process(es) without doing any useful work. This is similar to
deadlock in that no progress is made but differs in that neither process is
blocked or waiting for anything.

A human example of livelock would be two people who meet face-to-face in


a corridor and each moves aside to let the other pass, but they end up
swaying from side to side without making any progress because they always
move the same way at the same time.

Addressing deadlock in real systems

Deadlock is a terrific theoretical problem for graduate students, but none of


the solutions discussed above can be implemented in a real world, general
purpose operating system. It would be difficult to require a user program to
make requests for resources in a certain way or in a certain order. As a
result, most operating systems use the ostrich algorithm.

Some specialized systems have deadlock avoidance/prevention mechanisms.


For example, many database operations involve locking several records, and
this can result in deadlock, so database software often has a deadlock
prevention algorithm.

The Unix file locking system lockf has a deadlock detection mechanism built
into it. Whenever a process attempts to lock a file or a record of a file, the
operating system checks to see if that process has locked other files or

53
records, and if it has, it uses a graph algorithm similar to the one discussed
above to see if granting that request will cause deadlock, and if it does, the
request for the lock will fail, and the lockf system call will return and errno
will be set to EDEADLK.

Killing Zombies

Recall that if a child dies before its parent calls wait, the child becomes a
zombie. In some applications, a web server for example, the parent forks off
lots of children but doesn't care whether the child is dead or alive. For
example, a web server might fork a new process to handle each connection,
and each child dies when the client breaks the connection. Such an
application is at risk of producing many zombies, and zombies can clog up
the process table.

Pipes

A second form of redirection is a pipe. A pipe is a connection between two


processes in which one process writes data to the pipe and the other reads
from the pipe.

What is concurrency

"Concurrency occurs when two or more execution flows are able to run
simultaneously." – Edsger Dijkstra.

Concurrency is a property of systems which execute processes overlapped in


time on single or multiple processors, and which may permit the sharing of
common resources between those overlapped processes. Concurrent use of
shared resources is the source of many difficulties, such as race conditions
(as explained bellow). The introduction of mutual exclusion can prevent race
conditions, but can lead to problems such as deadlock, and starvation.

In a single-processor multiprogramming system, processes must be are


interleaved in time to yield the appearance of simultaneous execution. In a
multiple-processor system, it is possible not only to interleave the execution
of multiple processes but also to overlap them. Interleaving and overlapping
techniques can be viewed as examples of concurrent processing

Concurrency control is a method used to ensure that processes are executed


in a safe manner (i.e., without affecting each other) and correct results are
generated, while getting those results as quickly as possible.

54
Race Conditions

A race condition occurs when multiple processes or threads read and write
data items so that the final result depends on the order of execution of
instructions in the multiple processes.

Suppose that two processes, P1 and P2, share the global variable A. At some
point in its execution, P1 updates variable A to the value 1, and at some
point in its execution, P2 updates variable A to the value 2. Thus, the two
processes are in a race to write variable A. In this example the "loser" of the
race (the process that updates last) determines the final value of A.

Critical Section

A critical section is a part of program that accesses a shared resource


(data structure or device) that must not be concurrently accessed by more
than one process of execution. The key to preventing trouble involving
shared storage is find some way to prohibit more than one process from
reading and writing the shared data simultaneously. To avoid race conditions
and flawed results, one must identify codes in Critical Sections in each
process.

Mutual Exclusion

Mutual exclusion is a way of making sure that if one process is using a


shared modifiable data, the other processes will be excluded from doing the
same thing.

That is, while one process executes the shared variable, all other processes
desiring to do so at the same time moment should be kept waiting; when
that process has finished using the shared variable, one of the processes
waiting to do so should be allowed to proceed. In this fashion, each process
using the shared data (variables) excludes all others from doing so
simultaneously. This is called Mutual Exclusion.

Mutual exclusion needs to be enforced only when processes access shared


modifiable data - when processes are performing operations that do not
conflict with one another they should be allowed to proceed concurrently.

Requirements for mutual exclusion

Following are the six requirements for mutual exclusion.

55
1. Mutual exclusion must be enforced: Only one process at a time is
allowed into its critical section, among all processes that have critical
sections for the same resource or shared object.
2. A process that halts in its non critical section must do so without
interfering with other processes.
3. It must not be possible for a process requiring access to a critical
section to be delayed indefinitely.
4. When no process is in a critical section, any process that requests
entry to its critical section must be permitted to enter without delay.
5. No assumptions are made about relative process speed or number of
processors.
6. A process remains inside its critical section for a finite time only.

Following are some of the methods for achieving mutual exclusion.

Mutual exclusion by disabling interrupts:

In an interrupt driven system, context switches from one process to another


can only occur on interrupts (timer, I/O device, etc). If a process disables all
interrupts then it cannot be switched out.

On entry to the critical section the process can disable all interrupts, and on
exit from it can enable them again as shown bellow.

while (true)

/* disable interrupts */;

/* critical section */;

/* enable interrupts */;

/* remainder */;

Figure : Mutual exclusion by disabling interrupts

Because the critical section cannot be interrupted, mutual exclusion is


guaranteed. But as the processor can not interleave processes, the system
performance is degraded. Also this solution does not work for multi
processor system, where more than one process is run concurrently.

56
Mutual exclusion by using Lock variable:

In this method, we consider a single, shared, (lock) variable, initially 0.


When a process wants to enter in its critical section, it first tests the lock
value. If lock is 0, the process first sets it to 1 and then enters the critical
section. If the lock is already 1, the process just waits until (lock) variable
becomes 0. Thus, a 0 means that no process in its critical section and 1
mean some process is in its critical section.

process (i)

while(lock != 0)

/* no operation */;

lock = 1;

/* critical section */;

lock = 0;

/* remainder */;

Figure : Mutual exclusion using lock variable

The flaw in this proposal can be best explained by example. Suppose process
A sees that the lock is 0. Before it can set the lock to 1 another process B is
scheduled, runs, and sets the lock to 1. When the process A runs again, it
will also set the lock to 1, and two processes will be in their critical section
simultaneously. Thus this method does not guarantee mutual exclusion.

Mutual exclusion by Strict Alternation:

In this method, the integer variable 'turn' keeps track of whose turn is to
enter the critical section. Initially, process 0 inspect turn, finds it to be 0,
and enters in its critical section. Process 1 also finds it to be 0 and sits in a
loop continually testing 'turn' to see when it becomes 1. Process 0, after
coming out of critical section, sets turn to 1, to allow process 1 to enter in its
critical section, as shown bellow.

57
/* Process 0 */

while (true)

while(turn != 0)

/* no operation */;

/* critical section */;

turn = 1;

/* remainder */;

/* Process 1 */

while (true)

while(turn != 1)

/* no operation */;

/* critical section */;

turn = 0;

/* remainder */;

Figure : Mutual exclusion by strict alternation

Taking turns is not a good idea when one of the processes is much slower
than the other. Suppose process 0 finishes its critical section quickly, and
again wants to enter in its critical section, but it cannot do so, as the turn
value is set to 1. It has to wait for process 1 to finish its critical section part.
Here both processes are in their non-critical section. This situation violates
above mutual exclusion requirement condition no. 4.

58
Mutual exclusion by Peterson's Method:

The algorithm uses two variables, flag, a boolean array and turn, an integer.
A true flag value indicates that the process wants to enter the critical section.
The variable turn holds the id of the process whose turn it is. Entrance to the
critical section is granted for process P0 if P1 does not want to enter its critical
section or if P1 has given priority to P0 by setting turn to 0.

flag[0]=false;

flag[1]=false;

turn = 0;

/* Process 0 */

while (true)

flag[0] = true;

turn = 1;

while(flag[1] && turn == 1)

/* no operation */;

/* critical section */;

flag[0] = false;

/* remainder */;

/* Process 1 */

while (true)

flag[1] = true;

turn = 0;

while(flag[0] && turn == 0)

59
/* no operation */;

/* critical section */;

flag[1] = false;

/* remainder */;

Figure : Peterson's algorithm

Mutual exclusion by using Special Machine Instructions:

In a multiprocessor environment, the processors share access to a common


main memory and at the hardware level, only one access to a memory
location is permitted at a time. With this as a foundation, some computer
processors designed several machine instructions that carry out two actions,
such as reading and writing, of a single memory location. Since processes
interleave at the instruction level, so such special instructions are atomic and
are not subject to interference from other processes. Two of such kind of
instructions are discussed in the following parts.

Test and Set Instruction: The test and set instruction can be defined as
follows:

boolean testset (int i)

if (i = = 0)

i=1;

return true;

} else.

return false;

60
Figure : Test and Set Instructions

where the variable i is used like a traffic light. If it is 0, meaning green, then
the instruction sets it 1, i.e. red, and return true. Thus the current process is
permitted to pass but the others are told to stop. On the other hand, if the
light is already red, then the running process will receive false and realize
not supposed to proceed.

Exchange Instruction: The exchange instruction can be defined as follows:

void exchange (int register, int memory)

int temp;

temp = memory;

memory = register;

register = temp;

} Figure 7.6: Exchange Instruction

The instruction exchanges the contents of a register with that of a memory


location. A shared variable bolt is initialized to 0. Each process uses a local
variable key that is initialized to 1, and executes the instruction as
exchange(key, bolt). .The only process that may enter its critical section is
one that finds bolt equal to 0. It excludes all other processes from the critical
section by setting bolt to 1. When a process leaves its critical section, it
resets bolt to 0, allowing another process to gain access to its critical
section.

Semaphores

All the above methods of mutual exclusion have a basic problem of busy
waiting. If a process is unable to enter in to its critical section; it tightly
executes the loop of testing the shared global variable, wasting CPU time, as
well as resources. Semaphores avoid this wastage of time and resources by
blocking the process if it cannot enter into its critical section. This process
will be wake up by the currently running process after coming out of critical
section.

61
What are Semaphores

A semaphore is a mechanism that prevents two or more processes from


accessing a shared resource simultaneously. On the railroads a semaphore
prevents two trains from crashing on a shared section of track. On railroads
and computers, semaphores are advisory: if a train engineer doesn't observe
and obey it, the semaphore won't prevent a crash, and if a process doesn't
check a semaphore before accessing a shared resource, chaos might result.

Semaphores can be thought of as flags (hence their name, semaphores).


They are either on or off. A process can turn on the flag or turn it off. If the
flag is already on, processes that try to turn on the flag will sleep until the
flag is off. Upon awakening, the process will reattempt to turn the flag on,
possibly succeeding or possibly sleeping again. Such behavior allows
semaphores to be used in implementing a post-wait driver - a system where
processes can wait for events (i.e., wait on turning on a semaphore) and
post events (i.e. turning off of a semaphore).

Dijkstra in 1965 proposed semaphores as a solution to the problems of


concurrent processes. The fundamental principle is: That two or more
processes can cooperate by means of simple signals, such that a process can
be forced to stop at a specified place until it has received a specific signal.

For signaling, special variables called semaphores are used.

Primitive signal (s) is used to transmit a signal

Primitive wait (s) is used to receive a signal

Semaphore Implementation:

To achieve desired effect, view semaphores as variables that have an integer


value upon which three operations are defined:

A semaphore may be initialized to a non-negative value

The wait operation decrements the semaphore value. If the value becomes
negative, the process executing the wait is blocked

The signal operation increments the semaphore value. If the value is not
positive, then the process blocked by wait operation is unblocked. There is
no other way to manipulate semaphores

62
wait (S)

while (S£ 0); /*no-operation */;

S--;

signal (S)

S++;

Figure 7.7: Semaphore operations

Mutual Exclusion using Semaphore:

The following example illustrates mutual exclusion using semaphore:

A process before entering in to its critical section, performs wait(mutex)


operating and after coming out of critical section, signal(mutex) operation;
thus achieving mutual exclusion.

Shared data:

semaphore mutex; //initially mutex = 1

Process: Pi:

do

{ wait(mutex); /* critical section */

signal(mutex);

/* remainder section */

} while (1);

Figure: Mutual exclusion using semaphore

63
Following code gives the detailed implementation of wait and signal
procedures for above example. The structure definition has semaphore value
and process link. The wait operation decrements the semaphore value, and if
it is less than 0 then adds it to waiting queue and blocks the process.

Declaration:

typedef struct

int value;

struct process *L;

} semaphore;

wait(S):

S.value--;

if (S.value < 0)

add this process to S.L;

block;

signal(S):

S.value++;

if (S.value <= 0)

{ remove a process P from S.L;

wakeup(P);

64
}

Figure: wait() and signal() for mutual exclusion

The process which is currently in critical section; after coming out


increments the semaphore value, and checks if it is less than of equal to 0.
If so, it removes process from waiting queue and then wakes up the process.

QUESTIONS
1. What do you mean by a deadlock? Explain
2. Discuss various conditions to be true for deadlock to occur.
3. Discuss various applications to overcome the problem of deadlock.
4. What do you mean by a Zombie? Discuss in brief.
5. What is concurrency?
6. Discuss the problems caused by concurrent executions of processes.
7. What is race condition?
8. Describe critical section.
9. What is mutual exclusion? What are its requirements?
10. Discuss the process state with its five state process model.
11. Explain the seven state process models.
12. What is Process Control? Discuss the process control block.
13. What is dispatcher?
14. Write note on Context Switching.
a. CPU-I/O Burst Cycle
b. System call
15. Explain the several common scheduling strategies in brief.
16. Explain the Priority scheduling with a suitable example.
17. Write note on:
a. FCFS Scheduling b. RR Scheduling c. SJF Scheduling

65
Summary
Process Management, operating system function process creation, termination
process Context switching, dispatching, swapping
PCB process details contain Process state

(1) new,
(2) ready,
(3) running,
(4) waiting,
(5) terminate

Scheduling activity processess manage


processess execute maximum CPU utilization throughput
algorithms FCFS, SJF, Priority scheduling Round Robbin

Deadlock activity processor utilization maximum


throughput minimum

66
Chapter-3

DISK OPERATING SYSTEM (DOS)

Objectives
 Unit DOS DOS

MS-DOS
Disk Operating System is an operating system, which makes computer
useable, it is a program that has to be loaded to initialize computer.
The single user operating system used in microcomputers is called
DOS because it controls the storage of information and detail on disks.

Tasks for DOS,

To control input and output devices

To enable user to load and execute program

To maintain an orderly system of data on the disk

DOS COMMANDS

There are two types of DOS commands,

Internal Commands

External Commands

DOS INTERNAL COMMANDS

The internal DOS commands are those commands, which are loaded
automatically during boot up process and are present in the computer
memory. Internal commands (DOS disk is not needed use any time
except when you are in software package).

67
BREAK

CD CHDIR

CHCP

CLS

COPY

CTTY

DATE

DEL ERASE

DIR

MD
MKDIR

PATH

PROMPT

RD
RMDIR

SET

TIME

TYPE

VER

VOL

VERIFY

LOCK

UNLOCK

LOADHIGH

EXIT

TRUENAME

68
DOS EXTERNAL COMMANDS

These commands are not present in the computer’s memory but these
exists as separate files on the disk. Whenever you type an external
command it is first loaded in the RAM and then execute.

APPEND ASSIGN ATTRIB BACKUP COMP CHKDSK DEFRAG

DELTREE DISKCOMP DISKCOPY DOSKEY DEBUG EDIT EDLIN

EXE2BIN FASTOPEN FC FDISK FIND FORMAT GRAFTABL

GRAPHICS JOIN KEYB LABEL LINK MEM MODE

MORE MOVE NLSFUNC PRINT RECOVER REPLACE RESTORE

SCANDISK SELECT SETVER SHARE SMARTDRV SORT SUBST

TREE SYS XCOPY XCOPY32

Attrib
The attrib command is used to change the attributes of a single file or
a directory.

Break
The break command sets or clears extended CTRL+C checking.

Call
The call command is used to run a script or batch program from within
another script or batch program.

The call command has no effect outside of a script or batch file. In


other words, running the call command at the DOS prompt will do
nothing.

Cd
The cd command is the shorthand version of the chdir command.

Chcp
The chcp command displays or configures the active code page
number.

69
Chdir
The chdir command is used to display the drive letter and folder that
you are currently in. Chdir can also be used to change the drive and/or
directory that you want to work in.

Chkdsk
The chkdsk command, often referred to as check disk, is used to
identify and correct certain hard drive errors.

Choice
The choice command is used within a script or batch program to
provide a list of choices and return the value of that choice to the
program.

Cls
The cls command clears the screen of all previously entered
commands and other text.

Command
The command command starts a new instance of the command.com
command interpreter.

Copy
The copy command does exactly that - it copies one or more files from
one location to another.

Ctty
The ctty command is used to change the default input and output
devices for the system.

Date
The date command is used to show or change the current date.

Dblspace
The dblspace command is used to create or configure DoubleSpace
drives.

DriveSpace, executed using the drvspace command, is an updated


version of DoubleSpace.

70
Debug
The debug command starts Debug, a command line application used to
test and edit programs.

Defrag
The defrag command is used to defragment a drive you specify. The
defrag command is the command line version of Microsoft's Disk
Defragmenter.

Del
The del command is used to delete one or more files.

The del command is the same as the erase command.

Deltree
The deltree command is used to delete a directory and all the files and
subdirectories within it.

Dir
The dir command is used to display a list of files and folders contained
inside the folder that you are currently working in.

The dir command also displays other important information like the
hard drive's serial number, the total number of files listed, their
combined size, the total amount of free space left on the drive, and
more.

Diskcomp
The diskcomp command is used to compare the contents of two floppy
disks.

Diskcopy
The diskcopy command is used to copy the entire contents of one
floppy disk to another.

Doskey
The doskey command is used to edit command lines, create macros,
and recall previously entered commands.

71
Dosshell
The dosshell command starts DOS Shell, a graphical file management
tool for MS-DOS.

The dosshell command was only available up to MS-DOS 6.0 but most
MS-DOS 6.22 installations were upgrades from previous versions so
the dosshell command is usually still available.

Drvspace
The drvspace command is used to create or configure DriveSpace
drives.

DriveSpace is an updated version of DoubleSpace, executed using the


dblspace command.

Echo
The echo command is used to show messages, most commonly from
within script or batch files. The echo command can also be used to
turn the echoing feature on or off.

Edit
The edit command starts MS-DOS Editor, a tool used to create and
modify text files.

Edlin
The edlin command starts the Edlin tool which is used to create and
modify text files from the command line.

Edlin was only available up to MS-DOS 5.0 so unless your version of


MS-DOS 6.22 was upgraded from 5.0, you likely won't see the edlin
command. Later versions of Windows again included the edlin
command.

The emm386 command is used to give MS-DOS access to more than


640 KB of memory.

Erase
The erase command is used to delete one or more files.

The erase command is the same as the del command.

72
Exit
The exit command is used to end the command.com session that
you're currently working in.

Expand
The expand command is used to extract a single file or a group of files
from a compressed file.

Fasthelp
The fasthelp command provides more detailed information on any of
the other MS-DOS commands.

Fastopen
The fastopen command is used to add a program's hard drive location
to a special list stored in memory, potentially improving the program's
launch time by removing the need for MS-DOS to locate the
application on the drive.

Fc
The fc command is used to compare two individual or sets of files and
then show the differences between them.

Fdisk
The fdisk command is used to create, manage, and delete hard drive
partitions.

Find
The find command is used to search for a specified text string in one
or more files.

For
The for command is used to run a specified command for each file in a
set of files. The for command is most often used within a batch or
script file.

Format
The format command is used to format a drive in the file system that
you specify.

Goto
The goto command is used in a batch or script file to direct the
command process to a labeled line in the script.

73
Graphics
The graphics command is used to load a program that can print
graphics.

Help
The help command provides more detailed information on other DOS
commands.

If
The if command is used to perform conditional functions in a batch file.

Interlnk
The interlnk command is used to connect two computers via a serial or
parallel connection to share files and printers.

Intersvr
The intersvr command is used to start the Interlnk server and to copy
Interlnk files from one computer to another.

Keyb
The keyb command is used to configure a keyboard for a specific
language.

Label
The label command is used to manage the volume label of a disk.

Lh
The lh command is the shorthand version of the loadhigh command.

Loadfix
The loadfix command is used to load the specified program in the first
64K of memory and then runs the program.

Loadhigh
The loadhigh command is used to load a program into high memory
and is usually used from within the autoexec.bat file.

Md
The md command is the shorthand version of the mkdir command.

74
Mem
The mem command shows information about used and free
conventional, upper, reserved, and extended (XMS) memory.

Memmaker
The memmaker command is used to start MemMaker, a memory
optimization tool.

Mkdir
The mkdir command is used to create a new folder.

Mode
The mode command is used to configure system devices, most often
COM and LPT ports.

More
The more command is used to display the information contained in a
text file. The more command can also be used to paginate the results
of any other MS-DOS command.

Move
The move command is used to move one or files from one folder to
another. The move command is also used to rename directories.

Msav
The msav command starts Microsoft Antivirus.

Msbackup
The msbackup command starts Microsoft Backup, a tool used to back
up and restore one or more files.

Mscdex
The mscdex command is used to provide CD-ROM access to MS-DOS.

Msd
The msd command starts Microsoft Diagnostics, a tool used to display
information about your computer.

Nlsfunc
The nlsfunc command is used to load information specific to a
particular country or region.

75
Path
The path command is used to display or set a specific path available to
executable files.

Pause
The pause command is used within a batch or script file to pause the
processing of the file.

When the pause command is used, a "Press any key to continue…"


message is displayed.

Power
The power command is used to reduce the power consumed by a
computer by monitoring software and hardware devices.

Print
The print command is used to print a specified text file to a specified
printing device.

Prompt
The prompt command is used to customize the appearance of the MS-
DOS prompt.

Qbasic
The qbasic command starts QBasic, the MS-DOS based programming
environment for the BASIC programming language.

Rd
The rd command is the shorthand version of the rmdir command.

Rem
The rem command is used to record comments or remarks in a batch
or script file.

Ren
The ren command is the shorthand version of the rename command.

Rename
The rename command is used to change the name of the individual file
that you specify.

76
Replace
The replace command is used to replace one or more files with one or
more other files.

Restore
The restore command is used to restore files that were backed up
using the backup command.

The backup command was only available up to MS-DOS 5.00 but the
restore command was included by default with later versions of MS-
DOS to provide a way to restore files that were backed up in previous
versions of MS-DOS.

Rmdir
The rmdir command is used to delete a directory.

Scandisk
The scandisk command is used to start Microsoft ScanDisk, a disk
repair program.

Set
The set command is used to display, enable, or disable environment
variables in MS-DOS.

Setver
The setver command is used to set the MS-DOS version number that
MS-DOS reports to a program.

Share
The share command is used to install file locking and file sharing
functions in MS-DOS.

Shift
The shift command is used to change the position of replaceable
parameters in a batch or script file.

Smartdrv
The smartdrv command installs and configures SMARTDrive, a disk
caching utility for MS-DOS.

77
Sort
The sort command is used to read data from a specified input, sort
that data, and return the results of that sort to the MS-DOS prompt, a
file, or another output device.

Sys
The sys command is used to copy the MS-DOS system files and
command interpreter to a disk. The sys command is used most often
to create a simple bootable disk or hard drive.

Time
The time command is used to show or change the current time.

Tree
The tree command is used to graphically display the folder structure of
a specified drive or path.

Type
The type command is used to display the information contained in a
text file.

Undelete
The undelete command is used to undo a deletion performed with the
MS-DOS delete command.

Unformat
The unformat command is used to undo the formatting on a drive
performed by the MS-DOS format command.

Ver
The ver command is used to display the current MS-DOS version
number.

Verify
The verify command is used to enable or disable the ability of MS-DOS
to verify that files are written correctly to a disk.

Vol
The vol command shows the volume label and serial number of a
specified disk, assuming this information exists.

78
Vsafe
The vsafe command is used to start Vsafe, a basic virus protection
system for MS-DOS.

Xcopy
The xcopy command can copy one or more files or directory trees from
one location to another.

Summary
Disk Operating System (DOS) operating system command mode
Internal command
external command

Internal Command program computer initialization computer


memory load execute external command RAM load
execute

79
PART-II
BUSINESS APPLICATION -
FOXPRO

80
Chapter-1

INTRODUCTION TO DATABASE &


FOXPRO

Objectives
 Unit database concept
 Data manage
 DBMS RDBMS
 Foxpro unit

 Foxpro interface, menus command window


unit

Database technology has been described as one of the most rapidly


growing concepts in the field of computers. In the years ahead database
systems will become increasingly widespread and important. The speed
of processing the data or information, and number of data which can be
handled by a database play a considerable role in database technology.
The main advantage of database technology is that it provides an
organization with centralized control of its information which makes
things easier for the organization for analysis. FoxPro is a product
developed for managing information or data stored on the computer in an
efficient and optimum manner. This chapter introduces the concepts of
database and also gives an overview of FoxPro.

80
DATABASE CONCEPTS

A collection of interrelated data designed to be used by a variety of users


is called database.

The data must be organized for its effective and efficient use. Organize
data serves as a base form which desired information can be retrieved
and meaningful information can be drawn. These databases lie at the
heart of the information system.

Information in a database is usually organized and stored in the form of


tables, with rows and columns in each table. Row in a database table are
called records and columns are called fields.

Example : A Student Database

ROLL_NO NAME COURSE DATE CITY

KCC/04/01 AMIT KUMAR O-LEVEL 10/05/2004 PATNA

KCC/04/02 KESHAV KISHOR A-LEVEL 20/05/2004 PATNA

KCC/04/03 AJAY KUMAR A-LEVEL 20/05/2004 GAYA

KCC/04/04 RAVI PRAKASH O-LEVEL 05/06/2004 PATNA

Problems with Manual Database

1. Manual database are not effective and efficient for huge amount
of data.
2. In a manual database system, each application has its own set of
private files. This often leads to considerable redundancy in
stored data with wastage of storage space.
3. Searching is difficult in a manual database system.
4. Modification in a manual database system is cumbersome.

81
Advantages of Computerized Database System

In a large organization, databases are maintained by computers. When


this database is organized in a normalized form, it reduces the
redundancy [repetition of information] and avoids inconsistency. It also
provides a way to easy and quick access of relevant information.

Below are some advantages of a computerized database system :

1. Redundancy is reduced.
2. Integrity can be maintained.
3. Data can be shared.
4. Modification in database structure is possible and relatively
easier.
5. Security checks can be built.
6. Conflicting requirements can be balanced.
7. Searching is easy.

Data Base Management System

Software used for managing [creation, updation, deletion and access ] of


physical database is known as Data Base Management System[DBMS].

This DBMS acts as a layer between the physical storage of data and the
users of database. All requests from users for access to database are
handled by the DBMS.

Application Programs

DBMS

Operating System

DATABASE

[user interface in a database management system]

82
Examples of DBMS:

[1] dBASE [2] FOXBASE

[3] FOXPRO [4] PARADOX

Relational Database

Currently most popular one in DBMS. Data and relationship among data
is represented by tables.

In relational database management system[RDBMS], one can draw


information from different tables linked by a common field.

In relational database system, a field is known as an attribute and a


record is known as a tuple.

Relational tables show logical, and not physical relationships. Given


below is the sample data in relational form.

STUDENT Table

ROLL_NO NAME COURSE DATE CITY

KCC/04/01 AMIT KUMAR O-LEVEL 10/05/2004 PATNA

KCC/04/02 KESHAV KISHOR A-LEVEL 20/05/2004 PATNA

KCC/04/03 AJAY KUMAR A-LEVEL 20/05/2004 GAYA

KCC/04/04 RAVI PRAKASH O-LEVEL 05/06/2004 PATNA

83
INST_FEES Table

ROLL_NO DATE AMOUNT PAY_TYPE

KCC/04/02 10/06/2004 2000.00 CASH

KCC/04/03 14/06/2004 1500.00 CHEQUE

KCC/04/01 20/06/2004 2000.00 CASH

ADVANTAGES OF RDBMS
1. Multi user environment
2. Security
3. Concurrent operation
4. Query optimization
5. Backup and recovery
6. Transparent indexing

Examples of RDBMS

1. Oracle 2. Ingress

3. Sybase 4. MS-ACCESS

WHAT IS FOXPRO?

As already defined, a DBMS is a set of tools that helps in managing


information stored in a database. FoxPro is a high powered relational
database management system.

FoxPro helps you to design database files as per the requirements and as
per the specified format. It also enables to enter and manage data in
database files. Through simple built-in commands, you can easily edit,
view, and change your data in database.

84
Foxpro acts as an interface between the user and the data stored by the
user. Foxpro is one of the most widely used databases on PCs, and one of
the first to be ported on windows.

It can run on a single user, stand alone machine and also on multiple
user local area network [LAN].

FEATURES OF FOXPRO
Foxpro offers than the capability to create and maintain files; it provides
all the tools needed to create, maintain and extract data. Following are
the main features of FoxPro:

 Creating databases
 Adding new data to the database
 Editing existing data stored in the database
 Removing data from the database
 Searching and retrieving information from the database
using a powerful tool called RQBE (Relational Query By
Example)
 Creating labels using the label designer
 Designing and printing custom reports
 Simple to moderately complex screens can be created with
screen builder
 Managing various types of files, such as tables, screen,
reports, labels, queries, and programs
 Foxpro also includes a set of wizards – a graphical interface
that lets you create tables, reports, screens, labels, queries,
etc, very easily

STARTING FOXPRO
After loading windows in the program manager window, double click
foxpro icon for windows. An introductory screen and copyright message
appears. Within a moment, the Foxpro menus and command window
appear.

FOXPRO INTERFACES
Foxpro provides more than one method of interaction with the user: a
Catalog Manager, a Menu system, and a Command window.

85
The Catalog Manager
The Catalog manager feature makes it possible to work in foxpro without
the knowledge of menu options or commands. The catalog allows you to
group various kinds of files, such as database, screens, labels, reports,
queries, and programs. Catalog manager is activated by:

Selecting the File menu>>Catalog manager option.

The Menu System


At the top of the screen, the FoxPro menu system appears as part of the
desktop. The menu system consists of four basic components – a menu
bar, menu pads, menu popup, and menu options.

Highlight menu across the top of the screen is called menu bar. Each of
the menu option written in menu bar is called menu pad. Each pad acts
as button.

When you select one of the menu pads, a menu popup will appear,
containing a group of choice called menu options.

When you perform operations with Foxpro, you will find that some of the
menu pads that are no longer relevant to what you are doing will appear
in a lighter color or disappear altogether from the menu bar.

COMMAND WINDOW
Another method in which you can use Foxpro is to enter commands
directly in the Command window. Foxpro saves the commands entered in
the command window in a history list. This makes it easy to recall, edit,
and re-execute a command, position the cursor on the appropriate
command line and press ENTER.

QUITTING FOXPRO
Quitting Foxpro means to exit from Foxpro. Foxpro offers several ways of
ending a Foxpro session.

1. Select close from the Foxpro’s control menu.

86
2. Type QUIT in command window and press ENTER.
3. Select Exit from the file menu.
4. Press Alt + F4.

KEY-FEATURES
 A database is a collection of related data pertaining to a
certain topic.
 A database Management System [DBMS] is the set of data and
the programs needed to manipulate it.
 A table is an arrangement of data in a row and column format.
 A record is a set of information stored about a particular
entity.
 A field is a column in a table that contains particular
information about a record.
 Designing a database file involves three major steps: data
definition, data refinement, and establishing relationships
between the fields.
 Foxpro is a RDBMS that can store and manipulate large
volumes of data.
 Catalog manager, Screen builder, Report generator,
Application creator are some of the main features of Foxpro.
 A user can interact with Foxpro using a Catalog manager, a
Menu system, and a Command window.

Summary

chapter database Database


organization

DBMS RDBMS long-time or huge-data manage

Foxpro software interface

87
Foxpro traditional software DBMS RDBMS manage
programming support
Market software

Catalog manager, Screen builder, Report generator, Application creator


Foxpro

88
Chapter-2

CREATING AND DISPLAYING DATABASE

Objectives
 Unit Database Database structure
Database unit

 Database save unit

Database can be considered to be containers for the data that need to be


stored. Before any action is to be taken on the data, they need to be
stored in a proper fashion. So the first step is to create a skeleton
structure, in which the data can be stored.

An important point to keep in mind as you begin creating a database is a


good design. Without a good design, you will be constantly changing the
database structure or you may not be able to extract the information you
want from your database. Creating a database means to define data
structure. After creating the database file you can add data to database
and can examine to contents of a database. This chapter discusses all
about it.

CREATING A DATABASE FILE


Before working with a database file, the first step is to define and design
its structure. The structure defines how the information will be stored in
that database file, i.e., how many fields are there in the file and what
information is stored in each field. The structure also limits the length of
data stored in each field.

89
To create a new database file, choose any of the following methods:

 Using the FoxPro menu system


Select File>>New, a New dialog box will appears.

Choose Table/DBF option button.

Click OK.

 Using the command window the syntax is

CREATE <filename>

e.g.: CREATE STUDENT

when using this method, .DBF extension automatically adds


with filename.

As soon as the above mentioned operation is performed, the table


structure dialog box appears, to define a new database.

DEFINING A DATABASE STRUCTURE


The table structure dialog box has columns headed Tag, Name, Type,
Width, and Dec.

Field Name

 When naming a field, use a name that best describes the


contents of the field.
 Field name may have up to ten characters including letters
from A to Z, whole numbers, and the underscore character ( _ ).
 The field name must begin with a letter and must not contain
space.

90
Data type
 Different data types are supported by different DBMS.
Generally , the following data types are supported by all the
DBMS:
1. Character
2. Numeric
3. Float
4. Date
5. Logical
6. Memo
7. General

The data types available in FoxPro are :

1. Character field The character field can store all printable


characters including letters, numbers, and special characters.
Maximum width of a character field is 254 characters.
2. Numeric field The numeric field can hold numbers and a
decimal point and may also begin with a + or – sign. This field
can hold a maximum of 20 numeric digits.
3. Float field Float field is same as the numeric field, but the
float data type is designed or scientific calculation. Since it stores
more significant digits internally, it is not commonly used.
4. Date field The date field is used to store dates. The default
format of storage is American [MM/DD/YY]. The Date field itself
is always 8 char long.
5. Logical field The logical field is used to store logical data and
can contain only the values .T. or .F. to indicate true or false. The
maximum width of logical field is 1.
6. Memo field The memo data type may contain any amount
and type of data. A memo field occupies a 10 character width in a
table structure, but the actual contents of the memo field are
saved in a separate file. The only limit to the length of a memo
field is the amount of disk space.
7. General field The general field can be used to store pictures,
sound, or any other type of data that can be pasted in from other
window applications.

SAVING A DATABASE FILE


After defining the database structure :

91
Click OK button

Or

Press Ctrl+W.

After saving the file, a dialog box appears asking for adding new records.

OPENING A DATABASE FILE


For opening an existing database file, choose either of the following
method:

 Enter USE <filename> in the command window.


 Choose File>>Open.

CLOSING A DATABASE FILE


Normally, only one database file can be in use at a time. More than one
database files can be opened using the SELECT command. If another
database file is opened, the current file will no longer be in use.

To close an open database file:

 Enter CLOSE ALL in the command window.


OR

 Choose File>>Close

ADDING DATA
Once the table structure is ready, data can be added in the table. Record
are always added at the end of the table.

USING APPEND

APPEND command is used to add data to the end of the database file
that is open in the currently selected work area.

It opens a window in change mode, displaying a blank record


for data entry.

92
Press Ctrl+End or Ctrl+W to save your data entry session.

Syntax : APPEND [BLANK]

e.g.: USE STUDENT

APPEND

USING APPEND BLANK

It adds a single blank record to the end of the currently selected


database file. It does not open a change window, but data can be entered
through EDIT, CHANGE or BROWSE commands. This command is
generally used in the programming mode.

e.g.: USE STUDENT

APPEND BLANK

USING APPEND FROM

Adds data from another file to the end of the database file that is
currently selected.

Syntax: APPEND FROM <file> [FIELDS <field list>][FOR <condition>]

[DELIMITED [WITH <characters>]]

e.g.: USE STUDENT

APPEND FROM TEMP FIELDS ROLL_NO,ST_NAME

VIEWING DATABASE

After adding records to the table, the next logical step is to view the data.
The LIST and DISPLAY, are the two very useful commands for viewing
the data using, using a command window.

USING LIST

Displays the contents of all or selected records on the screen, prints to


the printer or store in a disk file, form the currently selected database
file.

93
Syntax: LIST [OFF][scope][field list][FOR <condition>][TO
PRINTER/TO

FILE
<filename>]

Options

OFF : To suppress record number display

Scope : quantifies the records to be listed. The scope can be


from the following:

ALL : To specify all records [default scope].

NEXT <n> : Specify range of records beginning with current record

And continuing for specified number <n> of records.

REST : Specify all the records beginning with current record

And ending with last record in file.

RECORD <n> : Specify the record number of the record on which

<n> command will act.

Field list : By default, all fields from the table are displayed. Includes only

those fields needed to displayed.

FOR : FOR clause conditionally displays records, filtering out undesired

records.

TO PRINTER : To direct output to a printer or to the disk file.

e.g.: LIST OFF NEXT 5

LIST ROLL_NO,ST_NAME

LIST FOR ST_NAME=”AMIT” TO PRINTER

LIST REST

94
USING DISPLAY

Displays a record from the active database. To display more records the
scope option is used.

Syntax: DISPLAY [scope][FIELDS <field list>][FOR <condition>][TO


PRINT/FILE]

e.g.: DISPLAY

DISPLAY NEXT 10 FOR COURSE=”O-LEVEL”

DISPLAY FIELDS ST_NAME,COURSE

NOTE : 1. The main difference between LIST and DISPLAY is that, LIST
command

Displays all records by default whereas the default scope of


DISPLAY is

The current record.

2. The similarity between the two is when DISPLAY is used with ALL
option.

But again, LIST scrolls information continuously, whereas


DISPLAY ALL

Pauses whenever the screen becomes full.

MOVING A RECORD POINTER

FoxPro pointer is always pointing to a particular record whenever you are


using a database. To move the pointer to a specific record, GO command
can be used.

Syntax : GO/GOTO <TOP> <BOTTOM> <record number>

TOP : Pointer will be at the first record in the file

BOTTOM : Pointer will be at the last record in the file.

Record no. : To move the pointer to the desired record number.

e.g. : GOTO 4

GO BOTTOM

95
KEY-FEATURES
 To store information in a database file, you first need to create it.
 To create a database file, select File>>New from the FoxPro menu
or enter Create command.
 Define name, type, and width for each field you want to include in
your database.
 There can be seven types of fields – character, numeric, float, date,
logical, memo, general in FoxPro.
 Use APPEND command to add records in database file.
 After entering records, you can use the LIST and DISPLAY
commands to display or print all or selected information.
 The GOTO, GO TOP, GO BOTTOM commands can be used to move
the record pointer.

Summary

database records store

database

Database structure name, type, width unit

Database open data entry LIST, DISPLAY, GOTO, GO TOP, GO

BOTTOM commands unit

96
Chapter-3

EDITING A DATABASE

Objectives
 Unit Database contents
 Database records delete delete records

 Database contents auto replace


 Database structure unit

Sometimes changes are necessary to the database file contents as well as


to the table design because of changes in the application’s specifications
or because the table structure does not generate the required output.
Therefore, you may want to change some data, remove unwanted records
permanently or temporarily, recall some deleted information, or even
update data to carry out the specified changes in all or selected records
of the database file. This chapter covers all aspects of editing the
database.

EDITING DATA IN A RECORD

After having entered data in the records of a database file, you


might need to change the data. Or due to some mistake in data,
correction may be needed in the data.

EDIT, CHANGE, and BROWSDE are useful commands for the above
mentioned purposes.

97
Using EDIT / CHANGE

The EDIT command invokes the FoxPro full screen editor.

If no record number is specified in the scope, the current record, which is


identified by the current position of the record pointer, will be displayed
for editing.

Syntax : EDIT [scope] [NOAPPEND] [NOCLEAR] [NOEDIT]


NODELETE]

[FIELDS <FIELD LIST>] [for < EXPl1> [WHILE <expl2>]

Fields option will display only the fields listed in field list

The NOCLEAR option causes the EDIT display to remain on the screen
after the changes are complete.

The NOAPPEND, NOEDIT, and NODELETE option restrict appending,


editing, or deleting in edit mode.

e.g. EDIT 4

EDIT FIELDS EMPNAME, EMPCODE

EDIT FOR DEPT = “Computer”

EDIT FIELDS EMPNAME, DEPT FOR DEPT = “Computer”

The CHANGE command is functionally identical to the EDIT command,


which is used to modify existing records in a table, using the Command
window.

USING BROWSE

Used to display a number of records in a tabular format from a database


on screen.

To save changes made during Browse, press Ctrl + W or Ctrl +


End; to exit Browse press Esc.

A new record at the end of the database can also be added using
Ctrl+N or select Append Record from Browse menu.

It is also possible to mark records for selection through the browse mode.

98
Syntax : BROWSE [FIELDS <field list> [FOR <expL1>]

[FREEZE <FIELD>] [NOAPPEND] [NOCLEAR]

[NODELETE] [NOEDIT] [LOCK <expN1>]

FIELDS : The listed fields are displayed in the order specified in <field
list>, <field list>

FOR : Conditionally displays records in a Browse window, filtering out


undersired <expL1> records.

FREEZE : Permits changes to be made to only one field in the Browse


window.

<field> The remaining fields are displayed and cannot be edited.

LOCK : Specifies the number of fields displayed in the left partition of the
Browse window.

e.g. BROWSE

BROWSE FIELDS EMPNAME, EMPCODE, DEPT

BROWSE NODELETE

Browse Menu Options

The Browse menu is available only in the browse mode. The option
present in this menu are discussed below :

 Change This option is equivalent to using Change or Edit


Command in the Command window or menu.
 Grid This causes vertical and horizontal lines to appear between
the columns and rows.
 Link Partitions When the window is divided into two parts, this
option lings or unlinks the two parts of the window.
 Change Partitions If the window is divided into two partitions, this
option alternately switches between the partitions.
 Font This option enables to select font, font size, and font style for
use in the browse mode.

99
 Size Field This option resizes a field.
 Move Fields This option changes the position of the field.
 Resize Partitions This option changes the size of an existing
partition.
 GoTo This option is used to go to a specific record.
 Seek This option is used to find an indexed record.
 Toggle Delete This marks a record for deletion.
 Append Record Choosing this option adds a blank record at the
end of the table for adding new data.

DELETING RECORDS
Sometimes, you may not require a particular record. There are three
useful commands to delete unwanted records from the database file
permanently or temporarily, the are Delete, Pack and Zap.

Using DELETE

 Marks specific record for deletion in the current database.


 Records marked for deletion are not physically removed from the
table until PACK (discussed shortly) is issued.

Syntax : DELETE [scop] [FOR <expL1>[WHILE <expL2]

Options

Scope : The scope clause are ALL, NEXT <n>, REST, Record <n>

FOR : Including FOR clause lets conditional deletion of records.

<expL1>

WHILE : If the WHILE clause is included records are marked for

Deletion <expL2> for as long as <expL> evaluate as true

e.g. : GOTO 5

DELETE NEXT 5

DELETE FOR DEPT = “Computer”

GOTO 10

DELETE REST

100
1. Browse, Edit or Change can also be used for the deletion purpose.
2. A function DELETED ([<expC> | <expN>]) is used to return logical
value that indicates whether the current record is marked for
deletion.
e.g. List for Deleted ()

Using PACK

Permanently removes all records marked for deletion in the current table.

When PACK is issued, FoxPro copies all records not marked for deletion
to a temporary database file and at last renames the temporary database
file with the original database file.

Syntax : PACK

Note Exercise caution when using PACK. There is no way to retrieve


deleted records after pack is completed.

Using Zap

Removes all records from an active database, file leaving just the table
structure.

Issuing ZAP is equivalent to issuing DELETE All followed by PACK, but


ZAP is much faster. Records zapped from the current database cannot be
recalled.

Syntax : ZAP

RECALLING DELETED RECORDS with RECALL


The deleted records are normally visible within a table and they can be
unmarked from the delete status.

RECALL unmarks records marked for deletion in the selected database


file.

RECALL can be used to recover records provided that a PACK or ZAP has
not been performed on the table.

Syntax : RECALL [SCOPE] [FOR <expL1>] WHILE [<expL2>]

101
e.g.: RECALL ALL

RECALL ALL RECALL FOR DEPT = “Computer”

RECALL NEXT 5

REPLACING FIELD CONTENTS with REPLACE


FoxPro offers a number of ways to change information stored in table.
The Edit, Change commands display a data entry form for editing while
with the Browse Command data can be edited in a tabular format. Both
these methods provide an alternative, visual method to change the
information stored in the tables.

The option REPLACE is another method to change data in tables.

Updates table records.

Used to replace the contents of a specified field with new values.

More than one field can be replaced.

No replacement occurs if the record pointer is at the end of the file.

Syntax : REPLACE <field> WITH <expr1> [ADDITIVE]

[<field2> WITH <expr2> [ADDITIVE]]…….

[scope] [FOR <expL1>] [WHILE <expL2>]

e.g. : USE EMPLOYEE

REPLACE ALL DEPT WITH “Comp” FOR DEPT =


“Computer”

REPLACE CITY WITH “PAT”, PIN WITH “800001”

Option
<field1>with <expr1>…. : The data in <field1> is replaced with value
of the expression <expr1> and so on. When the expression value is
longer than the width of a numeric field, REPLACE forces the value to
fit.

102
ADDITIVE : Applies to replacements in memo fields
only. If ADDITIVE is included,
replacement to memo fields are
appended to the end of the memo fields.

Modifying the Structure of a Database


You can change the structure of a opened database file using the
command MODIFY STRUCTURE. After entering this command a Table
Structure dialog box appears. Using this command you can :
 change field name
 add field using Ctrl+N or click Insert button of the Table Structure
dialog box
 change field type
 change field length
 delete a field using Ctrl+D or click Delete button button of the
Table Structure dialog box

Syntax : MODIFY STRUCTURE


 Save change using Ctrl-W or click OK.
NOTE Before modifying the database structure it is a good
practice to view its structure.

DISPLAY STRUCTUE command displays all the fields


their type, and the width of the active database file along
the number of records and the date of last update.

Syntax : DISPLAY STRUCTUE or F5 function key

KEY-FEATURES
 Records can be modified by using the CHANGE, EDIT, and
BROWSE commands.
 Records can be removed from the table by using the DELETE
command.
 Deleting records is a tow-step process in FoxPro. First the desired
record is marked for deletion. Then the PACK command is given
which physically, removes the record marked for deletion.

103
 The RECALL command removes the marker placed against the
record.
 The REPLACE command overwrites the contents of specified fields
in a table with new contents.
 Add, delete or change the field names, change their types and
width using MODIFY STRUCTURE.
 To display a database structure, use DISPLAY STRUCTURE command.

Summary
database concepts

Change, Edit Browse commands

Records delete recall

Replace command contents overwrite calculation

Database structure

104
Chapter-4

SORTING AND INDEXING A DATABASE

Objectives
 Unit Database arrange
 Index
 Index Sorting
 Re-index compound index

Records in a table are arranged in the same order in which they are
entered. This arrangement will not be desirable for all applications,
specially when records are to be accessed according to the values in a
specified data field. In a table, data can be kept in a required order using
either of the two methods – Sorting or Indexing. In sorting, the data is
physically copied in the desired order to a new table, whereas in
indexing, a separate file is used to provide a reference as to how the
records in the original table should be arranged.

WHAT IS SORTING ?
Sorting means to arrange, group or classify information in some
meaningful of known order, such as alphabetical, numerical,
alphanumeric or chronological order.
Sorting helps in locating and searching the desired information quickly.
The best example of sorting is found in the dictionary. FoxPro provides
two such commands to sort database file. They are SORT and INDEX

Sorting Information with SORT


The SORT command creates a rearranged copy of a database.

105
The order of the new database depends on the fields and the options
specified. Sorting can be done on a single field or combination of two or
more fields.
The records can be arranged in ascending or descending order.
Syntax: SORT TO filename ON field1 [/A] [/C] [/D]

[,field2 [/A] [/C] [/D]….] [ASCENDING/DESCENDING]

[scope] [FOR <expL1>] [WHILE<expL2>] [FIELDS

fieldlist]

Options
/A : For ascending order explicitly on a specific field

(default order)

/C : Makes the sort ignore the case of a character.

/D : For descending order on a specific field.

ASCENDING/: Apply only to fields that do not include the [/A]

or [/D] DESCENDING options.

Scope : By default, all the records in the currently open

file are sorted into a

new file

FOR/WHILE: if used, only the records that meet some logical

criterion are sorted into a new file

NOTE 1. In a single sort, upto 10 fields can be sorted.

2. Memo and logical fields cannot be sorted.

106
3. Sorting affects the order of the parent database, i.e., it

changes the original record numbers

e.g. : SORT ON EMPNAME TO NEWNAME NEXT 10 FOR BASIC>8000

SORT ON EMPNAME/C TO CASENAME FIELDS EMPNAME,

EMPCODE, BASIC

WHAT IS INDEXING ?
An index of a database file is just like and index of a book. It has a

separate section that indicates where information is located.

A FoxPro index file is a separate file that contains information regarding


the location of individual records in the parent database. In the figure
given below, ABC1. DBF is a parent database whose LASTNAME given
field is indexed. A separate index file called, LAST.IDX contains the
record number and LASTNAME field.

An index file consists of at least one field from a database.

Indexing does not affect the order of the parent database.

Basically and index should be created on a field if :

 the records are to be searched based on the contents of the


fields.
 the table is to be viewed in the field order.
 the fields are to be used in queries or reports.

Types of Indexes
There are two different types of index file :

 the single index file and


 the compound index file

107
The single index files store a single index based on a single index
expression or key. Many single-entry indexes can be created, but each
one is stored in a separate file and identified by its filename.

A compound index file can store many indexes in a single file. The
indexes are represented in the same manner as in the single entry index,
by specifying an index expression consisting of usually one or more
fields. In addition, each index is given a special name – TAG. The number
of indexes – and therefore tags – is limited only by available memory and
disk space.

Creating an Index
Using Single Index Files
Each index is kept in a separate file, with the extension .IDX.

For better management and to keep index files up to date, open each of
these index files explicitly while adding, editing or deleting records in the
database file.

Syntax : INDEX ON field expression To index filename

[FOR <expL1>] [UNIQUE] [COMPACT]

Field expression, which is usually a field name or combination of fields


from the active database.

FOR option is used to limit records included in the index.

UNIQUE option is used to omit duplicate entries from the index.

The COMPACT clause forces the creation of an index file in the compact
format, which takes up less disk space.

Indexing on Multiple Fields


 Same as sorting on multiple fields.
 The limitation is, multiple fields that are not of the same field type,
cannot be directly indexed.

108
e.g. : INDEX ON LASTNAME + FIRSTNAME TO M_IDX

INDEX ON EMPCODE TO CODE_IDX FOR DEPT= “Computer”

INDEX ON EMPNAME TO NAME_UNQ UNIQUE

Updating Single Index Files


When any change is made in a database file (e.g., addition, edition or

deletion), those changes are automatically reflected in the corresponding

index file, provided they are active.

e.g. : Look at the following set of commands :

USE EMPLOYEE

SET INDEX To code_idx, name_unq

Or

USE Employee INDEX code_idx, name_unq

APPEND

EDIT 7

FoxPro automatically places the newly entered record ant edited record.

Using Compound Index Files


Unlike IDX files, each of which can hold only one index, compound index
(CDX) files can hold multiple indexes in a single file.

Each index in a compound index file is called an index tag.

109
Structural Compound Indexes

A Special compound index is called a structure compound index, which

opens automatically whenever a database file is opened.

A structural compound index is automatically given the same name as


the database file, with the extension .CDX.

All the indexes are updated automatically whenever a database file is


updated.

The general format of INDEX command is

Syntax : INDEX ON <field expr> To <idx file> TAG<tag name>

[OF <cdx file>] [FOR <EXPl>] [COMPACT]

[ASCENDING/DESCENDING] [UNIQUE [ADDITIVE]

The keyword TAG creates a CDX index tag with the name that is
specified; if it already exists, it adds that tag to the CDX file.

If, ‘OF <cdx file>’, clause is used, the tag will be added to the CDX file
whose name is specified.

The optional ADDITIVE creates a new index file or tag without closing
indexes that are already open.

Working with Index Files


Opening Index Files
To open database file simultaneously with index file, the following

command is used.

Syntax : USE filename INDEX index_name_1 [,index_name_2]

Eg : USE EMPLOYEE INDEX CODE_IDX, NAME_UNQ

110
To open the database file with tag name use the following command:

Syntax : USE filename TAG tagname

DELETING INDEX TAGS


There will be instances when a few index tags, or single entry index files

will not be required any longer. To delete an index tag from an open

compound index file, use the following command :

Syntax : DELETE TAG <tagname>

eg: DELETE TAG CODE

If all the tags in a compound index file are deleted, the file is
automatically deleted.

This can be done using the following command:

DELETE TAG ALL

To delete a single index file, use the command

DELETE FILE <.IDX filename>

CLOSING INDEX FILES


Use the CLOSE INDEX command to close the index file and leave the

associated database open.

Index Order
Only one index file (the master index file) or tag (the master tag ) controls

the order in which the database is displayed or accessed.

However, all open .IDX and .CDX index files are updated as changes are
made to the database.

111
The SET INDEX command opens the index file(s), and sets the index
order.

e.g. SET INDEX TO CODE_IDX, NAME_UNQ

Using REINDEX

The REINDEX command rebuilds all open index files of the current

database.

If any changes have been made to the database while its index file was
closed, update the index files with REINDEX.

Syntax : REINDEX

eg : USE EMPLOYEE INDEX CODE_IDX, NAME_UNQ

REINDEX

NOTE : Because structural compound index files are automatically


opened when the database is opened, they are the preferred
index type.

Advantage of Indexing Over Sorting

All the disadvantage of SORT become the advantage of INDEX. These are

as follows:

 Unlike sorting, which requires almost equal space as the original


database, indexing just stores the index fields(s) and the
corresponding record number in the index file.
 Sorting is a slow process. On the other hand, indexing is faster
 Sorting does not automatically update date in the sorted files(s)
 When sorted file is used, the record number (as compared to the
original database file) get changed, whereas in indexing the original
record number remain the same.

112
 In spite of the fact that the data is arranged in the required order
in sorting, FoxPro will still search for the required information
sequentially. In indexing, this problem can be overcome by using
SEEK of FIND commands.

KEY-FEATURES
 Data can be kept in a required order by using Sorting and Indexing
 The SORT command is used to sort records of a database file on
one or more fields. SORT creates a new database file to store the
sorted records.
 Sorting is a slow process, and it cannot be used if data changes
frequently.
 Indexing a database file using INDEX command creates an index
file that keeps track of information in the index field as well as the
physical record number in the database file.
 A single index file stores a single index based on a single index
expression or key.
 A compound index file can store many indexes in a single file.

Summary
database arrange (ascending / descending) order

Indexing method Sorting method

Single index Compound index unit

Index Sorting key field

113
Chapter-5
PERFORMING QUERIES

Objectives
 Unit Queries
 Queries Unit

 Locate continue
 Find Seek Locate Continue
Unit
 SET Filter Queries

The primary purpose of DBMS is to provide accurate information in a


custom format. The efficiency of database is determined by the speed
with which it retrieves data and presents it in a use defined format. The
process of accessing the database and retrieving data selectively is
known as querying. As with most activities in FoxPro, data can be
retrieved both with the menus and commands. The first portion of this
chapter highlights queries performed with commands and the second
half covers queries performed through menu selections.

PERFORMING QUERIES WITH COMMANDS


There are four useful commands to search for items : LOCATE,
CONTINUE, FIND and SEEK.

114
Using LOCATE
Sequentially searches the database for the first record that matches a
given logical expression.
If LOCATE finds a matching record, its record number is displayed.

The default scope of LOCATE is ALL records.

Syntax : LOCATE FOR <expL1> [<scope>] [WHILE <expL2>]

eg. : LOCATE FOR EMPNAME=”Kapil”

SPECIFYING MULTIPLE CONDITIONS


 FoxPro allows to specify multiple conditions with commands using
the logical operators .AND. or .OR. or .NOT. or!
eg: LOCATE FOR DEPT = “Computer”.AND.BASIC>5000

LOCATE FOR DEPT = “Computer.OR.BASIC>5000

LOCATE FOR .NOT.DEPT = “Computer”

SEARCHING INFORMATION WITHIN A FIELD


 To locate those records that contain embedded data, we use the $
operator and the following structure of LOCATE.
e.g.: LOCATE FOR “Kumar”$EMPNAME

 This command searches the embedded “Kumar” in EMPNAME


field.

Using CONTINUE
Continues the previous LOCATE. Used after LOCATE succeeds in finding
a record, to continue the LOCATE operation. CONTINUE moves the
record pointer to the next record for which the logical expression
specified in the previous LOCATE evaluates to true (.T.) CONTINUE can

115
be repeated until the end of the file is encountered, or until the end of
the scope, specified with LOCATE is reached.
Syntax : CONTINUE

Using SEEK and FIND

SEEK searches the current indexed table for the first occurrence of a
record whose index key expression matches a general expression
SEEK is only used with indexed tables, and can search only on the index
key expression.

The match must be exact unless SET EXACT is OFF.

If SEEK finds a matching record, RECNO( ) function returns the record


number of matching record.

FOUND( ) function returns true (.T.) and EOF( ) function returns false
(.F.).

SEEK command operates with either character string or numeric values.


To use SEEK with character string, enclose it in quotation marks.

Syntax : SEEK <expr>

Specify the index key expression you want SEEK to search with <expr>

e.g.: USE CUSTOMER

index ON Quantity TAG QUAN

SEEK 55

DISPLAY

Use Employee

Index ON Empname TAG ename

SEEK “Kapil”

Or

116
SEEK ‘Kapil’

Or

SEEK [KAPIL]

FIND moves the record pointer to the first record in the database whose
index key matches the character expression <expC>

Syntax : FIND <expC>

e.g. : USE EMPLOYEE

Index on empname to ename

Find Kapil

DISPLAY

FIND is similar to SEEK command, except that FIND operates with


literals. If the literal is a character string, it does not need to be enclosed
in quotation marks.

Comparison of FIND & SEEK vs LOCATE & CONTINUE


FIND and SEEK find only the first matching record. An inherent
advantage to LOCATE and CONTINUE is that these commands find every
matching record (and, sooner or later, the desired one).

Another advantage of LOCATE is its ability to search within a field using


the $ operator, whereas you cannot search for something in the middle of
a field with FIND or SEEK.

Another problem with FIND and SEEK is the index file requirement. The
problem arises when a search is based on something different from what
you have indexed your file on.

FIND and SEEK is much faster than LOCATE because FIND and SEEK
search in the index file whereas LOCATE takes much time due to the
sequential search in a large database.

117
FIND and SEEK cannot locate logical values while LOCATE can be used
with logical values (.T.) or (.F.)

Using SET FILTER


The command hides records that do not meet the condition specified.
Syntax: SET FILTER TO <condition>

e.g.: SET FILTER TO CITY = “PAT” .AND. STATE = “BH”

limits a database to those records located in PAT, BH.

By issuing a SET FILTER command the LIST, BROWSE or REPORT


FORM commands can be used to view filtered data.

You can see whether a filter is in effect at any time by using the LIST
STATUS or DISPLAY STATUS command.

To cancel the effects of an existing filter SET FILTER TO command is


used.

Using View Files


The conditions placed in effect with a SET FILTER command can be
stored in the form of a view file for additional use at a later time.
View file is just “Snapshot” of overall FoxPro environment.

For creating view file, first open database and index files, load any
desired format file, and then set a filter condition with the SET FILTER
command.

To create a view file the command is:

CREATE VIEW filename FROM ENVIRONMENT

Here filename is the name for the view file. FoxPro assigns the extension.
View to it.

To open the view file, use the following syntax:

118
SET VIEW TO filename

Here, filename is the name of the view file. FoxPro will open the same
database and index files. Any filter conditions if saved with view files will
be placed back into effect. To close the view file, the following command
is used :

SET VIEW TO

Summary
 unit database queries

 Locate continue record position active

 SEEK FIND command data filter

 SET FILTER command queries effect

119
Chapter-6
FOXPRO’S RELATIONAL POWER

Objectives
 Unit Database relation
 SET relation command databases linking

 Update command
 Join command

FoxPro is a relational database manager, which means that it offers you


the ability to use more than one database file at a time, and to define
relationships between them. This chapter describes a number of ways
you can take advantage of the relational capabilities of FoxPro. For
example, with the SET RELATION command, you can link multiple
database file. You can also establish relationships using FoxPro’s RQBE.
RQBE feature is mainly useful for creating queries based on multiple
databases. When queries are created through the RQBE features, FoxPro
translates the specifications of the query into SQL SELECT command.
Queries designed by using the RQBE window operate much faster than
retrievals implemented with SET FILTER commands.

RELATIONAL DATABASES
FoxPro is a relational manager, i.e., it offers the ability to use more than
one database file at a time, and to establish relationships between them.

120
WHY WE USE MORE THAN ONE DATABASE ?

 A database contains one or more tables. An application that uses


multiple tables can manipulate data more efficiently.
 In relational database, the data to be stored in a database file is
divided into more than one database files. This makes the database
files small and modular, and leads to modular and efficient
program files.
 It also reduces disk space requirements.
 In order to relate more than two database files, a common key field
is used to establish a relationship that permits the retrieval of data
from both files.
 Let us consider a practical example of PART file, containing
computer parts and other contains purchasers who have ordered
certain parts, i.e., ORDER file. The structure of both files are :

PARTS.DBF ORDER.DBF

PART_NO N 4 CUST_NO N 4

DESCRIP C 20 CUST_NAME C 20

COST N 7 2 PART_NO N 4

QUANTITY N 4

Using a single file with all of the fields present in these two files.
Each time one customer ordered a part number, that had been
previously ordered by another customer, you would have to enter
the part description and part cost in the database even though the
same part description and part cost had been entered earlier.

To avoid the above duplication, two files are used, both of them
linked together, based upon the common key fields PART_NO.

Ways to Relate Databases in FoxPro


FoxPro provides three ways to draw relationships between database files.
You can relate files through SET RELATION command, using RQBE
window.

Most of the practical database applications are efficiently managed with


multiple database files. That is, the data to be stored in a database file is
divided into more than one database file.

121
Selecting a Work Area
FoxPro allows more than one table to be opened at a time. In FoxPro 2.5,
there are 225 work areas designated by their respective numbers. The
first ten can be referenced by the letters A to J and rest by using
numbers.

A database file can be opened in each of these work areas. A work area is
simply a place where FoxPro keeps track of a single table, and all related
information.

The SELECT command is used to select a work area.

Syntax : SELECT <WorkArea>

LINKING DATABASES WITH SET RELATION


Consider the EMP and DEPT databases files.

EMP.DBF

Empno Num 4

Ename Char 15

Salary Num 8 2

Deptno Num 2

Data for table EMP

Empno Ename Salary Deptno

1001 Satish 4000 20

1003 Rajeev 8000 10

1002 Sameer 6000 20

DEPT.DBF

Deptno Num 2

Dname Char 20

Location Char 15

122
Data for table DEPT

Deptno Dname Location

10 Training Delhi

20 Accounting Patna

30 Research Mumbai

To link these two databases together SET RELATION command is used.

Syntax : SET RELATION TO [ key-exp INTO alias,… ] [ADDITIVE]

The key-expression is the common field present in both databases.

The alias is usually the name of the other database that the active
database is to be linked to.

ADDITIVE is an optional clause, needed only when you are setting


a relation in more the one file at a time.

The process of linking the above two databases using a common field,
Deptno is as follows:

1. Open the file from which you want to establish the relation in one
work area ( in our case it is EMP.DBF).
2. In another work area, open the file to link to the first file. (i.e.
DEPT.DBF)
3. Activate an index file based on the field that is common to both
files.
4. Use the SET RELATION command to establish the link.

e.g.: CLOSE DATABASES

SELECT A

USE EMP

SELECT B

USE DEPT INDEX DEPTNO

SELECT A

SET RELATION TO DEPTNO INTO B

123
Multiple Relations
Up to 225 database files can be linked in FoxPro. To explain the concept
of multiple relations let us consider the following example:

ITEM.DBF ORDER.DBS CUSTOMER.DBF

Stockno Custno Custno

Descrip Stockno Name

Cost Quantity Address

City

State

Here, ITEM.DBF and ORDER.DBF are linked on the Stockno field, and
ORDER.DBF and CUSTOMER.DBF on Custno field. To establish multiple
relations of this type, the following sequence of commands are used:

CLOSE DATABASES

SELECT A

USE ITEM

INDEX ON STOCKNO TO ITEM

SELECT B

USE ORDER

INDEX ON CUSTNO TO ORDER

SELECT C

USE CUSTOMER

INDEX ON CUSTNO TO CUST

SELECT B

SET RELATION TO CUSTNO INTO CUST

SET RELATION TO STOCKNO INTO ITEM ADDITIVE

124
UPDATING INFORMATION WITH UPDATE
UPDATE command is used to replace the contents of one or more fields
in a database with the contents of one or more fields from another
database. The selected work area must contain the target database that
you are updating. The source database must also be active but in an
unselected work area.

Syntax :UPDATE ON <key field> FROM <source> REPLACE <field1>

with <exp1>,<field2> with <exp2>,…

The key field must have the same field name in both the source
and target databases.

JOINING TWO DATABASE FILES WITH JOIN


The JOIN command joins two databases files to create a new database
file. You can include specified or all fields in the new database file. The
database files are joined on some condition.

Syntax : JOIN WITH <alias> TO <newfilename>

FOR <condition> FIELDS <field list>

JOIN command may be very time consuming depending on the size


of the two database files you are joining.

e.g.: SELECT A

USE ORDER INDEX ORDER

SELECT B

USE CUSTOMER INDEX CUST

JOIN WITH A TO NEWCUST FOR CUSTNO=A.CUSTNO

FIELDS CUSTNO,NAME,A.STOCKNO,A.QUANTITY

125
KEY-FEATURES
 Relations on multiple databases can be set using SET RELATION
command.
 SELECT command is used to open and choose a work area for the
database.
 With the SET RELATION command, you can link multiple database
files through a field that is common to all of them.
 JOIN and UPDATE are the commands used on multiple files.
 SQL [Structured Query Language], is a data retrieval and
manipulation language.

Summary
unit database

RDBMS database relation Set

relation relation

Database update database

UPDATE command database update

Database JOIN command file

126
Chapter-7
MEMO FIELD & FILE HANDLING

Objectives
 Unit Memo field
 Memo field handle unit
 Foxpro file utilities unit

This chapter consists of two portions. The first portion is an overview of


Memo fields. For storing large block of text in a table memo field is used.
Memo fields are ideal for storing information like employee job
descriptions, product description. The second portion explains some
important file utilities. File utilities in FoxPro provides operations, such
as listing files in a diskette or directory, making a copy of a database file,
and erasing or renaming files.

MEMO FIELD HANDLING


Memo field is used to store long textual information. When a memo field
is used with a database file, the actual information that enters in a
memo field is stored into an auxiliary database file. Foxpro automatically
creates the auxiliary database file [.FPT] when a database file is created
with memo field.

Advantages of using Memo Field

A memo field occupies only 10 bytes of space in a database record.


However, each record can store any amount of text.

127
It helps in reducing the size of the main database file because the actual
data for the memo field is stored in the auxiliary database file.

With the help of FoxPro’s internal text editor, memo field can easily be
edited.

Information in memo field can be searched with help of


LOCATE,SEEK,FIND, etc., like a character field.

Entering Data in Memo Field

FoxPro displays ‘memo’ marker if Memo field is empty and ‘Memo’


marker if Memo field is nonempty. These markers help in identifying
whether memo field contains some data or not.

To enter data in the memo field, move the cursor to it and press Ctrl+Home
or Ctrl+Pgdn or double click on the marker with mouse. FoxPro opens a
window for entering text in the memo field for the current record.

To exit from the memo window, Ctrl+W or Ctrl+End or select File>>Close


to save changes or press Esc key to close the window without saving.
There is no need to close and reopen the Memo window, when moving
between records.

Listing Memo Fields

The contents of the memo field can be viewed using the memo field name
with LIST or DISPLAY command.

e.g.: LIST OFF ST_NAME, REMARK

(Here Remark is a memo field)

Default width of memo field in LIST or DISPLAY command is 50


characters. This default width can be changed through the SET
MEMOWIDTH command.

e.g.: SET MEMOWIDTH TO 30

The above given command changes the memo field width for display to
30 characters.

128
FILE UTILITIES IN FOXPRO
Displaying List of Files

Dir or Directory is the command to display the names of all tables in the
current directory, the number of records in each file, the date each file
was updated, and the size of each file in bytes.

It also displays the total number of files and the number of bytes free on
the disk.

Syntax : DIR [<path>]

e.g.: DIR [ displays the name of all database files ]

DIR *.* [ displays the name of all files ]

Using DOS Commands within FoxPro [ RUN / ! ]

Run command can be used to run a DOS command or any external


command that can be used at the DOS prompt from the FoxPro
command window.

Syntax : RUN <command>

Or

! <command>

 ! (exclamation mark) can be used in place of word ‘RUN’. If your


computer has enough memory (more than 512K) the program
executes, if it does not have enough memory, the operating system
displays the message “Insufficient Memory”.

COPY commands

Copy File

COPY FILE command can be used to make a copy of a database or any


other file. If the second file does not exist, it creates it. If the file exists
and SAFETY is ON it gives a warning before overwriting it, otherwise
overwrites, it without giving a warning.

Syntax : COPY FILE <source file> TO <target file>

e.g.: COPY FILE STUDENT.DBF TO TEMP.DBF

129
Copy Structure

 COPY STRUCTURE command creates a new database with the file


name that is specified. This new file has the same structure as the
data base file that is open in the current work area.
Syntax : COPY STRUCTURE TO <filename> [FIELDS <fields list>]

 If a FIELDS clause is included, the new file has only the fields that
are listed.

Copy To

 COPY TO command copies all or part of the active database to the


file whose name is specified.
Syntax : COPY TO <filename>

[scope] [FIELDS <field list>] [FOR <cond>]

[DELIMITED [WITH <character>]]

 The default scope is ALL


 The FIELDS option specifies the fields to be copied.
 The FOR option copies only those records meeting the condition.

Erase / Delete File

The command is similar to MS-DOS DEL command, i.e., used to remove


a file from the disk.

e.g.: ERASE STUDENT.DBF

DELETE FILE STUDENT.DBF

RENAME
Use to assign a new name to any file.

Syntax : Rename <old filename> TO <new filename>

NOTE : Close an open database file(s) which you want to rename or


delete.

130
Summary
 unit long-textual information store memo field

 Database copy copy queries

 Database database file delete rename

131
Chapter-8
MEMORY VARIABLES AND FUNCTIONS

Objectives
 Unit variable value store memory
 function
 Setting related command Mathematical command
unit

Almost anything, such as intermediate or final result of a calculation; a date;


fixed number; current or the next bill number. Etc., can be stored in RAM. The
data items stored in RAM are called memory variables. Think of a memory
variable as a temporary place to put a piece of information that will be needed
later in the calculation or to put results of calculations.

Functions are used in FoxPro to perform special operations that supplement


the normal FoxPro commands. FoxPro has a number of different functions that
perform operations ranging from calculating the square root of a number, to
finding the date. This chapter covers all mathematical commands and a few
important set commands and functions in detail.

MEMORY VARIABLES
Memory variables are temporary quantities that are stored in the memory
[RAM]. They are needed in FoxPro programs to store values which can be later
used in calculations or to store results of calculation. Up to 256 different data
items can be stored. A unique name, called the memory variable name, needs
to be assigned to each data item.

Variable names may consist of letters, digits, and the underscore ( _ )


character, subject to the following conditions :

132
1. It should be maximum of 10 characters in length spaces are not allowed.
2. The first character should be an alphabet.
3. Characters can be alphabets, numerals or the underscore character ( _ ).

Declaring Memory Variables

Memory variables can be declared in any one of the two ways :

(i) Using STORE command as follows :


STORE <value> to <memory variable name>

(ii) Using an assignment statement as follows :


<memory variable name> = <value>

Saving, Retrieving & Clearing Memory Variables

Memory variables can be stored & retrieved using SAVE TO and RESTORE
FROM command.

SAVE TO command

Syntax : SAVE TO <filename>

This command saves memory variables to a disk files. They can later be
retrieved with the RESTORE FROM command. These command are generally
used in programming.

RESTORE FROM command

Syntax : RESTORE FROM <file name>

This command restores memory variables that you previously saved to a disk
file with the SAVE TO command. It is often used in programming.

CLEAR ALL

Syntax : CLEAR ALL

This command clears a specified item form the screen. Use CLEAR alone to
erase the screen or current output window. Use the ALL modifier to release all
memory variables and arrays, select the primary work area, and close any open
databases.

133
Viewing Data with ? and ??

Syntax : ? | ?? <value / variable / expression>

This command is used to evaluate expressions and display the results. Use the
? to send a carriage-return and linefeed before the results of the expression.
Use the ?? to output results on the current line at the current position of the
screen or printer.

FoxPro FUNCTIONS
ABS() Function Syntax : ABS(<expN>)

Returns the absolute value of the specified numeric expression .

ALLTRIM() Function Syntax : ALLTRIM(<expC>)

This function returns the character expression with all leading and trailing
blanks removed.

ASC() Function Syntax : ASC(<expC>)

This function returns the ASCII number of the first character in any character
expression.

CAPSLOCK() Function Syntax : CAPSLOCK(<expL>)

Returns a logical value: indicates or sets the current state of CapsLock. The
logical expression returns the current mode and turns CapsLock on or off, if
the logical expression is not specified, the current CapsLock mode is returned,
but not changed.

CDOW() Function Syntax : CDOW(<expD>)

This function returns the day of the week in character form.

CHR() Function Syntax : CHR(<expN>)

This function returns the character corresponding to any ASCII number.

CTOD( ) Function Syntax : CTOD(<expC>)

 The CTOD(Character To Date) function is the reverse of DTOC().


 It converts a date stored as character data to a date-type data.
e.g.: C_DATE = “10/02/04”

?CTOD(C_DATE)

10/02/04

134
CMONTH() Function Syntax : CMONTH(<expD>)

This function returns the month of the date expression in character form.

CEILING() Function Syntax : CEILING(<expN>)

Returns a numeric value: the nearest integer greater than or equal to a given
numeric expression

DATE() Function Syntax : DATE()

This function returns the current system date -- the date on your computer's
clock/calendar or the date you entered when you started your computer.

DAY() Function Syntax : DAY(<expD>)

This function returns the day of the month of the specified date expression in
number form.

DOW() Function Syntax : DOW(<expD>)

This function returns a number corresponding to the day of the week of a


specified date expression. For example, if the date expression is a Sunday, this
function returns 1.

DTOC( ) Function Syntax : DTOC(<expD>)

An important function that converts a date type data to character ( D to


Character ).

e.g.: STORE DTOC(B_DATE) TO C_DATE

11/09/04

? DTOC(DATE())

10/02/04

INDEX ON S_NAME+DTOC(B_DATE) TAG NAME_DATE

FLOOR() Function Syntax : FLOOR(<expN>)

Returns a numeric value. Finds the integer immediate less than or equal to a
specified value.

135
IIF() Function Syntax : IIF(<expL>,<exp1>,<exp2>)

This function, the "immediate if," returns the value of the first expression if the
logical expression is true or the value of the second expression if the logical
expression is false.

ISUPPER() Syntax : ISUPPER(<expC>)

Returns true (.T.) if the first character expression is an uppercase alphabetic


character. Any characters after the first character in <expC> are ignored by
ISUPPER().

ISLOWER() Syntax : ISLOWER(<expC>)

Returns true (.T.) if the leftmost character in the specified character expression
is a lower case alphabetic character. Any characters after the first character in
<expC> are ignored by ISLOWER().

INT() Syntax : INT(<expN>)

Evaluates a numeric expression and returns the integer portion of the


expression INT() returns the integer portion of the numeric expression <expN>.

LEN() Function Syntax : LEN(<expC>)

This function returns the length of the specified character expression. The
expression may be a literal or a variable.

LOWER() Function Syntax : LOWER(<expC>)

This function returns the specified character expression with all its letters
converted to lowercase. It does not effect nonalphabetic characters.

LTRIM() Function Syntax : LTRIM(<expC>)

This function returns the specified character expression with all leading blanks
removed.

MONTH() Function Syntax : MONTH(<expD>)

This function returns the month of the date expression in numeric form.

136
PROPER() Function Syntax : PROPER(<expC>)

This function returns the specified character expression with the initial letter of
each word converted to uppercase and the other letters converted to lowercase.
It does not affect non alphabetic characters.

RECCOUNT() Function Syntax : RECCOUNT()

This function tells you how many records are contained in the database
currently in use.

RECNO() Function Syntax : RECNO()

This function returns the record number of the current record (the record
where the pointer is located).

REPLICATE() Function Syntax : REPLICATE(<expC>,<expN>)

This function repeats a particular character string a specified number of times.


For example, REPLICATE("-",80) returns an underline 80 characters long.

RTRIM() Function Syntax : RTRIM(<expC>)

This function removes spaces following a character expression or field that you
specify.

SPACE() Function Syntax : SPACE(<expN>)

This function returns a character string made up of a number of blank spaces


equal to the numeric expression specified.

STR() Function Syntax : STR(<expN>)

This function returns the value of the specified numeric expression as a


character string.

SUBSTR() Function Syntax : SUBSTR(<expC>,<expN1>,<expN2>)

This functions returns a substring of the specified character expression that


begins with the character indicated by the first numeric expression. The second
numeric expression is the length of the substring.

137
UPPER() Function Syntax : UPPER(<expC>)

This function returns the specified character expression with all alphabetic
characters capitalized. It does not affect any nonalphabetic characters in the
character expression.

VAL() Function Syntax : VAL(<expC>)

This function returns the specified character expression in the numeric data
type, so it can be used in calculations.

YEAR() Function Syntax : YEAR(<expD>)

Returns the numeric year from a date expression.

MATHEMATICAL COMMANDS
Commands that operates on numeric fields of a database file, such as SUM,
AVERAGE and COUNT.

SUM

Totals all or specified numeric field values in the current table/.DBF.

Syntax : SUM <Field Name> <TO FieldName> <FOR cond>

e.g.: SUM AMOUNT

SUM AMOUNT FOR NAME=”SATISH TIWARI”

AVERAGE

Computes the arithmetic mean of numeric expressions or fields in the current


table/.dbf.

Syntax : AVERAGE <Field Name> <TO FieldName> <FOR cond>

e.g.: AVERAGE AMOUNT

AVERAGE AMOUNT FOR ROLL_NO=”01”

COUNT

Counts the no. of records of the table/.dbf.

Syntax : COUNT <TO FieldName> <FOR cond>

e.g.: COUNT FOR AMOUNT>1000

138
SET COMMANDS
SET ALTERNATE TO Syntax : SET ALTERNATE TO <filename>

This command designates a text file to which you can send screen output by
using the command set alternate on.

SET ALTERNATE ON | OFF Default : OFF

This command saves unformatted screen output in a text file. Used with OFF,
it stops sending screen output to the text file.

SET BELL ON | OFF Default : ON

This command prevents FoxPro from beeping during data entry when you
reach the end of a field or enter invalid data.

SET CARRY ON | OFF Default : OFF

This command carries forward the data that is entered in each record while
you are appending data, so it appears as the default entry in the next record.

SET CENTURY ON | OFF Default : OFF

This command makes dates appear with all four digits of the year displayed.
SET CENTURY OFF makes dates appear with only the last two digits of the
year displayed.

SET CONFIRM ON | OFF Default : OFF

This command determines whether you must press Enter to move to the next
field when entering data using @… GET …. READ statements.

SET COLOR TO [STANDARD]

This command lets you specify color pairs from color scheme 1 and color
scheme 2. It is included here for backward compatibility.

SET CURRENCY TO (<expC>) Default : $

This command lets you specify and position the currency symbol; its default
values are $. Use the expC to specify a string of up to nine characters to
represent the currency symbol.

139
SET DATE TO [option] Default : AMERICAN

This command allows you to change the way dates are displayed. You can
determine the relative order of month, day, and year.

SET DEFAULT TO <path name>

This command lets you change the current drive or directory, where FoxPro
looks for files by default. The path name used is a disk drive designation.

SET DELETED ON | OFF Default : OFF

This command determines whether FoxPro commands disregard records that


are marked for deletion.

SET ECHO ON | OFF Default : OFF

This command controls the trace window, which is useful for debugging
programs. When it is ON, the source code for your program is displayed in the
trace window as it runs, and the line that is currently being executed is
highlighted.

SET ESCAPE ON | OFF Default : ON

This command controls whether the Esc key can be used to interrupt the
program. If it is used with OFF, the Esc key has no effect and the program
continues to execute.

SET EXACT ON | OFF Default : OFF

This command determines whether strings that are compared using the =
operator must be identical for there to be a match.

SET FIELDS TO <field list>

This command is used with a field list, only the fields that are listed will be
accessible to the user or to other commands. For example, if the user opens a
browse window, it will include only these fields.

SET FILTER TO <expL>

This command is used with a logical expression, only the records of the
currently selected database for which the logical expression is evaluated as
true are accessible.

140
SET PROCEDURE TO [<file name>]

This command activates the procedure file that is specified, so procedures and
user-defined functions in it can be used. If the file name does not include an
extension, FoxPro assumes the extension .PRG.

SET RELATION TO [<exp1> INTO <alias1>]

This command lets you relate two files, and its most important use is in
creating relational databases.

SET STATUS BAR ON | OFF Default : ON

This command lets you specify the status bar is displayed at the bottom of the
FoxPro desktop. Use OFF to suppress display of the status bar.

SET TALK ON | OFF Default : ON

This command lets you specify whether command processing information is


displayed on the screen. Use OFF to disable display of command processing
information.

SET SAFETY ON | OFF Default : ON

This command determines whether you will be warned before overwriting any files.

KEY-FEATURES
 A memory variable is a memory location within the computer that is used
to store data.
 Memory variables are referred to by their assigned names.
 FoxPro allows you to create up to 256 memory variables.
 You can store numeric, character, logical, or date type data in these
variables with the STORE command or by equating.
 SAVE command saves all or specified variables in a disk file.
 `CLEAR ALL erases all variables from the memory of the PC.
 RELEASE command erases all or specified variables from memory.
 ? displays the specified expression in the next row.
 ?? displays the specified expression in the same row.
 FoxPro supports several functions for manipulation of date and time.

141
Summary
 unit value store memory variable

 Mathematical function calculation

 Date function date manipulation date related queries

 String function string manipulation

 Foxpro default setting 'SET' related command

142

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy