Os Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

MAHAVEER INSTITUTE OF SCIENCE &

TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

CS406PC: OPERATING SYSTEMS LAB

IT II Year II Sem. L T PC 0 0 3 1.5


Co-requisites:

● A course on “Operating Systems”.

Course Objectives:

● To provide an understanding of the design aspects of operating system concepts through

simulation

● Introduce basic Unix commands, system call interface for process management, interprocess
communication and I/O in Unix
Course Outcomes:
● Simulate and implement operating system concepts such as scheduling,
deadlock management, file management and memory management.
● Able to implement C programs using Unix system calls

LIST OF EXPERIMENTS:

1. Write C programs to simulate the following CPU Scheduling algorithms


a) FCFS b) SJF c) Round Robin d) priority
2. Write programs using the I/O system calls of UNIX/LINUX operating system
(open, read, write, close, fcntl, seek, stat, opendir, readdir)

3. Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and Prevention.
4. Write a C program to implement the Producer – Consumer problem using semaphores using
UNIX/LINUX system calls.
5. Write C programs to illustrate the following IPC mechanisms

a) Pipes b) FIFOs c) Message Queues d) Shared Memory

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


a) Paging b) Segmentation

OPERATING SYSTEMS Page 1


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

TEXT BOOKS:
1. Operating System Principles- Abraham Silberchatz, Peter B. Galvin, Greg Gagne 7th

Edition, John Wiley

2. Advanced programming in the Unix environment, W.R.Stevens, Pearson education.

REFERENCES BOOKS:
1. Operating Systems – Internals and Design Principles, William Stallings, Fifth

Edition–2005,Pearson Education/PHI

2. Operating System - A Design Approach-Crowley, TMH.

3. Modern Operating Systems, Andrew S Tanenbaum, 2nd edition, Pearson/PHI

4. UNIX Programming Environment, Kernighan and Pike, PHI/Pearson Education

5. UNIX Internals: The New Frontiers, U. Vahalia, Pearson Education

OPERATING SYSTEMS Page 2


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

VISION OF THE INSTITUTE:


To be a Centre of Excellence in technical education with research orientation and to
develop Human resources to serve the society and nation building.

MISSION OF THE INSTITUTE:


M1:To provide comprehensive technical education programmes in various disciplines
and to contribute effectively to the profession and the society.
M2: Establishing Centers of Excellence in- inter disciplinary areas which are important
and relevant to Industry and Employment with scope for research
M3: To inculcate human values and ethical practices to the graduates through co-
curricular and Extra-curricular activities.

VISION OF THE DEPARTMENT:


To impart technical education with latest art of technology with scope for research and
development and groom the students with leadership skill to suit the challenging needs
industry and society.

MISSION OF THE DEPARTMENT:


Provide contemporary technical education programs, in the field of IT and prepare for
competitive employment and higher studies.Provide comprehensive in depth knowledge
with research orientation which are important and relevant to industry, society,
environment and global needs.Organize specific programs to inculcate values and ethical
practices to the students through co-curricular and extracurricular activities.

OPERATING SYSTEMS Page 3


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

PROGRAMME EDUCATIONAL OBJECTIVES (PEO’s)


Core Capabilities/Competence: Impart profound knowledge in humanities and basic
sciences along with core engineering concepts for practical understanding & project
development.[PO’s: 1,2,3,4,5,7,8,9,10,11 and 12] [PSO’s: 1 and 2]

Career Advancement: Enrich analytical skills and Industry-based modern technical


skills in core and interdisciplinary areas for accomplishing research, higher education,
entrepreneurship and to succeed in various engineering positions globally. [PO’s:
1,2,3,4,5,6,7,8,9,10 and 12] [PSO’s: 1, 2 and 3]

3. Life-Long Learning: Infuse life-long learning, professional ethics, responsibilities


and adaptation to innovation along with effective communication skills with a
sense of social awareness. [PO’s: 1,2,3,4,5,6,7,8,9,10,11 and 12] [PSO’s: 2 and
3]

II. PROGRAMME OUTCOMES (PO’s)


1. Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems. [PEO’s: 1,2 and 3] [PSO’s: 1,2 and 3]

2. Problem analysis: Identify, formulate, review research literature, and analyze


complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences. [PEO’s:
1,2 and 3] [PSO’s: 1,2 and 3]

