KEMBAR78
R20 OS Lab Manual | PDF | Computer File | Directory (Computing)
0% found this document useful (0 votes)
39 views26 pages

R20 OS Lab Manual

Uploaded by

Venkat Marturi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views26 pages

R20 OS Lab Manual

Uploaded by

Venkat Marturi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

COURSE STRUCTURE AND SYLLABUS

For UG –R20

B. TECH - COMPUTER SCIENCE & ENGINEERING

(Applicable for batches admitted from 2020-2021)


JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY
KAKINADA

KAKINADA - 533 003, Andhra Pradesh, India

L T P C
II Year – I Semester
0 0 3 1.5
OPERATING SYSTEM LAB

Course Objectives:
• To understand the design aspects of operating system
• To study the process management concepts & Techniques
• To study the storage management concepts
• To familiarize students with the Linux environment
• To learn the fundamentals of shell scripting/programming

Course Outcomes:
• To use Unix utilities and perform basic shell control of the utilities
• To use the Unix file system and file access control
• To use of an operating system to develop software
• Students will be able to use Linux environment efficiently
• Solve problems using bash for shell scripting
1. A). Study of Unix/Linux general purpose utility command list:
man,who,cat, cd, cp, ps, ls, mv, rm, mkdir, rmdir, echo, more, date, time,
kill, history, chmod, chown, finger, pwd, cal, logout, shutdown.

Experiment No: 1

Execution of all the commands or the programs are to be done at the “$” prompt
i.) man -- > manual – gives the complete information or the help regarding a particular command
Syntax : $man <commandname>
eg : $man date

ii.) who --> displays a list of users who are currently logged into the computer.
Syntax : $who
eg $who

iii.) cat –concatenation -->reads files sequentially, writing them to standard output.
Syntax : $cat <filename> -- displays the contents of the file
$cat ><filename> -- creates a file with the information

iv.) mkdir – make directory, simply creates a directory or the folder


Syntax : $mkdir<directoryname>
eg : $mkdirunixlab

v.) cd – change directory – changes to the directory nane


Syntax :$cd <directoryname>
eg $ cd unixlab

vi.) pwd – print working directory – displays the user in which directory or the folder he is in or
it displays the path.
Syntax :$pwd
eg.$pwd

vii.) ls – list the files in the directory or the folder


Check the help for ls “by applying “man” command
eg:$man ls -- gives complete information about the “ls” command

eg . $ls -l --> long listing , gives indetail information of the files created by the user with date
,time and the size occupied.

Viii.) cp -- > copying the files


Syntax : $cp <file1><file2> or $ cp <source file><destination file>
eg. $cp xyz xyz1 --> copies the content of xyz into xyz1(where xyz1 is a new file, no need to
create, it automatically creates, if already created, and information is available, it will overwrite)
ix.) mv – rename an existing file
Syntax : $mv <file1><file2>
eg. $mv xyz xyz2 -- now when u check using “ls” command the file name “xyz” won’t be
available

x.) rm – remove a file from the directory


Syntax .$rm <filename>
eg. $rm xyz2 -- when u apply “ls” command, u can’t found xyz2 file in the directory

xi.) rmdir – remove directory – removes an existing directory, keep a note that if the directory
contains files and if the user tries to remove, it won’t be possible, for that all the files are to be
removed and then apply “rmdir” command then only the directory will be permanantly removed.

Syntax : $rmdir<directoryname>
eg.$rmdirunixlab

xii.) echo --sed to display line of text/string that are passed as an argument . This is a built
incommand that is mostly used in shell scripts and batch files to output status text to the screen
or a file.
Syntax: $echo “string name”
eg: $echo “welcome to the unix operating system lab”

xiii.) date --> It is most commonly used to print the date and time in different formats and
calculate future and past dates
Syntax :$date
Eg. $date

xiv.) time-->time command in Linux is used to execute a command and prints a summary of
real-time,user CPU time and system CPU time spent by executing a command when it
terminates.
‘real‘ time is the time elapsed wall clock time taken by a command to get executed, while ‘user‘
and ‘sys‘ time are the number of CPU seconds that command uses in user and kernel mode
respectively.
Syntax :$time
eg. $time

