0% found this document useful (0 votes)
12 views47 pages

OS Lab Manual (R18)

The document is a laboratory manual for operating systems, specifically designed for II-B.Tech II-Semester students at Vignan’s Institute of Management and Technology for Women. It includes C programs to simulate various CPU scheduling algorithms such as FCFS, SJF, Round Robin, and Priority Scheduling, along with explanations and sample outputs. Additionally, it provides examples of using I/O system calls in UNIX/Linux for reading from and writing to files.

Uploaded by

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

OS Lab Manual (R18)

The document is a laboratory manual for operating systems, specifically designed for II-B.Tech II-Semester students at Vignan’s Institute of Management and Technology for Women. It includes C programs to simulate various CPU scheduling algorithms such as FCFS, SJF, Round Robin, and Priority Scheduling, along with explanations and sample outputs. Additionally, it provides examples of using I/O system calls in UNIX/Linux for reading from and writing to files.

Uploaded by

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

OPERATING SYSTEMS

LABORATORY MANUAL

II-B.TECH II-Semester(R18)

Department of Computer Science


Vignan’s Institute of Management and Technology for
Women
Kondapur, Ghatkesar, Medchal District - 501 301.
Sponsored by
Lavu Educational Society
(Approved by AICTE and Affiliated to JNT University, Hyderabad)
1. Write a C Program to simulate the following CPU Schedulling algorithms
a)FCFS B)SJF C)Round Robin d)Priority

(a) FCFS
Aim: Write a C program to implement the various process scheduling mechanisms such
Description:
First-come, first-serve scheduling(FCFS): In this, which process enter the ready queue first is
served first. The OS maintains DS that is ready queue. It is the simplest CPU scheduling
algorithm. If a process request the CPU then it is loaded into the ready queue, which process is
the head of the ready queue, connect the CPU to that process.
Algorithm for FCFS scheduling:

Step 1: Start the process

Step 2: Accept the number of processes in the ready Queue

Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time

Step 4: Set the waiting of the first process as ‘0’ and its burst time as its turn around time

Step 5: for each process in the Ready Q calculate

(c) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-
1)
(d) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for
process(n)

Step 6: Calculate

(e) Average waiting time = Total waiting Time / Number of process

(f) Average Turnaround time = Total Turnaround Time / Number of


process Step 7: Stop the process
Program to Simulate First Come First Serve CPU Scheduling Algorithm :

#include<stdio.h>
#include<string.h>
main()

{
int i,j,n,bt[10],compt[10],at[10], wt[10],tat[10];
float sumwt=0.0,sumtat=0.0,avgwt,avgtat;
printf("Enter number of processes: ");
scanf("%d",&n);
printf("Enter the burst time of %d process\n", n);
for(i=0;i<n;i++)
{

scanf("%d",&bt[i]);

}
printf("Enter the arrival time of %d process\n", n);
for(i=0;i<n;i++)

{
scanf("%d",&at[i]);
}
compt[0]=bt[0]-at[0];
for(i=1;i<n;i++)
compt[i]=bt[i]+compt[i-1];
for(i=0;i<n;i++)
{
tat[i]=compt[i]-at[i];
wt[i]=tat[i]-bt[i];
sumtat+=tat[i];
sumwt+=wt[i]; }
avgwt=sumwt/n;
avgtat=sumtat/n;
printf("---------------------------------- \n");
printf("PN\tBt\tCt\tTat\tWt\n");
printf("---------------------------------- \n");
for(i=0;i<n;i++)
{
printf("%d\t%2d\t%2d\t%2d\t%2d\n",i,bt[i],compt[i],tat[i],wt[i]);
}
printf("----------------------------------\n");
printf(" Avgwt = %.2f\tAvgtat = %.2f\n",avgwt,avgtat);
printf("-----------------------------------\n");
}
OUTPUT :

Enter number of processes: 5 Enter


the burst time of 5 process 3 6 4 5
2
Enter the arrival time of 5 process 0
2468
----------------------------------------
PN Bt Ct Tat Wt
----------------------------------------
0 3 3 3 0
1 6 9 7 1
2 4 13 9 5
3 5 18 12 7
4 2 20 12 10
---------------------------------------

Avgwt = 4.60 Avgtat = 8.60