3. Design/development of solutions: Design solutions for complex engineering


problems and design system components or processes that meet the specified
needs with appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations. [PEO’s: 1,2 and 3] [PSO’s:
1,2 and 3]

4. Conduct investigations of complex problems: Use research-based knowledge


and research methods including design of experiments, analysis and interpretation
of data, and synthesis of the information to provide valid conclusions. [PEO’s:
1,2 and 3] [PSO’s: 1,2 and 3]

5. Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations. [PEO’s:
1,2 and 3] [PSO’s: 1,2 and 3]

OPERATING SYSTEMS Page 4


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

6. The engineer and society: Apply reasoning informed by the contextual


knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
[PEO’s: 2 and 3]

7. Environment and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development. [PEO’s: 1,2 and 3]

8. Ethics: Apply ethical principles and commit to professional ethics and


responsibilities and norms of the engineering practice. [PEO’s: 1,2 and 3]
[PSO’s: 2 and 3]

9. Individual and team work: Function effectively as an individual, and as a


member or leader in diverse teams, and in multidisciplinary settings. [PEO’s: 1,2
and 3] [PSO’s: 3]

10. Communication: Communicate effectively on complex engineering activities


with the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions. [PEO’s: 1,2 and 3]
[PSO’s: 2 and 3]

11. Project management and finance: Demonstrate knowledge and understanding


of the engineering and management principles and apply these to one’s own work,
as a memberand leader in a team, to manage projects and in multidisciplinary
environments. [PEO’s: 1 and 3] [PSO’s: 2 and 3]

12. Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of
technological change. [PEO’s: 1,2 and 3] [PSO’s: 1,2 and 3]

OPERATING SYSTEMS Page 5


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

PROGRAMME SPECIFIC OUTCOMES (PSO’s)

Use mathematical abstractions and Algorithmic design along with open source programming
tools to solve complexities involved in efficient programming.[PO:1,2,3,4 and 5] & [PEO:1
and 2]

Ensure programming & documentation skills for each individual student in relevant su
bjects i.e., C, C++, Java, DBMS, Web Technologies (Development), Linux, Data
Warehousing & Data Mining and on Testing Tools.[PO:1,2,3,4,5,10 and 11] &
[PEO:1,2 and 3]

Ensure employability and career development skills through Industry oriented mini &
major projects, internship, industry visits, seminars and workshops. [PO:6,7,8,9,10,11
and 12] & [PEO:1,2 and 3]

OPERATING SYSTEMS Page 6


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

EXPERIMENT 1

1.1 OBJECTIVE
Write a C program to simulate the following non-preemptive CPU scheduling algorithms to find turnaround
time
and waiting time for the above problem.
a) FCFS b) SJF c) Round Robin d) Priority
DESCRIPTION
Assume all the processes arrive at the same time.
FCFS CPU SCHEDULING ALGORITHM
For FCFS scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times. The
scheduling is performed on the basis of arrival time of the processes irrespective of their other parameters. Each
process will be executed according to its arrival time. Calculate the waiting time and turnaround time of each of
the processes accordingly.
SJF CPU SCHEDULING ALGORITHM
For SJF scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times. Arrange
all the jobs in order with respect to their burst times. There may be two jobs in queue with the same execution
time, and then FCFS approach is to be performed. Each process will be executed according to the length of its
burst time. Then calculate the waiting time and turnaround time of each of the processes accordingly.
ROUND ROBIN CPU SCHEDULING ALGORITHM
For round robin scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times,
and the size of the time slice. Time slices are assigned to each process in equal portions and in circular order,
handling all processes execution. This allows every process to get an equal chance. Calculate the waiting time
and turnaround time of each of the processes accordingly.
PRIORITY CPU SCHEDULING ALGORITHM
For priority scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times, and
the priorities. Arrange all the jobs in order with respect to their priorities. There may be two jobs in queue with
the same priority, and then FCFS approach is to be performed. Each process will be executed according to its
priority. Calculate the waiting time and turnaround time of each of the processes accordingly.
PROGRAM
FCFS CPU SCHEDULING ALGORITHM
#include<stdio.h>
int main()
{
int bt[20], wt[20], tat[20], i, n;
float wtavg, tatavg;
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);

OPERATING SYSTEMS Page 1


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}