xv.) history --> is used to view the previously executed command.


Syntax : $history

xvi.) chmod --> change modifications , or grant the privilages to a file for the purpose of
execuition, reading and writing using “+” symbol, “-” symbol we can revoke the permissions
granted on a file

Syntax : $chmod<+/-><privilages(r/w/x)><filename>
Eg. $chmod +x xyz2
xvii.) chown – change owner--to change the owner of file system files, directories.

xviii.) finger -->Finger command is a user information lookup command which gives details
of all the users logged in. This tool is generally used by system administrators. It provides details
like login name, user name, idle time, login time, and in some cases their email address even.

xix.) cal -->calender -- display the current year calander


Syntax : $cal

xx.) kill --> which is used to terminate processes manually


Syntax : $kill -l --> displays all the available signals

xxi.) ps – list of process -- list the currently running processes and their PIDs along with some
other information depends on different options.

Syntax : $ps
eg. $ps

xxii.) more -->more command is used to view the text files in the command prompt, allows the
user do scroll up and down through the page.
Syntax : more [options] <filename>
eg: $more -d sample.txt

xxiii.) logout --> session-logout --allows the use to programmatically logout from your session.
Syntax : $logout
eg:$logout -- _ this will apply when the user gets login only, other than that “exit” command is
enough to come out of the session.

Xxiv.)shutdown --> used to shutdown the system in a safe way.


Syntax : $ shutdown [OPTIONS] [TIME] [MESSAGE]

eg: $shutdown -P –power off


$shutdown -r – reboots the system

B). Study of vi editor

The vi editor is elaborated as visual editor. It is installed in every Unix system. In other words, it
is available in all Linux distros. It is user-friendly and works same on different distros and
platforms. It is a very powerful application. An improved version of vi editor is vim.
The vi editor has two modes:

o Command Mode: In command mode, actions are taken on the file. The vi editor starts in
command mode. Here, the typed words will act as commands in vi editor. To pass a
command, you need to be in command mode.
o Insert Mode: In insert mode, entered text will be inserted into the file. The Esc key will
take you to the command mode from insert mode.

By default, the vi editor starts in command mode. To enter text, you have to be in insert mode, just
type 'i' and you'll be in insert mode. Although, after typing i nothing will appear on the screen but
you'll be in insert mode. Now you can type anything.

To exit from insert mode press Esc key, you'll be directed to command mode.

If you are not sure which mode you are in, press Esc key twice and you'll be in command mode.

Using vi

The vi editor tool is an interactive tool as it displays changes made in the file on the screen while
you edit the file.

In vi editor you can insert, edit or remove a word as cursor moves throughout the file.

Commands are specified for each function like to delete it's x or dd.

The vi editor is case-sensitive. For example, p allows you to paste after the current line
while P allows you to paste before the current line.

vi syntax:

vi <file-name>

In the terminal when you'll type vi command with a file name, the terminal will get clear and
content of the file will be displayed. If there is no such file, then a new file will be created and
once completed file will be saved with the mentioned file name.

Command mode

This is what you'll see when you'll press enter after the above command. If you'll start typing,
nothing will appear as you are in command mode. By default vi opens in command mode.
After opening the vi editor it will look like below

Insert mode

To move to the insert mode press i. Although, there are other commands also to move to insert
mode which we'll study in next page.
C). Study of Unix/Linux file system (tree structure):

A file system is a logical collection of files on a partition or disk UNIX uses a hierarchical file
system structure, much like an upside-down tree, with root (/) at the base of the file system and all
other directories spreading from there.

A UNIX filesystem is a collection of files and directories that has the following properties :
1. It has a root directory (/) that contains other files and directories.
2. Each file or directory is uniquely identified by its name, the directory in which it resides,
and a unique identifier, typically called an inode.
• By convention, the root directory has an inode number of 2 and the lost+found directory
has an inode number of 3. Inode numbers 0 and 1 are not used. File inode numbers can
be seen by specifying the -i option to ls command.
• It is self contained. There are no dependencies between one filesystem and any other.
The directories have specific purposes and generally hold the same types of information for easily
locating files. Following are the directories that exist on the major versions of Unix :