b)SJF
Description:

Shortest Job First: The criteria of this algorithm are which process having the smallest CPU
burst, CPU is assigned to that next process. If two process having the same CPU burst time
FCFS is used to break the tie.

Algorithm for SJF:

Step 1: Start the process

Step 2: Accept the number of processes in the ready Queue

Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time

Step 4: Start the Ready Q according the shortest Burst time by sorting according to lowest to

highest burst time.

Step 5: Set the waiting time of the first process as ‘0’ and its turnaround time as its burst time.

Step 6: For each process in the ready queue, calculate

(a) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-
1)
(b) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for
process(n)

Step 6: Calculate

(c) Average waiting time = Total waiting Time / Number of process

(d) Average Turnaround time = Total Turnaround Time / Number of


process Step 7: Stop the process
Program to Simulate Shortest Job First CPU Scheduling Algorithm:

#include<stdio.h>
#include<string.h>
int main()

{
int i,j,n,bt[10],compt[10], wt[10],tat[10],temp; float
sumwt=0.0,sumtat=0.0,avgwt,avgtat; printf("Enter number of processes: ");
scanf("%d",&n);printf("Enter the burst time of %d process\n", n); for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);

}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(bt[i]>bt[j])
{
temp=bt[i];
bt[i]=bt[j];
bt[j]=temp;
}
compt[0]=bt[0];
for(i=1;i<n;i++)
compt[i]=bt[i]+compt[i-1];
for(i=0;i<n;i++)
{
tat[i]=compt[i];
wt[i]=tat[i]-bt[i];
sumtat+=tat[i];
sumwt+=wt[i];
}
avgwt=sumwt/n;
avgtat=sumtat/n;
printf("------------------------------ \n");
printf("Bt\tCt\tTat\tWt\n");
printf("------------------------------ \n");
for(i=0;i<n;i++)
{
printf("%2d\t%2d\t%2d\t%2d\n",bt[i],compt[i],tat[i],wt[i]);}
printf("------------------------------\n");
printf(" Avgwt = %.2f\tAvgtat = %.2f\n",avgwt,avgtat);
printf("--------------
-------------- \n");
getch();
}

OUTPUT:
Enter number of processes: 4
Enter the burst time of 4 process

6873
------------------------------------
Bt Ct Tat Wt
------------------------------------
3 3 3 0
6 9 9 3
7 16 16 9
8 24 24 16
--------------------------------------
Avgwt = 7.00 Avgtat = 13.00

(C) Round Robin


#include<stdio.h>
struct process

{
char pn[10]; int
bt,ct,time;

}p[10];
int main()

int i,full,n,tq,wt[10],tat[10], time1=0;


float avgwt=0.0;
printf("Enter number of processes:");
scanf("%d",&n);
printf("Enter process name and burst time of %d process\n", n);
for(i=0;i<n;i++)

{
scanf("%s%d",&p[i].pn,&p[i].bt);
p[i].time=p[i].bt;
}
printf("Enter quantum:");
scanf("%d",&tq); full=n;
while(full)
{
for(i=0;i<n;i++)
{
if(p[i].bt>=tq)
{
p[i].bt-=tq;

time1=time1+tq;
}
else if(p[i].bt!=0)
{
time1+=p[i].bt;
p[i].bt=0;
}
else
continue;
if(p[i].bt==0)
{
full=full-1;
tat[i]=time1;
}
}
}
for(i=0;i<n;i++)
{
p[i].ct=tat[i];
wt[i]=tat[i]-p[i].time;
}
printf("---------------------------------- \n");
printf("PN\tBt\tCt\tTat\tWt\n");
printf("---------------------------------- \n");
for(i=0;i<n;i++)
{
printf("%2s\t%2d\t%2d\t%2d\t%2d\n",p[i].pn,p[i].time,p[i].ct,tat[i],wt[i]);
avgwt+=wt[i];
}

printf("----------------------------------\n");

avgwt=avgwt/n;
printf(" Average waiting time = %.2f\n",avgwt);
printf("-----------------------------------\n");

OUTPUT:
Enter number of processes: 5

Enter process name and burst time of 5 process


1 10
25
3 15
43
5 20
Enter quantum:5
--------------------------------------

