os lab manual - R22
os lab manual - R22
II B. TECH II SEMESTER
1 1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PRINCETON INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Approved by AICTE, New Delhi & Affiliated to JNTU Hyderabad)
Chowdaryguda (V), Ghatkesar (M), Medchal-Malkajgiri(D).TS-500088
Phone: 9394544566 / 6305324412
e-mail: [email protected]
JNTUH Code(6M) CIVIL–EEE–ECE-CSE-CSE(AI&ML)-CSE(DS)-CSE(CS) EAMCET Code– PETW
VISION
The educational environment in order to develop graduates with the strong academic technical backgrounds
needed to achieve distinction in the discipline and to bring up the Institution as an Institution of Academic
excellence of International standard.
MISSION
We transform persons into personalities by the state-of-the-art infrastructure, time consciousness, quick
response and the best academic practices through assessment and advice.
CORE VALUES
Attaining global eminence, by achieving excellence in all that we do in life education and service
The educational environment in order to develop graduates with the strong academic technical
backgrounds needed to achieve distinction in the discipline and to bring up the Institution as an
Institution of Academic excellence of International standard.
MISSION
We transform persons into personalities by the state-of-the-art infrastructure, time consciousness, quick
2
DEPARTMENT OF COMPUTER SCIENCE
AND ENGINEERING
3
P[
PROGRAM OUTCOMES:
Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
PO2 problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
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
PO3 public health and safety, and the cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and research methods
PO4 including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
PO5 and IT tools including prediction and modeling to complex engineering activities with an understanding
of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
PO6 health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and sustainability: Understand the impact of the professional engineering solutions in
PO7 societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
PO8 engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader in diverse
PO9
teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the engineering
PO10 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.
Project management and finance: Demonstrate knowledge and understanding of the engineering and
PO11 management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PO12 independent and life-long learning in the broadest context of technological change.
4
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PREREQUISITES:
A course on “Programming for Problem Solving”, A course on “Computer Organization and Architecture”.
COURSE OBJECTIVES:
The objective of this lab is to get an overview to To provide an understanding of the design aspects of
operating system concepts through simulation and Introduce basic Unix commands, system call interface for
process management, interprocess communication and I/O in Unix
COURSE OUTCOMES:
1. Simulate and implement operating system concepts such as scheduling, deadlock management, file
management and memory management.
2. Able to implement C programs using Unix system calls.
5
P[
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Course Name: OS LAB Course Code: CS406PC
Year/Semester: III/II Regulation: R22
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
6
S. No List of Experiments Page No.
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
Write C programs to simulate the following memory management techniques
6 a) Paging b)Segmentation
7 Write C programs to simulate Page replacement policies a) FCFS b) LRU c)
Optimal.
7
P[
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
EXPERIMENT 1
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
8
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 2 4 6 8
----------------------------------------
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
}
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];
10
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
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]);
12
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
14
{
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@:~/OSprograms> vi 2read.c
cse501@:~/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." ) ;
}
16
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@:~/OSprograms> vi 2write.c
cse501@:~/OSprograms> gcc -o op2write 2write.c
cse501@:~/OSprograms> ./op2write
The file is now opened.
Data successfully written in file abc.c
18
}
/**
* 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@:~/OSprograms> vi 2stat.c
cse501@:~/OSprograms> gcc -o op2stat 2stat.c
cse501@:~/OSprograms> ./op2stat
Enter source file path: abc1.txt
#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
20
puts("Sorry we need exactly 2 arguments.");
return (0);
}
OUTPUT:
All files and subdirectories of current directory
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.
22
(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.
24
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;
}
}
}
}
return (0);
}
OUTPUT:
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2
26
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
28
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@:~/OSprograms> vi 5apipes.c
cse501@:~/OSprograms> vi 5apipes.c
cse501@:~/OSprograms> gcc -o op5a 5apipes.c
cse501@:~/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>
30
char mesg_text[100];
} message;
int main()
{
key_t key;
int msgid;
#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@:~/OSprograms> vi 5cmsgqw.c
cse501@:~/OSprograms> gcc -o op5cmsgqw 5cmsgqw.c
cse501@:~/OSprograms> vi 5cmsgqr.c
cse501@:~/OSprograms> gcc -o op5cmsgqr 5cmsgqr.c
cse501@:~/OSprograms> ./op5cmsgqw
Write Data : hello
Data send is : hello
cse501@vignan:~/OSprograms> ./op5cmsgqr
Data Received is : hello
32
#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;
}
OUTPUT:
cse501@:~/OSprograms> vi 5dshmread.c
cse501@:~/OSprograms> vi 5dshmwrite.c
cse501@:~/OSprograms> gcc -o op5dshmwrite 5dshmwrite.c
cse501@:~/OSprograms> gcc -o op5dshmread 5dshmread.c
cse501@:~/OSprograms> ./op5dshmwrite
Write Data : Hi
Data written in memory: Hi
cse501@:~/OSprograms> ./op5dshmread
Data read from memory: Hi
34
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@/OSprograms> vi 6apaging.c
cse501@:~/OSprograms> gcc -o op6a 6apaging.c
cse501@:~/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;
}
36
Enter segmentation number:-1
Enter offset:90
Enter segment number:2
Address in physical memory 2590