ICS2305 - Systems Programming Lecture Notes ICS2305 - Systems Programming Lecture Notes

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

lOMoARcPSD|44175230

ICS2305 - Systems Programming Lecture notes

Business information technology (Jomo Kenyatta University of Agriculture and


Technology)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by OCEN JOHN BOSCO ([email protected])
lOMoARcPSD|44175230

JOMO KENYATTA UNIVERSITY


OF
AGRICULTURE & TECHNOLOGY

SCHOOL OF OPEN, DISTANCE &


eLEARNING
IN COLLABORATION WITH
SCHOOL OF HUMAN RESOURCE
MANAGEMENT

DEPARTMENT OF INFORMATION
TECHNOLOGY

ICS 2305 SYSTEMS PROGRAMMING

LAST REVISION ON September 12, 2014

Calvin Otieno
([email protected])

P.O. Box 62000, 00200


Nairobi, Kenya

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Course description
System Programming overview : Intro and Definitions, Application Vs System Pro-
gramming, System Software, Operating system, Device Drivers, OS Calls. Window
System Programming for Intel386 Architecture: 16 bit Vs 32 bit, Programming, 32
bit Flat memory model , Windows Architecture. Virtual Machine (VM) Basics, Sys-
tem Virtual Machine, Portable Executable Format, Ring O Computer, Linear Exe-
cutable format, Virtual Device, Device Driver Development. UNIX Unifying Ideas
Compilation C Data types, Pointers, etc. Standard I/O, Dynamic memory manage-
ment, System calls & error handling; Building, Debugging and Directories in Unix,
Unix File System Structure; Linux File System Kernel Data Structures; Low-level
I/O (Processes, File Descriptors, Opening/Creating/Closing/Deleting Files, Read-
ing and Writing); Intro to Processes (Programming with Processes: IPC, Pipes,
FIFO/Named Pipes, Message queues, Sockets, Semaphores and Locks, Signals;
Abnormal Termination, Orphaned Processes). Threads, Network File Systems (CVS,
NFS v2 spec). Subverting an interface: The SFS Server.

Prerequisites:
BIT 2203: Advanced Programming, ICS 2202: Computer Operating Systems

Course aims
This course aims at providing students a basic understanding of the issues involved
in writing system programs, manipulating system processes, system IO, system per-
missions, files, directories, signals, threads, sockets, terminal, etc. The primary op-
erating system discussed will be Unix (Linux) but Windows will also be discussed.
A primary goal of the course then is to reinforce, in a systems programming context,
the skills you have already acquired to develop code that is robust.

Learning outcomes
By the end of this course unit, the learner should be able to:

1. Identify the basic components of an operating system, describe their purpose,


and explain how they function.

ii

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

2. Write, compile, debug, and execute C programs that correctly use system
interfaces provided by UNIX (or a UNIX-like operating system).

3. List UNIX system calls, and invoke them correctly from within C programs.

4. Write, compile, debug, and execute C programs that create, manage and ter-
minate processes and threads on UNIX.

5. Write, compile, debug, and execute C programs with processes and threads
that interact by invoking and catching signals.

6. 6. Write, compile, debug, and execute C programs that use files and I/O on
UNIX.

7. Write, compile, debug, and execute C programs that make use of memory
management functions.

8. Write distributed applications that communicate across a network.

Instruction methodology
• Lectures,

• Tutorials,

• Practical,

• Presentations,

• Discussions,

• Industrial visits.

Assessment information
The module will be assessed as follows;

• 40% Continuous Assessment (Tests 10%, Assignment 10%, Practical 20%)

• 60% End of Semester Examination.

iii

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

Contents

1 Intro to systems programing 1


1.1 What is Systems Programming? . . . . . . . . . . . . . . . . . . . 1
1.2 Three Layered Approach . . . . . . . . . . . . . . . . . . . . . . . 1
1.2.1 Methods of I/O . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2.2 I/O controllers . . . . . . . . . . . . . . . . . . . . . . . . 2
•.1 • DMA controller . . . . . . . . . . . . 3
•.2 • Interrupt controller . . . . . . . . . . . 3
•.3 • Programmable Peripheral Interface (PPI)
• Interval Timer . . . . . . . . . . . . . 3
•.4 • Universal Asynchronous Receiver Trans-
mitter . . . . . . . . . . . . . . . . . . 3
•.5 We shall discuss all of them in detail and
how they can be used to perform I/O op-
erations. . . . . . . . . . . . . . . . . . 3
1.2.3 Operating systems . . . . . . . . . . . . . . . . . . . . . . 3
1.2.4 Memory management . . . . . . . . . . . . . . . . . . . . 4
1.2.5 Viruses and Vaccines . . . . . . . . . . . . . . . . . . . . . 5
1.2.6 Device Drivers . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Interupt mechanisms 9
2.1 introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1.1 The interrupt vector table . . . . . . . . . . . . . . . . . . 10
2.1.2 Interrupt Invocation . . . . . . . . . . . . . . . . . . . . . 11
2.1.3 Parameter passing into Software interrupts . . . . . . . . . . 12
2.1.4 Software interrupts invocation . . . . . . . . . . . . . . . . 12

3 Registry service 18

iv

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

CONTENTS CONTENTS

3.1 introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.2 Function pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
•.6 void myfunc() . . . . . . . . . . . . . . 20
3.3 Interrupt pointers and functions . . . . . . . . . . . . . . . . . . . . 21
3.3.1 Setting Interrupt Vector . . . . . . . . . . . . . . . . . . . 21
3.3.2 The Keep function . . . . . . . . . . . . . . . . . . . . . . 23

4 Port Programming in I/O 26


4.1 introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.1 Interrupt Driven Printer I/O . . . . . . . . . . . . . . . . . 26

5 System calls in unix 30


5.1 introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

6 Unix file system 35


6.1 introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.1.1 Types of files systems . . . . . . . . . . . . . . . . . . . . . 35
6.1.2 structure of file systems . . . . . . . . . . . . . . . . . . . 36
•.7 Structure of the file system . . . . . . . 36
• UNIX system directories . . . . . . . . . . . . . 36
• Pathnames . . . . . . . . . . . . . . . . . . . . . 37
• Directory Structure: . . . . . . . . . . . . . . . . 37
6.1.3 Navigating the File System: . . . . . . . . . . . . . . . . . 38
6.1.4 The df Command: . . . . . . . . . . . . . . . . . . . . . . 39
6.1.5 The du Command: . . . . . . . . . . . . . . . . . . . . . . 40
6.1.6 Mounting the File System: . . . . . . . . . . . . . . . . . . 40
6.1.7 Unmounting the File System: . . . . . . . . . . . . . . . . . 41
6.1.8 User and Group Quotas: . . . . . . . . . . . . . . . . . . . 41

7 System processes 44
7.1 introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
7.1.1 Starting a Process: . . . . . . . . . . . . . . . . . . . . . . 44
• Foreground Processes: . . . . . . . . . . . . . . . 44
• Background Processes: . . . . . . . . . . . . . . . 45
7.1.2 Listing Running Processes: . . . . . . . . . . . . . . . . . . 45

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

CONTENTS CONTENTS

7.1.3 Stopping Processes: . . . . . . . . . . . . . . . . . . . . . 47


7.1.4 Parent and Child Processes: . . . . . . . . . . . . . . . . . 47
7.1.5 Zombie and Orphan Processes: . . . . . . . . . . . . . . . 47
7.1.6 Daemon Processes: . . . . . . . . . . . . . . . . . . . . . . 48
7.1.7 The top Command: . . . . . . . . . . . . . . . . . . . . . . 48
7.1.8 Job ID Versus Process ID: . . . . . . . . . . . . . . . . . . 48
•.1 In addition, a job can consist of multi-
ple processes running in series or at the
same time, in parallel, so using the job
ID is easier than tracking the individual
processes. . . . . . . . . . . . . . . . . 49

8 The network utilities 51


8.1 introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
8.1.1 The ping Utility: . . . . . . . . . . . . . . . . . . . . . . . 51
8.1.2 The ftp Utility: . . . . . . . . . . . . . . . . . . . . . . . . 52
•.2 Example: . . . . . . . . . . . . . . . . 53
•.3 Following is the example to show few
commands: . . . . . . . . . . . . . . . 53
8.1.3 The telnet Utility: . . . . . . . . . . . . . . . . . . . . . . 54
8.1.4 The finger Utility: . . . . . . . . . . . . . . . . . . . . . . 54

9 Systems performance 57
9.1 introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
9.1.1 Performance Components: . . . . . . . . . . . . . . . . . . 57
9.1.2 Performance Tools: . . . . . . . . . . . . . . . . . . . . . . 58

10 User administration in unix 60


10.1 introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
10.1.1 Managing Users and Groups: . . . . . . . . . . . . . . . . 60
10.1.2 Create a Group . . . . . . . . . . . . . . . . . . . . . . . . 61
10.1.3 Modify a Group: . . . . . . . . . . . . . . . . . . . . . . . 62
10.1.4 Delete a Group: . . . . . . . . . . . . . . . . . . . . . . . 62
10.1.5 Create an Account . . . . . . . . . . . . . . . . . . . . . . 62
10.1.6 Modify an Account: . . . . . . . . . . . . . . . . . . . . . . 63