PN Bt Ct Tat Wt
--------------------------------------
1 10 28 28 18
2 5 10 10 5
3 15 43 43 28
4 3 18 18 15
5 20 53 53 33
--------------------------------------
Average waiting time = 19.80
--------------------------------------
(d)PRIORITY SCHEDULING

Aim: Write a C program to implement the various process scheduling mechanisms such

as Priority Scheduling.

Description:

Priority Scheduling: These are of two types.

One is internal priority, second is external priority. The cpu is allocated to the process with the
highest priority. Equal priority processes are scheduled in the FCFS order. Priorities are
generally some fixed range of numbers such as 0 to 409. The low numbers represent high
priority.

Algorithm for Priority Scheduling:

Step 1: Start the process

Step 2: Accept the number of processes in the ready Queue

Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time

Step 4: Sort the ready queue according to the priority number.

Step 5: Set the waiting of the first process as ‘0’ and its burst time as its turn around time

Step 6: For each process in the Ready Q calculate

(e) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-
1)
(f) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for
process(n)

Step 7: Calculate
(g) Average waiting time = Total waiting Time / Number of process

(h) Average Turnaround time = Total Turnaround Time / Number of


process Step 8: Stop the process

Program to Simulate Priority CPU Scheduling Algorithm:

#include<stdio.h>
int main()

