Você está na página 1de 65

SEC CSE/IV OS LAB MANUAL

1
SRINIVASAN ENGINEERING COLLEGE
COMPUTER SCIENCE AND ENGINEERING
ANNA UNIVERSITY OF TECHNOLOGY TRICHIRAPALLI
REGULATION 2009
II CSE (2011-2015)
CS2257
OPERATING SYSTEM LAB
LAB MANUAL
BY
VEENA ALPHONSA JOSE, Assistant Professor.
SEC CSE/IV OS LAB MANUAL
2
Preface
This laboratory manual is prepared by the Department of Computer Science and engineering
for Operating system Laboratory (CS-2257). This lab manual can be used as instructional book for
students, staff and instructors to assist in performing and understanding the experiments. In the first
part of the manual, experiments as per syllabus are described and in the second part of the manual,
experiments that are beyond the syllabus but expected for university laboratory examination are
displayed. This manual will be available in electronic form from Colleges official website, for the
betterment of students.
Acknowledgement
We would like to express our profound gratitude and deep regards to the support offered by
the Chairman Shri. A.Srinivasan. We also take this opportunity to express a deep sense of
gratitude to our Principal Dr.B.Karthikeyan,M.E,Ph.D, for his valuable information and
guidance, which helped us in completing this task through various stages. We extend our hearty
thanks to our head of the department Asst Prof.P.Jayanthi M.E, for her constant encouragement
and constructive comments.
Finally the valuable comments from fellow faculty and assistance provided by the
department are highly acknowledged.
SEC CSE/IV OS LAB MANUAL
3
TABLE OF CONTENTS
CHAPTER NO TOPIC PAGE NO
I
Introduction to the language
Main Features
Advantages
Limitations
Applications
4
II Syllabus 6
III
System Requirements 7
IV
Description about each experiment
Aim
Learning Objective
General procedure to execute programs
8
V Experiments
1
Write programs using the following system calls of UNIX
operating system: fork, exec, getpid, exit, wait, close, stat,
opendir, readdir.
10
2
Write programs using the I/O system calls of UNIX
operating system (open, read, write, etc)
16
3
Write C programs to simulate UNIX commands like ls, grep,
etc.
20
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)
24
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).
32
6
Developing Application using Inter Process Communication
(using shared memory, or message queues)
40
7
Implement the Producer Consumer problem using
semaphores (using UNIX system calls)
46
8
Implement some memory management schemes I
50
9 Implement some memory management schemes II 58
10
Implement any file allocation technique (Linked,
Indexed or Contiguous)
63
SEC CSE/IV OS LAB MANUAL
4
INTRODUCTION OF THE LANGUAGE (Linux)
MAIN FEATURES
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.
ADVANTAGES
Cost The most obvious advantage of using Linux is the fact that it is free to obtain, while
Microsoft products are available for a hefty and sometimes recurring fee.
Security In line with the costs, the security aspect of Linux is much stronger than that of
Windows.
Choice (Freedom) The power of choice is a great Linux advantage. With Linux, you
have the power to control just about every aspect of the operating system.
Software - There are so many software choices when it comes to doing any specific task.
You could search for a text editor on Freshmeat and yield hundreds, if not thousands of
results. My article on 5 Linux text editors you should know about explains how there are so
many options just for editing text on the command-line due to the open source nature
of Linux.
Hardware - Linux is perfect for those old computers with barely anyprocessing power or
memory you have sitting in your garage or basementcollecting dust.
LIMITATIONS
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 howtos
and guides for Linux.
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
SEC CSE/IV OS LAB MANUAL
5
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 cant.
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.
APPLICATIONS
1. OpenShot (Video editor)
2. Apache (Web server)
3. Firefox (Web browser)
4. Dropbox (Online storage)
5. Asterisk (Telephony)
SEC CSE/IV OS LAB MANUAL
6
SYLLABUS
CS2257 OPERATING SYSTEM LAB
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)
SEC CSE/IV OS LAB MANUAL
7
HARDWARE REQUIREMENTS
System : 1
O/S : Linux or Unix
Compiler : Turbo C or TC3
SEC CSE/IV OS LAB MANUAL
8
ABOUT THE OPERATING SYSTEM LAB
AIM
At the end of the course students should be able to

describe the general structure and purpose of an operating system;

explain the concepts of process, address space, and file;

compare and contrast various CPU scheduling algorithms;