vi

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

CONTENTS CONTENTS

10.1.7 Delete an Account: . . . . . . . . . . . . . . . . . . . . . . 63

vii

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

LESSON 1
Intro to systems programing

1.1. What is Systems Programming?


Computer programming can be categorized into two categories .i.e
1. Input

2. output
While designing software the programmer may determine the required inputs for
that program, the wanted outputs and the processing the software would perform
in order to give those wanted outputs. The implementation of the processing part
is associated with application programming. Application programming facilitates
the implementation of the required processing that software is supposed to perform;
everything that is left now is facilitated by system programming. Systems program-
ming is the study of techniques that facilitate the acquisition of data from input
devices, these techniques also facilitates the output of data which may be the result
of processing performed by an application.

1.2. Three Layered Approach


A system programmer may use a three layered approach for systems programming.
As you can see in the figure the user may directly access the programmable hard-
ware in order to perform I/O operations. The user may use the trivial BIOS (Ba-
sic Input Output System) routines in order to perform I/O in which case the pro-
grammer need not know the internal working of the hardware and need only the
knowledge BIOS routines and their parameters. In this case the BIOS programs the
hardware for required I/O operation which is hidden to the user. In the third case
the programmer may invoke operating systems (DOS or whatever) routines in order
to perform I/O operations. The operating system in turn will use BIOS routines or
may program the hardware directly in order to perform the operation.

1.2.1. Methods of I/O


In the three layered approach if we are following the first approach we need to
program the hardware. The hardware can be programmed to perform I/O in three
ways i.e

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

• Programmed I/O

• Interrupt driven I/O

• Direct Memory Access

In case of programmed I/O the CPU continuously checks the I/O device if the I/O
operation can be performed or not. If the I/O operations can be performed the CPU
performs the computations required to complete the I/O operation and then again
starts waiting for the I/O device to be able to perform next I/O operation. In this
way the CPU remains tied up and is not doing anything else besides waiting for the
I/O device to be idle and performing computations only for the slower I/O device.
In case of interrupt driven the flaws of programmed driven I/O are rectified. The
processor does not check the I/O device for the capability of performing I/O op-
eration rather the I/O device informs the CPU that it’s idle and it can perform I/O
operation, as a result the execution of CPU is interrupted and an Interrupt Service
Routine (ISR) is invoked which performs the computations required for I/O oper-
ation. After the execution of ISR the CPU continues with whatever it was doing
before the interruption for I/O operation. In this way the CPU does not remain
tied up and can perform computations for other processes while the I/O devices are
busy performing I/O and hence is more optimal. Usually it takes two bus cycles to
transfer data from some I/O port to memory or vice versa if this is done via some
processor register. This transfer time can be reduced bypassing the CPU as ports
and memory device are also interconnected by system bus. This is done with the
support of DMA controller. The DMA (direct memory access) controller can con-
troller the buses and hence the CPU can be bypassed data item can be transferred
from memory to ports or vice versa in a single bus cycle.

1.2.2. I/O controllers


No I/O device is directly connected to the CPU.
To provide control signals to the I/O device a I/O controller is required. I/O con-
troller is located between the CPU and the I/O device. For example the monitor is
not directly collected to the CPU rather the monitor is connected to a VGA card and
this VGA card is in turn connected to the CPU through busses.
The keyboard is not directly connected to CPU rather its connected to a keyboard
controller and the keyboard controller is connected to the CPU.

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

The function of this I/O controller is to provide

• I/O control signals

• Buffering

• Error Correction and Detection

We shall discuss various such I/O controllers interfaced with CPU and also the
techniques and rules by which they can be programmed to perform the required I/O
operation.
Some of such controllers are

•.1. • DMA controller

•.2. • Interrupt controller

•.3. • Programmable Peripheral Interface (PPI) • Interval Timer

•.4. • Universal Asynchronous Receiver Transmitter

•.5. We shall discuss all of them in detail and how they can be used to perform I/O
operations.

1.2.3. Operating systems


Systems programming is not just the study of programmable hardware devices. To
develop effective system software one needs to the internals of the operating system
as well. Operating systems make use of some data structures or tables for manage-
ment of computer resources. We will take up different functions of the operating
systems and discuss how they are performed and how can the data structures used
for these operations be accessed.
File management is an important function of the operating systems. DOS/Windows
uses various data structures for this purpose. We will see how it performs I/O man-
agement and how the data structures used for this purpose can be directly accessed.
The various data structures are popularly known as FAT which can be of 12, 16
and 32 bit wide, Other data structures include BPB(BIOS parameter block), DPB(

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

drive parameter block) and the FCBs(file control block) which collectively forms
the directory structure.
To understand the file structure the basic requirement is the understanding of the
disk architecture, the disk formatting process and how this process divides the disk
into sectors and clusters.

1.2.4. Memory management


Memory management is another important aspect of operating systems.
Standard PC operate in two mode in terms of memory which are

• Real Mode

• Protected Mode

In real mode the processor can access only first one MB of memory to control
the memory within this range the DOS operating system makes use of some data
structures called

• FCB (File control block )

• PSP (Program segment prefix)

We shall discuss how these data structures can be directly accessed, what is the
significance of data in these data structures. This information can be used to traverse
through the memory occupied by the processes and also calculate the total amount
of free memory available. Certain operating systems operate in protected mode. In
protected mode all of the memory interfaced with the processor can be accessed.
Operating systems in this mode make use of various data structures for memory
management which are

• Local Descriptor Table

• Global Descriptor Table

• Interrupt Descriptor Table

We will discuss the significance these data structures and the information stored in
them. Also we will see how the logical addresses can be translated into physical
addresses using the information these tables

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

1.2.5. Viruses and Vaccines


Once an understanding of the file system and the memory Management is developed
it is possible to understand the working of viruses. Virus is a simple program which
can embed itself within the computer resources and propagate itself. Mostly viruses
when activated would perform something hazardous.
We will see where do they embed themselves and how can they be detected. More-
over we will discuss techniques of how they can be removed and mostly impor-
tantly prevented to perform any infections. There are various types of viruses but
we will discuss those which embed themselves within the program or executable
code which are

1. Executable file viruses

2. Partition Table or boot sector viruses

1.2.6. Device Drivers


Just connecting a device to the PC will not make it work unless its device drivers
are not installed. This is so important because a device driver contains the routines
which perform I/O operations on the device. Unless these routines are provided
no I/O operation on the I/O device can be performed by any application. We will
discuss the integrated environment for the development of device drivers for DOS
and Windows. We shall begin our discussion from means of I/O. On a well designed
device it is possible to perform I/O operations from three different methods

• Programmed I/O

• Interrupt driven I/O

• DMA driven I/O

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

In case of programmed I/O the CPU is in a constant loop checking for an I/O op-
portunity and when its available it performs the computations operations required
for the I/O operations. As the I/O devices are generally slower than the CPU, CPU
has to wait for I/O operation to complete so that next data item can be sent to the
device. The CPU sends data on the data lines. The device need to be signaled that
the data has been sent this is done with the help of STROBE signal. An electrical
pulse is sent to the device by turning this signal to 0 and then 1. The device on
getting the strobe signal receives the data and starts its output. While the device
is performing the output it’s busy and cannot accept any further data on the other
and CPU is a lot faster device and can process lot more bytes during the output of
previously sent data so it should be synchronized with the slower I/O device.
This is usually done by another feed back signal of BUSY which is kept active as
long as the device is busy. So the CPU is only waiting for the device to get idle
by checking the BUSY signal as long as the device is busy and when the device
gets idle the CPU will compute the next data item and send it to the device for I/O
operation. Similar is the case of input, the CPU has to check the DR (data Ready)
signal to see if data is available for input and when its not CPU is busy waiting for
it.

The main disadvantage of programmed I/O as can be noticed is that the CPU is
busy waiting for an I/O opportunity and as a result remain tied up for that I/O
operation. This disadvantage can be overcome by means of interrupt driven I/O. In
Programmed I/O CPU itself checks for an I/O opportunity but in case of interrupt
driven I/O the I/O controller interrupts the execution of CPU when ever and I/O
operation is required for the computation of the required I/O operation. This way
the CPU can perform other computation and interrupted to perform and interrupt
service routine only when an I/O operation is required, which is quite an optimal
technique.

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

DMA driven I/O

In case data is needed to transferred from main memory to I/O port this can be
done using CPU which will consume 2 bus cyclesfor a single word, one bus cycle
from memory to CPU and other from CPU to I/O port in case of output and the
vice versa in case of input. In case no computation on data is required CPU can be
bypassed and another device DMA (direct memory access) controller can be used.
Its possible to transfer a data word directly from memory to CPU and vice versa in
a single bus cycle using the DMA, this technique is definitely faster.

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Revision questions

Example . Outline any three methods that you can use to perform I/O
Solution:

• Programmed I/O
• Interrupt driven I/O
• DMA driven I/O


E XERCISE 1.  ...

References and Additional Reading Materials


1. Recommended: An Introduction to Programming and Object Oriented De-
sign Using Java, Jaime

2. Nino and Frederick A. Hosch, John Wiley, New York.

3. Flanagan, D. (2005). Java in a nutshell : a desktop quick reference. O’Reilly


(5th ed.).

4. Flanagan, D. (2004). Java examples in a nutshell : a tutorial companion to


Java in a nutshell. O’Reilly (3rd ed.)

Course Journals
1. Acta Informatica ISSN 0001-5903

2. Advances in Computational Mathematics ISSN 1019-7168

3. Advances in data Analysis and Classification ISSN1 1862-5347

4. Annals Of software Engineering ISSN 1022-7091


Reference Journals
1. Journal of computer science and Technology ISSN 1000-9000

2. Journal of Science and Technology ISSN 1860-4749

3. Central European Journal Of Computer Science ISSN 1896-1533 Cluster


computing ISSN 1386-7857

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

LESSON 2
Interupt mechanisms

2.1. introduction
Interrupt follow a follow a certain mechanism for their invocation just like near or
far procedures. To understand this mechanism we need to understand its differences
with procedure calls. Difference between interrupt and procedure calls Procedures
or functions of sub-routines in various different languages are called by different
methods as can be seen in the examples.

• Call MyProc

• A= Addition(4,5);

• Printf(“hello world”);

The general concept for procedure call in most of the programming languages is
that on invocation of the procedure the parameter list and the return address (which
is the value if IP register in case of near or the value of CS and IP registers in case
of far procedure) is pushed Moreover in various programming languages whenever
a procedure is called its address need to be specified by some notation i.e. in C
language the name of the procedure is specified to call a procedure which effectively
can be used as its address.
However in case of interrupts the a number is used to specify the interrupt number
in the call

• Int 21h

• Int 10h

• Int3

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Moreover when an interrupt is invoked three registers are pushed as the return ad-
dress i.e. the values of IP, CS and Flags in the described order which are restored
on return. Also no parameters are pushed onto the stack on invocation parameters
can only be passed through registers.

2.1.1. The interrupt vector table


The interrupt number specified in the interrupt call is used as an index into the in-
terrupt vector table. Interrupt vector table is a global table situated at the address
0000:0000H. The size of interrupt vector table is 1024 bytes or 1 KB. Each entry in
the IVT is sized 4 bytes hence 256 interrupt vectors are possible numbered (0-FFH).
Each entry in the table contains a far address of an interrupt handlers hence there is
a maximum of 256 handlers however each handlers can have a number of services
within itself. So the number operations that can be performed by calling an inter-
rupt service routine (ISR) is indefinite depending upon the nature of the operating
system. Each vector contains a far address of an interrupt handler. The address of
the vector and not the address of interrupt handler can be easily calculated if the
interrupt number is known. The segment address of the whole IVT is 0000H the
offset address for a particular interrupt handler can be determined by multiplying
its number with 4 eg. The offset address of the vector of INT 21H will be 21H *
4 = 84H and the segment for all vectors is 0 hence its far address is 0000:0084H,(
this is the far address of the interrupt vector and not the interrupt service routine or
interrupt handler). The vector in turn contains the address of the interrupt service
routine which is an arbitrary value depending upon the location of the ISR residing
in memory.
Fig 2 (Interrupt Vector Table)

Moreover it is important to understand the meaning of the four bytes within the
interrupt vector. Each entry within the IVT contain a far address the first two bytes
(lower word) of which is the offset and the next two bytes (higher word) is the
segment address.

10

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Generally there are three kind of ISR within a system depending upon the entity
which implements it

• BIOS (Basic I/O services) ISRs

• DOS ISRs

• ISRs provided by third party device drivers

When the system has booted up and the applications can be run all these kind of
ISRs maybe provided by the system. Those provided by the ROM-BIOS would be
typically resident at any location after the address F000:0000H because this the ad-
dress within memory from where the ROM-BIOS starts, the ISRs provided by DOS
would be resident in the DOS kernel (mainly IO.SYS and MSDOS.SYS loaded in
memory) and the ISR provided by third party device drivers will be resident in the
memory occupied by the device drivers.

2.1.2. Interrupt Invocation


Although hardware and software interrupts are invoked differently i.e hardware in-
terrupts are invoked by means of some hardware whereas software interrupts are
invoked by means of software instruction or statement but no matter how an in-
terrupt has been invoked processor follows a certain set steps after invocation of
interrupts in exactly same way in both the cases.
These steps are listed as below

• Push Flags, CS, IP Registers, Clear Interrupt Flag