{
int i,j,n,bt[10],p[10],compt[10], wt[10],tat[10],temp1,temp2;
float sumwt=0.0,sumtat=0.0,avgwt,avgtat;
printf("Enter number of processes: "); scanf("%d",&n);
printf("Enter the burst time of %d process\n", n);
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
printf("Enter the priority of %d process\n", n);
for(i=0;i<n;i++)
scanf("%d",&p[i]);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(p[i]>p[j])
{
temp1=bt[i];

bt[i]=bt[j];
bt[j]=temp1;
temp2=p[i];
p[i]=p[j];
p[j]=temp2;
}
compt[0]=bt[0]; wt[0]=0;
for(i=1;i<n;i++) compt[i]=bt[i]
+compt[i-1]; for(i=0;i<n;i++)
{

tat[i]=compt[i];
wt[i]=tat[i]-bt[i];
sumtat+=tat[i];
sumwt+=wt[i];

}
avgwt=sumwt/n; avgtat=sumtat/n;
printf("------------------------------\n");
printf("Bt\tCt\tTat\tWt\n");
printf("------------------------------\n");
for(i=0;i<n;i++)
{
printf("%2d\t%2d\t%2d\t%2d\n",bt[i],compt[i],tat[i],wt[i]);
}
printf("------------------------------\n");
printf(" Avgwt = %.2f\tAvgtat = %.2f\n",avgwt,avgtat);
printf(“------ \n");

}
OUTPUT :
Enter number of processes: 4
Enter the burst time of 4 process
6535
Enter the priority of 4 process
4263

------------------------------------
Bt Ct Tat Wt
-----------------------------------
5 5 5 0
5 10 10 5
6 16 16 10
3 19 19 16
------------------------------------
Avgwt = 7.75 Avgtat = 12.50
2.Write programs using the I/O system calls of UNIX/LINUX operating system
(open, read, write, close, fcntl, seek, stat, opendir, readdir)
Program:
Aim: Programs to use I/O system calls of UNIX/LINUX operating system
Read from a text file:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("abc.txt","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
OUTPUT:
cse501@vignan:~/OSprograms> vi 2read.c
cse501@vignan:~/OSprograms> gcc -o op2read 2read.c
Error! opening filecse501@vignan:~/OSprograms> vi abc.txt
12345
cse501@vignan:~/OSprograms> ./op2read
Value of n=12345
Program to Open a File, Write in it, And Close the File
# include <stdio.h>
# include <string.h>
int main( )
{
// Declare the file pointer
FILE *filePointer ;
// Get the data to be written in file
char dataToBeWritten[50]
= "GeeksforGeeks-A Computer Science Portal for Geeks";
// Open the existing file abc.c using fopen()
// in write mode using "w" attribute
filePointer = fopen("abc.c", "w") ;
// Check if this filePointer is null
// which maybe if the file does not exist
if ( filePointer == NULL )
{
printf( "abc.c file failed to open." ) ;
}
else
{
printf("The file is now opened.\n") ;
// Write the dataToBeWritten into the file
if ( strlen ( dataToBeWritten ) > 0 )
{
// writing in the file using fputs()
fputs(dataToBeWritten, filePointer) ;
fputs("\n", filePointer) ;
}
// Closing the file using fclose()
fclose(filePointer) ;
printf("Data successfully written in file abc.c\n");
printf("The file is now closed.") ;
}
return 0;
}
OUTPUT:
cse501@vignan:~/OSprograms> vi 2write.c
cse501@vignan:~/OSprograms> gcc -o op2write 2write.c
cse501@vignan:~/OSprograms> ./op2write
The file is now opened.
Data successfully written in file abc.c
Program to use lseek system call.
#include <unistd.h>
#include<stdio.h>
#include <fcntl.h>
#include <sys/types.h>
int main()
{
int file=0;
if((file=open("abc1.txt",O_RDONLY)) < -1)
return 1;
char buffer[19];
if(read(file,buffer,19) != 19) return 1;
printf("%s\n",buffer);
if(lseek(file,10,SEEK_SET) < 0) return 1;
if(read(file,buffer,19) != 19) return 1;
printf("%s\n",buffer);
return 0;
}
OUTPUT:
cse501@vignan:~/OSprograms> vi abc1.txt

Hi vmtw Ghatkesar Kondapur

cse501@vignan:~/OSprograms> vi 2lseek.c

cse501@vignan:~/OSprograms> gcc -o op2lseek 2lseek.c

cse501@vignan:~/OSprograms> ./op2lseek

Hi vmtw Ghatkesar K

Program to use stat() system call


#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>
void printFileProperties(struct stat stats);
int main()
{
char path[100];
struct stat stats;
printf("Enter source file path: ");
scanf("%s", path);
// stat() returns 0 on successful operation,
// otherwise returns -1 if unable to get file properties.
if (stat(path, &stats) == 0)
{
printFileProperties(stats);
}
else
{
printf("Unable to get file properties.\n");
printf("Please check whether '%s' file exists.\n", path);
}
return 0;
}
/**
* Function to print file properties.
*/
void printFileProperties(struct stat stats)
{
struct tm dt;
// File permissions
printf("\nFile access: ");
if (stats.st_mode & R_OK)
printf("read ");
if (stats.st_mode & W_OK)
printf("write ");
if (stats.st_mode & X_OK)
printf("execute");
// File size
printf("\nFile size: %d", stats.st_size);
// Get file creation time in seconds and
// convert seconds to date and time format
dt = *(gmtime(&stats.st_ctime));
printf("\nCreated on: %d-%d-%d %d:%d:%d", dt.tm_mday, dt.tm_mon, dt.tm_year + 1900,
dt.tm_hour, dt.tm_min, dt.tm_sec);
// File modification time
dt = *(gmtime(&stats.st_mtime));
printf("\nModified on: %d-%d-%d %d:%d:%d", dt.tm_mday, dt.tm_mon, dt.tm_year + 1900,
dt.tm_hour, dt.tm_min, dt.tm_sec);

}
OUTPUT:
cse501@vignan:~/OSprograms> vi 2stat.c
cse501@vignan:~/OSprograms> gcc -o op2stat 2stat.c
cse501@vignan:~/OSprograms> ./op2stat
Enter source file path: abc1.txt

File access: read


File size: 28
Created on: 11-2-2020 8:58:41
Modified on: 11-2-2020 8:58:40
Program to use Opendir system call

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
int main(int c, char *v[])
{
DIR *myDirectory;
myDirectory = opendir(v[1]);
if (c == 2)
{
if (myDirectory)
{
puts("OK the folder is opened.");
/*
** closedir
*/
if (closedir(myDirectory) == 0)
puts("The directory is now closed.");
else
puts("The directory can not be closed.");
}
else if (errno == ENOENT)
puts("This directory does not exist.");
else if (errno == ENOTDIR)
puts("This file is not a directory.");
else if (errno == EACCES)
puts("You do not have the right to open this folder.");
else
puts("That's a new error, check the manual.");
}
else
puts("Sorry we need exactly 2 arguments.");
return (0);
}
OUTPUT:
All files and subdirectories of current directory

Program to use readdir() system call.


#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>

int main(int c, char *v[]) {


DIR *myDirectory;
struct dirent *myFile;

if (c == 2) {
myDirectory = opendir(v[1]);
if (myDirectory) {
puts("OK the directory is opened, let's see its files:");
while ((myFile = readdir(myDirectory)))
printf("%s\n", myFile->d_name);
/*
** closedir
*/
if (closedir(myDirectory) == 0)
puts("The directory is now closed.");
else
puts("The directory can not be closed.");
} else if (errno == ENOENT)
puts("This directory does not exist.");
else if (errno == ENOTDIR)
puts("This file is not a directory.");
else if (errno == EACCES)
puts("You do not have the right to open this folder.");
else
puts("That's a new error, check the manual.");
} else
puts("Sorry we need exactly 2 arguments.");
return (0);
}
3.Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and
Prevention.
Description:
Deadlock: A process request the resources, the resources are not available at that time, so the
process enter into the waiting state. The requesting resources are held by another waiting
process,both are in waiting state, this situation is said to be Deadlock.

A deadlocked system must satisfied the following 4 conditions. These are:


(i) Mutual Exclusion: Mutual Exclusion means resources are in non-sharable mode only, it
means only one process at a time can use a process.
(ii) Hold and Wait: Each and every process is the deadlock state, must holding at least one
resource and is waiting for additional resources, that are currently being held by another process.

(iii) No Preemption: No Preemption means resources are not released in the middle of the
work, they released only after the process has completed its task.

(iv) Circular Wait: If process P1 is waiting for a resource R1, it is held by P2, process P2 is
waiting for R2, R2 held by P3, P3 is waiting for R4, R4 is held by P2, P2 waiting for resource
R3, it is held by P1.

Deadlock Avoidance: It is one of the method of dynamically escaping from the deadlocks. In
this scheme, if a process request for resources, the avoidance algorithm checks before the
allocation of resources about the state of system. If the state is safe, the system allocate the
resources to the requesting process otherwise (unsafe) do not allocate the resources. So taking
care before the allocation said to be deadlock avoidance.

Banker’s Algorithm: It is the deadlock avoidance algorithm, the name was chosen because the
bank never allocates more than the available cash.

Available: A vector of length ‘m’ indicates the number of available resources of each type. If
available[j]=k, there are ‘k’ instances of resource types Rj available.

Allocation: An nxm matrix defines the number of resources of each type currently allocated to
each process. If allocation[i,j]=k, then process Pi is currently allocated ‘k’ instances of resources
type Rj.

Max: An nxm matrix defines the maximum demand of each process. If max[i,j]=k, then Pi may
request at most ‘k’ instances of resource type Rj.

Need: An nxm matrix indicates the remaining resources need of each process. If need[I,j]=k,
then Pi may need ‘k’ more instances of resource type Rj to complete this task. There fore,

Need[i,j]=Max[i,j]-Allocation[I,j]

Safety Algorithm:

1. Work and Finish be the vector of length m and n respectively, Work=Available and
Finish[i] =False.
2. Find an i such that both
Finish[i] =False
Need<=Work
If no such I exists go to step 4.
3. work=work+Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state.
Resource request algorithm
Let Request i be request vector for the process Pi, If request i=[j]=k, then process Pi
wants k instances of resource type Rj.
1. if Request<=Need I go to step 2. Otherwise raise an error condition.
2. if Request<=Available go to step 3. Otherwise Pi must since the resources are available.
3. Have the system pretend to have allocated the requested resources to process Pi by
modifying the state as follows;
Available=Available-Request I;
Allocation I =Allocation +Request I;
Need i=Need i-Request I;
If the resulting resource allocation state is safe, the transaction is completed and process Pi is
allocated its resources. However, if the state is unsafe, the Pi must wait for Request i and the old
resource-allocation state is restored.

Algorithm for Banker’s Deadlock Avoidance:

1. Start the program.


2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety.
9. or not if we allow the request.
10. stop the program.

/* Program to Simulate Bankers Algorithm for Dead Lock Avoidance */


#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here
int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4

int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix


{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4

int avail[3] = { 3, 3, 2 }; // Available Resources

int f[n], ans[n], ind = 0;


for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {

int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}

if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}

printf("Following is the SAFE Sequence\n");


for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);

return (0);
}

