1 SRINIVASAN ENGINEERING COLLEGE PERAMBALUR-621212 DEPARTMENT OF INFORMATION TECHNOLOGY CS2257 – OPERATING SYSTEMS LABORATORY II - IT (2011-2015) PREPARED BY Mr. G.Baskaran M.E., Assistant professor/Information Technology, Srinivasan Engineering college, Perambalur-621212 Anna university, Chennai (R-2008) Academic year (2012-13) IV SEMESTER
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1
SRINIVASAN ENGINEERING COLLEGE
PERAMBALUR-621212
DEPARTMENT OF INFORMATION TECHNOLOGY
CS2257 – OPERATING SYSTEMS LABORATORY
II - IT (2011-2015)
PREPARED BY
Mr. G.Baskaran M.E.,
Assistant professor/Information Technology,
Srinivasan Engineering college, Perambalur-621212
Anna university, Chennai (R-2008)
Academic year (2012-13) IV SEMESTER
2
DEDICATED TO
My Family &
My Friends
3
PREFACE Operating Systems Laboratory Manual is intended as an introduction of executing programs for reader and students. This manual provides a handy guide to the developers in managing computer hardware. The purpose of an operating system is to provide an environment in which a user can execute programs in a convenient and efficient manner.
4
ACKNOWLEDGEMENT Behind every achievement lies an unfathomable sea of gratitude to all those who made the
achievement possible without whom it would never have come into existence.
I give all glory and thanks to our god almighty for showering upon, the necessary wisdom and
grace for accomplishing the lab manual.
I am indebted to our honorable chairman and founder of Dhanalakshmi Srinivasan Group of
institutions, SHRI.A.SRINIVASAN , for his kind encouragement.
I am very much happy to thank our beloved Principal Dr.B.KARTHIKEYAN M.E., Ph.D.,
for his unflinching devotion and continuous encouragement motivated me to complete this lab
manual.
I extend my warm gratitude to our Head of the Department, Mr. S.SATHISHKUMAR ME.,
for his valuable suggestion and kind guidance throughout the manual preparation.
Finally, I thank my parents, and my friends without whom this course would have been a
dream.
5
CS2257 – OPERATING SYSTEMS LABORATORY
(Common to CSE and IT)
(Implement the following on LINUX or other Unix like platform. Use C for high level language
implementation)
LIST OF EXPERIMENTS
1. Write programs using the following system calls of UNIX operating system: fork, exec,
getpid, exit, wait, close, stat, opendir, readdir
2. Write programs using the I/O system calls of UNIX operating system (open, read, write, etc)
3. Write C programs to simulate UNIX commands like ls, grep, etc.
4. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt
chart for FCFS and SJF. For each of the scheduling policies, compute and print the average
waiting time and average turnaround time. (2 sessions)
5. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt
chart for Priority and Round robin. For each of the scheduling policies, compute and print the
average waiting time and average turnaround time. (2 sessions)
6. Developing Application using Inter Process Communication (using shared memory, or
message queues)
7. Implement the Producer – Consumer problem using semaphores (using UNIX system calls).
8. Implement some memory management schemes – I
9. Implement some memory management schemes – II
10. Implement any file allocation technique (Linked, Indexed or Contiguous)
Total: 45
6
Example for exercises 8 and 9:
Free space is maintained as a linked list of nodes with each node having the starting byte address and
the ending byte address of a free block. Each memory request consists of the process-id and the
amount of storage space required in bytes. Allocated memory space is again maintained as a linked
list of nodes with each node having the process-id, starting byte address and the ending byte address
of the allocated space. When a process finishes (taken as input) the appropriate node from the
allocated list should be deleted and this free disk space should be added to the free space list. [Care
should be taken to merge contiguous free blocks into one single block. This results in deleting more
than one node from the free space list and changing the start and end address in the appropriate node].
For allocation use first fit, worst fit and best fit.
7
CONTENTS
S.NO LIST OF EXPERIMENTS
PAGE NO
1 Implementation of System Calls 7
2 Implementation of I/O System Calls 18
3 Simulation of UNIX Commands 23
4 a Implementation of FCFS Scheduling 28
4 b Implementation of SJF Scheduling 33
5 a Implementation of Priority Scheduling 38
5 b Implementation of Round Robin Scheduling 42
6 a Inter Process Communication Using Shared Memory 47
6 b Inter Process Communication Using Message Queues 50
7 Producer – Consumer Problem Using Semaphores 55
8 Memory Management Schemes – I 59
9 Memory Management Schemes – II 67
10 File Allocation Technique (Linked, Indexed Or Contiguous) 74
8
STUDY OF LINUX
INTRODUCTION TO LINUX
Linux is a generic term referring to Unix-like computer operating systems based on the Linux
kernel. Their development is one of the most prominent examples of free and open source software
collaboration; typically all the underlying source code can be used, freely modified, and redistributed
by anyone.
The name "Linux" comes from the Linux kernel, originally written in 1991 by Linus Torvalds.
The rest of the system usually comprises components such as the Apache HTTP Server, the X
Window System, the K Desktop Environment, and utilities and libraries from the GNU operating
system (announced in 1983 by Richard Stallman). Many quantitative studies of free / open source
software focus on topics including market share and reliability, with numerous studies specifically
examining Linux. The Linux market is growing rapidly, and the revenue of servers, desktops, and
packaged software running Linux was expected to exceed $35.7 billion by 2008.
LINUX FILE SYSTEM
A file system is the methods and data structures that an operating system uses to keep track of
files on a disk or partition; that is, the way the files are organized on the disk. The word is also used
to refer to a partition or disk that is used to store the files or the type of the file system. The difference
between a disk or partition and the file system it contains is important. A few programs (including,
reasonably enough, programs that create file systems) operate directly on the raw sectors of a disk or
partition; if there is an existing file system there it will be destroyed or seriously corrupted. Most
programs operate on a file system, and therefore won't work on a partition that doesn't contain one (or
that contains one of the wrong type). Before a partition or disk can be used as a file system, it needs
to be initialized, and the bookkeeping data structures need to be written to the disk. This process is
called making a file system.
Most UNIX file system types have a similar general structure, although the exact details vary
quite a bit. The central concepts are superblock, inode, data block, directory block, and indirection
block. The superblock contains information about the file system as a whole, such as its size (the
exact information here depends on the file system). An inode contains all information about a file,
except its name. The name is stored in the directory, together with the number of the inode. A
directory entry consists of a filename and the number of the inode which represents the file. The
9
inode contains the numbers of several data blocks, which are used to store the data in the file. There is
space only for a few data block numbers in the inode, however, and if more are needed, more space
for pointers to the data blocks is allocated dynamically. These dynamically allocated blocks are
indirect blocks; the name indicates that in order to find the data block, one has to find its number in
the indirect block first.
Like UNIX, Linux chooses to have a single hierarchical directory structure. Everything starts
from the root directory, represented by /, and then expands into sub-directories instead of having so-
called 'drives'. In the Windows environment, one may put one's files almost anywhere: on C drive, D
drive, E drive etc. Such a file system is called a hierarchical structure and is managed by the programs
themselves (program directories), not by the operating system. On the other hand, Linux sorts
directories descending from the root directory / according to their importance to the boot process.
Linux, like Unix also chooses to be case sensitive. What this means is that the case, whether in
capitals or not, of the characters becomes very important. This feature accounts for a fairly large
proportion of problems for new users especially during file transfer operations whether it may be via
removable disk media such as floppy disk or over the wire by way of FTP.
The image below shows the file system of Linux
10
The following bin/ dev/ home/ lost+found/ proc/ sbin/ usr/ boot/ etc/ lib/ mnt/ root/ tmp/ var/ are
explained in detail.
/sbin - This directory contains all the binaries that are essential to the working of the system.
These include system administration as well as maintenance and hardware configuration
programs.
/bin - In contrast to /sbin, the bin directory contains several useful commands that are used by
both the system administrator as well as non privileged users.
/boot - This directory contains the system.map file as well as the Linux kernel. Lilo places the
boot sector backups in this directory.
11
/dev - This is a very interesting directory that highlights one important characteristic of the
Linux file system - everything is a file or a directory. Look through this directory and you
should see hda1, hda2 etc, which represent the various partitions on the first master drive of
the system. /dev/cdrom and /dev/fd0 represent your CDROM drive and your floppy drive.
/etc - This directory contains all the configuration files for your system. Your lilo.conf file lies
in this directory as does hosts, resolv.conf and fstab.
/home –These are the user home directories, which can be found under /home/username.
/lib - This contains all the shared libraries that are required by system programs. Windows
equivalent to a shared library would be a DLL file.
/lost+found - Linux should always go through a proper shutdown. Sometimes your system
might crash or a power failure might take the machine down. Either way, at the next boot, a
lengthy filesystem check using fsck will be done. Fsck will go through the system and try to
recover any corrupt files that it finds. The result of this recovery operation will be placed in
this directory.
/mnt - This directory usually contains mount points or sub-directories where you mount your
floppy and your CD.
/opt - This directory contains all the software and add-on packages that are not part of the
default installation.
/proc - This is a special directory on your system.
/root - We talked about user home directories earlier and well this one is the home directory
of the user root.
/tmp - This directory contains mostly files that are required temporarily.
/usr - This is one of the most important directories in the system as it contains all the user
binaries. /usr/src/linux contains the source code for the Linux kernel.
/var - This directory contains spooling data like mail and also the output from the printer
daemon. The above content briefs about Linux and the file system of Linux. Thus the Linux
file system is explained in detail.
12
Uses of Linux
Linux is a widely ported operating system kernel. The Linux kernel runs on a highly diverse range of
computer architectures: in the hand-held ARM-based iPAQ and the mainframe IBM System z9,
System z10; in devices ranging from mobile phones to supercomputers.[68] Specialized distributions
exist for less mainstream architectures. The ELKS kernel fork can run on Intel 8086 or Intel 80286
16-bit microprocessors, while the µClinux kernel fork may run on systems without a memory
management unit. The kernel also runs on architectures that were only ever intended to use a
manufacturer-created operating system, such as Macintosh computers (with both PowerPC and Intel
processors), PDAs, video game consoles, portable music players, and mobile phones. See List of
Linux supported architectures.
Applications of Linux
1. OpenShot (Video editor)
2. Apache (Web server)
3. Firefox (Web browser)
4. Dropbox (Online storage)
5. Asterisk (Telephony)
Linux Advantages
1. Low cost: You don’t need to spend time and money to obtain licenses since Linux and much
of its software come with the GNU General Public License. You can start to work
immediately without worrying that your software may stop working anytime because the free
trial version expire.s
2. Stability: Linux doesn’t need to be rebooted periodically to maintain performance levels. It
doesn’t freeze up or slow down over time due to memory leaks and such. Continuous up-
times of hundreds of days (up to a year or more) are not uncommon.
3. Performance: Linux provides persistent high performance on workstations and on networks.
It can handle unusually large numbers of users simultaneously, and can make old computers
sufficiently responsive to be useful again.
4. Network friendliness: Linux was developed by a group of programmers over the Internet and
has therefore strong support for network functionality; client and server systems can be easily
13
set up on any computer running Linux. It can perform tasks such as network backups faster
and more reliably than alternative systems.
5. Fast and easy installation: Most Linux distributions come with user-friendly installation and
setup programs. Popular Linux distributions come with tools that make installation of
additional software very user friendly as well.
6. Full use of hard disk: Linux continues work well even when the hard disk is almost full.
7. Multitasking: Linux is designed to do many things at the same time; e.g., a large printing job
in the background won’t slow down your other work.
8. Security: Linux is one of the most secure operating systems. “Walls” and flexible file access
permission systems prevent access by unwanted visitors or viruses. Linux users have to option
to select and safely download software, free of charge, from online repositories containing
thousands of high quality packages. No purchase transactions requiring credit card numbers or
other sensitive personal information are necessary.
9. Open Source: If you develop software that requires knowledge or modification of the
operating system code, Linux’s source code is at your fingertips. Most Linux applications are
Open Source as well.
Disadvantages of Linux:
1. Understanding – Becoming familiar with the Linux operating system requires patience as
well as a strong learning curve. You must have the desire to read and figure things out on your
own, rather than having everything done for you. Check out the 20 must read howto’s and
guides for Linux.
2. Compatibility – Because of its free nature, Linux is sometimes behind the curve when it
comes to brand new hardware compatibility. Though the kernel contributors and maintainers
work hard at keeping the kernel up to date, Linux does not have as much of a corporate
backing as alternative operating systems. Sometimes you can find third party applications,
sometimes you can’t.
3. Alternative Programs – Though Linux developers have done a great job at creating
alternatives to popular Windows applications, there are still some applications that exist on
Windows that have no equivalent Linux application. Read Alternatives to Windows
Applications to find out some of the popular alternatives.
14
Ex.No: 1
IMPLEMENTATION OF SYSTEM CALLS
Aim:
To write a program using process system call.
Algorithm:
����NAME
fork – create a new process system call.
SYNOPSIS
#include<unistd.h>
pid_t fork(void);
DESCRIPTION
The fork() function shall create a new process. The new process (child process) shall be an exact copy
of the calling process (parent process). The child process shall have a unique process ID.
System call fork() is used to create processes. It takes no arguments and returns a process ID.
The purpose of fork() is to create a new process, which becomes the child process of the caller. After
a new child process is created, both processes will execute the next instruction following the fork()
system call. Therefore, we have to distinguish the parent from the child. This can be done by testing
the returned value of fork() :
• If fork() returns a negative value, the creation of a child process was unsuccessful.
• fork() returns a zero to the newly created child process.
• fork() returns a positive value, the process ID of the child process, to the parent.
Thus the program to implement producer and consumer problem using semaphores was
executed.
66
Ex.No: 8
MEMORY MANAGEMENT SCHEMES – I
FIRST FIT BEST FIT
Aim:
To write a program for first fit and best fit algorithm for memory management.
DESCRIPTION
����Memory Management Algorithms
In an environment that supports dynamic memory allocation, the memory manager must keep a
record of the usage of each allocatable block of memory. This record could be kept by using almost
any data structure that implements linked lists. An obvious implementation is to define a free list of
block descriptors, with each descriport containing a pointer to the next descriptor, a pointer to the
block, and the length of the block. The memory manager keeps a free list pointer and inserts entries
into the list in some order conducive to its allocation strategy. A number of strategies are used to
allocate space to the processes that are competing for memory.
����First Fit
Another strategy is first fit, which simply scans the free list until a large enough hole is found.
Despite the name, first-fit is generally better than best-fit because it leads to less fragmentation. Small
holes tend to accumulate near the beginning of the free list, making the memory allocator search
farther and farther each time.Solution: Next Fit
����Best Fit
The allocator places a process in the smallest block of unallocated memory in which it will fit. It
requires an expensive search of the entire free list to find the best hole. More importantly, it leads to
the creation of lots of little holes that are not big enough to satisfy any requests. This situation is
called fragmentation, and is a problem for all memory-management strategies, although it is
67
particularly bad for best-fit. One way to avoid making little holes is to give the client a bigger block
than it asked for. For example, we might round all requests up to the next larger multiple of 64 bytes.
That doesn't make the fragmentation go away, it just hides it.
• Unusable space in the form of holes is called external fragmentation
• Unusable space in the form of holes is called external fragmentation
Algorithm:
1. Start the program.
2. Get the number of segments and size.
3. Get the memory requirement and select the option.
4. If the option is ‘2’ call first fit function.
5. If the option is ‘1’ call best fit function.
6. Otherwise exit.
7. For first fit, allocate the process to first possible segment which is free.
8. For best fit, do the following steps.
a. Sorts the segments according to their sizes.
b. Allocate the process to the segment which is equal to or slightly greater than the
process size.
9. Stop the program.
68
Program:
#include<stdio.h>
#include<conio.h>
#define MAXSIZE 25
void printlayout(int[],int );
int firstfit(int[],int, int);
int bestfit(int[],int, int);
void main()
{
int i,a[25],n,req,choice,pos,ch;
clrscr();
printf("How MAny Segments");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Segent Size");
scanf("%d",&a[i]);
}
loop:
printf("How Much Is Your Memory Requirment");
scanf("%d",&req);
printf("\n1.Bestfit\n2.Firstfit\n3.Exit\n");
printf("Enter Your Choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
pos=bestfit(a,n,req);
break;
case 2:
pos=firstfit(a,n,req);
69
break;
}
printf("\tBestfit and Firstfit Algorithm\n");
printf("\t______________________________\n\n");
printlayout(a,n);
printf("Your Memory Requirment is :%d\n\n",req);
printf("Alloted Memory Region is:%d\n\n",a[pos]);
a[pos]=0;
printf("Do You Want To Continue 1/0");
scanf("%d",&ch);
if(ch==1)
goto loop;
getch();
}
void printlayout(int a[],int n)
{
int i,j;
printf("\t\tMemory Free List");
printf("\n\t\t_______________\n\n");
printf("\t\t|~~~|\n");
for(i=0;i<n;i++)
{
if(a[i]!=0)
{
for(j=1;j<=(a[i]/100);j++)
printf("\t\t| |\n");
printf("\t\t| %d|\n",a[i]);
printf("\t\t|---|\n");
}}
printf("\n\n");
}
70
int firstfit(int a[],int n,int r)
{
int i;
for(i=0;i<n;i++)
if(a[i]>=r)
break;
return i;
}
int bestfit(int a[],int n,int r)
{
int b[25],i,j,temp,val;
for(i=0;i<n;i++)
b[i]=a[i];
for(i=0;i<n-1;i++)
for(j=i;j<n-1;j++)
if(b[i]>b[j])
{
temp=b[i];
b[i]=b[j];
b[j]=temp;
}
for(i=0;i<n;i++)
if(b[i]>=r)
break;
val=b[i];
for(i=0;i<n;i++)
if(a[i]==val)
break;
return i;
}
71
OUTPUT:
How Many Segments4
Segent Size500
Segent Size200
Segent Size300
Segent Size400
How Much Is Your Memory Requirment200
1.Bestfit
2.Firstfit
3.Exit
Enter Your Choice 1
Bestfit and Firstfit Algorithm
___________________________________
Memory Free List
___________________________________
|~~~|
| |
| |
| |
| |
|500|
| --- |
| |
| |
|200|
| --- |
| |
| |
| |
|300|
72
| --- |
| |
| |
| |
| |
|400|
| --- |
Your Memory Requirment is :200
Alloted Memory Region is:200
Do You Want To Continue 1/0
1
How Much Is Your Memory Requirment250
1.Bestfit
2.Firstfit
3.Exit
Enter Your Choice
1
Bestfit and Firstfit Algorithm
___________________________________
Memory Free List
___________________________________
|~~~|
| |
| |
| |
|500|
73
| --- |
| |
| |
|300|
| --- |
| |
| |
| |
|400|
| --- |
Your Memory Requirment is :250
Alloted Memory Region is:300
Do You Want To Continue 1/0
0
Result:
Thus the program for best fit and first fit algorithm for memory management was executed.
74
Ex.No:9
MEMORY MANAGEMENT SCHEMES – II
PAGE REPLACEMENT
Aim:
To write a program for page replacement algorithms (FIFO and LRU) for memory
management.
DESCRIPTION
�Page replacement algorithms are used to decide what pages to page out when a page needs to be
allocated. This happens when a page fault occurs and free page cannot be used to satisfy allocation
FIFO:
�The frames are empty in the beginning and initially no page fault occurs so it is set to minus one.
When a page fault occurs the page reference string is brought into memory. The operating system
keeps track of all the pages in memory, herby keeping track of the most recently arrived and the
oldest one. If the page in the page reference string is not in memory, the page fault is incremented and
the oldest page is replaced. If the page in the page reference string is in the memory, take the next
page without calculating the page fault. Take the next page in the page reference string and check if
the page is already present in the memory or not. Repeat the process until all the pages are referred
and calculate the page fault for all those pages in the page reference string for the number of available
frames.
LRU :
�A good approximation to the optimal algorithm is based on the observation that pages that have
been heavily used in the last few instructions will probably be heavily used again in the next few.
Conversely, pages that have not been used for ages will probably remain unused for a long time. This
idea suggests a realizable algorithm: when a page fault occurs, throw out the page that has been
unused for the longest time. This strategy is called LRU (Least Recently Used) paging.
75
Algorithm:
1. Start the program
2. Obtain the number of sequences, number of frames and sequence string from the user
3. Now when a page is not in the frame comes, increment the number of page fault and remove
the page that come in the first in FIFO algorithm
4. In LRU algorithm, when a page fault occurs, the page which most recently used is removed
5. Display the number of faults
6. Stop the program
76
Program:
#include<stdio.h>
int m,n,i,j,k,flag,count=0,refer[100],page_frame[100][2],fault=0,min,no_frames;
void replace(int z)
{
for(i=0;i<n;i++)
{
flag=1;
for(j=0;j<no_frames;j++)
if(refer[i]==page_frame[j][0])
{
m=j;
flag=0;
}
if(flag)
{
fault++;
min=32000;
for(j=0;j<no_frames;j++)
if(page_frame[j][1]<min)
{
min=page_frame[j][1];
k=j;
}
page_frame[k][0]=refer[i];
page_frame[k][1]=++count;
for(j=0;j<no_frames;j++)
printf("%d",page_frame[j][0]);
printf("\n");
}
else
77
{
printf("no page fault\n");
if(z==2)
page_frame[m][1]=++count;
}
}
printf("number of page fault is:%d\n",fault);
}
int main()
{
printf("\nEnter the number of reference:");
scanf("%d",&n);
printf("\nEnter the number of frames:");
scanf("%d",&no_frames);
printf("\nEnter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&refer[i]);
printf("\t\t\tFIFO ALGORITHM \n");
for(i=0;i<no_frames;i++)
{
page_frame[i][0]=-1;
page_frame[i][1]=count;
}
replace(1);
fault=0;
count=0;
printf("\t\t\tLRU ALGORITHM \n");
for(i=0;i<no_frames;i++)
{
page_frame[i][0]=-1;
page_frame[i][1]=count;
78
}
replace(2);
return 0;
getch();
}
79
OUTPUT:
Enter the number of reference:10
Enter the number of frames:3
Enter the reference string:7 0 1 2 0 3 0 4 2 6
FIFO ALGORITHM
7 -1 -1
7 0 -1
7 0 1
2 0 1
no page fault
2 3 1
2 3 0
4 3 0
4 2 0
4 2 6
number of page fault is:9
LRU ALGORITHM
7 -1 -1
7 0 -1
7 0 1
2 0 1
no page fault
2 0 3
no page fault
4 0 3
4 0 2
4 6 2
number of page fault is:8
80
Result:
Thus the program for page replacement algorithms for memory management was successfully
executed.
81
Ex.No:10 FILE ALLOCATION TECHNIQUE-CONTIGUOUS
AIM:
To Write a C Program to implement file allocation technique.
DESCRIPTION
File Allocation Methods
One main problem in file management is how to allocate space for files so that disk space is utilized effectively and files can be accessed quickly. Three major methods of allocating disk space are: * Contiguous Allocation * Linked Allocation * Indexed Allocation. Each method has its advantages and disadvantages. Accordingly, some systems support all three (e.g. Data General's RDOS). More commonly, a system will use one particular method for all files. Contiguous File Allocation
• Each file occupies a set of contiguous block on the disk • Allocation using first fit/best fit. • A need for compaction • Only starting block and length of file in blocks are needed to work with the file • Allows random access • Problems with files that grow
ALGORITHM:
1. Start the process
2. Declare the necessary variables
3. Get the number of files
4.Get the total no. of blocks that fit in to the file
5. Display the file name, start address and size of the file.
6.Stop the program.
82
PROGRAM:
#include<stdio.h>
void main()
{
int i,j,n,block[20],start:
printf(“Enter the no. of file:\n”);
scanf(“%d”,&n);
printf(“Enter the number of blocks needed for each file:\n”);
for(i=0,i<n;i++)
scanf(“%d”,&block[i]);
start=0;
printf(“\t\tFile name\tStart\tSize of file\t\t\n”);