Directory Description

This is the root directory which should contain only the directories needed at
/
the top level of the file structure

/bin This is where the executable files are located. They are available to all user.

/dev These are device drivers.

Supervisor directory commands, configuration files, disk configuration files,


/etc
valid user lists, groups, ethernet, hosts, where to send critical messages

/lib Contains shared library files and sometimes other kernel-related files

/boot Contains files for booting the system.

/home Contains the home directory for users and other accounts

Used to mount other temporary file systems, such as cdrom and floppy for the
/mnt
CDROM drive and floppy diskette drive, respectively
Directory Description

Contains all processes marked as a file by process number or other information


/proc
that is dynamic to the system

/tmp Holds temporary files used between system boots

Used for miscellaneous purposes, or can be used by many users. Includes


/user
administrative commands, shared files, library files, and others

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

Contains binary (executable) files, usually for system administration. For


/sbin
examplefdisk and ifconfig utlities.

/kernel Contains kernel files

D). Study of .bashrc, /etc/bashrc and Environment variables:

The /etc/bashrc is executed for both interactive and non-interactive


shells. /etc/bashrc or /etc/bash.bashrc is the systemwide bash per-interactive-shell startup file. Is is
used system wide functions and aliases. However, environment stuff goes
in /etc/profile file.the /etc/profile is executed only for interactive shells
.bashrc is a shell script that Bash runs whenever it is started interactively. It initializes an
interactive shell session.
.bashrc runs on every interactive shell launch.

Following is the partial list of important environment variables :-

1. DISPLAY : Contains the identifier for the display that X11 programs should use by
default.
2. HOME : Indicates the home directory of the current user: the default argument for the
cd built-in command.
3. IFS : Indicates the Internal Field Separator that is used by the parser for word splitting
after expansion.
4. LANG : LANG expands to the default system locale; LC_ALL can be used to override
this. For example, if its value is pt_BR, then the language is set to (Brazilian) Portuguese
and the locale to Brazil.
5. LD_LIBRARY_PATH : On many Unix systems with a dynamic linker, contains a
colonseparated list of directories that the dynamic linker should search for shared
objects when building a process image after exec, before searching in any other
directories.
6. PATH : Indicates search path for commands. It is a colon-separated list of directories
in which the shell looks for commands.
7. PWD : Indicates the current working directory as set by the cd command.
8. RANDOM : Generates a random integer between 0 and 32,767 each time it is
referenced.
9. SHLVL : Increments by one each time an instance of bash is started. This variable is
useful for determining whether the built-in exit command ends the current session.
10. TERM : Refers to the display type
11. VZ : Refers to Time zone. It can take values like GMT, AST, etc.
12. UID : Expands to the numeric user ID of the current user, initialized at shell startup.

Experiment 2 :

Write a C program that makes a copy of a file using standard I/O, and system
calls

#include <stdio.h>
int main(int argc, char *argv[])
{
int f1, f2;
char buff[50];
long int n;
if(((f1 = open(argv[1], O_RDONLY)) == -1 || ((f2=open(argv[2], O_CREAT | O_WRONLY |
O_TRUNC,
0700))== 1)))
{
perror("problem in file");
exit(1);
}
while((n=read(f1, buff, 50))>0)
if(write(f2, buff, n)!=n)
{
perror("problem in writing");
exit(3);
}
if(n==-1)
{
perror("problem in reading");
exit(2);
}
close(f2);
exit(0); }
/*OUTPUT:

Step1: Create an empty file expt2.txt


Step2: save the program as expt2.c
Babu@Ricky-virtual-machine:~/Documents$ touch expt2.txt
Babu@Ricky -virtual-machine:~/Documents$ cc expt2.c
Babu@Ricky -virtual-machine:~/Documents$ ./a.out expt2.c expt2.txt
Babu@Ricky -virtual-machine:~/Documents$ cat expt2.txt
step5: open the file expt2.txt to see if content is copied or not.*/

Experiment 3: Write a C program to emulate the UNIX ls –l command.