OUTPUT:
Following is the SAFE Sequence

P1 -> P3 -> P4 -> P0 -> P2

Bankers Algorithm for DeadLock Prevention

Aim: To Simulate Bankers Algorithm for Deadlock Prevention.


/* Program to Simulate Bankers Algorithm for Dead Lock Prevention */

#include<stdio.h>
main()

char job[10][10];

int time[10],avail,tem[10],temp[10]; int safe[10];

int ind=1,i,j,q,n,t;

printf("Enter no of jobs: ");

scanf("%d",&n);

for(i=0;i<n;i++)

printf("Enter name and time: ");

scanf("%s%d",&job[i],&time[i]);

printf("Enter the available resources:");


scanf("%d",&avail);

for(i=0;i<n;i++)

temp[i]=time[i];

tem[i]=i;

for(i=0;i<n;i++)

for(j=i+1;j<n;j++)

if(temp[i]>temp[j])

t=temp[i];
temp[i]=temp[j];

temp[j]=t; t=tem[i];

tem[i]=tem[j];

tem[j]=t;

for(i=0;i<n;i++)

{
q=tem[i];

if(time[q]<=avail)

safe[ind]=tem[i];

avail=avail-tem[q];

printf("%s",job[safe[ind]]);

ind++;

else

printf("No safe sequence\n");

printf("Safe sequence is:");

for(i=1;i<ind; i++)

printf("%s %d\n",job[safe[i]],time[safe[i]]);

getch();

OUTPUT:
Enter no of jobs:4

Enter name and time: A 1

Enter name and time: B 4

Enter name and time: C 2

Enter name and time: D 3

Enter the available resources: 20

Safe sequence is: A 1, C 2, D 3, B 4.

4.A C program that implements a producer-consumer system with two processes using
Semaphores using UNIX/LINUX system calls.
Program:
#include<stdio.h>
int main()
{
int buffer[10], bufsize, in, out, produce, consume,choice=0; in = 0;
out = 0;
bufsize = 10;
while(choice !=3){
printf(“\n1. Produce \t 2. Consume \t3. Exit”);

printf(“\nEnter your choice: ”);

scanf(“%d”,&choice);
switch(choice)

{
case 1: if((in+1)%bufsize==out)
printf(“\nBuffer is Full”);
else
{
printf(“\nEnter the value: “);
scanf(“%d”, &produce);

buffer[in] = produce;
in = (in+1)%bufsize;

break;
case 2:if(in == out)
printf(“\nBuffer is Empty”);
else
{
consume = buffer[out];
printf(“\nThe consumed value is %d”, consume);

out = (out+1)%bufsize;
}
break;
}}}

OUTPUT

1. Produce 2. Consume 3. Exit

Enter your choice: 2

Buffer is Empty
1. Produce 2. Consume 3. Exit

Enter your choice: 1

Enter the value: 100

1. Produce 2. Consume 3. Exit

Enter your choice: 2

The consumed value is 100

1. Produce 2. Consume 3. Exit

Enter your choice: 3

5. Write C programs to illustrate the following IPC mechanisms


(a) Pipes (b) FIFOs (c) Message Queues (d) Shared Memory
(a) Pipes
Program: implement pipe in Linux
#include<stdio.h>
#include<unistd.h>
int main() {
int pipefds[2];
int returnstatus;
int pid;
char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];
returnstatus = pipe(pipefds);
if (returnstatus == -1) {
printf("Unable to create pipe\n");
return 1;
}
pid = fork();
// Child process
if (pid == 0) {
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Child Process - Reading from pipe – Message 1 is %s\n", readmessage);
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Child Process - Reading from pipe – Message 2 is %s\n", readmessage);
} else { //Parent process
printf("Parent Process - Writing to pipe - Message 1 is %s\n", writemessages[0]);
write(pipefds[1], writemessages[0], sizeof(writemessages[0]));
printf("Parent Process - Writing to pipe - Message 2 is %s\n", writemessages[1]);
write(pipefds[1], writemessages[1], sizeof(writemessages[1]));
}
return 0;}
Output:
codecse501@vignan:~/OSprograms> vi 5apipes.c
cse501@vignan:~/OSprograms> vi 5apipes.c
cse501@vignan:~/OSprograms> gcc -o op5a 5apipes.c
cse501@vignan:~/OSprograms> ./op5a
Parent Process - Writing to pipe - Message 1 is Hi
Parent Process - Writing to pipe - Message 2 is Hello
Child Process - Reading from pipe – Message 1 is Hi
Child Process - Reading from pipe – Message 2 is Hello
(b)Named Pipe or FIFO
Program:
c1.c
#include<stdio.h>
#include<errno.h>
#include<string.h>
#define MSG 63
main()
{
int fd,j,f1,r1;
char msgbuf[MSG];
f1=mknod("fif1",010666,0);
fd=open("fif1",O_RDWR);
if(fd<0)
printf("FIFO OPEN FAI;ED");

if((r1=read(fd,msgbuf,40))>0)
{
printf("%d",r1);
printf("Iam server:%s",msgbuf);
}
named.c
#include<fcntl.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
#define MSG 63

main()
{
int fd,j,nwrite;
char msgbuf[MSG];
char s[10]="anusha1";/*you may take any string here*/
if((fd=open("fif1",O_WRONLY))<0)
perror("FIFO OPEN FAI;ED");
strcpy(msgbuf,s);
if((nwrite=write(fd,msgbuf,40))<=0)
printf("msg write failed");
else
printf("message is written:%s",msgbuf);
exit(0);
}
OUTPUT:

(iii)Message Queues

// C Program for Message Queue (Writer Process)


#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>

// structure for message queue


struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;

int main()
{
key_t key;
int msgid;

// ftok to generate unique key


key = ftok("progfile", 65);

// msgget creates a message queue


// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
message.mesg_type = 1;

printf("Write Data : ");


scanf(“%s”,message.mesg_text);
// msgsnd to send message
msgsnd(msgid, &message, sizeof(message), 0);

// display the message


printf("Data send is : %s \n", message.mesg_text);
return 0;
}

// C Program for Message Queue (Reader Process)

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// structure for message queue
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_t key;
int msgid;
// ftok to generate unique key
key = ftok("progfile", 65);
// msgget creates a message queue
// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
// msgrcv to receive message
msgrcv(msgid, &message, sizeof(message), 1, 0);
// display the message
printf("Data Received is : %s \n",
message.mesg_text);
// to destroy the message queue
msgctl(msgid, IPC_RMID, NULL);

return 0;
}
OUTPUT:
cse501@vignan:~/OSprograms> vi 5cmsgqw.c
cse501@vignan:~/OSprograms> gcc -o op5cmsgqw 5cmsgqw.c
cse501@vignan:~/OSprograms> vi 5cmsgqr.c
cse501@vignan:~/OSprograms> gcc -o op5cmsgqr 5cmsgqr.c
cse501@vignan:~/OSprograms> ./op5cmsgqw
Write Data : hello
Data send is : hello
cse501@vignan:~/OSprograms> ./op5cmsgqr
Data Received is : hello

(iv) SHARED MEMORY


Shared Memory for Writer process

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
printf(“Write Data : ");
scanf(“%s”,str);
printf("Data written in memory: %s\n",str);
//detach from shared memory
shmdt(str);
return 0;
}

Shared Memory For Reader Process

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
printf("Data read from memory: %s\n",str);
//detach from shared memory
shmdt(str);
// destroy the shared memory
shmctl(shmid,IPC_RMID,NULL);
return 0;
}