printf("\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");


for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
return 0;
}

output

OPERATING SYSTEMS Page 2


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

B) SJF CPU SCHEDULING ALGORITHM

#include<stdio.h>
int main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp;
float wtavg, tatavg;
printf("\n /*****SJF****/");
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=p[i];
p[i]=p[k];
p[k]=temp;
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f\n", tatavg/n);

OPERATING SYSTEMS Page 3


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
}

OUTPUT

c)Round Robin CPU SCHEDULING ALGORITHM


#include<stdio.h>
int main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
printf("\n/**** ROUND ROBIN SCHEDULING ALGOITHM****/\n");
printf("Enter the no of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");

OPERATING SYSTEMS Page 4


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i])
max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];
att+=tat[i];
awt+=wa[i];
}

printf("\n\tPROCESS\t BURST TIME \t WAITINGTIME\tTURNAROUND TIME\n");


for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is -- %f ",awt/n);
return 0;
}

OUTPUT:

OPERATING SYSTEMS Page 5


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

d) Priority
#include<stdio.h>
int main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp;
float wtavg, tatavg;
printf("\n priority scheduling \n");
printf("\nEnter the number of processes --- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("\n Enter the Burst Time & Priority of Process %d",i);
scanf("%d %d",&bt[i], &pri[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(pri[i] > pri[k])
{
temp=p[i];

OPERATING SYSTEMS Page 6


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=pri[i];
pri[i]=pri[k];
pri[k]=temp;
}
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING TIME\tTURNAROUNDTIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]);
printf("\nAverage Waiting Time is --- %f",wtavg/n);
printf("\nAverage Turnaround Time is --- %f",tatavg/n);

}
output

OPERATING SYSTEMS Page 7


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

OPERATING SYSTEMS Page 8


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

EXPERIMENT 2

C program to illustrate I/O system Calls (open ,close ,write,read,FCNTL,SEEK)

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
main()
{
int fd[2];
char buf1[25]=”just a test\n”;
char buf2[50];
fd[0]=open(“file1”,O_RDWR);
fd[1]=open(“file2”,O_RDWR);
write(fd[0],buf1,strlen(buf1);
printf(“\n enter the text now…”);
scanf(“\n %s”,buf1);
printf(“\n cat file1 is \n hai”);
write(fd[0],buf2,sizeof(buf1));
write(fd[1],buf2,sizeof(buf2));
close(fd[0]);
}

OPERATING SYSTEMS Page 9


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

EXPERIMENT 3

Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and Prevention

a)Write a C program to simulate Bankers Algorithm for Dead Lock Avoidance.

//C program to simulate Bankers Algorithm for Dead Lock Avoidance.


#include<stdio.h>
struct file
{
int all[10];
int max[10];
int need[10];
int flag;
};
void main()
{
struct file f[10];
int fl;
int i, j, k, p, b, n, r, g, cnt=0, id, newr;
int avail[10],seq[10];

printf("Enter number of processes -- ");


scanf("%d",&n);
printf("Enter number of resources -- ");
scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("Enter details for P%d",i);
printf("\nEnter allocation\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]);
printf("Enter Max\t\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("\nEnter Available Resources\t -- \t");
for(i=0;i<r;i++)

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
scanf("%d",&avail[i]);
printf("\nEnter New Request Details -- ");
printf("\nEnter pid \t -- \t");
scanf("%d",&id);
printf("Enter Request for Resources \t -- \t");
for(i=0;i<r;i++)
{
scanf("%d",&newr);
f[id].all[i] += newr;
avail[i]=avail[i] - newr;
}
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
f[i].need[j]=f[i].max[j]-f[i].all[j];
if(f[i].need[j]<0)
f[i].need[j]=0;
}
}
cnt=0;
fl=0;
while(cnt!=n)
{
g=0;
for(j=0;j<n;j++)
{
if(f[j].flag==0)
{
b=0;
for(p=0;p<r;p++)
{
if(avail[p]>=f[j].need[p])
b=b+1;
else
b=b-1;
}
if(b==r)
{
printf("\nP%d is visited",j);
seq[fl++]=j;
f[j].flag=1;
for(k=0;k<r;k++)

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
avail[k]=avail[k]+f[j].all[k];
cnt=cnt+1;
printf("(");
for(k=0;k<r;k++)
printf("%3d",avail[k]);
printf(")");
g=1;
}
}
}
if(g==0)
{
printf("\n REQUEST NOT GRANTED -- DEADLOCK OCCURRED"); printf("\n SYSTEM
IS IN UNSAFE STATE");
printf("\nProcess\t\tAllocation\t\tMax\t\t\tNeed\n");
}

printf("\nSYSTEM IS IN SAFE STATE");


printf("\nThe Safe Sequence is -- (");
for(i=0;i<fl;i++)
printf("P%d ",seq[i]);
printf(")");
for(i=0;i<n;i++)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
printf("%6d",f[i].all[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].max[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].need[j]);
printf("\n");
}
}
Output:

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

3(B). Write a C program to simulate Bankers Algorithm for Dead Lock Prevention

//C program to simulate Bankers Algorithm for Dead Lock Prevention.

#include<stdio.h>
void 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);

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
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]]);

}
Output:

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
EXPERIMENT 4