#include <stdio.h>
int main(void)
{
struct dirent *de; // Pointer for directory entry
// opendir() returns a pointer of DIR type.
DIR *dr = opendir(".");
if (dr == NULL) // opendir returns NULL if couldn't open directory
{
printf("Could not open current directory" );
return 0;
}
// Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
// for readdir()
while ((de = readdir(dr)) != NULL)
printf("%s\n", de->d_name);
closedir(dr);
return 0;
}

Output:

Babu@Ricky-virtual-machine:~/Documents$ cc expt3.c
Babu@Ricky -virtual-machine:~/Documents$ ./a.out
expt2.txt
expt
expt3.c
chown.doc
expt2.out
ff
a.out
.
..
expt2.c
attachments
multipledirectory.doc
Babu@Ricky -virtual-machine:~/Documents$ ^C */

Experiment 4:
Simulate the following CPU scheduling algorithms: (a) Round Robin (b) SJF (c) FCFS (d)
Priority

A). FIRST COME FIRST SERVE


#include<stdio.h>
intmain()
{
intn,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
printf("Entertotalnumberofprocesses(maximum20):");scanf("%d",&
n);
printf("\nEnterProcessBurstTime\n");for(i=0;i<n;i++)
{
printf("P[%d]:",i+1);
scanf("%d",&bt[i]);
}
wt[0]=0; //waitingtimeforfirstprocessis0
//calculatingwaitingtimefor(i=1;i<n;i++)
{
wt[i]=0;for(j=0;j<i;j++)
wt[i]+=bt[j];
}
printf("\nProcess\t\tBurstTime\tWaitingTime\tTurnaroundTime");
//calculatingturnaroundtimefor(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];avwt+=wt[
i];avtat+=tat[i];
printf("\nP[%d]\t\t%d\t\t%d\t\t%d",i+1,bt[i],wt[i],tat[i]);
}
avwt/=i;avtat/=i;
printf("\n\nAverageWaitingTime:%d",avwt);printf("\nAverageTurnaroun
dTime:%d",avtat);
return0;
}
Output:

B).SHORTEST JOB FIRST

#include<stdio.h>

voidmain()
{
int
bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;floatavg_wt,
avg_tat;
printf("Enternumberofprocess:");scanf("%d",&n);
printf("\nEnterBurstTime:\n");for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);p[i]=i+1; //containsprocessnumber
}

//sortingbursttimeinascendingorderusingselectionsortfor(i=0;i<n;i++)
{
pos=i;for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])pos=j;
}
temp=bt[i];bt[i]=bt[pos];bt[pos]
=temp;

temp=p[i];p[i]=p[pos];p[pos]=
temp;
}
wt[0]=0;