OUTPUT:
cse501@vignan:~/OSprograms> vi 5dshmread.c
cse501@vignan:~/OSprograms> vi 5dshmwrite.c
cse501@vignan:~/OSprograms> gcc -o op5dshmwrite 5dshmwrite.c
cse501@vignan:~/OSprograms> gcc -o op5dshmread 5dshmread.c
cse501@vignan:~/OSprograms> ./op5dshmwrite
Write Data : Hi
Data written in memory: Hi
cse501@vignan:~/OSprograms> ./op5dshmread
Data read from memory: Hi

6.Write C programs to simulate the following memory management techniques


a) Paging b) Segmentation
a) Paging
AIM:To implement the Memory management policy- Paging.
Description: Paging is an efficient memory management scheme because it is non-contiguous
memory allocation method. The basic idea of paging is the physical memory (main memory) is
divided into fixed sized blocks called frames, the logical address space is divided into fixed sized
blocks, called pages, but page size and frame size should be equal. The size of the frame or a
page is depending on operating system.

In this scheme the operating system maintains a data structure that is page table, it is used for
mapping purpose. The page table specifies the some useful information, it tells which frames are
there and so on. The page table consisting of two fields, one is the page number and other one is
frame number. Every address generated by the CPU divided into two parts, one is page number
and second is page offset or displacement. The pages are loaded into available free frames in the
physical memory.