understand the differences between segmented and paged memories, and be able to
describe the advantages and disadvantages of each;
Compare and contrast polled, interrupt-driven and DMA-based access to I/O devices..
OVERVIEW OF THE EXPERIMENTS
To implement various page replacement memory management schemes to compare and
contrast the relative performance of different page replacement schemes.
Inter Process Communication Using Shared Memory and Message Queuescan
communicates among them using the Shared Memory regions. Shared Memory is an
efficient means of passing data between programs. One program will create a memory
portion, which other processes (if permitted) can access. A shared segment can be attached
multiple times by the same process
The way to use the most common system calls in order to make input-output operations on
files, as well as operations to handle files and directories in the Linux operating system.
Implementation of FCFS and SJF Scheduling, This selects each process from the processes
in memory that are ready to execute, and allocates the CPU to one of them using First In
First Out and Shortest Job First Scheduling .
LEARNING OBJECTIVES
.
The objective of this lab is to teach students about various operating systems including
Windows, Mac and Unix. Students learn about systems configuration and administration. Students
learn, explore and practice technologies related to mobile computing.
SEC CSE/IV OS LAB MANUAL
9
.
GENERAL PROCEDURE FOR EXECUTING PROGRAMS
1. Use the pico editor to create a file called hello.c containing the following lines:
#include <stdio.h>
int main() {
printf("Hello World\n");
}
2. Save this file. At the UNIX command prompt, invoke the gcc compiler as follows:
gcc hello.c
3. The result of this step (provided there are no syntax errors in the program) will be an
Executable file called a.out. This is the default file name given by the compiler
4. To execute the program type: ./a.out
The period and slash in front of the a.out indicate to run the a.out file in the current
directory
5. To compile a program and save the compiled version in a different file name, use the
-o option as in: gcc -o hello.exe hello.c
6. Note: To avoid having to put the ./ in front of the file name to execute a program, you may
add the current directory (indicated by a period) in your PATH by typing: PATH=$PATH:.
Note the final two characters are a full colon followed by a period
SEC CSE/IV OS LAB MANUAL
10
EX.NO:1
DATE:
IMPLEMENTATION OF SYSTEM CALLS
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.
The exec family of functions shall replace the current process image with a new process
image. The new image shall be constructed from regular, executable file called the new
process image file
The exit status will be n, if specified. Otherwise, the value will be the exit value of the last
command executed, or zero if no command was executed. When exit is executed in a trap
action, the last command is considered to be the command that executed immediately
preceding the trap action
The readdir() function returns a pointer to a dirent structure representing the next directory
entry in the directory stream pointed to by dir.
The opendir() function opens a directory stream corresponding to the directory name, and
returns a pointer to the directory stream. The stream is positioned at the first entry in the
directory
OBJECTIVE
To keep track of how many times each of the fork, vfork, execl, readdir, opendir and wait
system
calls is invoked
Place counters in kernel code
Implement a new system call providing this information
Request/retrieve these values from user space by invoking the new system call/s
SYNTAXES & KEYWORDS
Fork:
#include<unistd.h>
pid_t fork(void);
execl:
#include<unistd.h>
SEC CSE/IV OS LAB MANUAL
11
extern char **environ;
int execl(const char *path, const char *arg(), /*, (char *)0 */);
exit:
#include<stdlib.h>
void exit(int status);
wait:
#include<sys/types.h>
#include<sys/wait.h>
pid_t wait(int *stat_loc);
Readdir() :
#include <sys/types.h>
#include <dirent.h>
struct dirent *readdir(DIR *dir);
Opendir():
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
HOW TO EXECUTE THE PROGRAM
Creates New child process
Gets the process id
Waits until the process resumes
Exits the program
ADVANTAGE
Each device can be accessed as though it was a file in the file system. Since most of the kernel
deals with devices through this file interface, it is relatively easy to add a new device driver by
implementing the hardware-specific code to support this abstract file interface. Therefore, this
benefits the development of both user program code, which can be written to access devices and
files in the same manner, and device driver code, which can be written to support a well-defined
API.
SEC CSE/IV OS LAB MANUAL
12
DISADVANTAGE
The disadvantage with using the same interface is that it might be difficult to capture the
functionality of certain devices within the context of the file access API, thereby either resulting in
a loss of functionality or a loss of performance. Some of this could be overcome by the use of ioctl
operation that provides a general purpose interface for processes to invoke operations on devices.
APPLICATIONS
To serve an average Web page that includes five external links (for instance images), a Web server
executes12 read and write system calls. Thus a busy Web server serving 1000 hits per second will
have executed more than one
ALGORITHM
Open the VI text editor
Create a sub directory under home directory.
Type the codes using C language.
Use the system calls such as fork(), stat(), getpid(), wait(), exit()
Save the file using filename.c.
Compile the program using gcc filename.c.
Execute the program using ./a.out.
PROGRAM
(A)fork, execl, getpid, exit, wait
#include<stdio.h>
#include<sys/types.h>
void main()
{
pid_t pid; int i; pid=getpid()
printf("\nbefore fork %d",pid);
pid=fork();
if(pid==0)
printf("/n nth this line from child \n thechild processid %d value=%d",getpid(),i); else if(pid==1)
printf("\nthis line is from parent value=%d",i); else if(pid<1)
{
printf("\n fork failed"); exit(1);
}
if(pid==0)
{
execl("/bin/ls", "ls" ,"-1",(char*)0);
SEC CSE/IV OS LAB MANUAL
13
}
if(pid > 0) wait((int *)0);
}
OUTPUT:
[cs2002@localhost ~]$ cc psc.c [cs2002@localhost ~]$ ./a.out
before fork 3749/n nth this line from child a.out
data elamugil hai.c isc.c kumar l4.c
b) stat
#include<stdio.h>
#include<sys/stat.h>
main()
{
int fd;
char pathl[10]; struct stat*nfile;
nfile=(struct stat*)malloc(sizeof(struct stat)); printf("\n Enter the file name:\t");
scanf("%s",pathl);
stat(pathl,nfile);
printf("Program inodeno:%d\n",nfile->st_ino);
printf("Program Size :%d\n",nfile->st_blksize);
printf("Access Time :%s\n",ctime(&nfile->st_atime));
printf("Modified Time :%s\n",ctime(&nfile->st_mtime));
printf("Protection :%d\n",nfile->st_mode);
printf("User id :%d\n",nfile->st_uid);
printf("Group id :%d\n",nfile->st_gid);
printf("Device driverno:%d\n",nfile->st_dev);
printf("No. of links :%d\n",nfile->st_nlink);
return 0;
}
OUTPUT:
[cse04@LINUXSERVER aravind]$ cc status.c
[cse04@LINUXSERVER aravind]$ ./a.out
Enter the file name: sum.sh
SEC CSE/IV OS LAB MANUAL
14
Program inodeno:1815607
Program Size :4096
Access Time :Thu Mar 30 11:45:06 2006
Modified Time :Tue Mar 7 10:31:36 2006
Protection :33204
User id :514
Group id :514
Device driverno:769
No. of links :1
c) opendir & readdir
//ls command implementation using opendir & readdir //ls command implementation
#include<stdio.h>
#include<dirent.h> main(int argc,char *argv[])
{
DIR * dir;
struct dirent *direntry; dir=opendir(argv[1]); while((direntry=readdir(dir))!=NULL)
printf("%d %s\n",direntry->d_ino,direntry->d_name); closedir(dir);
}
OUTPUT:
[cse04@LINUXSERVER vaishu]$ cc ordir.c
[cse04@LINUXSERVER vaishu]$ ./a.out uma
1750301 .
3270767 ..
1750302 aaa
RESULT
The program for process system call has been executed and shown the result as above.
VIVA QUESTIONS
1. What is an Operating system?
An operating system is a program that manages the computer hardware. It also provides a
basis for application programs and act as an intermediary between a user of a computer and the
computer hardware. It controls and coordinates the use of the hardware among the various
SEC CSE/IV OS LAB MANUAL
15
application programs for the various users.
2. What is the use of fork and exec system calls?
Fork is a system call by which a new process is created. Exec is also a system call, which is
used after a fork by one of the two processes to replace the process memory space with a new
program.
POSSILBLE QUESTIONS
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 getpid, exit, wait system calls.
SEC CSE/IV OS LAB MANUAL
16
EX.NO:2
DATE:
IMPLEMENTATION OF I/O SYSTEM CALL
DESCRIPTION
File-I/O through system calls is simpler and operates at a lower level than making calls to the C
file-I/O library. There are seven fundamental file-I/O system calls:
creat() Create a file for reading or writing.
open() Open a file for reading or writing.
close() Close a file after reading or writing.
write() Write bytes to file.
read() Read bytes from file.
These calls were devised for the UNIX operating system and are not part of the ANSI C spec. Use
of these system calls requires a header file named "fcntl.h":
SYNTAXES & KEYWORDS
open() :
<file descriptor variable> = open( <filename>, <access mode> );
write() :
write( <file descriptor>, <buffer>, <buffer length> );
read() :
read( <file descriptor>, <buffer>, <buffer length> );
HOW TO EXECUTE THE PROGRAM
Creates a new file
Opens an existing fie
Closes a file that is open
Reads a file
Writes the bytes of data into a file
SEC CSE/IV OS LAB MANUAL
17
ADVANTAGE
Each device can be accessed as though it was a file in the file system. Since most of the
kernel deals with devices through this file interface, it is relatively easy to add a new device driver
by implementing the hardware-specific code to support this abstract file interface. Therefore, this
benefits the development of both user program code, which can be written to access devices and
files in the same manner, and device driver code, which can be written to support a well-defined
API.
DISADVANTAGE
The disadvantage with using the same interface is that it might be difficult to capture the
functionality of certain devices within the context of the file access API, thereby either resulting in
a loss of functionality or a loss of performance. Some of this could be overcome by the use of ioctl
operation that provides a general purpose interface for processes to invoke operations on devices.
APPLICATIONS
System calls acts as entry point to OS kernel. There are certain tasks that can only be done
if a process is running in kernel mode. Examples of these tasks can be interacting with hardware
etc. So if a process wants to do such kind of task then it would require itself to be running in kernel
mode which is made possible by system calls.
ALGORITHM:
1. Start the Program.
2. Open a file for O_RDWR for read and write, O_CREATE for creating a file, O_TRUNC
for truncates a file.
3. Using getchar function, read the character and stored in the string [] array.
4. The string [] array is write into a file and close it.
5. Then the file is opened for read only mode and read the characters and displayed it and
close the file.
6. Stop the program.
PROGRAM
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
SEC CSE/IV OS LAB MANUAL
18
#include<sys/types.h> int main()
{
int n,i=0; int f1,f2;
char c,strin[100]; f1=open("data",O_RDWR|O_CREAT|O_TRUNC); while((c=getchar())!='\n')
{
strin[i++]=c;
}
strin[i]='\0';
write(f1,strin,i);
close(f1); f2=open("data",O_RDONLY); read(f2,strin,0);
printf("\n%s\n",strin); close(f2);
return 0;
}
OUTPUT:
[cs2002@localhost ~]$ cc isc.c
[cs2002@localhost ~]$ ./a.out HAI
WELCOME TO CSE
HAI WELCOME TO CSE [cs2002@localhost ~]$
RESULT
The i/o system call program has been executed and shown the results as above.
VIVA QUESTIONS
1. What is a process?
A process is a program in execution. It is the unit of work in a modern operating system. A
process is an active entity with a program counter specifying the next instructions to execute and a
set of associated resources. It also includes the process stack, containing temporary data and a data
section containing global variables.
2. What is a process state and mention the various states of a process?
As a process executes, it changes state. The state of a process is defined in part by the
current activity of that process. Each process may be in one of the following states:
New
Running
SEC CSE/IV OS LAB MANUAL
19
Waiting
Ready
Terminated
POSSILBLE QUESTIONS:
1. Write programs using the I/O system calls of UNIX operating system (open, read, write,
etc)
2. Write programs using the I/O system call(write).
\
SEC CSE/IV OS LAB MANUAL
20
EX.NO:3
DATE:
SIMULATION OF UNIX COMMANDS
DESCRIPTION
ls -a
The -a option tells the ls command to report information about all files, including hidden files.
ls -l
The -l option tells the "ls" command to provide a long listing of information about the files and
directories it reports. The long listing will provide important information about file permissions,
user and group ownership, file size, and creation date
ls -al
This command provides a long listing of information about all files in the current directory. It
combines the functionality of the -a and -l options. This is probably the most used version of the ls
command.
ls -alR /usr | more
This command lists long information about all files in the "/usr" directory, and all sub-directories
of /usr. The -R option tells the ls command to provide a recursive listing of all files and sub-
directories
ls -ld /usr
Rather than list the files contained in the /usr directory, this command lists information about the
/usr directory itself (without generating a listing of the contents of /usr). This is very useful when
you want to check the permissions of the directory, and not the files the directory contains.
SYNTAXES & KEYWORDS
ls Command:
ls [options] [names]
grep Command:
grep flag PatternList filename
EXPECTED OUTPUT AND ITS FORM
List the files in the directory.
List the files of a particular user in a directory.
List the files with its description.
SEC CSE/IV OS LAB MANUAL
21
Searches the patterns in a file
ADVANTAGES
Full multitasking with protected memory.
Multiple users can run multiple programs each at the same time.
Very efficient virtual memory, so many programs can run with a modest amount of
physical memory.
Access controls and security
A rich set of small commands and utilities that do specific tasks well
DISADVANTAGES
The traditional command line shell interface is user hostile -- designed for the
programmer, not the casual user.
Commands often have cryptic names and give very little response to tell the user what
they are doing.
APPLICATIONS
Commands you use in a Unix based computer OS to achieve certain things. Similar to MS/DOS
commands in Windows. Mostly used in computers running the Linux OS.
ALGORITHM:
1. Start the program.
2. Enter the options.
3. If the option is 1 call ls command and it display the files.
4. If the option is 2 call gerp command and match the given pattern with the read word and
if it matches, display the line of occurance.
5. If the option is 3 call cp command.
6. If the option is 4 call rm command.
7. Stop the program.
PROGRAM
#include<stdio.h>
main()
{
char c; int n;
SEC CSE/IV OS LAB MANUAL
22
printf("1.list of files in the directory\n2.list the lines\n3.copy\n4.remove\n"); scanf("%d",&n);
switch(n)
{
case 1: system("ls"); break;
case 2:
system("grep argc lsgp.c"); break;
case 3:
system(" cp lsgp.c gpls.c"); printf("the file is
copied"); break;
case 4:
system("rm lsgp.c"); printf("the file is deleted");
break;
}
}
OUTPUT
[it53@localhost ~]$ cc lsgp.c [it53@localhost ~]$
./a.out 1.list of files in the directory 2.list the lines
3.copy
4.remove
1
3q bit.c ftp.c ospf1.c praba.c rarp.c smp.c sort.sh
a.out forkexec.c io.c praba1.sh praba.sh sample sorting.sh syscall.c [it53@localhost ~]$ ./a.out
1.list of files in the directory 2.list the lines
3.copy
4.remove
2
system("grep argc lsgp.c"); [it53@localhost ~]$
./a.out 1.list of files in the directory 2.list the lines
3.copy
4.remove
3
the file is copied[it53@localhost ~]$ ./a.out 1.list of files in the
SEC CSE/IV OS LAB MANUAL
23
directory
2.list the lines 3.copy 4.remove
4
the file is deleted
RESULT
The program for simulation of unix commands ls and grep has been executed and the shown
the results as above
VIVA QUESTIONS:
1. Compare user threads and kernel threads.
User threads
User threads are supported above the Kernel threads are supported directly kernel and are
implemented by a thread library at the user level Thread creation & scheduling are done in the user
space, without kernel intervention. Therefore they are fast to create and manage Blocking system
call will cause the entire process to block
Kernel threads
Thread creation, scheduling and management are done by the operating If the thread
performs a blocking system call, the kernel can schedule another thread in the application for
execution.
2. How can a user program disrupt the normal operations of a system?
A user program may disrupt the normal operation of a system by Issuing illegal I/O operations By
accessing memory locations within the OS itself Refusing to relinquish the CPU
POSSIBLE QUESTIONS:
1. Write C programs to simulate UNIX commands like ls, grep, etc
2. Write C programs to simulate UNIX commands like grep
SEC CSE/IV OS LAB MANUAL
24
EX.NO:4(a)
DATE:
IMPLEMENTATION OF FCFS SCHEDULING
DESCRIPTION
The FCFS scheduler simply executes processes to completion in the order they are submitted.
This code implements the First come First Served Scheduled algorithm. It gets the number of
processes and the process name, burst time and arrival time for each user from the user. It then
sorts the processes depending upon the arrival time. Calculates and displays the average
turnaround time and waiting time. Then it will display the Gantt chart.
EXPECTED OUTPUT AND ITS FORM
Performs FCFS scheduling ie) the process that enters the queue first is served first.
ADVANTAGES
simple
easy to understand first
come, first served
DISADVANTAGES
This scheduling method is nonpreemptive, that is, the process will run until it finishes.
Because of this nonpreemptive scheduling, short processes which are at the back of the
queue have to wait for the long process at the front to finish
ALGORITHM:
1. Start the program.
2. Get the number of processes and their burst time.
3. Initialize the waiting time for process 1 is 0.
4. The waiting time and turn around time for other processes are calculated as
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
5. The waiting time and turn around time for all the processes are summed and then the
average waiting time and turn around time are calculated.
6. The average waiting time and turn around time are displayed.
7. Stop the program.
SEC CSE/IV OS LAB MANUAL
25
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> struct process
{
int pid;
int wt,tt,bt;
}
p[100]; void main()
{
int tottt,totwt,avgtt,avgwt,i,j,n; clrscr();
printf("\nEnter Number of process"); scanf("\n%d",&n); for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("\nEnter %dst Burst Time:",i); scanf("\n%d",&p[i].bt);
}
p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n)
{
p[i].wt=p[i-1].tt; p[i].tt=p[i].bt+p[i].wt; i++;
}
totwt=tottt=0;
i=1;
printf("\n\t============================="); printf("\n\tProcess id\tBT\tWT\tTT");
printf("\n\t============================="); while(i<=n)
{
printf("\n\t%d\t%d\t%d\t%d\t",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}
SEC CSE/IV OS LAB MANUAL
26
totwt=totwt/n;
tottt=tottt/n;
printf("\n\n\n\tAVGWT\tAVGTT");
printf("\n\t%d\t%d",totwt,tottt);
getch();
}
OUTPUT
Enter Number of process3
Enter 1st Burst Time:12
Enter 2st Burst Time:34
Enter 3st Burst Time:56
===============================
Process id BT WT TT
===============================
1 12 0 12
2 34 12 46
3 56 46 102
VGWT AVGTT
19 53
RESULT
The program for first come first serve algorithm has been executed and shown the results as above.
VIVA QUESTION
1. What is the Kernel?
A more common definition is that the OS is the one program running at all times on the
computer, usually called the kernel, with all else being application programs.
2. What are Batch systems?
Batch systems are quite appropriate for executing large jobs that need little interaction. The user
can submit jobs and return later for the results.
POSSIBLE QUESTIONS:
1. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt
chart for FCFS
SEC CSE/IV OS LAB MANUAL
27
DESCRIPTION
Associate with each process the length of its next CPU burst. Use these lengths to schedule the
process with the shortest time
Two schemes:
non preemptive once CPU given to the process it cannot be preempted until completes its
CPU burst
preemptive if a new process arrives with CPU burst length less than remaining time of
current executing process, preempt. This scheme is known as the Shortest-Remaining-
Time-First (SRTF) SJF is optimal gives minimum average waiting time for a given set of
processes objective
EXPECTED OUTPUT AND ITS FORM
Performs SJF scheduling ie) the process that has the shortest burst time is processed first
ADVANTAGES
o simple
o easy to understand
o shortest job is served
first
DISADVANTAGES
Long-burst (CPU-intensive) processes are hurt with a long mean waiting time. In fact, if short-
burst processes are always available to run, the long-burst ones may never get scheduled.
Moreover, the effectiveness of meeting the scheduling criteria relies on our ability to estimate the
CPU burst time.
ALGORITHM:
1. Start the program.
2. Get the number of processes and their burst time.
3. Initialize the waiting time for process 1 is 0.
4. The processes are stored according to their burst time.
5. The waiting time and turn around time for other processes are calculated as
p[i].wt=p[i-1].bt+p[i-1].wt;
EX.NO:4 (b)
DATE:
IMPLEMENTATION OF SJF SCHEDULING
SEC CSE/IV OS LAB MANUAL
28
p[i].tt=p[i].bt+p[i].wt;
6. The waiting time and turn around time for all the processes are summed and then the
average waiting time and turn around time are calculated.
7. The average waiting time and turn around time are displayed.
Stop the program
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> struct process
{
int pid;
int wt,tt,bt;
}
p[100]; void main()
{
struct process temp;
int tottt,totwt,avgtt,avgwt,i,j,n; clrscr();
printf("\nEnter Number of process"); scanf("\n%d",&n); for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("\nEnter %d Burst Time:",i); scanf("\n%d",&p[i].bt);
}
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(p[i].bt>p[j].bt)
{
/*temp.pid=p[j].pid;
p[j].pid=p[i].pid;
SEC CSE/IV OS LAB MANUAL
29
p[i].pid=temp.pid;
temp.bt=p[j].bt;
p[j].bt=p[i].bt; p[i].bt=temp.bt; */ temp=p[j]; p[j]=p[i];
p[i]=temp;
} } }
p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n)
{
p[i].wt=p[i-1].tt; p[i].tt=p[i].bt+p[i].wt; i++;
}
totwt=tottt=0;
i=1;
printf("\n\t================================="); printf("\n\t Process id \tBT\tWT\tTT");
printf("\n\t================================"); while(i<=n)
{
printf("\n\t%d\t%d\t%d\t%d\t",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}
totwt=totwt/n;
tottt=tottt/n;
printf("\n\n\n\tAVGWT\tAVGTT");
printf("\n\t%d\t%d",totwt,tottt);
getch();
}
OUTPUT
Enter Number of process:5
Enter 1 Burst Time: 8
Enter 2 Burst Time: 4
SEC CSE/IV OS LAB MANUAL
30
Enter 3 Burst Time: 7
Enter 4 Burst Time: 2
Enter 5 Burst Time: 9
===================================
Process id BT WT TT
===================================
4 2 0 2
2 4 2 6
3 7 6 13
1 8 13 21
5 9 21 30
AVGWT AVGTT
8 14
RESULT:
The program for shortest job first algorithm has been executed and shown the results as above.
VIVA QUESTION:
1. What are multiprocessor systems & give their advantages?
Multiprocessor systems also known as parallel systems or tightly coupled systems are
systems that have more than one processor in close communication, sharing the computer bus, the
clock and sometimes memory & peripheral devices. Their main advantages are
Increased throughput
Economy of scale
Increased reliability
2. What is a process state and mention the various states of a process?
As a process executes, it changes state. The state of a process is defined in part by the
current activity of that process. Each process may be in one of the following states:
New
Running
Waiting
SEC CSE/IV OS LAB MANUAL
31
Ready
Terminated
POSSIBLE QUESTION:
1 . Given the list of processes, their CPU burst times and arrival times, display/print the Gantt
chart for SJF
SEC CSE/IV OS LAB MANUAL
32
DESCRIPTION
Each process gets a small unit of CPU time (time quantum), usually 10-100 milliseconds. After
this time has elapsed, the process is preempted and added to the end of the ready queue.
If there are n processes in the ready queue and the time quantum is q, then each process gets 1/n of
the CPU time in chunks of at most q time units at once. No process waits more
than (n-1)q time units.
Performance
q large -FIFO
q small- q must be large with respect to context switch, otherwise overhead is too high
EXPECTED OUTPUT AND ITS FORM
Performs round robin scheduling ie) the process that is assigned with a Quantum time and the
process is processed for the given quantum time in fcfs fashion.
ADVANTAGES:
simple,
low overhead,
works for interactive systems
DISADVANTAGES:
o if quantum is too small, too much time wasted in context switching
o if too large (i.e., longer than mean CPU burst), approaches
ALGORITHM:
1. Start the program.
2. Get the number of processes, their burst time and time slice for each process.
3. Calculate the total burst time.
4. To check whether the burst time of process is less then the time slice, the required time
only allotted to the process.
5. If the burst time of process is greater than the time slice one time slice is allotted for the
process and burst time is subtracted by one time slice.
6. Step 4 and 5 is repeated up to process burst time is 0.
EX.NO:5(a)
DATE:
IMPLEMENTATION OF ROUND ROBIN SCHEDULING
SEC CSE/IV OS LAB MANUAL
33
7. The waiting time and turn around time for all the processes are summed and then the
average waiting time and turn around time are calculated.
8. The average waiting time and turn around time are displayed.
9. Stop the program.
PROGRAM
#include<stdio.h>
#include<conio.h> struct process
{
int pid,bt,tt,wt; };
int main()
{
struct process x[10],p[30]; int i,j,k,tot=0,m,n;
float wttime=0.0,tottime,a1,a2; clrscr();
printf("\nEnter No.of process\t"); scanf("%d",&n); for(i=1;i<=n;i++)
{
x[i].pid=i;
printf("Enter The Burst Time \t"); scanf("%d",&x[i].bt); tot=tot+x[i].bt;
}
printf("Total Burst Time:\t%d",tot); p[0].tt=0;
k=1;
printf("\nEnter The Time Slice:\t"); scanf("%d",&m); for(j=1;j<=tot;j++)
{
for(i=1;i<=n;i++)
{
if(x[i].bt!=0)
{
p[k].pid=i; if(x[i].bt-m<0)
{
p[k].wt=p[k-1].tt; p[k].bt=x[i].bt; p[k].tt=p[k].wt+x[i].bt; x[i].bt=0;
k++;
}
else
SEC CSE/IV OS LAB MANUAL
34
{
p[k].wt=p[k-1].tt; p[k].tt=p[k].wt+m; x[i].bt=x[i].bt-m; k++;
} } }
}
printf("\nprocess id\ttwt\ttt"); for(i=1;i<k;i++)
{
printf("\n\t%d\t%d\t%d",p[i].pid,p[i].wt,p[i].tt);
wttime=wttime+p[i].wt;
tottime=tottime+p[i].tt;
a1=wttime/n;
a2=tottime/n;
}
printf("\n\nAverage Waiting Time:\t%f",a1); printf("\n\nAverage TurnAround Time:\t%f",a2);
getch();
return 0;
}
OUTPUT:
Enter No.of process 3
Enter The Burst Time 5
Enter The Burst Time 6
Enter The Burst Time 7
Total Burst Time: 18
Enter The Time Slice: 3
process id Twt tt
1 0 3
2 3 6
3 6 9
1 9 11
2 11 14
3 14 17
SEC CSE/IV OS LAB MANUAL
35
3 17 18
Average Waiting Time: 20.000000
Average TurnAround Time:26.000000
RESULT:
The program for implementation of round robin scheduling has been executed and shown the
results as above.
VIVA QUESTION
1. Define CPU scheduling.
CPU scheduling is the process of switching the CPU among various processes. CPU
scheduling is the basis of multi programmed operating systems. By switching the CPU among
processes, the operating system can make the computer more productive.
2. What is preemptive and non preemptive scheduling?
Under non preemptive scheduling once the CPU has been allocated to a process, the
process keeps the CPU until it releases the CPU either by terminating or switching to the waiting
state. Preemptive scheduling can preempt a process which is utilizing the CPU in between its
execution and give the CPU to another process.
POSSIBLE QUESTION:
1. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt
chart for Round robin.
2. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt
chart for Round robin. , compute and print the average waiting time and average
turnaround time
SEC CSE/IV OS LAB MANUAL
36
DESCRIPTION
A priority number (integer) is associated with each process
The CPU is allocated to the process with the highest priority (smallest integer highest priority)
- Preemptive
- non preemptive
SJF is a priority scheduling where priority is the predicted next CPU burst time
Problem Starvation low priority processes may never execute
Solution Aging as time progresses increase the priority of the process
Performs priority scheduling ie) the process that is assigned with a highest priority is processed
first.
ADVANTAGES:
simple,
low overhead,
works for interactive systems
DISADVANTAGES:
The job remains in the queue for a long time.
ALGORITHM:
1. Start the program.
2. Get the number of processes, their burst time and priority.
3. Initialize the waiting time for process 1 is 0.
4. Based upon the priority processes are arranged.
5. The waiting time and turn around time for other processes are calculated as
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
6. The waiting time and turn around time for all the processes are summed and then the
average waiting time and turn around time are calculated.
7. The average waiting time and turn around time are displayed.
8. Stop the program.
EX.NO:5(b)
DATE:
IMPLEMENTATION OF PRIORITY SCHEDULING
SEC CSE/IV OS LAB MANUAL
37
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> struct process
{
int pid;
int wt,tt,bt,prior;
}
p[100],temp; void main()
{
int tottt,totwt,avgtt,avgwt,i,j,n; clrscr();
printf("\nEnter Number of process"); scanf("\n%d",&n); for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("\nEnter %dst Burst Time:",i); scanf("\n%d",&p[i].bt); printf("\nEnter
%dpriority",i); scanf("\n%d",&p[i].prior);
}
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(p[i].prior>p[j].prior)
{
temp=p[j];
p[j]=temp;
} } }
p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n)
{
p[i].wt=p[i-1].tt; p[i].tt=p[i].bt+p[i].wt; i++; }
SEC CSE/IV OS LAB MANUAL
38
totwt=tottt=0;
i=1;
printf("\n\t===============================");
printf("\n\tPSSID\tBT\tWT\tTT");
printf("\n\t===============================");
while(i<=n)
{
printf("\n\t%d\t%d\t%d\t%d\t",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}
totwt=totwt/n;
tottt=tottt/n;
printf("\n\n\n\tAVGWT\tAVGTT");
printf("\n\t%d\t%d",totwt,tottt);
getch();
OUTPUT:
Enter Number of process3
Enter 1st Burst Time:5
Enter 1priority3
Enter 2st Burst Time:7
Enter 2priority1
Enter 3st Burst Time:8
Enter 3priority2
SEC CSE/IV OS LAB MANUAL
39
===============================
PSSID BT WT TT
===============================
1 5 0 5
2 7 5 12
3 8 12 20
AVGWT AVGTT
5 12
RESULT
The program for priority scheduling has been executed and shown the results as above.
VIVA QUESTION:
1. Define throughput?
Throughput in CPU scheduling is the number of processes that are completed per unit time.
For long processes, this rate may be one process per hour; for short transactions, throughput might
be 10 processes per second.
2. What is turnaround time?
Turnaround time is the interval from the time of submission to the time of completion of a
process. It is the sum of the periods spent waiting to get into memory, waiting in the ready queue,
executing on the CPU, and doing I/O
POSSIBLE QUESTION:
1. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt
chart for Priority Scheduling.
2. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt
chart for Priority Scheduling. compute and print the average waiting time and average
turnaround time
SEC CSE/IV OS LAB MANUAL
40
DESCRIPTION
A shared memory is an extra piece of memory that is attached to some address spaces for
their owners to use. As a result, all of these processes share the same memory segment and have
access to it. Consequently, race conditions may occur if memory accesses are not handled
properly. The following figure shows two processes and their address spaces. The yellow rectangle
is a shared memory attached to both address spaces and both process 1 and process 2 can have
access to this shared memory as if the shared memory is part of its own address space. In some
sense, the original address space is "extended" by attaching this shared memory.
EXPECTED OUTPUT AND ITS FORM
This program is designed in such a way that the first instance is automatically the server and any
other instance started later is a client. The communication handles correctly the situation when the
server is closed while the clients are running.
ADVANTAGES:
transferring large amounts of data between processes
Speed of communication
This method is available on any platform (Windows 95/98 as well as Windows NT).
DISADVANTAGES:
Synchronizing access
Security
ALGORITHM:
1. Start the program
2. Create the child process using fork()
3. Create the shared memory for parent process using shmget() system call
4. Now allow the parent process to write inn shared memory using shmpet pointer which is
return type of shmat()
5. Now across and attach the same shared memory to the child process
EX.NO:6(a)
DATE:
IMPLEMENTATION OF PRIORITY SCHEDULING
SEC CSE/IV OS LAB MANUAL
41
6. The data in the shared memory is read by the child process using the shnot pointer
7. Now, detach and rebase the shared memory
8. Stop the program
PROGRAM:
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
main()
{
int shmid;
key_t key=0*10; shmid=shmget(key,100,IPC_CREAT|0666); if(shmid<0)
printf("\nfirst SHMID failed\n"); else
printf("\n first SHMID succeded id=%d\n",shmid);
shmid=shmget(key,101,IPC_CREAT|0666); if(shmid<0)
printf("\nsecond SHMID failed\n"); else
printf("\n secondt SHMID succeded id=%d\n",shmid); shmid=shmget(key,90,IPC_CREAT|0666);
if(shmid<0)
printf("\nthird SHMID failed\n"); else
printf("\n third SHMID succeded id=%d\n",shmid);
}
OUTPUT:
[cse2@localhost ~]$ cc share.c
[cse2@localhost ~]$ ./a.out
first SHMID succeded id=589833
secondt SHMID succeded id=622604
third SHMID succeded id=655373
[cse2@localhost ~]$
RESULT
The program for interprocess communication using shared memory has been executed and shown
SEC CSE/IV OS LAB MANUAL
42
results as above.
VIVA QUESTION:
1.What is process control block?
Each process is represented in the operating system by a process
It contains the following information:
Process state
Program counter
CPU registers
CPU-scheduling information
Memory-management information
Accounting information I/O
status information
2. What are the use of job queues, ready queues & device queues?
As a process enters a system, they are put into a job queue. This queue consists of all jobs in the
system. The processes that are residing in main memory and are ready & waiting to execute are
kept on a list called ready queue. The list of processes waiting for a particular I/O device is kept in
the device queue
POSSIBLE QUESTION:
1. Developing Application using Inter Process Communication using shared memory)
2. Developing Application using Inter Process Communication using message queues)
SEC CSE/IV OS LAB MANUAL
43
DESCRIPTION
Using pipes for establishing a communication between two processes. As a first step we
need to identify two executables that need to communicate. As an example, consider a case where
one process gets a character string input and communicates it to the other process which reverses
strings. Then we have two processes which need to communicate. Next we define a pipe and
connect it between the processes to facilitate communication. One process gets input strings and
writes into the pipe. The other process, which reverses strings, gets its input (i.e. reads) from the
pipe.
Figure explains how the pipes are used. As shown in the upper part of the figure, a pipe has
an input end and an output end. One can write into a pipe from the input end and read from the
output end. A pipe descriptor, therefore, has an array that stores two pointers. One pointer is for its
input end and the other is for its output end. When a process defines a pipe it gets both the
addresses, as shown in the middle part of Figure. Let us suppose array pp is used to store the
descriptors. pp[0] stores the write end address and pp[1] stores the read end address. Suppose two
processes, Process A and Process B, need to communicate, then it is imperative that the process
which writes closes its read end of the pipe and the process which read closes its write end of the
pipe. Essentially, for a communication from Process A to process B the following should happen.
Process A should keep its write end open and close read end of the pipe. Similarly, Process B
should keep its read end open and close its write end.
EXPECTED OUTPUT AND ITS FORM
To use these pipes, we will write two program's one to represent the server and other to represent
the client. The server will read from the pipe fifo_server to which the client will send a request. On
receiving the request, the server will send the information to the client on fifo_client.
ADVANTAGES:
Speed of communication
This method is available on any platform (Windows 95/98 as well as Windows NT).
EX.NO:6(b)
DATE:
IMPLEMENTATION OF PRIORITY SCHEDULING
SEC CSE/IV OS LAB MANUAL
44
DISADVANTAGES:
Synchronizing access
security
ALGORITHM:
1. Start the program.
2. Create the child process using fork().
3. Create the pipe structure using pipe().
4. Now close the read end of the parent process using close().
5. Write the data in the pipe using write().
6. Now close the write end of child process using close().
7. Read the data in the pipe using read().
8. Display the string.
9. Stop the program.
PROGRAM:
#include<unistd.h>
main()
{
int fd[3],pid;
char *msg=("OS LAB\n"); char buff[25];
pipe(fd);
pid=fork();
if(pid==0)
{
puts("child process\n"); close(fd[0]); write(fd[1],msg,30);
}
else
{
sleep(1);
puts("parent process\n"); close(fd[1]); read(fd[0],buff,30); printf("%s",buff);
}
}
SEC CSE/IV OS LAB MANUAL
45
OUTPUT:
[cse2@localhost ~]$ cc pipe.c
[cse2@localhost ~]$ ./a.out child
process
parent process
OS LAB
[cse2@localhost ~]$
RESULT
The program for interprocess communication using pipe process has been executed and shown
results as above
VIVA QUESTION:
What are the various file operations?
The six basic file operations are
Creating a file
Writing a file
Reading a file
Repositioning within a file
Deleting a file
Truncating a file
2. What are the information associated with an open file?
Several pieces of information are associated with an open file which may be:
File pointer
File open count
Disk location of the file Access
rights
Possible Question:
1 Developing Application using Inter Process Communication (using shared memory, or message queues)
SEC CSE/IV OS LAB MANUAL
46
DESCRIPTION
This is an illustration of a solution to the classic producer-consumer (bounded-buffer) problem
using semaphores.
CONCEPT Producers produce items to be stored in the buffer. Consumers remove and consume
items which have been stored. Mutual exclusion must be enforced on the buffer itself. Moreover,
producers can store only when there is an empty slot, and consumers can remove only when there
is a full slot. Three semaphores are used. The binary semaphore mutex controls access to the buffer
itself. The counting semaphore empty keeps track of empty slots, and the counting semaphore full
keeps track of full slots. In this example, the buffer is implemented as an array of size MAX
treated as a circular (ring) buffer. Variables in and out give the index of the next position for
putting in and taking out (if any). Variable count gives the number of items in the buffer.
EXPECTED OUTPUT AND ITS FORM
one or more producers are generating data and placing these in a buffer
a single consumer is taking items out of the buffer one at time
only one producer or consumer may access the buffer at any one time
ADVANTAGES:
Effective resource utilization
DISADVANTAGES:
A semaphore does not keep track of which of the resources are free.
This includes:
Requesting a resource and forgetting to release it releasing a
resource that was never requested holding a resource for a
long time without needing it
using a resource without requesting it first (or after releasing it).
ALGORITHM:
1. Start the program.
2. Declare the variables in the type of pthread_t as tid_produce tid_consume.
3. Declare a structure for semaphore variables.
EX. NO: 7
PRODUCER-CONSUMER PROBLEMUSING SEMAPHORES.
DATE:
SEC CSE/IV OS LAB MANUAL
47
4. During run time read the number of items to be produced and consumed.
5. Declare and define semaphore function for creation and destroy.
6. Define producer function.
7. Define consumer function.
8. Call producer and consumer function.
9. Stop the execution.
PROGRAM:
#include <stdio.h> #include <semaphore.h>
#include <pthread.h> #define NBUFF 10
int nitems; struct {
int buff[NBUFF];
sem_t mutex, nempty, nstored; } shared;
void *produce (void *); void *consume (void *);
int main(int argc, char **argv)
{
pthread_t tid_produce, tid_consume; if(argc !=2)
{
printf("Useage: filename <nitems> "); return 0;
}
printf ("\n\n Producer - Consumer Problem using Semaphore\n"); printf (" --------------------
-----------------------\n\n"); nitems=atoi(argv[1]);
sem_init(&shared.mutex,0,1); sem_init(&shared.nempty,0,NBUFF);
sem_init(&shared.nstored,0,0); pthread_setconcurrency(2);
pthread_create(&tid_produce,NULL,produce,NULL);
pthread_create(&tid_consume,NULL,consume,NULL);
pthread_join(tid_produce,NULL); pthread_join(tid_consume,NULL);
sem_destroy(&shared.mutex);
sem_destroy(&shared.nempty);
sem_destroy(&shared.nstored);
}
void *produce (void *arg)
{
SEC CSE/IV OS LAB MANUAL
48
int i; for(i=0;i<nitems;i++)
{
sem_wait(&shared.nempty);
sem_wait(&shared.mutex); shared.buff[i % NBUFF]=i;
printf ("\tProducer.....");
printf ("buff[%d] = %d\n\n",i,shared.buff[i % NBUFF]);
sem_post(&shared.mutex);
sem_post(&shared.nstored); sleep(3);
}
return NULL;
}
void *consume (void *arg)
{
int i; for(i=0;i<nitems;i++)
{
sem_wait(&shared.nstored);
sem_wait(&shared.mutex);
printf("\tConsumer.....");
printf("buff[%d] = %d\n\n\n",i,shared.buff[i%NBUFF]);
sem_post(&shared.mutex);
sem_post(&shared.nempty);
sleep(3);
}
return NULL;
}
OUTPUT:
[root@NS2-05 root]# cc -pthread prod_cons.c
[root@NS2-05 root]# ./a.out 4
Producer - Consumer Problem using Semaphore
-------------------------------------------
SEC CSE/IV OS LAB MANUAL
49
Producer.....buff[0] = 0
Consumer.....buff[0] = 0
Producer.....buff[1] = 1
Consumer.....buff[1] = 1
Producer.....buff[2] = 2
Consumer.....buff[2] = 2
Producer.....buff[3] = 3
Consumer.....buff[3] = 3
RESULT
The program to implement producer and consumer problem using semaphores has been
executed and shown the results as above.
VIVA QUESTION:
1. What is semaphores?
A semaphore S is a synchronization tool which is an integer value that, apart from
initialization, is accessed only through two standard atomic operations; wait and signal.
Semaphores can be used to deal with the n-process critical section problem. It can be also used to
solve various synchronization problems.
The classic definition of wait
wait (S)
{ }
while (S<=0)
S--;
The classic definition of signal
signal (S)
{
}
S++;
;
SEC CSE/IV OS LAB MANUAL
50
2. Define deadlock prevention.
Deadlock prevention is a set of methods for ensuring that at least one of the four necessary
conditions like mutual exclusion, hold and wait, no pre- emption and circular wait cannot hold. By
ensuring that that at least one of these conditions cannot hold, the occurrence of a deadlock can be
prevented.
3. Define deadlock avoidance.
An alternative method for avoiding deadlocks is to require additional information about how
resources are to be requested. Each request requires the system consider the resources currently
available, the resources currently allocated to each process, and the future requests and releases of
each possible future deadlock.
POSSIBLE QUESTION:
1. Implement the Producer Consumer problem using semaphores (using UNIX system
calls).
2. Implement the Producer Consumer problem using UNIX system calls.
SEC CSE/IV OS LAB MANUAL
51
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
EXPECTED OUTPUT AND ITS FORM
The memory segments are allocated with the memory space using First fit and Best Fit techniques.
ADVANTAGES:
effective memory utilization
EX NO : 8
MEMORY MANAGEMENT SCHEMES I
FIRST FIT BEST FIT
DATE:
SEC CSE/IV OS LAB MANUAL
52
DISADVANTAGES:
First fit wastes memory space Best Fit more time consuming suffer from 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.
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)
SEC CSE/IV OS LAB MANUAL
53
{
case 1: pos=bestfit(a,n,req); break;
case 2: pos=firstfit(a,n,req);
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");
}
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)
{
SEC CSE/IV OS LAB MANUAL
54
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;
}
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
|~~~|
SEC CSE/IV OS LAB MANUAL
55
| |
| |
| |
| |
|500| | --- |
| |
| |
|200| | --- |
| |
| |
| |
|300|| --- |
| |
| |
| |
|
|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
SEC CSE/IV OS LAB MANUAL
56
|~~~|
| |
| |
| |
|500|
Your Memory Requirment is :250
Alloted Memory Region is:300
Do You Want To Continue 1/0
0
RESULT
The program for best fit and first fit algorithm for memory management has been executed
and shown the results as above.
VIVA QUESTION:
1. What is the main function of the memory-management unit?
The runtime mapping from virtual to physical addresses is done by a hardware device
called a memory management unit (MMU).
2. What are the common strategies to select a free hole from a set of available holes?
The most common strategies are
a. First fit
b. Best fit
c. Worst fit
3. What is virtual memory?
Virtual memory is a technique that allows the execution of processes that may not be
completely in memory. It is the separation of user logical memory from physical memory. This
separation provides an extremely large virtual memory, when only a smaller physical memory is
available.
SEC CSE/IV OS LAB MANUAL
57
POSSIBLE QUESTION:
1. Implement some memory management schemes I
SEC CSE/IV OS LAB MANUAL
58
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
EXPECTED OUTPUT AND ITS FORM
Minimizing the number of (major) page faults (situations where a page must be brought in from
disk) using LRU and FIFO.
ADVANTAGES:
effective memory utilization
DISADVANTAGES:
Time consuming
EX.NO: 9
DATE:
MEMORY MANAGEMENT SCHEMES II
PAGE REPLACEMENT
SEC CSE/IV OS LAB MANUAL
59
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
Stop the program
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];
SEC CSE/IV OS LAB MANUAL
60
page_frame[k][1]=++count;
for(j=0;j<no_frames;j++)
printf("%d",page_frame[j][0]); printf("\n");
}
else
{
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;
replace(2);
return 0;
getch();
}
SEC CSE/IV OS LAB MANUAL
61
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
RESULT:
The program for page replacement algorithms for memory management has been executed and
shown the results as above.
VIVA QUESTION:
1. What is Demand paging?
Virtual memory is commonly implemented by demand paging. In demand paging, the
pager brings only those necessary pages into memory instead of swapping in a whole process.
Thus it avoids reading into memory pages that will not be used anyway, decreasing the swap time
and the amount of physical memory needed.
2. What are the various page replacement algorithms used for page replacement?
FIFO page replacement
Optimal page replacement
SEC CSE/IV OS LAB MANUAL
62
LRU page replacement
LRU approximation page replacement
Counting based page replacement
Page buffering algorithm.
POSSIBLE QUESTION:
1. Implement some memory management schemes II
SEC CSE/IV OS LAB MANUAL
63
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
EXPECTED OUTPUT AND ITS FORM
Allocates blocks of memory for files using file allocation techniques.
ADVANTAGES:
effective memory utilization
each file occupies set of contiguous blocks on the disk. Random access
DISADVANTAGES:
Time consuming
Wastes lot of memory space
EX.NO: 10
DATE:
FILE ALLOCATION TECHNIQUE-CONTIGUOUS
SEC CSE/IV OS LAB MANUAL
64
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
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);
printf(\n\t\tFile1\t\t%d\t\t\t%d\n,start,block[0]); for(i=2;i<=n;i++)
{
Start=start+block[i-2];
Printf(\t\tFile%d\t\t%d\t\tD\n,i,start,block[i-1]);
}
}
OUTPUT
Enter the number of file:4
Enter the number of blocks needed for each file: 3
5
6
1
Filename start size of file
File 1 0 3
File 2 3 5
SEC CSE/IV OS LAB MANUAL
65
File 3 8 6
File 4 14 1
RESULT:
The program for file allocation technique has been executed and shown the results as above.
VIVA VOICE
1. What are the allocation methods of a disk space?
Three major methods of allocating disk space which are widely in use are
a. Contiguous allocation
b. Linked allocation
c. Indexed allocation
2. What is Directory?
The device directory or simply known as directory records information- such as name,
location, size, and type for all files on that particular partition. The directory can be viewed as a
symbol table that translates file names into their directory entries.
Search for a file
Create a file
Delete a file
Rename a file
List directory
Traverse the file system
POSSIBLE QUESTION:
1. Implement any file allocation technique (Linked, Indexed or Contiguous)