//calculatewaitingtime
for(i=1;i<n;i++)
{
wt[i]=0;for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}
avg_wt=(float)total/n; //averagewaitingtimetotal=0;
printf("\nProcess\t BurstTime
\tWaitingTime\tTurnaroundTime");for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
//calculateturnaroundtimetotal+=tat
[i];
printf("\np%d\t\t%d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
avg_tat=(float)total/n;
//averageturnaroundtimeprintf("\n\nA
verageWaitingTime=%f",avg_wt);printf("\nAverageTurnaround
Time=%f\n",avg_tat);}

Output:
C). PRIORITY SCHEDULING

#include<stdio.h>

intmain()
{
intbt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat;printf("EnterTotalNum
berofProcess:");
scanf("%d",&n);
printf("\nEnterBurstTimeandPriority\n");for(i=0;i<n;i++)
{
printf("\nP[%d]\n",i+1);printf("BurstTime:"
);scanf("%d",&bt[i]);printf("Priority:");scan
f("%d",&pr[i]);
p[i]=i+1; //containsprocessnumber
}
//sortingbursttime,priorityandprocessnumberinascendingorderusingselectionsort
for(i=0;i<n;i++)
{
pos=i;for(j=i+1;j<n;j++)
{
if(pr[j]<pr[pos])pos=j;
}
temp=pr[i];pr[i]=pr[pos];pr[
pos]=temp;
temp=bt[i];bt[i]=bt[pos];bt[p
os]=temp;
temp=p[i];p[i]=p[pos];p[pos
]=temp;
}
wt[0]=0; //waitingtimeforfirstprocessiszero //calculatewaitingtimefor(i=1;i<n;i++)
{
wt[i]=0;for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}
avg_wt=total/n;
//averagewaitingtimetotal
=0;
printf("\nProcess\t BurstTime
\tWaitingTime\tTurnaroundTime");for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
//calculateturnaroundtimetotal+
=tat[i];
printf("\nP[%d]\t\t%d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
avg_tat=total/n;
//averageturnaroundtimeprintf("\n\nAv
erageWaitingTime=%d",avg_wt);printf("\nAverageTurnaro
undTime=%d\n",avg_tat);
return0;
}

Output:

D). ROUND ROBIN


#include<stdio.h>
intmain()
{
intcount,j,n,time,remain,flag=0,time_quantum;
intwait_time=0,turnaround_time=0,at[10],bt[10],rt[10];printf("EnterTotalP
rocess:\t");
scanf("%d",&n);remain=n;
for(count=0;count<n;count++)
{
printf("EnterArrivalTimeandBurstTimeforProcessProcessNumber%d
:",count+1);scanf("%d",&at[count]);
scanf("%d",&bt[count]);rt[cou
nt]=bt[count];
}
printf("EnterTimeQuantum:\t");scanf("%d",&time_quantum);printf("\n\
nProcess\t|TurnaroundTime|WaitingTime\n\n");for(time=0,count=0;re
main!=0;)
{
if(rt[count]<=time_quantum&&rt[count]>0)
{
time+=rt[count];rt[coun
t]=0;flag=1;
}
elseif(rt[count]>0)
{
rt[count]-=time_quantum;time+=time_quantum;
}
if(rt[count]==0&&flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-
bt[count]);wait_time+=time-at[count]-bt[count];
turnaround_time+=time-at[count];flag=0;
}
if(count==n-1)count=0;
elseif(at[count+1]<=time)count++;
else
count=0;
}
printf("\nAverageWaitingTime=%f\n",wait_time*1.0/n);printf("Avg
TurnaroundTime=%f",turnaround_time*1.0/n);
return0;
}
Output:

Experiment 5 :. Multiprogramming-Memory management-Implementation of fork (), wait (),


exec() and exit (), System calls

#include <stdio.h>
int main(int argc,char** argv)
{
/*Spawn a child to run the program.*/
pid_tpid=fork();
if (pid==0)
{
/* child process */
execv("/bin/ls",argv);
exit(127);
/* only if execv fails */
}
else
{
/* pid!=0; parent process */
printf("\nWaiting Child process to finish");
//waitpid(pid,0,0);
/* wait for child to exit */
wait(NULL);
}
printf("\nExiting main process\n");
return 0;
}

/* Output

Babu@Ricky-virtual-machine:~/Documents$ cc expt6.c
Babu@Ricky -virtual-machine:~/Documents$ ./a.out

a.out chown.doc expt2.c expt2.txt expt4.c ff


attachments expt expt2.out expt3.c expt6.c multipledirectory.doc
Waiting Child process to finish
Exiting main process
Babu@Ricky -virtual-machine:~/Documents$ */

Experiment 6: Write C program to create a thread using pthreads library and let it run its
function.
#include<unistd.h> //header file for sleep
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *mythread(void *vargp)
{
sleep(1);
printf("welcome to Narasaropet Institute of Technology!! ·\n");
return NULL;
}
int main()
{
pthread_ttid;
printf("before thread\n");
pthread_create(&tid,NULL,mythread,NULL);
pthread_join(tid,NULL);
exit(0);
}

/* Output

Babu@Ricky-virtual-machine:~/Documents$ cc expt14.c -l pthread


Babu@Ricky -virtual-machine:~/Documents$ ./a.out
before thread
welcome to Narasaropet Institute of Technology!! ·
Babu@Ricky -virtual-machine:~/Documents$ */

Experiment 7: Simulate Bankers Algorithm for Dead Lock Avoidance

#include<stdio.h>
//#include<conio.h>
void main()
{
int n,r,i,j,k,p,u=0,s=0,m;
int block[10],run[10],active[10],newreq[10];
int max[10][10],resalloc[10][10],resreq[10][10];
int totalloc[10],totext[10],simalloc[10];
//clrscr();
printf("Enter the no of processes:");
scanf("%d",&n);
printf("Enter the no ofresource classes:");
scanf("%d",&r);
printf("Enter the total existed resource in each class:");
for(k=1; k<=r; k++)
scanf("%d",&totext[k]);
printf("Enter the allocated resources:");
for(i=1; i<=n; i++)
for(k=1; k<=r; k++)
scanf("%d",&resalloc);
printf("Enter the process making the new request:");
scanf("%d",&p);
printf("Enter the requested resource:");
for(k=1; k<=r; k++)
scanf("%d",&newreq[k]);
printf("Enter the process which are n blocked or running:");
for(i=1; i<=n; i++)
{
if(i!=p)
{
printf("process %d:\n",i+1);
scanf("%d%d",&block[i],&run[i]);
}
}
block[p]=0;
run[p]=0;
for(k=1; k<=r; k++)
{
j=0;
for(i=1; i<=n; i++)
{
totalloc[k]=j+resalloc[i][k];
j=totalloc[k];
}
}
for(i=1; i<=n; i++)
{
if(block[i]==1||run[i]==1)
active[i]=1;
else
active[i]=0;
}
for(k=1; k<=r; k++)
{
resalloc[p][k]+=newreq[k];
totalloc[k]+=newreq[k];
}
for(k=1; k<=r; k++)
{
if(totext[k]-totalloc[k]<0)
{
u=1;
break;
}
}
if(u==0)
{
for(k=1; k<=r; k++)
simalloc[k]=totalloc[k];
for(s=1; s<=n; s++)
for(i=1; i<=n; i++)
{
if(active[i]==1)
{
j=0;
for(k=1; k<=r; k++)
{
if((totext[k]-simalloc[k])<(max[i][k]-resalloc[i][k]))
{
j=1;
break;
}
}
}
if(j==0)

{
active[i]=0;
for(k=1; k<=r; k++)
simalloc[k]=resalloc[i][k];
}
}
m=0;
for(k=1; k<=r; k++)
resreq[p][k]=newreq[k];
printf("Deadlock willn't occur");
}
else
{
for(k=1; k<=r; k++)
{
resalloc[p][k]=newreq[k];
totalloc[k]=newreq[k];
}
printf("Deadlock will occur");
}
//getch();
}

/* Output

Babu@Ricky-virtual-machine:~/Documents$ cc expt8.c
Babu@Ricky -virtual-machine:~/Documents$ ./a.out
Enter the no of processes:4
Enter the no ofresource classes:3
Enter the total existed resource in each class:3 2 2
Enter the allocated resources:1 0 0 5 1 1 2 1 1 0 0 2
Enter the process making the new request:2
Enter the requested resource:1 1 2
Enter the process which are n blocked or running:process 2:
21
process 4:
10
process 5:
10
Deadlock will occur
Babu@Ricky -virtual-machine:~/Documents$
Experiment 8: Simulate Bankers Algorithm for Dead Lock Prevention.
Aim : Simulate Dead lock Prevention (Bankers Algorithm)

#include<stdio.h>
//#include<conio.h>
void main()
{
int allocated[15][15],max[15][15],need[15][15],avail[15],tres[15],work[15],flag[15];
int pno,rno,i,j,prc,count,t,total;
count=0;
//clrscr();
printf("\n Enter number of process:");
scanf("%d",&pno);
printf("\n Enter number of resources:");
scanf("%d",&rno);
for(i=1;i<=pno;i++)
{
flag[i]=0;
}
printf("\n Enter total numbers of each resources:");
for(i=1;i<= rno;i++)
scanf("%d",&tres[i]);
printf("\n Enter Max resources for each process:");
for(i=1;i<= pno;i++)
{
printf("\n for process %d:",i);
for(j=1;j<= rno;j++)
scanf("%d",&max[i][j]);
}
printf("\n Enter allocated resources for each process:");
for(i=1;i<= pno;i++)
{
printf("\n for process %d:",i);
for(j=1;j<= rno;j++)
scanf("%d",&allocated[i][j]);
}
printf("\n available resources:\n");
for(j=1;j<= rno;j++)
{
avail[j]=0;
total=0;
for(i=1;i<= pno;i++)
{
total+=allocated[i][j];
}
avail[j]=tres[j]-total;
work[j]=avail[j];
printf(" %d \t",work[j]);
}
do
{
for(i=1;i<= pno;i++)
{
for(j=1;j<= rno;j++)
{
need[i][j]=max[i][j]-allocated[i][j];
}
}

printf("\n Allocated matrix Max need");


for(i=1;i<= pno;i++)
{
printf("\n");
for(j=1;j<= rno;j++)
{
printf("%4d",allocated[i][j]);
}
printf("|");
for(j=1;j<= rno;j++)
{
printf("%4d",max[i][j]);
}
printf("|");
for(j=1;j<= rno;j++)
{
printf("%4d",need[i][j]);
}
}
prc=0;
for(i=1;i<= pno;i++)
{
if(flag[i]==0)
{
prc=i;
for(j=1;j<= rno;j++)
{
if(work[j]< need[i][j])
{
prc=0;
break;
}
}
}
if(prc!=0)
break;
}
if(prc!=0)
{
printf("\n Process %d completed",i);
count++;
printf("\n Available matrix:");
for(j=1;j<= rno;j++)
{
work[j]+=allocated[prc][j];
allocated[prc][j]=0;
max[prc][j]=0;
flag[prc]=1;
printf(" %d",work[j]);
}
}
}while(count!=pno&&prc!=0);
if(count==pno)
printf("\nThe system is in a safe state!!");
else
printf("\nThe system is in an unsafe state!!");
//getch();
}

/* Output

Babu@Ricky-virtual-machine:~/Documents$ ./a.out
Enter number of process:3
Enter number of resources:2
Enter total numbers of each resources:2
3
Enter Max resources for each process:
for process 1:1
2
for process 2:1 2
for process 3:2 2
Enter allocated resources for each process:
for process 1:1 2
for process 2:2 3
for process 3: 1 2
available resources:
-2 -4
Allocated matrix Max need
1 2| 1 2| 0 0
2 3| 1 2| -1 -1
1 2| 2 2| 1 0
The system is in an unsafe state!! Babu@Ricky -virtual-machine:~/Documents$
*/

Experiment 9: Simulate the following page replacement algorithm FIFO

#include <stdio.h>
int main()
{
int referenceString[10], pageFaults = 0, m, n, s, pages, frames;
printf("\nEnter the number of Pages:\t");
scanf("%d", &pages);
printf("\nEnter reference string values:\n");
for(int m = 0; m < pages; m++)
{
printf("Value No. [%d]:\t", m + 1);
scanf("%d", &referenceString[m]);
}
printf("\n What are the total number of frames:\t");
{
scanf("%d", &frames);
}
int temp[frames];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(referenceString[m] == temp[n])
{
s++;
pageFaults--;
}
}
pageFaults++;
if((pageFaults<= frames) && (s == 0))
{
temp[m] = referenceString[m];
}
else if(s == 0)
{
temp[(pageFaults - 1) % frames] = referenceString[m];
}
printf("\n");
for(n = 0; n < frames; n++)
{
printf("%d\t", temp[n]);
}
}
printf("\nTotal Page Faults:\t%d\n", pageFaults);
return 0;
}

Output:

Babu@Ricky-virtual-machine:~/Documents$ cc expt10_a.c
Babu@Ricky -virtual-machine:~/Documents$ ./a.out
Enter the number of Pages: 5
Enter reference string values:
Value No. [1]: 4
Value No. [2]: 1
Value No. [3]: 2
Value No. [4]: 4
Value No. [5]: 5
What are the total number of frames: 3
4 -1 -1
4 1 -1
4 1 2
4 1 2
5 1 2
Total Page Faults: 4
Babu@Ricky -virtual-machine:~/Documents$ */

You might also like