Algorithm for Paging Technique:


Step 1: Read all the necessary input from the keyboard.
Step 2: Pages - Logical memory is broken into fixed - sized blocks.
Step 3: Frames – Physical memory is broken into fixed – sized blocks.
Step 4: Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
Step 5: Display the physical address.
Step 6: Stop the process.

/* Program to simulate paging technique of memory management */

#include<stdio.h>
int main()
{
int memsize=15;
int pagesize,nofpage;
int p[100];
int frameno,offset;
int logadd,phyadd;
int i;
int choice=0;
printf("\nYour memsize is %d ",memsize);
printf("\nEnter page size:");
scanf("%d",&pagesize);
nofpage=memsize/pagesize;
for(i=0;i<nofpage;i++)
{
printf("\nEnter the frame of page%d:",i+1);
scanf("%d",&p[i]);
}
do
{
printf("\nEnter a logical address:");
scanf("%d",&logadd);
frameno=logadd/pagesize;
offset=logadd%pagesize;
phyadd=(p[frameno]*pagesize)+offset;
printf("\nPhysical address is:%d",phyadd);
printf("\nDo you want to continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1);}
OUTPUT:
cse501@vignan:~/OSprograms> vi 6apaging.c
cse501@vignan:~/OSprograms> gcc -o op6a 6apaging.c
cse501@vignan:~/OSprograms> ./op6a
Your memsize is 15
Enter page size:5
Enter the frame of page1:2
Enter the frame of page2:4
Enter the frame of page3:7
Enter a logical address:3
Physical address is:13
Do you want to continue(1/0)?:1
Enter a logical address:1
Physical address is:11
Do you want to continue(1/0)?:0
b) Segmentation
#include<stdio.h>
#define MAX 50
int main()
{
int segment[MAX][2],i,n,f,off,sno;
printf("\nEnter the no of segments in memory");
scanf("%d",&n);
for(i=0;i<n;i++)
{
segment[i][0]=-1;
segment[i][1]=-1;
}

printf("\nEnter the segment table\n");


printf("(Enter base no as -1 if that segment is not present in memory)\n\n");
printf("\nsegment no\t base no\tlimit \n-------\t-------");
for(i=0;i<n;i++)
{
printf("\n\n%d\t\t",i);
scanf("%d",&segment[i][0]);
scanf("%d",&segment[i][1]);
}
printf("\n\nEnter the logical address(i.e,segment no & offset):");
scanf("%d%d",&sno,&off);
if(segment[sno][0]==-1)
printf("\n\nThe required segment is not available in Memory");
else
if(off<segment[sno][1])
printf("\n\nPhysical address(i.e,base no & offset):%d,%d",segment[sno][0],off);
else
printf("\noffset is greater than limit of segment:Addressing error");
return 1;
}
OUTPUT:
cse501@vignan:~/OSprograms> vi 6bsegmentation.c
cse501@vignan:~/OSprograms> gcc -o op6b 6bsegmentation.c
cse501@vignan:~/OSprograms> ./op6b
Enter the no of segments in memory 2
Enter the segment table
Enter segment number:0
Enter base value:2000
Enter value for limit:100
Enter segment number:1
Enter base value:2500
Enter value for limit:100
Enter the logical address(ie. segmentation number & offset)
Enter offset:90
Enter segment number:1
Address in physical memory 2500
Enter value for limit:100
Enter segment number:2
Enter base value:2500
Enter value for limit:100
Enter segmentation number:-1
Enter offset:90
Enter segment number:2
Address in physical memory 2590

You might also like