Write a C program to implement the Producer – Consumer problem using semaphores using
UNIX/LINUX system calls

DESCRIPTION

Producer-consumer problem, is a common paradigm for cooperating processes. A producer process


produces information that is consumed by a consumer process. One solution to the producer-consumer
problem uses shared memory. To allow producer and consumer processes to run concurrently, there must be
available a buffer of items that can be filled by the producer and emptied by the consumer. This buffer will
reside in a region of memory that is shared by the producer and consumer processes. A producer can
produce one item while the consumer is consuming another item. The producer and consumer must be
synchronized, so that the consumer does not try to consume an item that has not yet been produced.
PROGRAM

#include<stdio.h>

void 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”);

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
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;

}
br
ea
k;
} } }

OUTPUT
3.
2. Ex
1. Produce Consume it
Enter your choice: 2
Buffer is
Empty
3.
2. Ex
1. Produce Consume it
Enter your choice: 1

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
Enter the value: 100
3.
2. Ex
1. Produce Consume it
Enter your choice: 2
The consumed value is
100
3.
2. Ex
1. Produce Consume it

Enter your choice: 3

EXPERIMENT 5

Write C programs to illustrate the following IPC mechanisms

a) Pipes b) FIFOs c) Message Queues d) Shared Memory

IPC through shared memory

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
Inter Process Communication through shared memory is a concept where two or more process can access the
common memory. And communication is done via this shared memory where changes made by one process can be
viewed by another process.
A total of four copies of data are required (2 read and 2 write). So, shared memory provides a way by letting two or
more processes share a memory segment. With Shared Memory the data is only copied twice – from input file into
shared memory and from shared memory to the output file.
SYSTEM CALLS USED ARE:
ftok(): is use to generate a unique key.
shmget(): int shmget(key_t,size_tsize,intshmflg); upon successful completion, shmget() returns an identifier for the
shared memory segment.
shmat(): Before you can use a shared memory segment, you have to attach yourself
to it using shmat(). void *shmat(int shmid ,void *shmaddr ,int shmflg);
shmid is shared memory id. shmaddr specifies specific address to use but we should set
it to zero and OS will automatically choose the address.
shmdt(): When you’re done with the shared memory segment, your program should
detach itself from it using shmdt(). int shmdt(void *shmaddr);
shmctl(): when you detach from shared memory,it is not destroyed. So, to destroy
shmctl() is used. shmctl(int shmid,IPC_RMID,NULL);
SHARED MEMORY FOR WRITER PROCESS
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
usingnamespacestd;

intmain()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);

// shmget returns an identifier in shmid


intshmid = shmget(key,1024,0666|IPC_CREAT);

// shmat to attach to shared memory


char*str = (char*) shmat(shmid,(void*)0,0);

cout<<"Write Data : ";


gets(str);

printf("Data written in memory: %s\n",str);

//detach from shared memory


OPERATING SYSTEMS Page
MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
shmdt(str);

return0;
}
SHARED MEMORY FOR READER PROCESS
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
usingnamespacestd;

int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);

// shmget returns an identifier in shmid


intshmid = 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);

return0;
}
Output:

Output:

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
Pipe:

Conceptually, a pipe is a connection between two processes, such that the standard output from one process
becomes the standard input of the other process. In UNIX Operating System, Pipes are useful for communication
between related processes(inter-process communication).