• Use (INT#)*4 as Offset and Zero as Segment

This is the address of interrupt Vector and not the ISR

• Use lower two bytes of interrupt Vector as offset and move into IP

• Use the higher two bytes of Vector as Segment Address and move it into
CS=0:[offset+2]

• Branch to ISR and Perform I/O Operation

• Return to Point of Interruption by Popping the 6 bytes i.e. Flags CS, IP.

11

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Moreover the instruction INT 21H can be assembled and executed in the debug pro-
gram, on doing exactly so the instruction is traced through and the result is moni-
tored. It can be seen that on execution of this instruction the value of IP is changed
to 107CH and the value of CS is changed to 00A7H which cause the execution to
branch to the Interrupt # 21H in memory and the previous values of flags, CS and
IP registers are temporarily saved onto the stack as the value of SP is reduced by 6
and the dump at the location SS:SP will show these saved values as well.

2.1.3. Parameter passing into Software interrupts


In case of procedures or function in various programming languages parameters are
passed through stack. Interrupts are also kind of function provided by the operat-
ing system but they do not accept parameters by stack rather they need to passed
parameters through registers.

2.1.4. Software interrupts invocation


Now let’s see how various interrupts can be invoked by means of software state-
ments. First there should be way to pass parameters into a software interrupt before
invoking the interrupt; there are several methods for doing this. One of the methods
is the use of pseudo variables. A variable can be defined a space within the mem-
ory whose value can be changed during the execution of a program but a pseudo
variable acts very much like a variable as its value can be changed anywhere in the
program but is not a true variable as it is not stored in memory. C programming
language provides the use of pseudo variables to access various registers within the
processor.
The are various registers like AX, BX, CX and DX within the processor they can
be directly accessed in a program by using their respective pseudo variable by just
attaching a “_” (underscore) before the register’s name eg. _AX = 5; A = _BX .
After passing the appropriate parameters the interrupt can be directly invoked by
calling the geninterrupt () function. The interrupt number needs to be passed as
parameter into the geninterrupt() function.
Interrupt # 21H, Service # 09 description
Now lets learn by means of an example how this can be accomplished. Before
invoking the interrupt the programmer needs to know how the interrupt behaves
and what parameters it requires. Lets take the example of interrupt # 21H and

12

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

service # 09 written as 21H/09H in short. It is used to print a string ending by a ‘$’


character and other parameters describing the string are as below
Inputs AH = 0x09
DS = Segment Address of string
DX = Offset Address of string
Output
The ‘$’ terminated string at the address DS:DX is displayed
One thing is note worthy that the service # is placed in AH which is common with
almost all the interrupts and its service. Also this service is not returning any sig-
nificant data, if some service needs to return some data it too is received in registers
depending upon the particular interrupt.
Example:
#include<stdio.h>
#include<BIOS.H>
#include<DOS.H>
#include<conio.h>
char st[80] ={"Hello World$"};
void main()
{
clrscr(); //to clear the screen contents
_DX = (unsigned int) st;
_AH = 0x09;
geninterrupt(0x21);
getch(); //waits for the user to press any key
}
this is a simple example in which the parameters of int 21H/09H are loaded and then
int 21H is invoked. DX and AH registers are accessed through pseudo variables and
then geninterrupt()is called to invoke the ISR. Also note that _DS is not loaded.
This is the case as the string to be loaded is of global scope and the C language
compiler automatically loads the segment address of the global data into the DS
register.
Another Method for invoking software interrupts
This method makes use of a Union. This union is formed by two structure which
correspond to general purpose registers AX, BX, CX and DX. And also the half

13

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

register AH, AL, BH, BL, CH, CL, DH, DL. These structures are combined such
that through this structure the field ax can be accessed to load a value and also its
half components al and ah can be accessed individually. The declaration of this
structure goes as below. If this union is to be used a programmer need not declare
the following declaration rather declaration already available through its header file
“dos.h”
struct full
{
unsigned int ax;
unsigned int bx;
unsigned int cx;
unsigned int dx;
};
struct half
{
unsigned char al;
unsigned char ah;
unsigned char bl;
unsigned char bh;
unsigned char cl;
unsigned char ch;
unsigned char dl; unsigned char dh;
};
typedef union tagREGS
{
struct full x;
struct half h;
}REGS;
This union can be used to signify any of the full or half general purpose register
shows if the field ax in x struct is to be accessed then accessing the fields al and ah
in h will also have the same effect as show in the example below.
Example:
#include<DOS.H>
union REGS regs;

14

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

void main (void )


{
regs.h.al = 0x55;
regs.h.ah = 0x99;
printf (“%x”,regs.x.ax); }
The int86() function
The significance of this REGS union can only be understood after understanding
the int86() function. The int86() has three parameters. The first parameter is the
interrupt number to be invoked, the second parameter is the reference to a REGS
type union which contains the value of parameters that should be passed as inputs,
and third parameter is a reference to a REGS union which will contain the value
of registers returned by this function. All the required parameters for an ISR are
placed in REGS type of union and its reference is passed to an int86() function.
This function will put the value in this union into the respective register and then
invoke the interrupt. As the ISR returns it might leave some meaningful value in
the register (ISR will return values), these values can be retrieved from the REGS
union whose reference was passed into the function as the third parameter.
Example using interrupt # 21H service # 42H
To make it more meaningful we can again elaborate it by means of an example.
Here we make use of ISR 21H/42H which is used to move the file pointer. Its detail
is as follows
Int # 21 Service # 42H
Inputs
AL = Move Technique
BX = File Handle
CX-DX = No of Bytes File to be moved
AH = Service # = 42H
Output
DX-AX = No of Bytes File pointer actually moved
This service is used to move the file pointer to a certain position relative to a certain
point. The value in AL specify the point relative to which the pointer is moved. If
the value of AL = 0 then file pointer is moved relative to the BOF (begin of File)
if AL=1 then its moved relative to current position and if AL = 2 then its moved
relative to the EOF (end of file).

15

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

CX-DX specify the number of bytes to move a double word is needed to specify
this value as the size of file in DOS can be up to 2 GB.
On return of the service DX-AX will contain the number of bytes the file pointer is
actually moved eg. If the file pointer is moved relative to the EOF zero bytes the
DX-AX on return will contain the size of file if the file pointer was at BOF before
calling the service.

16

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Revision questions

Example . Outline any three ISR that can be used in systems


Solution:

BIOS (Basic I/O services) ISRs


DOS ISRs
ISRs provided by third party device drivers


E XERCISE 2.  ....

17

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

LESSON 3
Registry service

3.1. introduction
The above described service can be used to get the size of a file in the described
manner. The following C language program tries to accomplish just that. This
program has been saved as .C file and not as .CPP file and then compiled.
Example 21H/42H:
#include<stdio.h>
#include<fcntl.h>
#include<io.h>
#include<BIOS.H>
#include<DOS.H>
unsigned int handle;
void main()
{
union REGS regs;
unsigned long int size;
handle = open("c:\\abc.txt",O_RDONLY);
regs.x.bx = handle;
regs.h.ah = 0x42;
regs.h.al = 0x02; //correction
regs.x.cx = 0;
regs.x.dx = 0;
int86(0x21,&regs,&regs);
*((int*)(&size)) = regs.x.ax;
*(((int*)(&size))+1) =regs.x.dx;
printf ("Size is %d“ ,size);
}
This program opens a file and saves its handle in the handle variable. This handle
is passed to the ISR 21H/42H along with the move technique whose value is 2 sig-
nifing movement relative to the EOF and the number of bytes to move are specified
to be zero indicating that the pointer should move to the EOF. As the file was just
opened the previous location of the file pointer will be BOF.

18

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

On return of this service DX-AX will contain the size of the file. The low word of
this size in ax is placed in the low word of size variable and the high word in dx is
placed in the high word of size variable.
Another Example: Lets now illustrate how ISR can be invoked by means of another
example of BIOS service. Here we are choosing the ISR 10h/01h. This interrupt
is used to perform I/O on the monitor. Moreover this service is used to change the
size of cursor in text mode. The description of this service is given as under.
Int # 10H Service # 01H
Entry
AH = 01 CH = Beginning Scan Line
CL = Ending Scan Line
On Exit
Unchanged
The size of the cursor depends upon the number of net scan lines used to display
the cursor if the beginning scan line is greater than the ending scan line the cursor
will disappear. The following tries to accomplish just that
void main()
{
char st[80];
union REGS regs;
regs.h.ah = 0x01;
regs.h.ch = 0x01;
regs.h.cl = 0x00;
int86(0x10,&regs,&regs); //corrected
gets(st);
}
The program is quite self explanatory as it puts the starting scan line to be 1 and
the ending scan line to be 0. Henceforth when the service execute the cursor will
disappear. Use of ISRs for C Library functions
There are various library function that a programmer would typically use in a pro-
gram to perform input output operations. These library functions perform trivial
I/O operations like character input (putch()) and character output (getch(), getc()
etc).

19

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

All these function call various ISRs to perform this I/O. In BIOS and DOS docu-
mentation number of services can be found that lie in correspondence with some C
library function in terms of its functionality. Writing S/W ISRs Lets now see how
can a programmer write an ISR routine and what needs to be done in order make
the service work properly. To exhibit this we will make use of an interrupt which
is not used by DOS or BIOS so that our experiment does not put any interference
to the normal functions of DOS and BIOS. One such interrupt is interrupt # 65H.
The vector of int 65H is typically filled with zeros another indication that it is not
being used. Getting interrupt vector As we have discussed earlier IVT is a table
containing 4 byte entries each of which is a far address of an interrupt service rou-
tine. All the vectors are arranged serially such that the interrupt number can be used
as an index into the IVT. Getting interrupt vector refers to the operation which used
to reading the far address stored within the vector. The vector is double word, the
lower word of it being the offset address and the higher word being the segment
address. Moreover the address read from a vector can be used as a function pointer.
The C library function used to do the exactly

3.2. Function pointers


Another thing required to be understood are the function pointers. C language is a
very flexible language just like there are pointers for integers, characters and other
data types there are pointers for functions as well as illustrated by the following
example

•.6. void myfunc() {


}
void (*funcptr) ( )
funcptr = myfunc;
(*funcptr) ( );
myfunc();
There are three fragments of code in this example. The first fragment shows the dec-
laration of a function myfunc() The second fragment show declaration of a pointer
to function named funcptr which is a pointer to a function that returns void. In the
third fragment funcptr is assigned the address of myfunc as the name of the func-
tion can be used as its address just like in the cases of arrays in C. Then the function

20

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

pointed by funcptr by the statement (*funcptr)(); is called and then the original my-
func() is called. The user will observe in both the cases same function myproc()
will be invoked.

3.3. Interrupt pointers and functions


Interrupt functions are special function that as compared to simple functions for
reasons discussed earlier. It can be declared using the keyword interrupt as shown
in the following examples.
void interrupt newint ( )
{
...
...
}
Similarly a pointer to such interrupt type function can also be declared as following
void interrupt (*intptr) ( );
where intptr is the interrupt pointer and it can be assigned an address using the
getvect() function
intptr = getvect(0x08);
Now interrupt number 8 can be invoked using the interrupt vector as following
(*intptr) ( );

3.3.1. Setting Interrupt Vector


Setting interrupt vector is just the reverse process of getting interrupt vector. To
set the interrupt vector means is to change the double word sized interrupt vector
within the IVT. This task can be accomplished using the function setvect(int #,
newint) which requires the number of interrupt whose vector is to be changed and
the new value of the vector.
In the following example a certain interrupt type function has been declared.
The address of this function can be placed on to the vector of any interrupt using
setvect() function as following. The following code places the address of newint
function at the vector of int 8
void interrupt newint ( )
{
...

21

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

...
}
setvect(0x08, newint);
C program making use of Int 65H
Here is a listing of a program that makes use of int 65H to exhibit how software
interrupts needs to be programmed.
void interrupt (*oldint65)( );
char st[80] = {“Hello World$”};
void interrupt newint65(void);
void main()
{
oldint65 = getvect(0x65);
setvect(0x65, newint65);
geninterrupt (0x65);
geninterrupt (0x65);
geninterrupt (0x65);
setvect(0x65, oldint65);
}
void interrupt newint65( )
{
_AH = 0x09;
_DX=(unsigned int)st;
geninterrupt (0x21);
}
The above listing saves the address of original int 65H in the pointer oldint65.
It then places the address of its own function newint65 at the vector of interrupt
number 65H. From this point onwards whenever int 65H is invokes the function
newint65 will be invoked. Int 65 is invoked thrice which will force the newint65
function to be invoked thrice accordingly. After this the original value of the vector
stored in oldint65 is restored. The newint65 function only displays the string st. As
the interrupt 65 is invoked thrice this string will be printed thrice.

22

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

3.3.2. The Keep function


One deficiency in the above listing is that it is not good enough for other application
i.e. after the termination of this program the newint65 function is de-allocated from
the memory and the interrupt vector needs to be restored otherwise it will act as a
dangling pointer (pointing to a place where there is garbage or where there is no
meaningful function).
To make the effect of this program permanent the newint65 function need to be
memory resident. This can be achieved by the function keep() which is quite sim-
ilar to exit() function. The exit() function returns the execution to the parent shell
program and de-allocates the memory allocated to the program whereas the keep()
function also returns the execution to the parent program but the memory allocated
to the process may still remain allocated. keep (return code, no. of paras); the keep()
function requires the return code which is usually zero for normal termination and
the number of paragraphs required to be allocated.
Each paragraph is 16 bytes in size. TSR Programs Following is a listing of a TSR
(Terminate and Stay Resident) program which programs the interrupt number 65H
but in this case the new interrupt 65H function remains in memory even after the
termination of the program and hence the vector of int 65h does not become a
dangling pointer.
#include<BIOS.H>
#include<DOS.H>
char st[80] ={"Hello World$"};
void interrupt (*oldint65)( );
void interrupt newint65( );
void main()
{
oldint65 = getvect(0x65);
setvect(0x65, newint65);
keep(0, 1000);
}
void interrupt newint65( )
{
_AH = 0x09;
_DX=(unsigned int)st;

23

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

geninterrupt (0x21);
}
The main()function gets and sets the vector of int 65H such that the address of
newint65 is placed at its vector. In this case the program is made memory resident
using the keep function and 1000 paragraphs of memory is reserved for the program
(the amount of paragraphs is just a calculated guess work based upon the size of
application). Now if any application as in the following case invokes int 65H the
string st which is also now memory resident will be displayed.
#include<BIOS.H>
#include<DOS.H>
void main()
{
geninterrupt (0x65);
geninterrupt (0x65);
}
This program invokes the interrupt 65H twice which has been made resident.

24

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Revision questions

Example . State one deficiency of keep function instruction


Solution:

One deficiency in the above listing is that it is not good enough for other application
i.e. after the termination of this program the newint65 function is de-allocated from
the memory and the interrupt vector needs to be restored otherwise it will act as a
dangling component


E XERCISE 3.  ....

25

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

LESSON 4
Port Programming in I/O

4.1. introduction
file *fptr;
unsigned far *base=(unsigned int far *)0x00400008
void main (void)
{
fptr=fopen(“c:\\abc.txt”,”rb”);
while( ! feof (fptr) )
{
if( ! ( inport (*base + 1 ) & 0x80)
{
outport(*base,getc(fptr));
outport ((*base+2,inport((*base+2) | 0x01);
outport((*base+2,inport((*base+2) & 0xFE); } }}
The above program directly accesses the registers of the PPI to print a file. The
while loop terminates when the file ends. The if statement only schecks if the
printer is busy of not. If the printer is idle the program writes the next byte in file on
to the data port and then turns the strobe bit to 1 and then 0 to indicate that a byte
has been sent to the printer.
The loop then again starts checking the busy status of the printer and the process
continue.

4.1.1. Interrupt Driven Printer I/O


char buf [1024]; int i = 0;
void interrupt (*oldint)( );
void interrupt newint ();
void main (void)
{
outport(( *lpt), inport( *lpt) | 4);
outport(( *lpt), inport( *lpt) | 0x10);
oldint =getvect (0x0F);
setvect (0x0F, newint);

26

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

outport(0x21, inport( 0x21) & 0x7F);//corrected


keep(0,1000);
}
Above is a listing of a program that uses int 0x0f to perform interrupt driven I/O. To
enable the interrupt 0x0f three things are required to be done. The interrupt should
be enabled in the printer control register, secondly it should also be unmasked in
the IMR in PIC. The program can then intercept or set the vector of interrupt 0x0f
by placing the address of its function newint();
The newint() will now be called whenever the printer can perform output. This
newint() function writes the next byte in buffer to the data registers and then send
a pulse on the strobe signal to tell the printer that data has been sent to it. When
whole of the buffer has been sent the int 0x0f vector is restored, interrupt is masked
and the memory for the program is de-allocated.
The above listing might not work.
Not all of the printer interfaces are designed as described above. Some modifica-
tions in the printer interface will not allow the interrupt driven I/O to work in this
manner. If this does not work the following strategy can be adopted to send printing
to the printer in background.
#include <stdio.h>
#include <dos.h>
#include <bios.h>
#include <conio.h>
#include <stdlib.h>
void interrupt (*oldint)();
void interrupt newint();
unsigned int far * lpt = (unsigned int far *)0x00400008;
char st[80]= "this is a test print string !!!!!!!!!!!";
int i ;
void main ()
{
oldint = getvect(0x08);
setvect(0x08,newint);
keep(0,1000);
}

27

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

void interrupt newint()


{
if ((( inport((*lpt) +1)) & 0x80) == 0x80)
{
outport (*lpt,st[i++]);
outport ((*lpt)+2, inport((*lpt)+2) & 0xfe);
outport ((*lpt)+2, inport((*lpt)+2) | 1);
}
if (i==32)
{
setvect (0x08,oldint);
freemem(_psp);
}
(*oldint) ();
}
This program uses the timer interrupt to send printing to the printer in the back
ground. Whenever the timer interrupt occurs the interrupt function checks if the
printer is idle or not. If it’s the printer is idle it takes a byte from the buffer and
sends it to the data port of the printer interface and then sends a pulse through the
strobe signal. When the buffer is full the program restores the int 8 vector and the
relinquishes the memory occupied by the program.
It might be desirable to connect one computer to another via PPIs to transfer data.
One might desire to connect them such that one port of PPI at one end is connected
to another port of the other PPI at the other end. But interconnecting the whole
8 bits of PPI cannot be made possible as all the bits of the internal ports are not
available as pinouts. So the answer is to connect a nibble (4-bits) at one end to the
nibble at the other. In this way two way communication can be performed. The
nibbles are connected as shown in the slide above.

28

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Revision questions

Example . Write a sample program implement a printer program file


Solution:

*fptr;
unsigned far *base=(unsigned int far *)0x00400008
void main (void)
{
fptr=fopen(“c:\\abc.txt”,”rb”);
while( ! feof (fptr) )
{
if( ! ( inport (*base + 1 ) & 0x80)
{
outport(*base,getc(fptr));
outport ((*base+2,inport((*base+2) | 0x01);
outport((*base+2,inport((*base+2) & 0xFE);
}
}
}
. 

E XERCISE 4.  .....

29

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

LESSON 5
System calls in unix

5.1. introduction
A system call is just what its name implies – a request for the operating system
to do something on behalf of the user’s program. The system calls are functions
used in the kernel itself. To the programmer, the system call appears as a normal C
function call.
However since a system call executes code in the kernel, there must be a mechanism
to change the mode of a process from user mode to kernel mode. The C compiler
uses a predefined library of functions (the C library) that have the names of the
system calls. The library functions typically invoke an instruction that changes the
process execution mode to kernel mode and causes the kernel to start executing
code for system calls. The instruction that causes the mode change is often referred
to as an "operating system trap" which is a software generated interrupt.
The library routines execute in user mode, but the system call interface is a special
case of an interrupt handler. The library functions passthe kernel a unique number
per system call in a machine dependent way – either as a parameter to the operating
system trap, in a particular register, or on the stack – and the kernel thus determines
the specific system call the user is invoking. In handling the operating systemtrap,
the kernel looks up the system call number in a table to find the address of the
appropriate kernel routine that is the entry point for the system call and to find the
number of parameters the system callexpects.
The kernel calculates the (user) address of the first parameter to the system call by
adding (or subtracting, depending on the direction of stack growth) an offset to the
user stack pointer, corresponding to the number of the parameters to the system
call.
Finally, it copies the user parameters to the "u area" and call the appropriate system
call routine. After executing the code for the system call, the kernel determines
whether there was an error. If so, it adjusts register locations in the saved user
register context, typically setting the "carry" bit for the PS (processor status) register
and copying the error number into register 0 location. If there were no errors in the
execution of the system call, the kernel clears the "carry" bit in the PS register
and copies the appropriate return values from the system call into the locations for

30

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

registers 0 and 1 in the saved user register context. When the kernel returns from
the operating system trap to user mode, it returns to the library instruction after the
trap instruction. The library interprets the return values from the kernel and returns
a value to the user program.
UNIX system calls are used to manage the file system, control processes,and to
provide interprocess communication. The UNIX system interface consists of about
80 system calls (as UNIX evolves this number will increase).

31

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

[NOTE: The system call interface is that aspect of UNIX that has changed the most
since the inception of the UNIX system. Therefore, when you write a software tool,
you should protect that tool by putting system calls in other subroutines within your
program and then calling only those subroutines. Should the next version of the
UNIX system change the syntax and semantics of the system calls you’ve used, you
need only change your interface routines.]
When a system call discovers and error, it returns -1 and stores the reason the called
failed in an external variable named "errno". The "/usr/include/errno.h" file maps
these error numbers to manifest constants, and it these constants that you should
use in your programs.
When a system call returns successfully, it returns something other than -1, but it
does not clear "errno". "errno" only has meaning directly after a system call that
returns an error.
When you use system calls in your programs, you should check the value returned
by those system calls. Furthermore, when a system call discovers an error, you
should use the "perror()" subroutine to print a diagnostic message on the standard
error file that describes why the system call failed. The syntax for "perror()" is:
void perror(string)
char string;
"perror()" displays the argument string, a colon, and then the error message, as
directed by "errno", followed by a newline. The output of "perror()" is displayed
on "standard error". Typically, the argument give to "perror()" is the name of the
program that incurred the error, argv[0]. However, when using subroutines and
system calls on files, the related file name might be passed to "perror()".
There are occasions where you the programmer might wish to maintain more con-
trol over the printing of error messages than "perror()" provides – such as with a
formatted screen where the newline printed by "perror()" would destroy the for-
matting. In this case, you can directly access the same system external (global)
variables that "perror()" uses. They are:

32

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

extern int errno;


extern char *sys_errlist[];
extern int sys_nerr;
"errno" has been described above. "sys_errlist" is an array (table) of pointers to the
error message strings. Each message string is null terminated and does not contain a
newline. "sys_nerr" is the number of messages in the error message table and is the
maximum value "errno" can assume. "errno" is used as the index into the table of
error messages. Following are two sample programs that display all of the system
error messages on standard error.

33

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Revision questions

Example . Define the term system call


Solution:

A request for the operating system to do something on behalf of the user’s program.
The system calls are functions used in the kernel itself. To the programmer, the
system call appears as a normal C function call.


E XERCISE 5.  ....

34

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

LESSON 6
Unix file system

6.1. introduction
A file system is a logical method for organising and storing large amounts of in-
formation in a way which makes it easy manage. The file is the smallest unit in
which information is stored. The UNIX file system has several important features.
to you, the user, it appears as though there is only one type of file in UNIX - the
file which is used to hold your information. In fact, the UNIX filesystem contains
several types of file.

6.1.1. Types of files systems


1. Ordinary files

(a) This type of file is used to store your information, such as some text
you have written or an image you have drawn. This is the type of file
that you usually work with. Files which you create belong to you - you
are said to "own" them - and you can set access permissions to control
which other users can have access to them. Any file is always contained
within a directory.

2. Special files

(a) This type of file is used to represent a real physical device such as a
printer, tape drive or terminal. It may seem unusual to think of a physical
device as a file, but it allows you to send the output of a command to a
device in the same way that you send it to a file. For example:

cat scream.au > /dev/audio


This sends the contents of the sound file scream.au to the file /dev/audio
which represents the audio device attached to the system. Guess what sound
this makes? The directory /dev contains the special files which are used to
represent devices on a UNIX system.

3. Directories

35

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

(a) A directory is a file that holds other files and other directories. You can
create directories in your home directory to hold files and other sub-
directories. Having your own directory structure gives you a definable
place to work from and allows you to structure your information in a
way that makes best sense to you. Directories which you create belong
to you - you are said to "own" them - and you can set access permissions
to control which other users can have access to the information they
contain.

4. Pipes

(a) UNIX allows you to link commands together using a pipe. The pipe acts
as a temporary file which only exists to hold data from one command
until it is read by another.

6.1.2. structure of file systems


•.7. Structure of the file system

The UNIX file system is organised as a hierarchy of directories starting fro


Immediately below the root directory are several system directories that con

• UNIX system directories

• Home directory

• Pathnames

• UNIX system directories


The standard system directories are shown below. Each one contains specific types
of file. The details may vary between different UNIX systems, but these directories
should be common to all. Select one for more information on it.

36

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

• Pathnames
Every file and directory in the file system can be identified by a complete list of the
names of the directories that are on the route from the root directory to that file or
directory. Each directory name on the route is separated by a / (forward slash).
For example: /usr/local/bin/ue
This gives the full pathname starting at the root directory and going down through
the directories usr, local and bin to the file ue - the program for the MicroEMACS
editor. You can picture the full pathname as looking like this:

• Directory Structure:
Unix uses a hierarchical file system structure, much like an upside-down tree, with
root (/) at the base of the file system and all other directories spreading from there.
A UNIX filesystem is a collection of files and directories that has the following
properties:

• It has a root directory (/) that contains other files and directories.

• Each file or directory is uniquely identified by its name, the directory in which
it resides, and a unique identifier, typically called an inode.

• By convention, the root directory has an inode number of 2 and the lost+found
directory has an inode number of 3. Inode numbers 0 and 1 are not used. File
inode numbers can be seen by specifying the -i option to ls command.

• It is self contained. There are no dependencies between one filesystem and


any other.

The directories have specific purposes and generally hold the same types of infor-
mation for easily locating files. Following are the directories that exist on the major
versions of Unix:

37

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

additional

• /var Typically contains variable-length files such as log and print files and any
other type of file that may contain a variable amount of data

• /sbin Contains binary (executable) files, usually for system administration.


For example fdisk and ifconfig utlities.

• /kernel Contains kernel files

6.1.3. Navigating the File System:


Now that you understand the basics of the file system, you can begin navigating to
the files you need. The following are commands you’ll use to navigate the system:

extras

• rmdir dirname Removes a directory.

• tail filename Shows the end of a file.

38

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

• touch filename Creates a blank file or modifies an existing file.s attributes.

• whereis filename Shows the location of a file.

• which filename Shows the location of a file if it is in your PATH.

You can use Manpage Help to check complete syntax for each command mentioned
here.

6.1.4. The df Command:


The first way to manage your partition space is with the df (disk free) command.
The command df -k (disk free) displays the disk space usage in kilobytes, as shown
below:

Some of the directories, such as /devices, shows 0 in the kbytes, used, and avail
columns as well as 0% for capacity. These are special (or virtual) file systems, and
although they reside on the disk under /, by themselves they do not take up disk
space.
The df -k output is generally the same on all Unix systems. Here’s what it usually
includes:

1. Filesystem

(a) The physical file system name.

2. kbytes

(a) Total kilobytes of space available on the storage medium.

3. used

(a) Total kilobytes of space used (by files).

4. avail

(a) Total kilobytes available for use.

39

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

5. capacity

(a) Percentage of total space used by files.

6. Mounted on

(a) What the file system is mounted on.

You can use the -h (human readable) option to display the output in a format that
shows the size in easier-to-understand notation.

6.1.5. The du Command:


The du (disk usage) command enables you to specify directories to show disk space
usage on a particular directory. This command is helpful if you want to determine
how much space a particular directory is taking. Following command would display
number of blocks consumed by each directory. A single block may take either 512
Bytes or 1 Kilo Byte depending on your system.
$du /etc
10 /etc/cron.d
126 /etc/default
6 /etc/dfs
...
$
The -h option makes the output easier to comprehend:
$du -h /etc
5k /etc/cron.d
63k /etc/default
3k /etc/dfs
...
$

6.1.6. Mounting the File System:


A file system must be mounted in order to be usable by the system. To see what is
currently mounted (available for use) on your system, use this command:
$mount

40

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

/dev/vzfs on / type reiserfs (rw,usrquota,grpquota)


proc on /proc type proc (rw,nodiratime)
devpts on /dev/pts type devpts (rw)
$
The /mnt directory, by Unix convention, is where temporary mounts (such as CD-
ROM drives, remote network drives, and floppy drives) are located. If you need to
mount a file system, you can use the mount command with the following syntax:
mount -t file_system_type device_to_mount directory_to_mount_to
For example, if you want to mount a CD-ROM to the directory /mnt/cdrom, for
example, you can type:
$ mount -t iso9660 /dev/cdrom /mnt/cdrom
This assumes that your CD-ROM device is called /dev/cdrom and that you want to
mount it to /mnt/cdrom. Refer to the mount man page for more specific information
or type mount -h at the command line for help information.
After mounting, you can use the cd command to navigate the newly available file
system through the mountpoint you just made.

6.1.7. Unmounting the File System:


To unmount (remove) the file system from your system, use the umount command
by identifying the mountpoint or device
For example, to unmount cdrom, use the following command:
$ umount /dev/cdrom
The mount command enables you to access your file systems, but on most modern
Unix systems, the automount function makes this process invisible to the user and
requires no intervention.

6.1.8. User and Group Quotas:


User and group quotas provide the mechanisms by which the amount of space used
by a single user or all users within a specific group can be limited to a value defined
by the administrator.
Quotas operate around two limits that allow the user to take some action if the
amount of space or number of disk blocks start to exceed the administrator defined
limits:

41

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Soft Limit: If the user exceeds the limit defined, there is a grace period that allows
the user to free up some space.
Hard Limit: When the hard limit is reached, regardless of the grace period, no
further files or blocks can be allocated.
here are a number of commands to administer quotas:
(Command and their Description)

• quota

– Displays disk usage and limits for a user of group.

• edquota

– This is a quota editor. Users or Groups quota can be edited using this
command.

• quotacheck

– Scan a filesystem for disk usage, create, check and repair quota files

• setquota

– This is also a command line quota editor.

• quotaon

– This announces to the system that disk quotas should be enabled on one
or more filesystems.

• quotaoff

– This announces to the system that disk quotas should be disabled off
one or more filesystems.

• repquota

– This prints a summary of the disc usage and quotas for the specified file
systems

42

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

REVISION QUESTIONS

Example . Outline any four properties of unix file system


Solution:

It has a root directory (/) that contains other files and directories.
Each file or directory is uniquely identified by its name, the directory in which it
resides, and a unique identifier, typically called an inode.
By convention, the root directory has an inode number of 2 and the lost+found
directory has an inode number of 3. Inode numbers 0 and 1 are not used. File inode
numbers can be seen by specifying the -i option to ls command.
It is self contained. There are no dependencies between one filesystem and any
other. 

E XERCISE 6.  ....

43

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

LESSON 7
System processes

7.1. introduction
When you execute a program on your UNIX system, the system creates a special
environment for that program. This environment contains everything needed for the
system to run the program as if no other program were running on the system.
Whenever you issue a command in UNIX, it creates, or starts, a new process. When
you tried out the ls command to list directory contents, you started a process.
A process, in simple terms, is an instance of a running program.
The operating system tracks processes through a five digit ID number known as the
pid or process ID . Each process in the system has a unique pid.
Pids eventually repeat because all the possible numbers are used up and the next
pid rolls or starts over. At any one time, no two processes with the same pid exist
in the system because it is the pid that UNIX uses to track each process.

7.1.1. Starting a Process:


When you start a process (run a command), there are two ways you can run it:

• Foreground Processes

• Background Processes

• Foreground Processes:
By default, every process that you start runs in the foreground. It gets its input from
the keyboard and sends its output to the screen.
You can see this happen with the ls command. If I want to list all the files in my
current directory, I can use the following command: $ls ch*.doc
This would display all the files whose name start with ch and ends with .doc:
ch01-1.doc ch010.doc ch02.doc ch03-2.doc
ch04-1.doc ch040.doc ch05.doc ch06-2.doc
ch01-2.doc ch02-1.doc
The process runs in the foreground, the output is directed to my screen, and if the
ls command wants any input (which it does not), it waits for it from the keyboard.

44

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

While a program is running in foreground and taking much time, we cannot run any
other commands (start any other processes) because prompt would not be available
until program finishes its processing and comes out.

• Background Processes:
A background process runs without being connected to your keyboard. If the back-
ground process requires any keyboard input, it waits.
The advantage of running a process in the background is that you can run other
commands; you do not have to wait until it completes to start another!
The simplest way to start a background process is to add an ampersand ( &) at the
end of the command.
$ls ch*.doc &
This would also display all the files whose name start with ch and ends with .doc:
ch01-1.doc ch010.doc ch02.doc ch03-2.doc
ch04-1.doc ch040.doc ch05.doc ch06-2.doc
ch01-2.doc ch02-1.doc
Here if the ls command wants any input (which it does not), it goes into a stop state
until I move it into the foreground and give it the data from the keyboard.
That first line contains information about the background process - the job num-
ber and process ID. You need to know the job number to manipulate it between
background and foreground.
If you press the Enter key now, you see the following:
[1] + Done ls ch*.doc &
$
The first line tells you that the ls command background process finishes success-
fully.
The second is a prompt for another command.

7.1.2. Listing Running Processes:


It is easy to see your own processes by running the ps (process status) command as
follows:
$ps
PID TTY TIME CMD
18358 ttyp3 00:00:00 sh

45

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

18361 ttyp3 00:01:31 abiword


18789 ttyp3 00:00:00 ps
One of the most commonly used flags for ps is the -f ( f for full) option, which
provides more information as shown in the following example:
$ps -f
UID PID PPID C STIME TTY TIME CMD
amrood 6738 3662 0 10:23:03 pts/6 0:00 first_one
amrood 6739 3662 0 10:22:54 pts/6 0:00 second_one
amrood 3662 3657 0 08:10:53 pts/6 0:00 -ksh
amrood 6892 3662 4 10:51:50 pts/6 0:00 ps -f
Here is the description of all the fileds displayed by ps -f command:

1. UID

(a) User ID that this process belongs to (the person running it).

2. PID

(a) Process ID.

3. PPID

(a) Parent process ID (the ID of the process that started it).

4. C

(a) CPU utilization of process.

5. STIME

(a) Process start time.

6. TTY

(a) Terminal type associated with the process

7. TIME CPU

(a) time taken by the process.

46

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

8. CMD

(a) The command that started this process.

7.1.3. Stopping Processes:


Ending a process can be done in several different ways. Often, from a console-
based command, sending a CTRL + C keystroke (the default interrupt character)
will exit the command.
This works when process is running in foreground mode.
If a process is running in background mode then first you would need to get its Job
ID using ps command and after that you can use kill command to kill the process
as follows:
$ps -f
UID PID PPID C STIME TTY TIME CMD
amrood 6738 3662 0 10:23:03 pts/6 0:00 first_one
amrood 6739 3662 0 10:22:54 pts/6 0:00 second_one
amrood 3662 3657 0 08:10:53 pts/6 0:00 -ksh
amrood 6892 3662 4 10:51:50 pts/6 0:00 ps -f
$kill 6738
Terminated
Here kill command would terminate first_one process. If a process ignores a regular
kill command, you can use kill -9 followed by the process ID as follows:
$kill -9 6738
Terminated

7.1.4. Parent and Child Processes:


Each unix process has two ID numbers assigned to it: Process ID (pid) and Parent
process ID (ppid). Each user process in the system has a parent process. Most of the
commands that you run have the shell as their parent. Check ps -f example where
this command listed both process ID and parent process ID.

7.1.5. Zombie and Orphan Processes:


Normally, when a child process is killed, the parent process is told via a SIGCHLD
signal. Then the parent can do some other task or restart a new child as needed.

47

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

However, sometimes the parent process is killed before its child is killed. In this
case, the "parent of all processes," init process, becomes the new PPID (parent
process ID). Sometime these processes are called orphan process.
When a process is killed, a ps listing may still show the process with a Z state. This
is a zombie, or defunct, process. The process is dead and not being used. These
processes are different from orphan processes.
They are the processes that has completed execution but still has an entry in the
process table.

7.1.6. Daemon Processes:


Daemons are system-related background processes that often run with the permis-
sions of root and services requests from other processes.
A daemon process has no controlling terminal. It cannot open /dev/tty. If you do a
"ps -ef" and look at the tty field, all daemons will have a ? for the tty.
More clearly, a daemon is just a process that runs in the background, usually waiting
for something to happen that it is capable of working with, like a printer daemon is
waiting for print commands.
If you have a program which needs to do long processing then its worth to make it
a daemon and run it in background.

7.1.7. The top Command:


The top command is a very useful tool for quickly showing processes sorted by
various criteria.
It is an interactive diagnostic tool that updates frequently and shows information
about physical and virtual memory, CPU usage, load averages, and your busy pro-
cesses.
Here is simple syntax to run top command and to see the statistics of CPU utilization
by different processes:
$top

7.1.8. Job ID Versus Process ID:


Background and suspended processes are usually manipulated via job number (job
ID). This number is different from the process ID and is used because it is shorter.

48

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

•.1. In addition, a job can consist of multiple processes running in series or at the
same time, in parallel, so using the job ID is easier than tracking the individual
processes.

49

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Revision questions

Example . Explain the term Daemons Process


Solution:

Daemons are system-related background processes that often run with the permis-
sions of root and services requests from other processes.


E XERCISE 7.  ...

50

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

LESSON 8
The network utilities

8.1. introduction
When you work in a distributed environment then you need to communicate with
remote users and you also need to access remote UNIX machines
There are several Unix utilities which are especially useful for users computing in
a networked, distributed environment. This tutorial lists few of them:

8.1.1. The ping Utility:


The ping command sends an echo request to a host available on the network. Using
this command you can check if your remote host is responding well or not.
The ping command is useful for the following:

• Tracking and isolating hardware and software problems.

• Determining the status of the network and various foreign hosts.

• Testing, measuring, and managing networks.

Syntax:
Following is the simple syntax to use ping command:
$ping hostname or ip-address
Above command would start printing a response after every second. To come out
of the command you can terminate it by pressing CNTRL + C keys.
Example . Example:
Following is the example to check the availability of a host available on the network:
$ping google.com
PING google.com (74.125.67.100) 56(84) bytes of data.
64 bytes from 74.125.67.100: icmp_seq=1 ttl=54 time=39.4 ms
64 bytes from 74.125.67.100: icmp_seq=2 ttl=54 time=39.9 ms
64 bytes from 74.125.67.100: icmp_seq=3 ttl=54 time=39.3 ms
64 bytes from 74.125.67.100: icmp_seq=4 ttl=54 time=39.1 ms
64 bytes from 74.125.67.100: icmp_seq=5 ttl=54 time=38.8 ms
— google.com ping statistics —

51

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

22 packets transmitted, 22 received, 0% packet loss, time 21017ms


rtt min/avg/max/mdev = 38.867/39.334/39.900/0.396 ms
$
If a host does not exist then it would behave something like this:
$ping giiiiiigle.com
ping: unknown host giiiiigle.com
$

8.1.2. The ftp Utility:


Here ftp stands for File Transfer Protocol. This utility helps you to upload and
download your file from one computer to another computer.
The ftp utility has its own set of UNIX like commands which allow you to perform
tasks such as:

• Connect and login to a remote host.

• Navigate directories.

• List directory contents

• Put and get files

• Transfer files as ascii, ebcdic or binary

Syntax:
Following is the simple syntax to use ping command:
$ftp hostname or ip-address
Above command would prompt you for login ID and password. Once you are
authenticated, you would have access on the home directory of the login account
and you would be able to perform various commands.
Few of the useful commands are listed below:

1. put filename Upload filename from local machine to remote machine.

2. get filename Download filename from remote machine to local machine.

3. mput file list Upload more than one files from local machine to remote ma-
chine.

52

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

4. mget file list Download more than one files from remote machine to local
machine.

5. prompt off Turns prompt off, by default you would be prompted to upload
or download movies using mput or mget commands.

6. prompt on Turns prompt on.

7. dir List all the files available in the current directory of remote machine.

8. cd dirname Change directory to dirname on remote machine.

9. lcd dirname Change directory to dirname on local machine.

10. quit Logout from the current login.

It should be noted that all the files would be downloaded or uploaded to or from
current directories. If you want to upload your files in a particular directory then
first you change to that directory and then upload required files.

•.2. Example:

•.3. Following is the example to show few commands:

53

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

8.1.3. The telnet Utility:


Many times you would be in need to connect to a remote Unix machine and work
on that machine remotely. Telnet is a utility that allows a computer user at one site
to make a connection, login and then conduct work on a computer at another site.
Once you are login using telnet, you can perform all the activities on your remotely
connect machine. Here is example telnet session:

8.1.4. The finger Utility:


The finger command displays information about users on a given host. The host
can be either local or remote. Finger may be disabled on other systems for security
reasons.
Following are the simple syntax to use finger command:
Check all the logged in users on local machine as follows:

54

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

55

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Revision Questions

Example . Explain any three important applications of the ping commands


Solution:

• Tracking and isolating hardware and software problems.


• Determining the status of the network and various foreign hosts.
• Testing, measuring, and managing networks.


E XERCISE 8.  ...

56

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

LESSON 9
Systems performance

9.1. introduction
The purpose of this tutorial is to introduce the performance analyst to some of the
free tools available to monitor and manage performance on UNIX systems, and
to provide a guideline on how to diagnose and fix performance problems in Unix
environment.
UNIX has following major resource types that need to be monitored and tuned:

• CPU

• Memory

• Disk space

• Communications lines

• I/O Time

• Network Time

• Applications programs

9.1.1. Performance Components:


There are following major five component where total system time goes:

1. User state CPU The actual amount of time the CPU spends running the users
program in the user state. It includes time spent executing library calls, but
does not include time spent in the kernel on its behalf.

2. System state CPU This is the amount of time the CPU spends in the system
state on behalf of this program. All I/O routines require kernel services. The
programmer can affect this value by the use of blocking for I/O transfers.

3. I/O Time and Network Time These are the amount of time spent moving
data and servicing I/O requests

57

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

4. Virtual Memory Performance This includes context switching and swap-


ping.

5. Application Program Time spent running other programs - when the system
is not servicing this application because another application currently has the
CPU.

9.1.2. Performance Tools:


Unix provides following important tools to measure and fine tune Unix system per-
formance:

1. nice/renice Run a program with modified scheduling priority

2. netstat Print network connections, routing tables, interface statistics, mas-


querade connections, and multicast memberships

3. time Time a simple command or give resource usage

4. uptime System Load Average

5. ps Report a snapshot of the current processes.

6. vmstat Report virtual memory statistics

7. gprof Display call graph profile data

8. prof Process Profiling

9. top Display system tasks

58

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Revision questions

Example . Outline any resource types in UNIX that should be managed and
controlled
Solution:

• CPU
• Memory
• Disk space
• Communications lines
• I/O Time
• Network Time
• Applications programs


E XERCISE 9.  ....

59

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

LESSON 10
User administration in unix

10.1. introduction
There are three types of accounts on a Unix system:

1. Root account: This is also called superuser and would have complete and
unfettered control of the system. A superuser can run any commands without
any restriction. This user should be assumed as a system administrator.

2. System accounts: System accounts are those needed for the operation of
system-specific components for example mail accounts and the sshd accounts.
These accounts are usually needed for some specific function on your system,
and any modifications to them could adversely affect the system.

3. User accounts: User accounts provide interactive access to the system for
users and groups of users. General users are typically assigned to these ac-
counts and usually have limited access to critical system files and directories.

Unix supports a concept of Group Account which logically groups a number of


accounts. Every account would be a part of any group account. Unix groups plays
important role in handling file permissions and process management.

10.1.1. Managing Users and Groups:


There are three main user administration files:

1. /etc/passwd: Keeps user account and password information. This file holds
the majority of information about accounts on the Unix system.

2. /etc/shadow: Holds the encrypted password of the corresponding account.


Not all the system support this file.

3. /etc/group: This file contains the group information for each account.

4. /etc/gshadow: This file contains secure group account information.

Check all the above files using cat command.


Following are commands available on the majority of Unix systems to create and
manage accounts and groups:

60

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

• useradd Adds accounts to the system.

• usermod Modifies account attributes.

• userdel Deletes accounts from the system.

• groupadd Adds groups to the system.

• groupmod Modifies group attributes.

• groupdel Removes groups from the system.

You can use Manpage Help to check complete syntax for each command mentioned
here.

10.1.2. Create a Group


You would need to create groups before creating any account otherwise you would
have to use existing groups at your system. You would have all the groups listed in
/etc/groups file.
All the default groups would be system account specific groups and it is not recom-
mended to use them for ordinary accounts. So following is the syntax to create a
new group account:
groupadd [-g gid [-o]] [-r] [-f] groupname
Here is the detail of the parameters:

• -g GID The numerical value of the group’s ID.

• -o This option permits to add group with non-unique GID

• -r This flag instructs groupadd to add a system account

• -f This option causes to just exit with success status if the specified group
already exists. With -g, if specified GID already exists, other (unique) GID is
chosen

• groupname Actaul group name to be created.

If you do not specify any parameter then system would use default values.
Following example would create developers group with default values, which is
very much acceptable for most of the administrators.
$ groupadd developers

61

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

10.1.3. Modify a Group:


To modify a group, use the groupmod syntax:
$ groupmod -n new_modified_group_name old_group_name
To change the developers_2 group name to developer, type:
$ groupmod -n developer developer_2
Here is how you would change the financial GID to 545:
$ groupmod -g 545 developer

10.1.4. Delete a Group:


To delete an existing group, all you need are the groupdel command and the group
name.
To delete the financial group, the command is:
$ groupdel developer
This removes only the group, not any files associated with that group. The files are
still accessible by their owners.

10.1.5. Create an Account


Let us see how to create a new account on your Unix system. Following is the
syntax to create a user’s account:
useradd -d homedir -g groupname -m -s shell -u userid accountname
Here is the detail of the parameters:

• -d homedir Specifies home directory for the account.

• -g groupname Specifies a group account for this account.

• -m Creates the home directory if it doesn’t exist.

• -s shell Specifies the default shell for this account.

• -u userid You can specify a user id for this account.

• accountname Actual account name to be created

If you do not specify any parameter then system would use default values. The
useradd command modifies the /etc/passwd, /etc/shadow, and /etc/group files and
creates a home directory.

62

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Following is the example which would create an account mcmohd setting its home
directory to /home/mcmohd and group as developers.
This user would have Korn Shell assigned to it.
$ useradd -d /home/mcmohd -g developers -s /bin/ksh mcmohd
Before issuing above command, make sure you already have developers group cre-
ated using groupadd command.
Once an account is created you can set its password using the passwd command as
follows:
$ passwd mcmohd20
Changing password for user mcmohd20.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
When you type passwd accountname, it gives you option to change the password
provided you are super user otherwise you would be able to change just your pass-
word using the same command but without specifying your account name.

10.1.6. Modify an Account:


The usermod command enables you to make changes to an existing account from
the command line. It uses the same arguments as the useradd command, plus the -l
argument, which allows you to change the account name.
For example, to change the account name mcmohd to mcmohd20 and to change
home directory accordingly, you would need to issue following command:
$ usermod -d /home/mcmohd20 -m -l mcmohd mcmohd20

10.1.7. Delete an Account:


The userdel command can be used to delete an existing user. This is a very danger-
ous command if not used with caution.
There is only one argument or option available for the command: .r, for removing
the account’s home directory and mail file.
For example, to remove account mcmohd20, you would need to issue following
command:
$ userdel -r mcmohd20

63

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

If you want to keep her home directory for backup purposes, omit the -r option.
You can remove the home directory as needed at a later time.

64

Downloaded by OCEN JOHN BOSCO ([email protected])


lOMoARcPSD|44175230

ICS 2305 SYSTEMS PROGRAMMING

Revision questions

Example . Explain the three main user administration files:


Solution:

1. /etc/passwd: Keeps user account and password information. This file holds the
majority of information about accounts on the Unix system.
2. /etc/shadow: Holds the encrypted password of the corresponding account. Not
all the system support this file.
3. /etc/group: This file contains the group information for each account.


E XERCISE 10.  ...

65

Downloaded by OCEN JOHN BOSCO ([email protected])

You might also like