os lab manual (1)
os lab manual (1)
OPERATING
SYSTEMS
Computer Science & Engineering | Information
Technology
1
SYLLABUS
Prerequisites:
Co-requisite:
• A course on “Operating Systems”.
Course Objectives:
• To provide an understanding of the design aspects of operating system
concepts throughsimulation
• 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, deadlockmanagement, 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 usingUNIX/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 managementtechniques
a) Paging b) Segmentation
TEXT BOOKS: 2
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
3
WEEK-1
In the "First come first serve" scheduling algorithm, as the name suggests,
the process which arrives first, gets executed first, or we can say that the process
which requests the CPU first, gets the CPU allocated first.
First Come First Serve, is just like FIFO(First in First out) Queue data
structure, where the data element which is added to the queue first, is the one who
leaves the queue first. This is used in Batch Systems. It's easy to understand and
implement.
OUTPUT :
Enter number of processes: 3
Enter the burst time of 3 process
24
3
3
Enter the arrival time of 3 process
0
0
0
----------------------------------
PN Bt Ct Tat Wt
----------------------------------
0 24 24 24 0
1 3 27 27 24
2 3 30 30 27
----------------------------------
5
Avgwt = 17.00 Avgtat = 27.00
-----------------------------------
}
printf("------------------------------\n");
printf(" Avgwt = %.2f\tAvgtat = %.2f\n",avgwt,avgtat);
printf("---------------------------- \n");
getch();
}
OUTPUT :
7
Shortest Remaining Time First(SRTF) CPU Scheduling Algorithm
This Algorithm is the preemptive version of SJF scheduling. In SRTF, the execution of the
process can be stopped after certain amount of time. At the arrival of every process, the short term
scheduler schedules the process with the least remaining burst time among the list of available
processes and the running process.
Once all the processes are available in the ready queue, No preemption will be done and
the algorithm will work as SJF scheduling. The context of the process is saved in the Process
Control Block when the process is removed from the execution and the next process is scheduled.
This PCB is accessed on the next execution of this process.
#include <stdio.h>
int main()
{
int arrival_time[10], burst_time[10], temp[10];
int i, smallest, count = 0, time, n;
double wait_time = 0, turnaround_time = 0, end;
float average_waiting_time, average_turnaround_time;
printf("\nEnter the Total Number of Processes:");
scanf("%d", &n);
printf("\nEnter Details of %d Processes", n);
for(i = 0; i < n; i++)
{
printf("\nEnter Arrival Time:");
scanf("%d", &arrival_time[i]);
printf("\nEnter Burst Time:");
scanf("%d", &burst_time[i]);
temp[i] = burst_time[i];
}
burst_time[9] = 9999;
for(time = 0; count != n; time++)
{
smallest = 9;
for(i = 0; i < n; i++)
{
if(arrival_time[i] <= time && burst_time[i] < burst_time[smallest] && burst_time[i] > 0)
{
smallest = i;
}
}
burst_time[smallest]--;
if(burst_time[smallest] == 0)
{
count++;
8
end = time + 1;
wait_time = wait_time + end - arrival_time[smallest] - temp[smallest];
turnaround_time = turnaround_time + end - arrival_time[smallest];
}
}
average_waiting_time = wait_time / n;
average_turnaround_time = turnaround_time / n;
printf("Average Waiting Time:\t %lf\n", average_waiting_time);
printf("Average Turnaround Time:\t %lf\n", average_turnaround_time);
return 0;
}
OUTPUT :
OUTPUT:
Enter Total Number of Processes: 3
Enter Details of Process[1]
Arrival Time: 0
Burst Time: 24
Enter Details of Process[2]
Arrival Time: 0
Burst Time: 3
Enter Details of Process[3]
Arrival Time: 0
Burst Time: 3
Enter Time Quantum: 4
Process ID Burst Time Turnaround Time Waiting Time
Process[2] 3 7 4
Process[3] 3 10 7
Process[1] 24 30 6
d) PRIORITY SCHEDULING
12
In a Priority based Scheduling Algorithm in Operating Systems, every process is assigned
a Priority Number. Based on this Priority Number, the processes are executed. This scheduling
algorithm is normally very useful in real-time systems. The process having the highest priority
(1) is executed first and then priority 2, 3 and so on.
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
Turn around time for Process(n)= Completion Time - Arrival Time
Waiting time for process(n)= Turnaround time - Burst Time
Step 7: Calculate
Average waiting time = Total waiting Time / Number of process
Average Turnaround time = Total Turnaround Time / Number of process
Step 8: Stop the process.
#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];
13
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
4
5
7
8
Enter the priority of 4 process
4
3
1
2
------------------------------
Bt Ct Tat Wt
------------------------------
7 7 7 0
8 15 15 7
5 20 20 15
4 24 24 20
------------------------------
Avgwt = 10.50 Avgtat = 16.50
WEEK 2
14
Write programs using the I/O system calls of UNIX/LINUX operating system (open, read,
write, close, fcntl, seek, stat, opendir, readdir) process(fork, wait, exec, exit)
System Calls:
When a computer is turned on, the program that gets executed first is called the
``operating system.'' It controls pretty much all activity in the computer. This includes who logs
in, how disks are used, how memory is used, how the CPU is used, and how you talk with other
computers. The operating system we use is called "Unix".
The way that programs talk to the operating system is via ``system calls.'' A system call
looks like a procedure call, but it's different -- it is a request to the operating system to
perform some activity.
System Calls for I/O:
There are 5 basic system calls that Unix provides for file I/O.
1. int open(char *path, int flags [ , int mode ] );
2. int close(int fd);
3. int read(int fd, char *buf, int size);
4. int write(int fd, char *buf, int size);
5. off_t lseek(int fd, off_t offset, int whence);
Aim: C program using open, read, write, close system calls
Theory:
There are 5 basic system calls that Unix provides for file I/O.
1. Create: Used to Create a new
empty file Syntax :int creat(char
*filename, mode_t mode) filename :
name of the file which you want to
createmode : indicates permissions of
new file.
2. open: Used to Open the file for reading, writing or both.
Syntax: int open(char *path, int flags [ , int mode ] );
Path : path to file which you
want to useflags : How you
like to use
O_RDONLY: read only, O_WRONLY: write only, O_RDWR: read and write,
O_CREAT: createfile if it doesn’t exist, O_EXCL: prevent creation if it already
exists
3. close: Tells the operating system you are done with a file descriptor and Close
the file which pointed by fd.
Syntax: int
close(int fd); fd :file
descriptor
4. read: From the file indicated by the file descriptor fd, the read() function
reads cnt bytes of input into the memory area indicated by buf. A successful read()
updates the access time for thefile.
Syntax: int read(int fd, char
*buf, int size);fd: file descripter 15
buf: buffer to
read data from
cnt: length of
buffer
5. write: Writes cnt bytes from buf to the file or socket associated with fd. cnt
should not begreater than INT_MAX (defined in the limits.h header file). If cnt is
zero, write() simply returns 0without attempting any other action.
Syntax: int write(int fd, char
*buf, int size);fd: file descripter
buf: buffer to
write data to
cnt: length of
buffer
*File descriptor is integer that uniquely identifies an open file of the process.
Algorithm
1. Star the program.
2. Open a file for O_RDWR for R/W,O_CREATE for creating a file
,O_TRUNC for truncatea file.
3. Using getchar(), read the character and stored in the string[] array.
4. The string [] array is write into a file close it.
5. Then the first is opened for read only mode and read the characters and
displayed it andclose the file.
6. Stop the program.
Output:
aiml_dept@desktop-vmtw:~$ vi sample5.c
aiml_dept@desktop-vmtw:~$ gcc sample5.c
aiml_dept@desktop-vmtw:~$ ./a.out
hello welcome to vmtw
Algorithm:
1. Start the program
2. Open a file in read mode
3. Read the contents of the file
4. Use lseek to change the position of pointer in the read process
5. Stop
20
Program: #include<stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
int main()
{
int file=0;
if((file=open("testfile.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:
aiml_dept@desktop-vmtw:~$ vi testfile.txt
aiml_dept@desktop-vmtw:~$ cat testfile.txt
A system call is a mechanism that provides the interface between a process and the
operating system.
It is a programmatic method in which a computer program requests a service from the
kernel of the OS.
aiml_dept@desktop-vmtw:~$ vi sample6.c
aiml_dept@desktop-vmtw:~$ gcc sample6.c
aiml_dept@desktop-vmtw:~$ ./a.out
A system call is a �
all is a mechanism �
21
c) Aim: C program using opendir(), closedir(), readdir()
Theory:
The following are the various operations using directories
1. Creating directories.
Syntax : int mkdir(const char *pathname, mode_t mode);
2. The ‘pathname’ argument is used for the name of the directory.
3. Opening directories
Syntax : DIR *opendir(const char *name);
4. Reading directories.
Syntax: struct dirent *readdir(DIR *dirp);
5. Removing directories.
Syntax: int rmdir(const char *pathname);
6. Closing the directory.
Syntax: int closedir(DIR *dirp);
7. Getting the current working directory.
Syntax: char *getcwd(char *buf, size_t size);
Algorithm:
1. Start the program
2. Print a menu to choose the different directory operations
3. To create and remove a directory ask the user for name and create and
remove the samerespectively.
4. To open a directory check whether directory exists or not. If yes open the
directory .If itdoes not exists print an error message.
5. Finally close the opened directory.
6. Stop
Program:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<dirent.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
struct stat buf;
int exists;
DIR *d;
struct dirent *de;
d = opendir(".");
if (d == NULL)
{
fprintf(stderr, "Couldn't open \".\"\n");
exit(1); 22
}
for (de = readdir(d); de != NULL;
de = readdir(d))
{
exists = stat(de->d_name, &buf);
if (exists < 0)
{
fprintf(stderr, "%s not found\n", de->d_name);
}
else
{
printf("%s %ld\n", de->d_name, buf.st_size);
}
}
closedir(d);
return 0;
}
Output:
aiml_dept@desktop-vmtw:~$ vi sample7.c
aiml_dept@desktop-vmtw:~$ gcc sample7.c
aiml_dept@desktop-vmtw:~$ ./a.out
data 3
a1 0
a2 0
.sudo_as_admin_successful 0
sample5.c 444
.cache 4096
.bash_history 295
.config 4096
testfile.txt 204
.profile 807
sample3.c 174
.bash_logout 220
b2 0
.viminfo 8706
sample2.c 213
.bashrc 3771
sample1.c 143
sample4.c 541
b1 0
sample6.c 385
a.out 8744
.. 4096
. 4096
sample7.c 639
23
Program:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<dirent.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
char d[10]; int c,op; DIR *e; struct dirent *sd;
printf("**menu**\n1.create dir\n2.remove dir\n 3.read dir\n enter ur choice"); scanf("%d",&op);
switch(op)
{
case 1: printf("enter dir name\n"); scanf("%s",&d); c=mkdir(d,777);
if(c==1)
printf("dir is not created"); else
printf("dir is created"); break;
case 2: printf("enter dir name\n"); scanf("%s",&d); c=rmdir(d);
if(c==1)
printf("dir is not removed"); else
printf("dir is removed"); break;
case 3: printf("enter dir name to open"); scanf("%s",&d);
e=opendir(d); if(e==NULL)
printf("dir does not exist"); else
{
printf("dir exist\n"); while((sd=readdir(e))!=NULL)
printf("%s\t",sd->d_name);
}
closedir(e); break;
}
}
Output:
24
WEEK -3
Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and Prevention
a) Aim
Write a C program to simulate the Bankers Algorithm for Deadlock Avoidance.
Data structures
1. n- Number of process, m-number of resource types.
2. Available: Available[j]=k, k – instance of resource type Rj is available.
3. Max: If max [i, j]=k, Pi may request at most k instances resource Rj.
4. Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj
5. Need: If Need[I, j]=k, Pi may need k more instances of resource type Rj,
6. 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
3. Finish[i] =False
4. Need<=Work
5. If no such I exist go to step 4.
6. work=work+Allocation, Finish[i] =True;
7. If Finish [1] =True for all I, then the system is in safe state.
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 restore.
Algorithm:
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 it is 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.
25
9. Or not if we allow the request.
10. Stop the program.
#include<stdio.h>
int main ()
{
int allocated[15][15], max[15][15], need[15][15], avail[15], tres[15],
work[15], flag[15];
int pno, rno, i, j, prc, count, t, total;
count = 0;
//clrscr ();
printf ("\n Enter number of process:");
scanf ("%d", &pno);
printf ("\n Enter number of resources:");
scanf ("%d", &rno);
for (i = 1; i <= pno; i++)
{
flag[i] = 0;
}
printf ("\n Enter total numbers of each resources:");
for (i = 1; i <= rno; i++)
scanf ("%d", &tres[i]);
printf ("\n Enter Max resources for each process:");
for (i = 1; i <= pno; i++)
{
printf ("\n for process %d:", i);
for (j = 1; j <= rno; j++)
scanf ("%d", &max[i][j]);
}
printf ("\n Enter allocated resources for each process:");
for (i = 1; i <= pno; i++)
{
printf ("\n for process %d:", i);
for (j = 1; j <= rno; j++)
scanf ("%d", &allocated[i][j]);
}
printf ("\n available resources:\n");
for (j = 1; j <= rno; j++)
{
avail[j] = 0;
total = 0;
for (i = 1; i <= pno; i++)
{
total += allocated[i][j];
}
avail[j] = tres[j] - total;
26
work[j] = avail[j];
printf (" %d \t", work[j]);
}
do
{
for (i = 1; i <= pno; i++)
{
for (j = 1; j <= rno; j++)
{
need[i][j] = max[i][j] - allocated[i][j];
}
}
printf ("\n Allocated matrix Max need");
for (i = 1; i <= pno; i++)
{
printf ("\n");
for (j = 1; j <= rno; j++)
{
printf ("%4d", allocated[i][j]);
}
printf ("|");
for (j = 1; j <= rno; j++)
{
printf ("%4d", max[i][j]);
}
printf ("|");
for (j = 1; j <= rno; j++)
{
printf ("%4d", need[i][j]);
}
}
prc = 0;
for (i = 1; i <= pno; i++)
{
if (flag[i] == 0)
{
prc = i;
for (j = 1; j <= rno; j++)
{
if (work[j] < need[i][j])
{
prc = 0;
break;
}
}
}
27
if (prc != 0)
break;
}
if (prc != 0)
{
printf ("\n Process %d completed", i);
count++;
printf ("\n Available matrix:");
for (j = 1; j <= rno; j++)
{
work[j] += allocated[prc][j];
allocated[prc][j] = 0;
max[prc][j] = 0;
flag[prc] = 1;
printf (" %d", work[j]);
}
}
}
while (count != pno && prc != 0);
if (count == pno)
printf ("\nThe system is in a safe state!!");
else
printf ("\nThe system is in an unsafe state!!");
return 0;
}
Output:
28
Enter allocated resources for each process:
for process 1:0 1 0
available resources:
3 3 2
Allocated matrix Max need
0 1 0| 7 5 3| 7 4 3
2 0 0| 3 2 2| 1 2 2
3 0 2| 9 0 2| 6 0 0
2 1 1| 2 2 2| 0 1 1
0 0 2| 4 3 3| 4 3 1
Process 2 completed
Available matrix: 5 3 2
Allocated matrix Max need
0 1 0| 7 5 3| 7 4 3
0 0 0| 0 0 0| 0 0 0
3 0 2| 9 0 2| 6 0 0
2 1 1| 2 2 2| 0 1 1
0 0 2| 4 3 3| 4 3 1
Process 4 completed
Available matrix: 7 4 3
Allocated matrix Max need
0 1 0| 7 5 3| 7 4 3
0 0 0| 0 0 0| 0 0 0
3 0 2| 9 0 2| 6 0 0
0 0 0| 0 0 0| 0 0 0
0 0 2| 4 3 3| 4 3 1
Process 1 completed
Available matrix: 7 5 3
Allocated matrix Max need
0 0 0| 0 0 0| 0 0 0
0 0 0| 0 0 0| 0 0 0
3 0 2| 9 0 2| 6 0 0
0 0 0| 0 0 0| 0 0 0
0 0 2| 4 3 3| 4 3 1
Process 3 completed
Available matrix: 10 5 5
Allocated matrix Max need
29
0 0 0| 0 0 0| 0 0 0
0 0 0| 0 0 0| 0 0 0
0 0 0| 0 0 0| 0 0 0
0 0 0| 0 0 0| 0 0 0
0 0 2| 4 3 3| 4 3 1
Process 5 completed
Available matrix: 10 5 7
The system is in a safe state!!
Algorithm:
1. Start
2. Attacking Mutex condition : never grant exclusive access. but this may not be possible for
several resources.
3. Attacking preemption: not something you want to do.
4. Attacking hold and wait condition : make a process hold at the most 1 resource at a time.make
all the requests at the beginning. All or nothing policy. If you feel,retry. eg. 2- phase locking 34
5. Attacking circular wait: Order all the resources. Make sure that the requests are issued in the
correct order so that there are no cycles present in the resource graph. Resources numbered 1 ...
n. Resources can be requested only in increasing order. ie. you cannot request a resource whose
no is less than any you may be holding.
6. Stop
#include<stdio.h>
#include<conio.h>
int max[10][10],alloc[10][10],need[10][10],avail[10],i,j,p,r,finish[10]={0},flag=0;
void main( )
{
Output:
lack of preemption
32
WEEK-4
Write a C program to implement the Producer – Consumer problem using semaphores
using UNIX/LINUX system calls.
Aim: Write a C program to implement the Producer – Consumer problem using
semaphores using UNIX/LINUX system calls.
Algorithm:
1. The Semaphore mutex, full & empty are initialized.
2. In the case of producer process
3. Produce an item in to temporary variable. If there is empty space in the buffer check the mutex
value for enter into the critical section. If the mutex value is 0, allow the producer to add value in
the temporary variable to the buffer.
4. In the case of consumer process
i) It should wait if the buffer is empty
ii) If there is any item in the buffer check for mutex value, if the mutex==0, remove item from
buffer
iii) Signal the mutex value and reduce the empty value by 1.
iv) Consume the item.
5. Print the result
#include<stdio.h>
#include<stdlib.h>
int mutex = 1, full = 0, empty = 3, x = 0;
int main () {
int n;
void producer ();
void consumer ();
int wait (int);
int signal (int);
printf (" \n1.Producer\n2.Consumer\n3.Exit");
while (1)
{
printf ("\nEnter your choice:");
scanf ("%d", &n);
switch (n)
{
case 1:
if ((mutex == 1) && (empty != 0))
producer ();
else
printf ("Buffer is full!!");
break;
33
case 2:
if ((mutex == 1) && (full != 0))
consumer ();
else
printf ("Buffer is empty!!");
break;
case 3:
exit (0);
break; }
}
return 0;
}
int wait (int s)
{
return (--s);
}
int signal (int s)
{
return (++s);
}
void producer ()
{
mutex = wait (mutex);
full = signal (full);
empty = wait (empty);
x++;
printf ("\nProducer produces the item %d", x);
mutex = signal (mutex);
}
void consumer ()
{
mutex = wait (mutex);
full = wait (full);
empty = signal (empty);
printf ("\nConsumer consumes item %d", x);
x--;
mutex = signal (mutex);
}
Output:
1.Producer
2.Consumer
3.Exit
Enter your choice:1
34
Producer produces the item 1
Enter your choice:1
35
Week: 5
Write C programs to illustrate the following IPC mechanisms
ALGORITHM:
1. Start the program.
2. Declare the variables.
3. Read the choice.
4. Create a piping processing using IPC.
5. Assign the variable lengths
6. “strcpy” the message lengths.
7. To join the operation using IPC .
8. Stop the program.
36
Program : ( PIPE PROCESSING)
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MSG_LEN 64
int main()
{
int result;
int fd[2];
char message[MSG_LEN];
char recvd_msg[MSG_LEN];
result = pipe(fd);
//Creating a pipe//fd[0] isfor reading and fd[1] isfor writing
if (result < 0)
{
perror("pipe ");
exit(1);
}
strncpy(message,"Linux World!! ",MSG_LEN);
result=write(fd[1],message,strlen(message));
if (result < 0)
{
perror("write");
exit(2);
}
strncpy(message,"Understanding ",MSG_LEN);
result=write(fd[1],message,strlen(message));
if(result < 0)
{
perror("write");
exit(2);
}
strncpy(message,"Concepts of ",MSG_LEN);
result=write(fd[1],message,strlen(message));
if (result < 0)
{
perror("write");
exit(2);
}
strncpy(message,"Piping ", MSG_LEN);
result=write(fd[1],message,strlen(message));
if (result < 0){
perror("write");
exit(2);
}
37
result=read(fd[0],recvd_msg,MSG_LEN);
if (result < 0)
{
perror("read");
exit(3);
}
printf("%s\n",recvd_msg);
return 0;
}
Output:
a) FIFO
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/stat.h>
#define FIFO_FILE "MYFIFO"
int main(void)
{
FILE *fp;
char readbuf[80];
/* Create the FIFO if it does not exist */
umask(0);
mknod(FIFO_FILE, S_IFIFO|0666, 0);
while(1)
38
{
fp = fopen(FIFO_FILE, "r");
fgets(readbuf, 80, fp);
printf("Received string: %s\n", readbuf);
fclose(fp);
}
return(0);
}
Output:
ithod@DESKTOP-0SCES8B:~$ vi sample1.c
ithod@DESKTOP-0SCES8B:~$ gcc sample1.c
ithod@DESKTOP-0SCES8B:~$ ./a.out
hello
FIFO
gfjdsjdfkdsghjghfg
#include <stdio.h>
#include <stdlib.h>
#define FIFO_FILE "MYFIFO"
int main(int argc, char *argv[])
{
FILE *fp;
if ( argc != 2 ) {
printf("USAGE: fifoclient [string]\n");
exit(1);
}
if((fp = fopen(FIFO_FILE, "w")) == NULL) {
perror("fopen");
exit(1);
}
fputs(argv[1], fp);
fclose(fp);
return(0);
}
Output:
return 0;
}
Output:
ithod@DESKTOP-0SCES8B:~$ vi sample3.c
ithod@DESKTOP-0SCES8B:~$ vi write.c
ithod@DESKTOP-0SCES8B:~$ gcc write.c
write.c: In function ‘main’:
write.c:23:15: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-
Wimplicit-function-declaration]
gets(message.msg_text);
^~~~
fgets
/tmp/cc7AZsHP.o: In function `main':
write.c:(.text+0x57): warning: the `gets' function is dangerous and should not be used.
ithod@DESKTOP-0SCES8B:~$ ./a.out
Write Data : hello world
Data send is : hello world
int main()
{
shmdt(str);
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
Output:
ubuntu@ubuntu-vbox:~/Desktop/cseit$ ./smr
Data read from memory: haicsit
Week: 6
Aim: Write C programs to simulate the following memory management techniques
a) Paging
AIM: To write a C program to implement memory management using paging technique.
ALGORITHM:
Step1 : Start the program.
Step2 : Read the base address, page size, number of pages and memory unit.
Step3 : If the memory limit is less than the base address display the memory limit is less than
limit.
Step4 : Create the page table with the number of pages and page address.
Step5 : Read the page number and displacement value.
Step6 : If the page number and displacement value is valid, add the displacement value with the
address corresponding to the page number and display the result.
Step7 : Display the page is not found or displacement should be less than page size.
Step8 : Stop the program.
#include<stdio.h>
#include<conio.h>
void main()
{
int ms, ps, nop, np, rempages, i, j, x, y, pa, offset; int s[10], fno[10][20];
printf("\nEnter the memory size -- ");
scanf("%d",&ms);
printf("\nEnter the page size -- ");
scanf("%d",&ps);
42
nop = ms/ps;
printf("\nThe no. of pages available in memory are -- %d ",nop);
printf("\nEnter number of processes -- ");
scanf("%d",&np);
rempages = nop; for(i=1;i<=np;i++)
{
printf("\nEnter no. of pages required for p[%d]-- ",i);
scanf("%d",&s[i]);
if(s[i] >rempages)
{
printf("\nMemory is Full");
break;
}
rempages = rempages - s[i];
printf("\nEnter pagetable for p[%d] --- ",i);
for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);
}
printf("\nEnter Logical Address to find Physical Address ");
printf("\nEnter process no. and pagenumber and offset -- ");
scanf("%d %d %d",&x,&y, &offset);
if(x>np || y>=s[i] || offset>=ps)
printf("\nInvalid Process or Page Number or offset");
else
{
pa=fno[x][y]*ps+offset;
printf("\nThe Physical Address is -- %d",pa);
}
getch();
}
Output
Enter the memory size -- 1000
Memory is Full
Enter Logical Address to find Physical Address
Enter process no. and pagenumber and offset -- 1
43
2
6
b) Segmentation
Aim: To write a C program to implement memory management using segmentation
Algorithm:
Step1 : Start the program.
Step2 : Read the base address, number of segments, size of each segment, memory limit.
Step3 : If memory address is less than the base address display “invalid memory limit”.
Step4 : Create the segment table with the segment number and segment address and display it.
Step5 : Read the segment number and displacement.
Step6 : If the segment number and displacement is valid compute the real address and display the
same.
Step7 : Stop the program.
Program:
#include<stdio.h>
#include <stdlib.h>
struct list
{
int seg;
int base;
int limit;
struct list *next;
} *p;
void insert(struct list *q,int base,int limit,int seg)
{
if(p==NULL)
{
p=malloc(sizeof(struct list));
p->limit=limit;
p->base=base;
p->seg=seg;
p->next=NULL;
}
else
{
while(q->next!=NULL)
{
q=q->next;
printf("yes");
}
q->next=malloc(sizeof(struct list)); 44
q->next ->limit=limit;
q->next ->base=base;
q->next ->seg=seg;
q->next ->next=NULL;
}
}
int find(struct list *q,int seg)
{
while(q->seg!=seg)
{
q=q->next;
}
return q->limit;
}
void main()
{
p=NULL;
int seg,offset,limit,base,c,s,physical;
printf("Enter segment table/n");
printf("Enter -1 as segment value for termination\n");
do{
printf("Enter segment number");
scanf("%d",&seg);
if(seg!=-1)
{
printf("Enter base value:");
scanf("%d",&base);
printf("Enter value for limit:");
scanf("%d",&limit);
insert(p,base,limit,seg);
}
}
while(seg!=-1);
printf("Enter offset:");
scanf("%d",&offset);
45
printf("Enter bsegmentation number:");
scanf("%d",&seg);
c=find(p,seg);
s=search(p,seg);
if(offset<c)
{
physical=s+offset;
printf("Address in physical memory %d\n",physical);
}
else
{
printf("error");
}
}
OUTPUT:
Enter segment table
Enter
-1 as segmentation value for termination
Enter segment number:1
Enter base value:2000
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
Enter segment table
Enter
-1 as segmentation value for termination
Enter segment number:1
Enter base value:2000
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:1
46
Address in physical memory 2
47