● Pipe is one-way communication only i.e we can use a pipe such that One process write to the pipe, and the
other process reads from the pipe. It opens a pipe, which is an area of main memory that is treated as
a “virtual file”.
● The pipe can be used by the creating process, as well as all its child processes, for reading and writing. One
process can write to this “virtual file” or pipe and another related process can read from it.
● If a process tries to read before something is written to the pipe, the process is suspended until something is
written.
● The pipe system call finds the first two available positions in the process’s open file table and allocates them
for the read and write ends of the pipe.

Syntax in C language:

int pipe(int fds[2]);

Parameters :
fd[0] will be the fd(file descriptor) for the
read end of pipe.
fd[1] will be the fd for the write end of pipe.
Returns : 0 on Success.
-1 on error.

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

// C program to illustrate pipe system call in C


#include <stdio.h>
#include <unistd.h>
#define MSGSIZE 16
char* msg1 = "hello, world #1";
char* msg2 = "hello, world #2";
char* msg3 = "hello, world #3";

intmain()
{
charinbuf[MSGSIZE];
intp[2], i;

if(pipe(p) < 0)
exit(1);

/* continued */
/* write pipe */

write(p[1], msg1, MSGSIZE);


write(p[1], msg2, MSGSIZE);
write(p[1], msg3, MSGSIZE);

for(i = 0; i < 3; i++) {


/* read pipe */
read(p[0], inbuf, MSGSIZE);
printf("% s\n", inbuf);
}
return0;
}

Output:

hello, world #1
hello, world #2
hello, world #3
IPC using Message Queues
OPERATING SYSTEMS Page
MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
A message queue is a linked list of messages stored within the kernel and identified by a message queue identifier.
A new queue is created or an existing queue opened by msgget().
New messages are added to the end of a queue by msgsnd(). Every message has a positive long integer type field, a
non-negative length, and the actual data bytes (corresponding to the length), all of which are specified to msgsnd()
when the message is added to a queue. Messages are fetched from a queue by msgrcv(). We don’t have to fetch the
messages in a first-in, first-out order. Instead, we can fetch messages based on their type field.

All processes can exchange information through access to a common system message queue. The sending process
places a message (via some (OS) message-passing module) onto a queue which can be read by another process.
Each message is given an identification or type so that processes can select the appropriate message. Process must
share a common key in order to gain access to the queue in the first place.

System calls used for message queues:

ftok(): is use to generate a unique key.

msgget(): either returns the message queue identifier for a newly created message
queue or returns the identifiers for a queue which exists with the same key value.

msgsnd(): Data is placed on to a message queue by calling msgsnd().


OPERATING SYSTEMS Page
MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

msgrcv(): messages are retrieved from a queue.

msgctl(): It performs various operations on a queue. Generally it is use to


destroy message queue.

MESSAGE QUEUE FOR WRITER PROCESS

// C Program for Message Queue (Writer Process)


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

// structure for message queue


structmesg_buffer {
longmesg_type;
charmesg_text[100];
} message;

intmain()
{
key_t key;
intmsgid;

// 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 : ");


gets(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);

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
return0; }

MESSAGE QUEUE FOR READER PROCESS

// C Program for Message Queue (Reader Process)


#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// structure for message queue
structmesg_buffer {
longmesg_type;
charmesg_text[100];
} message;

intmain()
{
key_t key;
intmsgid;

// 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);

return0;
}

Output:

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

EXPERIMENT 6

Write C programs to simulate the following memory management techniques


a) Paging b) Segmentation

(A)C programs to simulate the Paging techniqueof memory management


#include <stdio.h>
struct pstruct

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
{
int fno;
int pbit;
}ptable[10];
int pmsize,lmsize,psize,frame,page,ftable[20],frameno;
void info()
{
printf("\nMEMORY MANAGEMENT USING PAGING");
printf("\nEnter the Size of Physical memory: ");
scanf("%d",&pmsize);
printf("\n\nEnter the size of Logical memory: ");
scanf("%d",&lmsize);
printf("\n\nEnter the partition size: ");
scanf("%d",&psize);
frame = (int) pmsize/psize;
page = (int) lmsize/psize;
printf("\nThe physical memory is divided into %d no.of frames\n",frame);
printf("\nThe Logical memory is divided into %d no.of pages",page);
}
void assign()
{
int i;
for (i=0;i<page;i++)
{
ptable[i].fno = -1;
ptable[i].pbit= -1;
}
for(i=0; i<frame;i++)
ftable[i] = -1;
for (i=0;i<page;i++)
{
printf("\nEnter the Frame number where page %d must be placed: ",i);
scanf("%d",&frameno);
ftable[frameno] = i;
if(ptable[i].pbit == -1)
{
ptable[i].fno = frameno;
ptable[i].pbit = 1;
}
}
printf("\nPAGE TABLE\n\n");
printf("PageAddress FrameNo. PresenceBit\n\n");
for (i=0;i<page;i++)

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
printf("%d\t\t%d\t\t%d\n",i,ptable[i].fno,ptable[i].pbit);
printf("\n\tFRAME TABLE\n");
printf("FrameAddress PageNo\n");
for(i=0;i<frame;i++)
printf("%d\t\t%d\n",i,ftable[i]);
}
void cphyaddr()
{
int laddr,paddr,disp,phyaddr,baddr;
printf("\n\n\tProcess to create the Physical Address\n\n");
printf("\nEnter the Base Address: ");
scanf("%d",&baddr);
printf("\nEnter theLogical Address: ");
scanf("%d",&laddr);
paddr = laddr / psize;
disp = laddr % psize;
if(ptable[paddr].pbit == 1 )
{
phyaddr = baddr + (ptable[paddr].fno*psize) + disp;
printf("\nThe Physical Address where the instruction present: %d",phyaddr);
}
else
printf("\nThe Physical Address where the instruction present: is not available");
}
void main()
{
//clrscr();
info();
assign();
cphyaddr();
//getch();
}

output

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

6)(B)C programs to simulate the segmentation techniqueof memory management.

#include <stdio.h>
//#include <conio.h>
#include <math.h>
#include<stdlib.h>

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
int sost;
void gstinfo();
void ptladdr();
struct segtab
{
int sno;
int baddr;
int limit;
int val[10];
}st[10];
void gstinfo()
{
int i,j;
printf("\n\tEnter the size of the segment table: ");
scanf("%d",&sost);
for(i=1;i<=sost;i++)
{
printf("\n\tEnter the information about segment: %d",i);
st[i].sno = i;
printf("\n\tEnter the base Address: ");
scanf("%d",&st[i].baddr);
printf("\n\tEnter the Limit: ");
scanf("%d",&st[i].limit);
for(j=0;j<st[i].limit;j++)
{
printf("Enter the %d address Value: ",(st[i].baddr + j));
scanf("%d",&st[i].val[j]);
}
}
}
void ptladdr()
{
int i,swd,d=0,n,s,disp,paddr;
//clrscr();
printf("\n\n\t\t\t SEGMENT TABLE \n\n");
printf("\n\t SEG.NO\tBASE ADDRESS\t LIMIT \n\n");
for(i=1;i<=sost;i++)
printf("\t\t%d \t\t%d\t\t%d\n\n",st[i].sno,st[i].baddr,st[i].limit);
printf("\n\nEnter the logical Address: ");
scanf("%d",&swd);
n=swd;
while (n != 0)
{

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.
n=n/10;
d++;
}
s = swd/pow(10,d-1);
disp = swd%(int)pow(10,d-1);
if(s<=sost)
{
if(disp < st[s].limit)
{
paddr = st[s].baddr + disp;
printf("\n\t\tLogical Address is: %d",swd);
printf("\n\t\tMapped Physical address is: %d",paddr);
printf("\n\tThe value is: %d",( st[s].val[disp] ) );
}
else
printf("\n\t\tLimit of segment %d is high\n\n",s);
}
else
printf("\n\t\tInvalid Segment Address \n");
}
void main()
{
char ch;
gstinfo();
do
{
ptladdr();
printf("\n\t Do U want to Continue(Y/N)");
scanf("%c",&ch);
}while (ch == 'Y' || ch == 'y' );
}
Output

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

OPERATING SYSTEMS Page


MAHAVEER INSTITUTE OF SCIENCE &
TECHNOLOGY
( Approved by AICTE, Affiliated to JNTU, Hyd) Vyasapuri,
Bandlaguda, Post : Keshavgiri, Hyderabad - 500 005.

OPERATING SYSTEMS Page

You might also like