Vous êtes sur la page 1sur 76

CS8461-Operating systems Lab Department of IT 2019-2020

CS8461 OPERATING SYSTEMS LABORATORY LTPC 0042

OBJECTIVES

 To learn Unix commands and shell programming


 To implement various CPU Scheduling Algorithms
 To implement Process Creation and Inter Process Communication.
 To implement Deadlock Avoidance and Deadlock Detection Algorithms
 To implement Page Replacement Algorithms
 To implement File Organization and File Allocation Strategies

LIST OF EXPERIMENTS

1. Basics of UNIX commands


2. Write programs using the following system calls of UNIX operating system fork, exec, getpid, exit, wait,
close, stat, opendir, readdir
3. Write C programs to simulate UNIX commands like cp, ls, grep, etc.
4. Shell Programming
5. Write C programs to implement the various CPU Scheduling Algorithms
6. Implementation of Semaphores
7. Implementation of Shared memory and IPC
8. Bankers Algorithm for Deadlock Avoidance
9. Implementation of Deadlock Detection Algorithm
10. Write C program to implement Threading & Synchronization Applications
11. Implementation of the following Memory Allocation Methods for fixed partition
a) First Fit b) Worst Fit c) Best Fit
12. Implementation of Paging Technique of Memory Management
13. Implementation of the following Page Replacement Algorithms
a) FIFO b) LRU c) LFU
14. Implementation of the various File Organization Techniques
15. Implementation of the following File Allocation Strategies
a) Sequential b) Indexed c) Linked
TOTAL: 60 PERIODS
OUTCOMES:
 At the end of the course, the student should be able to
 Compare the performance of various CPU Scheduling Algorithms
 Implement Deadlock avoidance and Detection Algorithms
 Implement Semaphores
 Create processes and implement IPC
 Analyze the performance of the various Page Replacement Algorithms
 Implement File Organization and File Allocation Strategies

St.Joseph’s College of Engineering ISO 9001:2008


1
CS8461-Operating systems Lab Department of IT 2019-2020

LIST OF EXPERIMENTS

OPERATING SYSTEMS LAB

SEM/YEAR: IV SEM & II YEAR BRANCH: IT

NAME OF THE PROGRAM PAGE


S.NO
NO

1. Basics of UNIX commands.

2. UNIX system calls implementation

3. Simulation of UNIX commands

4. Shell Programming

Implement the following CPU scheduling algorithms


5. a)FCFS b)SJF c) Priority d)Round Robin

6. Implement Semaphores

7. Implement Shared memory and IPC

8. Implement Bankers Algorithm for Dead Lock Avoidance

9. Implement an Algorithm for Dead Lock Detection

10. Implement Threading & Synchronization Applications

Implementation of the following Memory Allocation Methods for fixed


11. partition a) First Fit b) Best Fit c)Worst Fit

12. Implement Paging Technique of memory management

Implement all page replacement algorithms


13.
a) FIFO b) LRU c)LFU

14. Implement all File Organization Techniques

a) Singleall
15. Implement level
file directory
allocation strategies

b)a)Two level
Contiguous
16. Implement Segmentation Technique of memory management
b) Linked
c)c)Hierarchical
Indexed

d) DAG

St.Joseph’s College of Engineering ISO 9001:2008


2
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 1 Basics of UNIX commands.

1. Calendar Command:
[IT@it clab]$ cal 11 2018
November 2018
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 22 29 30 31

2. Date command:
[IT@it clab]$ date
Wed Oct 21 12:45:25 IST 2018
[IT@it clab]$ date +%m
10

3.Who command:
[IT@it ~]$ who
IT tty5 2018-10-21 12:50
IT pts/1 2018-10-21 10:50 (197.168.1.5)
karthi pts/2 2018-10-21 10:51 (197.168.1.6)

4.Who am I command:

[IT@it ~]$ whoami


IT

5.Finger Command:
[IT@it ~]$ finger
Login Name Tty Idle Login Time Office Office Phone
karthi pts/2 29 Oct 22 12:53 (197.168.1.6)
IT tty5 31 Oct 22 12:52
IT pts/1 Oct 22 12:55 (197.168.1.5)

6.Help command:
To display the help information about a particular command.
[IT@it clab]$ man clear
clear - clear the terminal screen

7.Clear Command:
To clear the screen.
[IT@it clab]$ clear

8. ID command:
To display the user id and group id information about a user. i.e. user identity.
[IT@it clab]$ id
uid=835(IT) gid=835(IT) groups=835(IT) context=user_u:system_r:unconfined_t

9. write command:

St.Joseph’s College of Engineering ISO 9001:2008


3
CS8461-Operating systems Lab Department of IT 2019-2020

Send message to another user.


[IT@it clab]$ write IT
hru
10. echo command:
Display a line of text.
[IT@it clab]$ echo SJCE
SJCE

11. tty command:


print the file name of the terminal connected to standard input

[IT@it clab]$ tty


/dev/pts/5
12. Changing Password:

[IT@it clab]$ passwd - update a user’s authentication tokens(s)


Changing password for user IT.
Changing password for IT
(current) UNIX password:
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.

FILE MANIPULATION COMMANDS

1.Create a file:

[IT@it ~]$ vi f1.c


[IT@it ~]$ vi f2.c

2.Head Command:
Displays the initial part of the text file. By default, it displays the first 10 lines of a file.

[IT@it clab]$ head -1 f3.txt


Hi this is Unix Lab

3.Tail command:
Displays the last part of he text file. By default, it displays the last 10 lines of a file.
[IT@it clab]$ tail -1 f3.txt
I am studying B.Tech IT in SJCE.

4.List information about files and directories


[IT@it ~]$ ls
f1.c f2.c f3.txt f4.txt ITal

5.Copy a file:
[IT@it ~]$ cp f1.c f5.c
[IT@it ~]$ ls
f1.c f2.c f3.txt f4.txt f5.c ITal

St.Joseph’s College of Engineering ISO 9001:2008


4
CS8461-Operating systems Lab Department of IT 2019-2020

6.Move or rename a file:


[IT@it ~]$ mv f1.c f4.c
[IT@it ~]$ ls
f2.c f3.txt f4.txt f5.c f4.c ITal
[IT@it ~]$

7.Remove a file:
[IT@it ~]$ rm f3.txt
[IT@it ~]$ ls
f2.c f4.txt f5.c f4.c ITal
[IT@it ~]$

8.Change the access permission of a file:


[IT@it ~]$ chmod 777 f2.c
-rwxrwxrwx 1 IT IT 52 Oct 29 11:31 f2.c

9.Display the contents of a file onto screen:


[IT@it ~]$ cat f4.c
India is good country

10.Word count command:


It is used to count the number of lines,words and characters in a file.
[IT@it clab]$ wc f1.txt
8 26 150 f4.txt

11.Find Command:
It is used to locate files in a directory and its subdirectories.
[IT@it clab]$ find
.
./1.c
./asd.bak
./f1.txt
./file_copy.c
./f2.c
./a.out

12. Comparing files:


compare two files
[IT@it clab]$ cmp f1 f2 -
f1 f2 differ: byte 3, line 2

13. Differentiating Files:


find differences between two files
[IT@it clab]$ diff f1 f2
3c2
< I am
---
> IT

St.Joseph’s College of Engineering ISO 9001:2008


5
CS8461-Operating systems Lab Department of IT 2019-2020

14. Touch Command:


change file timestamps
[IT@it clab]$ ls -l f2
-rw-rw-r-- 1 IT IT 6 Oct 29 09:50 f2

[IT@it clab]$ touch f2


[IT@it clab]$ ls -l f2
-rw-rw-r-- 1 IT IT 6 Oct 29 09:53 f2

DIRECTORY COMMANDS
1. Create a directory:
[IT@it ~]$ mkdir chem.

2.List all directories (including .(dot) entries in the long listing.)


[IT@it ~]$ ls -la
total 104
drwx------ 4 IT IT 4096 Oct 29 11:31 .
drwxr-xr-x 17 root root 4096 Oct 29 11:52 ..
-rw------- 1 IT IT 3 Oct 29 10:55 .IT_history
-rw-r--r-- 1 IT IT 24 Oct 29 10:51 .IT_logout

3. Change from one directory to another:


[IT@it ~]$ cd ITal
[IT@it ITal]$

4. Display the full path of the current working directory:


[IT@it ]$ pwd
/home/IT/ITal.

5. Remove a directory:
[IT@it ~]$ rmdir ITal
[IT@it ~]$ ls
f1.c f2.c f3.txt f4.txt f4.c f5.c

6.Change the owner of a specified file:


Only the super-user can change this.
[root@it ~]$chown IT f2.c

7.Change the group of a file:


Only the super-user can change this. It changes the group-id of the file o a group called ‘IT’ .
[root@it ~]$chgrp IT f2.c

8.Link Command:
make link between files
[IT@it clab]$ ls
f1.c f2.c f4.c f5.c f3.txt f4.txt IT
[IT@it clab]$ ln -t IT f5.c
[IT@it clab]$ cd IT
[IT@it dma]$ ls
F5.c

St.Joseph’s College of Engineering ISO 9001:2008


6
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 2 UNIX SYSTEM CALLS IMPLEMENTATION

AIM:
To write a ‘C’ program for implementing OS system calls fork, exec, getpid, exit, wait, close,
stat, opendir, readdir.

ALGORITHM:
1. Start
2. Create process using fork system call.
3. Check the fork() return value to ensure successful process creation.
4. Display the parent and child pid.
5. Stop.

PROGRAM

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

int main()
{
int pid,pid1,pid2;
pid=fork();
if(pid==-1)
{
printf(“ERROR IN PROCESS CREATION \n”);
exit(1);
}
if(pid!=0)
{
pid1=getpid();
printf(“\n The Parent Process ID is %d\n”, pid1);
}
else
{
pid2=getpid();
printf(“\n The Child Process ID is %d\n”, pid2);
}
}

OUTPUT
The Child Process ID is 8640

The Parent Process ID is 8644

St.Joseph’s College of Engineering ISO 9001:2008


7
CS8461-Operating systems Lab Department of IT 2019-2020

ALGORITHM:
1. Start
2. Input directory name to opendir and readdir system call to open and read contents from
directory.
3. Use exit system call if directory not exists.
4. Close directory after reading using closedir()
5. Stop.

#include<stdio.h>
#include<dirent.h>
struct dirent *dptr;
int main(int argc, char *argv[])
{
char buff[100];
DIR *dirp;
printf(“\n\n ENTER DIRECTORY NAME:”);
scanf(“%s”, buff);
if((dirp=opendir(buff))==NULL)
{
printf(“The given directory does not exist”);
exit(1);
}
while(dptr=readdir(dirp))
{
printf(“%s\n”,dptr->d_name);
}
closedir(dirp);
}

OUTPUT
ENTER THE DIRECTORY NAME: UNITS

CHAP1.C

CHAP2.C

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


8
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 3 SIMULATION OF UNIX COMMANDS

AIM:
To write a ‘C’ program for implementing OS system calls fork, exec, getpid, exit, wait, close,
stat, opendir, readdir.

ALGORITHM:
1. Start
2. Input directory name to opendir and readdir system call to open and read contents from directory
3. Display the file names inside directory.
4. Stop.

PROGRAM

#include<stdio.h>
#include<dirent.h>
main(int argc, char **argv)
{
DIR *dp;
struct dirent *link;
dp=opendir(argv[1]);
printf(“\n Contents of the directory %s are \n”, argv[1]);
while((link=readdir(dp))!=0)
printf(“%s”,link->d_name);
closedir(dp);
}

OUTPUT
Contents of the directory OS are
Priority.c
Robin.c
Copy

ALGORITHM:
1. Start
2. Input file name and word to be searched.
3. Use fopen to open file in read mode.
4. Use fgets to read each string from file.
5. Find the occurrences of the given word in a file using strstr() string handling function.
6. Stop.

PROGRAM

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 1024
void usage()
{

St.Joseph’s College of Engineering ISO 9001:2008


9
CS8461-Operating systems Lab Department of IT 2019-2020

printf(“usage:\t. /a.out filename word \n “);


}
int main(int argc, char *argv[])
{
FILE *fp;
char fline[max];
char *newline;
int count=0;
int occurrences=0;
if(argc!=3)
{
usage();
exit(1);
}
if(!(fp=fopen(argv[1],”r”)))
{
printf(“grep: couldnot open file : %s \n”,argv[1]);
exit(1);
}
while(fgets(fline,max,fp)!=NULL)
{
count++;
if(newline=strchr(fline, ‘\n’))
*newline=’\0’;
if(strstr(fline,argv[2])!=NULL)
{
printf(“%s: %d %s \n”, argv[1],count, fline);
occurrences++;
}
}
}

OUTPUT

Runtime input : filename , word to be searched

//file name // line number //searched word

Sample.txt 2 apple

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


10
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 4 SHELL PROGRAMMING

LARGEST OF N NUMBERS
AIM:
To write a shell program to find largest of n numbers.
ALGORITHM:
1. Input the total number of elements (n) .
2. Let i=0
3. Read the elements one by one in an array a$i .
4. Initialize large=0 .
5. Using a for loop, do the following for all elements in the array:
Let temp=a$i ie. Assign the array element to temp.
If temp greater than large, then reassign large=temp
6. large displays the largest of all elements.
7. Stop.
PROGRAM:
echo "Enter the total number of elements"
read n
echo "Enter the elements One by One"
i=0
for((i=0 ; i<$n ; i++))
do
read a$i
done
large=0
for((i=0 ; i<$n ; i++))
do
((temp=a$i))
if (($temp>$large))
then
((large=$temp))
fi
done
echo "The largest of all the elements is: $large"
OUTPUT:
[IT@it ~]$ sh 2C.sh
Enter the total number of elements
4
Enter the elements one by one
20
25
50
10
The largest of all the elements is: 50

St.Joseph’s College of Engineering ISO 9001:2008


11
CS8461-Operating systems Lab Department of IT 2019-2020

IMPLEMENT UNIX COMMANDS USING CASE


AIM:
To write a shell program using case…esac to execute unix commands.
ALGORITHM:
1. Get the choice from the user.
2. List the choices for date command, list of users logged in and name of the home directory.
3. Date command displays today’s date.
4. Who command displays the users who have logged in.
5. $Home command is used to display the home directory.
6. Depending upon the choice, any one of the above command is executed using case…esac.
7. Stop.
PROGRAM:
while true
do
echo "Enter your choice:"
echo "Enter w to quit"
echo "Menu"
echo "1.Today's date"
echo "2.List of users logged in"
echo "3.Name of the home directory"
read choice
case $choice in
1) date;;
2) who;;
3) echo "Home directory is $HOME";;
w)break;;
*)echo "Invalid choice"
esac
done
OUTPUT:
[IT@it~]$ sh 2e.sh
Enter your choice: Enter w to quit
Menu
1.Today's date
2.List of users logged in
3.Name of the home directory
1
Wed OCT 30 10:45:31 IST 2018
Enter your choice:
Enter w to quit
2
IT pts/1 2018-1-3 10:19 (197.168.1.1)
Enter your choice:
Enter w to quit
3
Home directory is /home/IT
Enter your choice:
Enter w to quit
W
RESULT

St.Joseph’s College of Engineering ISO 9001:2008


12
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 5A FCFS SCHEDULING

AIM:
To write a ‘C’ program to implement FCFS Scheduling.

ALGORITHM:
1. Start.
2. Include the header files for simulating FCFS scheme.
3. Declare the variables to calculate the essential aspects of FCFS.
4. Initially get the process time, arrival time and burst time.
5. Swap all the processes in such a way that they are arranged in FCFS order.
6. Prepare the gantt chart for each process so that their waiting time, turn around time is calculated.
7. Calculate the average waiting time and average turn around time and display the result.
8. Stop

// FCFS SCHEDULING ALGORITHM

PROGRAM:
#include<stdio.h>
void main()
{
int i,n,br[10],wt[10],wat[10],tr[10],ttr=0,twt=0,twat=0;
float awat,atur;
printf("Enter no. of process :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the burst time for process %d: ",(i+1));
scanf("%d",&br[i]);
}
printf("\nPROCESS\tBURST TIME\tWAITING TIME\tTURN AROUND TIME\n");
wt[0]=0;
for(i=0;i<n;i++)
{
wt[i+1]=wt[i]+br[i];
tr[i]=wt[i]+br[i];
printf("\n%d\t\t%d\t\t%d\t\t%d\n",i+1,br[i],wt[i],tr[i]);
}
for(i=0;i<n;i++)
{
ttr=ttr+tr[i];
twat=twat+wt[i];//wat i changed to wt
}
printf("\nGAANT CHART\n\n");
for(i=0;i<n;i++)
{
printf("--------");
}
printf("\n");
for(i=0;i<n;i++)
{

St.Joseph’s College of Engineering ISO 9001:2008


13
CS8461-Operating systems Lab Department of IT 2019-2020

printf(" P%d |",i+1);


}
printf("\n");
for(i=0;i<n;i++)
{
printf("--------");
}
printf("\n");
for(i=0;i<=n;i++)
{
printf("%d\t",wt[i]);
}
awat=(float)twat/n;
atur=(float)ttr/n;
printf("\n\nTotal waiting time :%d",twat);
printf("\nTotal turn around time :%d",ttr);
printf("\n\nAverage waiting time :%.2f",awat);
printf("\nAverage turn around time :%.2f\n",atur);
}

OUTPUT
[IT@localhost ~]$ ./a.out
Enter no. of process :3
Enter the burst time for process 1: 1
Enter the burst time for process 2: 4
Enter the burst time for process 3: 5
PROCESS BURST TIME WAITING TIME TURN AROUND TIME

1 1 0 1
2 4 1 5
3 5 5 10
GAANT CHART
-------------------------
|p1 |p2 |p3 |
-------------------------
0 1 5 10

Total waiting time :6


Total turn around time :16
Average waiting time :2.00
Average turn around time :5.33

RESULT:

St.Joseph’s College of Engineering ISO 9001:2008


14
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 5B SJF SCHEDULING

AIM:
To write a ‘C’ program to implement SJF Scheduling.
ALGORITHM:
1. Include the header files for simulating SJF scheme.
2. Declare the variables to calculate the essential aspects of SJF.
3. Initially get the process time and burst time.
4. Swap all the processes in such a way that they are arranged in shortest job first (SJF) order.
5. Prepare the gantt chart for each process so that their waiting time, turn around time is calculated.
6. Calculate the average waiting time and average turn around time and display the result.
// SJF SCHEDULING ALGORITHM
PROGRAM:
#include<stdio.h>
void main()
{
int i,j,k,n,p[10],br[10],wt[10],tr[10],ttr=0,twt=0,t;
float awat,atur;
printf("\nEnter no. of process :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the burst time for process %d: ",(i+1));
scanf("%d",&br[i]);
p[i]=i+1;
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(br[i]>br[j])
{
t=br[i];
br[i]=br[j];
br[j]=t;
t=p[i];
p[i]=p[j];
p[j]=t;
}}}
printf("\nPROCESS\tBURST TIME \t WAITING TIME \t TURN AROUND TIME\n");
wt[0]=0;
for(i=0;i<n;i++)
{
wt[i+1]=wt[i]+br[i];
tr[i]=wt[i]+br[i];
}
for(i=0;i<n;i++)
{
ttr=ttr+tr[i];
twt=twt+wt[i];
} for(i=0;i<n;i++) { printf("\n%d\t\t%d\t\t%d\t\t%d\n",p[i],br[i],wt[i],tr[i]);

St.Joseph’s College of Engineering ISO 9001:2008


15
CS8461-Operating systems Lab Department of IT 2019-2020

} printf("\nGAANT CHART\n\n");
for(i=0;i<n;i++)
{
printf("--------");
}
printf("\n");
for(i=0;i<n;i++)
{
printf(" P%d |",p[i]);
}
printf("\n");
for(i=0;i<n;i++)
{
printf("--------");
}
printf("\n");
for(i=0;i<=n;i++)
{
printf("%d\t",wt[i]);
}
awat=(float)twt/n;
atur=(float)ttr/n;
printf("\nTotal waiting time :%d\n",twt);
printf("\nTotal turnaround time :%d\n",ttr);
printf("\nAverage waiting time :%.2f\n",awat);
printf("\nAverage turn around time :%.2f\n",atur);
}
OUTPUT
[IT@localhost ~]$ ./a.out
[IT@localhost~]$ gcc sjf.c
[IT@localhost~]$ ./a.out
Enter no. of process :3
Enter the burst time for process 1: 3
Enter the burst time for process 2: 2
Enter the burst time for process 3: 1
PROCESS BURST TIME WAITING TIME TURN AROUND TIME
3 1 0 1
2 2 1 3
1 3 3 6
GAANT CHART
------------------------
| P3 | P2 | P1 |
------------------------
0 1 3 6
Total waiting time :4
Total turnaround time :10
Average waiting time :1.33
Average turn around time :3.33
RESULT:

St.Joseph’s College of Engineering ISO 9001:2008


16
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 5C PRIORITY SCHEDULING

AIM:
To write a ‘C’ program to implement PRIORITY Scheduling.

ALGORITHM:
1. Start
2. Include the header files for simulating priority scheme.
3. Declare the variables to calculate the essential aspects of priority scheme.
4. Initially get the process time, arrival time and burst time along with their priorities.
5. Execute the process by referring to their priority values.
6. Prepare the gantt chart for each process so that their waiting time, turn around time is calculated.
7. Calculate the average waiting time and average turn around time and display the result.
8. Stop.

// PRIORITY SCHEDULING ALGORITHM


PROGRAM:
#include<stdio.h>
void main()
{
int i,j,k,n,p[10],pri[10],bur[10],wat[10], tur[10],ttur=0,twat=0,t;
float awat,atur;
printf("\nEnter no. of process :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the burst time for process %d: ",(i+1));
scanf("%d",&bur[i]);
p[i]=i+1;
}
for(i=0;i<n;i++)
{
printf("\nEnter the priority for process %d: ",(i+1));
scanf("%d",&pri[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(pri[i]>pri[j])
{
t=bur[i];
bur[i]=bur[j];
bur[j]=t;
t=p[i];
p[i]=p[j];
p[j]=t;
t=pri[i];
pri[i]=pri[j];
pri[j]=t;
}}}

St.Joseph’s College of Engineering ISO 9001:2008


17
CS8461-Operating systems Lab Department of IT 2019-2020

printf("\nPROCESS\tBURST TIME \t PRIORITY \t WAITING TIME \tTURNAROUND TIME\n");


wat[0]=0;
for(i=0;i<n;i++)
{
wat[i+1]=wat[i]+bur[i];
tur[i]=wat[i]+bur[i];
}
for(i=0;i<n;i++)
{
ttur=ttur+tur[i];
twat=twat+wat[i];
}
for(i=0;i<n;i++)
{
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d\n",p[i],bur[i],pri[i],wat[i],tur[i]);
}
printf("\nGAANT CHART\n\n");
for(i=0;i<n;i++)
{
printf("--------");
}
printf("\n");
for(i=0;i<n;i++)
{
printf(" P%d |",p[i]);
}
printf("\n");
for(i=0;i<n;i++)
{
printf("--------");
}
printf("\n");
for(i=0;i<=n;i++)
{
printf("%d\t",wat[i]);
}
awat=(float)twat/n;
atur=(float)ttur/n;
printf("\nTotal waiting time :%d\n",twat);
printf("\nTotal turnaround time :%d\n",ttur);
printf("\nAverage waiting time :%.2f\n",awat);
printf("\nAverage turn around time :%.2f\n",atur);
}

St.Joseph’s College of Engineering ISO 9001:2008


18
CS8461-Operating systems Lab Department of IT 2019-2020

OUTPUT
[IT@localhost~]$ gcc prior.c
[IT@localhost~]$ ./a.out
Enter no. of process :4
Enter the burst time for process 1: 8
Enter the burst time for process 2: 6
Enter the burst time for process 3: 4
Enter the burst time for process 4: 5
Enter the priority for process 1: 3
Enter the priority for process 2: 1
Enter the priority for process 3: 2
Enter the priority for process 4: 4
PROCESS BURST TIME PRIORITY WAITING TIME TURNAROUND TIME
2 6 1 0 6
3 4 2 6 10
1 8 3 10 18
4 5 4 18 23
GAANT CHART
--------------------------------
P2 | P3 | P1 | P4 |
--------------------------------
0 6 10 18 23
Total waiting time :34
Total turnaround time :57
Average waiting time :8.50
Average turn around time :14.25

RESULT:

St.Joseph’s College of Engineering ISO 9001:2008


19
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 5D ROUND ROBIN SCHEDULING


AIM:
To write a ‘C’ program to implement ROUND ROBIN Scheduling.
ALGORITHM:
1. Include the header files for simulating ROUND ROBIN scheduling scheme.
2. Declare the variables to calculate the essential aspects of ROUND ROBIN.
3. Initially get the time slice along with process time and burst time.
4. Start from the 1st process and execute it for the given time slice and move to 2nd process and so on till
all process gets executed for each of the time slice allotted.
5. Prepare the gantt chart for each process getting executed within the time slice in a round robin
fashion.
6. Calculate the waiting time and turn around time along with their averages display the result.
// ROUND ROBIN SCHEDULING ALGORITHM
PROGRAM:
#include<stdio.h>
void main()
{
int i,x=-1,k[10],m=0,n,t,s=0;
int a[50],temp,b[50],p[10],bur[10],bur1[10];
int wat[10],tur[10],ttur=0,twat=0,tres=0,j=0;
float awat,atur,ares;
printf("Enter no. of process :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the burst time for process %d: ",(i+1));
scanf("%d",&bur[i]);
bur1[i]=bur[i];
}
printf("\nEnter the slicing time :");
scanf("%d",&t);
for(i=0;i<n;i++)
{
b[i]=bur[i]/t;
if((bur[i]%t)!=0)
b[i]=b[i]+1;
m=b[i]+m;
}
printf("\nGAANT CHART\n\n");
for(i=0;i<m;i++)
{
printf("--------");
}
printf("\n");
a[0]=0;
while(j<m)
{
if(x==n-1)
x=0;
else
x++;

St.Joseph’s College of Engineering ISO 9001:2008


20
CS8461-Operating systems Lab Department of IT 2019-2020

if(bur[x]>=t)
{
bur[x]=bur[x]-t;
a[j+1]=a[j]+t;
if(b[x]==1)
{
p[s]=x;
k[s]=a[j+1];
s++;
}
j++;
b[x]=b[x]-1;
printf(" P%d |",x+1);
}
else if(bur[x]!=0)
{
a[j+1]=a[j]+bur[x];
bur[x]=0;
if(b[x]==1)
{
p[s]=x;
k[s]=a[j+1];
s++;
}
j++;
b[x]=b[x]-1;
printf(" P%d |",x+1);
}
}
printf("\n");
for(i=0;i<m;i++)
printf("--------");
printf("\n");
for(j=0;j<=m;j++)
printf("%d\t",a[j]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(p[i]>p[j])
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
temp=k[i];
k[i]=k[j];
k[j]=temp;
} } }
for(i=0;i<n;i++)
{
wat[i]=k[i]-bur1[i];

St.Joseph’s College of Engineering ISO 9001:2008


21
CS8461-Operating systems Lab Department of IT 2019-2020

tur[i]=k[i];
}
printf("\nPROCESS\tBURST TIME \t WAITING TIME \t TURN AROUND TIME\t");
printf("RESPONSE TIME\n");
for(i=0;i<n;i++)
{
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d\n",p[i]+1,bur1[i],wat[i],
tur[i],a[i]);
}
for(i=0;i<n;i++)
{
ttur=ttur+tur[i];
twat=twat+wat[i];
tres=tres+a[i];
}
awat=(float)twat/n;
atur=(float)ttur/n;
ares=(float)tres/n;
printf("\nTotal waiting time:%d",twat);
printf("\nTotal turnaround time:%d",ttur);
// printf("\nTotal response time:%d",tres);
printf("\nAverage waiting time :%.2f",awat);
printf("\nAverage turn around time :%.2f",atur);
//printf("\nAverage response time:%.2f",ares);
}
OUTPUT
[IT@localhost ~]$ ./a.out
[IT@localhost~]$ gcc round.c
[IT@localhost~]$ ./a.out
Enter no. of process :3
Enter the burst time for process 1: 10
Enter the burst time for process 2: 12
Enter the burst time for process 3: 15
Enter the slicing time :5
GAANT CHART
----------------------------------------------------------------
| P1 | P2 | P3 | P1 | P2 | P3 | P2 | P3 |
----------------------------------------------------------------
0 5 10 15 20 25 30 32 37
PROCESS. BURST TIME. WAITING TIME. TURNAROUND TIME. RESPONSE TIME
1 10 10 20 0
2 12 20 32 5
3 15 22 37 10
Total waiting time:52
Total turnaround time:89
Average waiting time :17.33
Average turn around time :29.67
RESULT:

St.Joseph’s College of Engineering ISO 9001:2008


22
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 6 PRODUCER CONSUMER PROBLEM USING SEMAPHORES

AIM:
To write a program to implement producer consumer problem using semaphore

ALGORITHM:
1. Declare the buffer size variable.
2. Initialize empty, full and the value of mutex.
3. For case 1 , produce the item till the buffer is full after performing the wait operation
Of variables empty and mutex.
4. Then perform signal of full.
5. For case 2, consume the item till the buffer is empty. Perform the wait and signal operation..
6. print the contents of the buffer.

//PRODUCER CONSUMER PROBLEM USING SEMAPHORE


PROGRAM:
#include<stdio.h> #include<string.h>
#define SIZE 3
struct process
{
char a[10];
}buffer[SIZE];
int mutex=1,full=0,empty=SIZE,f=0;
int main()
{
//int mutex=1,full=0,empty=SIZE,f=0;
int ch,i;
printf("\tProducer Consumer Problem:\n");
while(1)
{
printf("\n The choices are\n");
printf("1.Producer Routine\n2.Consumer Routine\n3.Buffer Contents\n4.Exit\n");
printf("Enter your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
empty=wait(empty);
mutex=wait(mutex);
if(f==0)
{
printf("\nEnter the item to be added:\n");
scanf("%s",&buffer[full]);
full=signal(full);
printf("\nItem Produced Successfully:\n");
}
else
{
printf("\nBuffer is full\n");
f=0;
}

St.Joseph’s College of Engineering ISO 9001:2008


23
CS8461-Operating systems Lab Department of IT 2019-2020

mutex=signal(mutex);
break;
case 2:
full=wait(full);
mutex=wait(mutex);
if(f==0)
{
printf("\nOne Item is Consumed:\n");
printf("\nConsumed item is: %s\n",buffer[0].a);
for(i=0;i<SIZE;i++)
strcpy(buffer[i].a,buffer[i+1].a);
empty=signal(empty);
}
else
{
printf("\nBuffer is empty\n");
f=0;
}
mutex=signal(mutex);
break;
case 3:
if(full!=0)
{
for(i=0;i<full;i++)
printf("\n%s\n",buffer[i].a);
}
else
printf("\nBuffer is empty\n");
break;
case 4:
exit(0);
default:
printf("Enter Correct Option");
break;
}}}
int wait(int s)
{
if(s==0)
f=1;
else
s--;
return s;
}
int signal(int s)
{
s++;
return s;
}
OUTPUT
[IT@localhost ~]$ ./a.out
Producer Consumer Problem:

St.Joseph’s College of Engineering ISO 9001:2008


24
CS8461-Operating systems Lab Department of IT 2019-2020

The choices are


1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:1
Enter the item to be added:
yellow
Item Produced Successfully:
The choices are
1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:1
Enter the item to be added:
Green
Item Produced Successfully:
The choices are
1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:3
Yellow
Green
The choices are
1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:2
One Item is Consumed:
Consumed item is: Yellow
The choices are
1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:2
One Item is Consumed:
Consumed item is: Green
The choices are
1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:3
Buffer is empty

RESULT:

St.Joseph’s College of Engineering ISO 9001:2008


25
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 7 INTER PROCESS COMMUNICATION


(Using shared memory, pipes or message queues)

AIM:
To write a program to implement inter process communication using queues.
ALGORITHM:
1. Create and declare two description for reading and writing.
2. Set child process to write the message to the buffer.
3. Set the parent to read the message from buffer.
4. Print the message from the buffer.
5. Stop the execution.

PROGRAM
//PIPES
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hai How are you!\n";
char readbuffer[80];

pipe(fd);

if((childpid = fork()) == -1)


{
perror("fork");
exit(1);
}

if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);

/* Send "string" through the output side of pipe */


write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);

/* Read in a string from the pipe */


nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}

St.Joseph’s College of Engineering ISO 9001:2008


26
CS8461-Operating systems Lab Department of IT 2019-2020

return(0);
}
OUTPUT
[IT@localhost ~]$ ./a.out
client writing ...
: server Received string: Hai How are you !
[IT@localhost ~]$

//SHARED MEMORY
ALGORITHM:
1. Create and shared memory using shmget.
2. Attach pointer to a memory using shmat.
3. Create child process to write data to memory.
4. Print the shared memory data using server process.
5. Stop the execution.

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSZ 27
main()
{
char c;
int shmid,childpid;
key_t key;
char *shm, *s;

key = 5679;

if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {


perror("shmget");
exit(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
s = shm;
if((childpid = fork()) < 0) // error occured
{
perror("Fork Failed");
exit(1);
}
else if(childpid == 0) // child process
{
for (c = 'a'; c <= 'z'; c++)
*s++ = c;
*s = NULL;

St.Joseph’s College of Engineering ISO 9001:2008


27
CS8461-Operating systems Lab Department of IT 2019-2020

}
else
{
wait(15);
for (s = shm; *s != NULL; s++)
putchar(*s);
putchar('\n');

}
exit(0);
}

OUTPUT
[IT@localhost ~]$ ./a.out
abcdefghijklmnopqrstuvwxyz
[IT@localhost ~]$ ipcs

------ Shared Memory Segments --------


key shmid owner perms bytes nattch status
0x0000162e 426035 IT666 27 0
0x0000162f 455568 IT666 27 0

------ Semaphore Arrays --------


key semid owner perms nsems

------ Message Queues --------


key msqid owner perms used-bytes messages

//MESSAGE QUEUE
ALGORITHM:
1. Create a queue using msgget()system call.
2. Create child process using fork() system call.
3. The fork returns a zero to the child process and process id of child to parent.
4. The child process sends messages to the queue using msgsnd(0system call.
5. The parent process reads from the queue using msgrcv() system call.
6. The parent waits for the child to exit and then exit.

// INTER PROCESS COMMUNICATION USING QUEUE


PROGRAM:
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/types.h>

St.Joseph’s College of Engineering ISO 9001:2008


28
CS8461-Operating systems Lab Department of IT 2019-2020

#define key 50
main()
{
int msgqid,pid;
struct
{
int mtype;
char mtost[30];
}buf;
msgqid=msgget(key,IPC_CREAT|0454);
if(msgqid==0)
{
printf("Error in the queue creation");
exit(1);
}
pid=fork();
if(pid==1)
{
printf("Error in the process creation");
exit(1);
}
if(pid==0)
{
strcpy(buf.mtost,"Happy day ahead”);
buf.mtype=2;
msgsnd(msgqid,&buf,sizeof(buf.mtost),IPC_NOWAIT);
strcpy(buf.mtost,"Apple keeps doc away");
buf.mtype=1;
msgsnd(msgqid,&buf,sizeof(buf.mtost),IPC_NOWAIT);
msgrcv(msgqid,&buf,sizeof(buf.mtost),1,IPC_NOWAIT);
printf("Message is %s",buf.mtost);
}
}
OUTPUT
[IT@localhost~]$gcc ipcqueue.c
[IT @elserver ~]$ ./a.out
Message is Apple keeps doc away.
[IT @elserver ~]$

RESULT:

St.Joseph’s College of Engineering ISO 9001:2008


29
CS8461-Operating systems Lab Department of IT 2019-2020

Ex.No:8 DEAD LOCK AVOIDANCE USING BANKERS ALGORITHM

AIM: To implement deadlock avoidance by using Banker’s Algorithm.

Data structures
 n-Number of process, m-number of resource types.
 Available: Available[j]=k, k – instance of resource type Rj is available.
 Max: If max[i, j]=k, Pi may request at most k instances resource Rj.
 Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj
 Need: If Need[I, j]=k, Pi may need k more instances of resource type Rj,
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.

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 its possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety or not if we allow the request.
9. Stop the program.

St.Joseph’s College of Engineering ISO 9001:2008


30
CS8461-Operating systems Lab Department of IT 2019-2020

PROGRAM
#include<stdio.h>
#include<process.h>

void main()
{
int allocation[10][5],max[10][5],need[10][5],available[3],flag[10],sq[10];
int n,r,i,j,k,count,count1=0;
printf("\n Input the number of processes running ( <10 )..");
scanf("%d",&n);
for(i=0;i<10;i++)
flag[i]=0;
printf("\n Input the number of resources ( <5 )..");
scanf("%d",&r);
printf("\n Input the allocation matrix for the processes in row major order..\n");
for(i=0;i<n;i++)
{
printf("\n Process %d\n",i);
for(j=0;j<r;j++)
{
printf("\n Resource %d\n",j);
scanf("%d",&allocation[i][j]);
}
}
printf("\n Input the no. of resources that a process can maximum have..\n");
for(i=0;i<n;i++)
{
printf("\n Process %d\n",i);
for(j=0;j<r;j++)
{
printf("\n Resource %d\n",j);
scanf("%d",&max[i][j]);
}
}
printf("\n Input the no. of available instances of each resource..\n");
for(i=0;i<r;i++)
{
printf("\n Resource %d : ",i);
scanf("%d",&available[i]);
}
printf("\n The need matrix is as follows : \n");
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
need[i][j]= max[i][j]-allocation[i][j];
printf("\t %d",need[i][j]);
}
printf("\n");
}
do{

St.Joseph’s College of Engineering ISO 9001:2008


31
CS8461-Operating systems Lab Department of IT 2019-2020

for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
if(flag[i]==0)
{
count=0;
for(j=0;j<r;j++)
{
if(available[j]>=need[i][j])
count++;
}
if(count==r)
{
count1++;
flag[i]=1;
sq[count1-1]=i;
for(j=0;j<r;j++)
{
available[j]=available[j]+allocation[i][j];
}
break;
}
}
}
}
if(count1!=n)
{
printf("\n---------------IT'S AN UNSAFE STATE---------------");
break;
}
}while(count1!=n);
if(count1==n)
{
printf("\n *******************IT'S A SAFE STATE*******************");
printf("\n The safe sequence is....\n");
for(i=0;i<n;i++)
printf("\t P%d",sq[i]);
printf("\n");
printf("\n The available matrix is now : ");
for(i=0;i<r;i++)
printf("\t %d",available[i]);
}

St.Joseph’s College of Engineering ISO 9001:2008


32
CS8461-Operating systems Lab Department of IT 2019-2020

OUTPUT

[IT@localhost ~]$

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


33
CS8461-Operating systems Lab Department of IT 2019-2020

Ex.No:9 DEAD LOCK DETECTION USING BANKERS ALGORITHIM

AIM: To implement deadlock detection by using Banker’s Algorithm.

ALGORITHM:

1. Start the program.


2. Get the values of resources and processes.
3. Get the allocation and request matrix value.
4. Get the available instances for each resources
5. Check whether its possible to allocate using below condition.
6. If Need<=Work update work as work=work +allocation
7. Else proceed with next process.
8. If it is possible to allocate then the system is in safe state.
9. Else system is not in safe state.
10. Stop the program.

PROGRAM
#include<stdio.h>
int main()
{
int alloc[10][10],req[10][10],ins[10],avail[10],tp,tr,i,j;
int tmp[10]={0},count=0;
int finish[10]={0},flag;
printf("Enter total no of processes:");
scanf("%d",&tp);
printf("Enter total no of resources:");
scanf("%d",&tr);
printf("Enter the Allocation Matrix:\n");
for(i=0;i<tp;i++)
{
for(j=0;j<tr;j++)
{
scanf("%d",&alloc[i][j]);
}
}
printf("Enter the Request Matrix:\n");
for(i=0;i<tp;i++)
{
for(j=0;j<tr;j++)
{
scanf("%d",&req[i][j]);
}
}
printf("Enter the resource instance vector:\n");
for(i=0;i<tr;i++)
{
scanf("%d",&ins[i]);
}
//To calculate resource availability vector

St.Joseph’s College of Engineering ISO 9001:2008


34
CS8461-Operating systems Lab Department of IT 2019-2020

for(i=0;i<tp;i++)
{
for(j=0;j<tr;j++)
{
tmp[i]+=alloc[j][i]; //sum calculated columnwise for allocation matrix
}
}
printf("\nCalculated Availability Vector:\n");
for(i=0;i<tp;i++)
{
avail[i]=ins[i]-tmp[i];
printf("\t%d",avail[i]);
}
while(count!=tp)
{ //if finish array has all true's(all processes to running state)
//deadlock not detected and loop stops!
for(i=0;i<tp;i++)
{
count=0;
//To check whether resources can be allocated any to blocked process
if(finish[i]==0)
{
for(j=0;j<tr;j++)
{
if(req[i][j]<=avail[j])
{
count++;
}
}
flag=0;
if(count==tr)
{
for(j=0;j<tr;j++)
{
avail[j]+=alloc[i][j]; //allocated reources are released and added to available!
}
finish[i]=1;
printf("\nProcess %d is transferred to running state and assumed finished",i+1);
}
else
flag=1;
}
}
count=0;
for(j=0;j<tr;j++)
{
if(finish[j]==1)
{
count++;
}
}

St.Joseph’s College of Engineering ISO 9001:2008


35
CS8461-Operating systems Lab Department of IT 2019-2020

}
for(i=0;i<tp;i++)
{
if(finish[i]==0)
{
printf("\n Oops! Deadlock detected and causing process is:process(%d)\n",i+1);
break;
}
}
i=i-1;
if(finish[i]==1)
printf("\nHurray! Deadlock not detected:-)\n");
return 0;
}

OUTPUT

[IT@localhost ~]$

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


36
CS8461-Operating systems Lab Department of IT 2019-2020

Ex.No:10 PTHREADS & ITS SYNCHRONIZATION

AIM
To implement POSIX thread operations and synchronize using mutex variable.

ALGORITHIM

1. Start the process

2. Intialize mutex lock ,thread id and required other variables

3. Create POSIX threads using pthread_create

4. Define thread task by creating new function.

5. Synchronize threads using mutex lock and unlock variables

6. Using pthread_join allow threads to wait until parent process completes

7. Destroy the synchronization variable mutex using pthread_mutex_destroy


8. Stop the process

PROGRAM
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>

pthread_t tid[2];
int counter;
pthread_mutex_t lock;

void* doSomeThing(void *arg)


{
pthread_mutex_lock(&lock);

unsigned long i = 0;
counter += 1;
printf("\n Job %d started\n", counter);

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

printf("\n Job %d finished\n", counter);

pthread_mutex_unlock(&lock);

return NULL;
}

St.Joseph’s College of Engineering ISO 9001:2008


37
CS8461-Operating systems Lab Department of IT 2019-2020

int main(void)
{
int i = 0;
int err;

if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init failed\n");
return 1;
}

while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
i++;
}

pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock);

return 0;
}

OUTPUT

//Thread created and called for execution

[IT@localhost ~]$

Job 1 started
Job 2 started

Job 1 finished
Job 2 finished

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


38
CS8461-Operating systems Lab Department of IT 2019-2020

Ex.No:11 MEMORY ALLOCATION METHODS

AIM:
To implement memory allocation methods first fit, best fit & worst fit for fixed partitions.

FIRST FIT ALGORITHM:

1. Get no. of Processes and no. of blocks.


2. After that get the size of each block and process requests.
3. Now allocate processes
if(block size >= process size)
//allocate the process
else
//move on to next block
4. Display the processes with the blocks that are allocated to a respective process.
5. Stop.
PROGRAM

#include<stdio.h>
void main()
{
int bsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j;
for(i = 0; i < 10; i++)
{
flags[i] = 0;
allocation[i] = -1;
}
printf("Enter no. of blocks: ");
scanf("%d", &bno);
printf("\nEnter size of each block: ");
for(i = 0; i < bno; i++)
scanf("%d", &bsize[i]);
printf("\nEnter no. of processes: ");
scanf("%d", &pno);
printf("\nEnter size of each process: ");
for(i = 0; i < pno; i++)
scanf("%d", &psize[i]);
for(i = 0; i < pno; i++) //allocation as per first fit
for(j = 0; j < bno; j++)
if(flags[j] == 0 && bsize[j] >= psize[i])
{
allocation[j] = i;
flags[j] = 1;
break;
}
//display allocation details

St.Joseph’s College of Engineering ISO 9001:2008


39
CS8461-Operating systems Lab Department of IT 2019-2020

printf("\nBlock no.\tsize\t\tprocess no.\t\tsize");


for(i = 0; i < bno; i++)
{
printf("\n%d\t\t%d\t\t", i+1, bsize[i]);
if(flags[i] == 1)
printf("%d\t\t\t%d",allocation[i]+1,psize[allocation[i]]);
else
printf("Not allocated");
}
}

OUTPUT

Enter no. of blocks: 4

Enter size of each block: 20


30
40
50

Enter no. of processes: 4

Enter size of each process: 10


20
15
25

Block no. size process no. size


1 20 1 10
2 30 2 20
3 40 3 15
4 50 4 25

BEST FIT ALGORITHM


1. Get no. of Processes and no. of blocks.
2. After that get the size of each block and process requests.
3. Then select the best memory block that can be allocated using the above definition.
4. Display the processes with the blocks that are allocated to a respective process.
5. Value of Fragmentation is optional to display to keep track of wasted memory.
6. Stop.

PROGRAM

#include<stdio.h>
void main()
{
int fragment[20],b[20],p[20],i,j,nb,np,temp,lowest=9999;
static int barray[20],parray[20];
St.Joseph’s College of Engineering ISO 9001:2008
40
CS8461-Operating systems Lab Department of IT 2019-2020

printf("\n\t\t\tMemory Management Scheme - Best Fit");


printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of processes:");
scanf("%d",&np);

printf("\nEnter the size of the blocks:-\n");


for(i=1;i<=nb;i++)
{
printf("Block no.%d:",i);
scanf("%d",&b[i]);
}
printf("\nEnter the size of the processes :-\n");
for(i=1;i<=np;i++)
{
printf("Process no.%d:",i);
scanf("%d",&p[i]);
}
for(i=1;i<=np;i++)
{
for(j=1;j<=nb;j++)
{
if(barray[j]!=1)
{
temp=b[j]-p[i];
if(temp>=0)
if(lowest>temp)
{
parray[i]=j;
lowest=temp;
}
}
}

fragment[i]=lowest;
barray[parray[i]]=1;
lowest=10000;
}

printf("\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment");
for(i=1;i<=np && parray[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,p[i],parray[i],b[parray[i]],fragment[i]);
}

OUTPUT

Memory Management Scheme - Best Fit


Enter the number of blocks:3
Enter the number of processes:3

St.Joseph’s College of Engineering ISO 9001:2008


41
CS8461-Operating systems Lab Department of IT 2019-2020

Enter the size of the blocks:-


Block no.1:30
Block no.2:20
Block no.3:40

Enter the size of the processes :-


Process no.1:15
Process no.2:25
Process no.3:35

Process_no Process_size Block_no Block_size Fragment


1 15 2 20 5
2 25 1 30 5
3 35 3 40 5

WORST FIT ALGORITHM


1. Start
2. Input memory blocks and processes with sizes.
3. Initialize all memory blocks as free.
4. Arrange the partion in desecnding order.
5. Start picking each process and allocate to block only if process memory size is less than block size.
6. Else leave that process and keep checking other process.
7. Allocate process to blocks and calculate the fragment in each block.
8. Leave process unallocated if not satisfying above conditions.
9. Stop

PROGRAM

#include<stdio.h>
main()
{
int i,j,temp,f[10],fp[10];
int no,p[15],part[15],pno,pr[15],prmem[15];
printf("\n*******************************************");
printf("\n IMPLEMENTATION OF WORST-FITALGORITHM");
printf("\n*******************************************");
printf("\n Enter the number of partitions");
scanf("%d",&no);
for(i=1;i<=no;i++)
{
p[i]=i;
printf("Enter the memory for partition %d:\t",i);
scanf("%d",&part[i]);
}
//Arrange partitions in descending order
for(i=1;i<=no;i++)
{
for(j=1;j<=i;j++)
{
if(part[j]<part[i])
St.Joseph’s College of Engineering ISO 9001:2008
42
CS8461-Operating systems Lab Department of IT 2019-2020

{
temp=part[i];
part[i]=part[j];
part[j]=temp;
temp=p[i];
p[i]=p[j];
p[j]=temp:
}}}
printf("\nFree memory");
for(i=1;i<=no;i++)
{
printf("\n partition %d: \t %d",p[i],part[i]);
}
//Input process details
printf("\n Enter the number of process");
scanf("%d",&pno);
for(i=1;i<=pno;i++)
{
pr[i]=i;
printf("Enter the size for process %d:\t",i);
scanf("%d",&prmem[i]);
}
//Applying Worst-Fit Method
printf("\n----------------------------------------\n");
printf("PROCESS|\t PARTITION| \t FREE_MEMORY|\n");
printf("\n----------------------------------------\n");
j=1;
for(i=1;i<=no;i++)
{
f[i]=0;
fp[j]=0;
}
while(j<=pno)
{
for(i=1;i<=no;i++)
{
if((part[i]>=prmem[j]) && (f[i]==0))
{
part[i]=part[i]-prmem[j];
fp[j]=1;//process alloted
f[i]=1; //partition alloted
printf("%d \t %d \t %d \n",pr[j],p[i],part[i]);
goto l1;
}}
l1:
j++;
}
for(i=1;i<=no;i++)
{
if(f[i]==0)
{

St.Joseph’s College of Engineering ISO 9001:2008


43
CS8461-Operating systems Lab Department of IT 2019-2020

printf(" \t %d \t %d \n",p[i],part[i]);
}}
printf("The following process is not allocatted:");
for(i=1;i<=pno;i++)
{
if(fp[i]==0)
{
printf(" %d ",pr[i]);
}}}

OUTPUT

*******************************************
IMPLEMENTATION OF WORST-FITALGORITHM
*******************************************
Enter the number of partitions4
Enter the memory for partition 1: 35
Enter the memory for partition 2: 25
Enter the memory for partition 3: 50
Enter the memory for partition 4: 60

Free memory
partition 4: 60
partition 3: 50
partition 1: 35
partition 2: 25
Enter the number of process4
Enter the size for process 1: 25
Enter the size for process 2: 15
Enter the size for process 3: 20
Enter the size for process 4: 30

----------------------------------------
PROCESS| PARTITION| FREE_MEMORY|

----------------------------------------
1 4 35
2 3 35
3 1 15
2 25
The following process is not allocatted: 4 i

RESULT:

St.Joseph’s College of Engineering ISO 9001:2008


44
CS8461-Operating systems Lab Department of IT 2019-2020

Ex.No:12 MEMORY MANAGEMENT USING PAGING TECHNIQUE

AIM:
To implement the Memory management policy- Paging.

ALGORITHM:

1. Read all the necessary input from the keyboard.


2. Pages - Logical memory is broken into fixed - sized blocks.
3. Frames – Physical memory is broken into fixed – sized blocks.
4. Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
5. Display the physical address.
6. Stop the process.
/* Memory Allocation with Paging Technique */

PROGRAM
#include <stdio.h>

struct pstruct
{
int fno;
int pbit;
}ptable[10];

int pmsize,lmsize,psize,frame,page,ftable[20],frameno;

void info()
{
printf("\n\nMEMORY MANAGEMENT USING PAGING\n\n");
printf("\n\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;
}

St.Joseph’s College of Engineering ISO 9001:2008


45
CS8461-Operating systems Lab Department of IT 2019-2020

for(i=0; i<frame;i++)
ftable[i] = 32555;
for (i=0;i<page;i++)
{
printf("\n\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("\n\nPAGE TABLE\n\n");
printf("PageAddress FrameNo. PresenceBit\n\n");
for (i=0;i<page;i++)
printf("%d\t\t%d\t\t%d\n",i,ptable[i].fno,ptable[i].pbit);
printf("\n\n\n\tFRAME TABLE\n\n");
printf("FrameAddress PageNo\n\n");
for(i=0;i<frame;i++)
printf("%d\t\t%d\n",i,ftable[i]);
}
void cphyaddr()
{
int laddr,paddr,disp,phyaddr,baddr;

// clrscr();
printf("\n\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);
}
void main()
{

info();
assign();
cphyaddr();

St.Joseph’s College of Engineering ISO 9001:2008


46
CS8461-Operating systems Lab Department of IT 2019-2020

OUTPUT

[IT@localhost ~]$ ./a.out

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


47
CS8461-Operating systems Lab Department of IT 2019-2020

Ex.No:13A FIFO PAGE REPLACEMENT ALGORITHM

AIM
To write a c program to implement FIFO page replacement algorithm

ALGORITHM
1. Start the process
2. Declare the size with respect to page length
3. Check the need of replacement from the page to memory
4. Check the need of replacement from old page to new page in memory
5. Forma queue to hold all pages
6. Insert the page require memory into the queue
7. Check for bad replacement and page fault
8. Get the number of processes to be inserted
9. Display the values
10. Stop the process

PROGRAM:

#include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\n ENTER THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}

St.Joseph’s College of Engineering ISO 9001:2008


48
CS8461-Operating systems Lab Department of IT 2019-2020

printf("\n");
}
printf("Page Fault Is %d",count);
return 0;
}

OUTPUT

[IT@localhost ~]$ ./a.out

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


49
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No:13B LRU PAGE REPLACEMENT ALGORITHM

AIM:

To implement LRU page replacement technique.

ALGORITHM:

1. Start the process


2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least recently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process

PROGRAM
#include<stdio.h>
main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];

printf("Enter no of pages:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;
k++;
for(i=1;i<n;i++)
{
c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)

St.Joseph’s College of Engineering ISO 9001:2008


50
CS8461-Operating systems Lab Department of IT 2019-2020

printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j];
b[j]=t;
}
}
}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf("\t%d",q[r]);
}
printf("\n");
}
}
}
printf("\nThe no of page faults is %d",c);

return 0;
}

St.Joseph’s College of Engineering ISO 9001:2008


51
CS8461-Operating systems Lab Department of IT 2019-2020

OUTPUT

[IT@localhost ~]$ ./a.out

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


52
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No:13C OPTIMAL PAGE REPLACEMENT ALGORITHM

AIM:
To implement optimal page replacement technique.

ALGORITHM:
Here we select the page that will not be used for the longest period of time.
1. Start Program
2. Read Number Of Pages And Frames
3. Read Each Page Value
4. Search For Page In The Frames
5. If Not Available Allocate Free Frame
6. If No Frames Is Free Repalce The Page With The Page That Is Not Used In Next N
Pages(N Is Number Of Frames)
7. Print Page Number Of Page Faults
8. Stop process.

PROGRAM
#include<stdio.h>

int findmax(int*);
int n;
int main()
{
int seq[30],fr[5],pos[5],find,flag,max,i,j,m,k,t,s,pf=0;
int count=1,p=0;
float pfr;

printf("enter max limit of the sequence:");


scanf("%d",&max);
printf("enter the sequence:");
for(i=0;i<max;i++)
scanf("%d",&seq[i]);
printf("enter the no of frames:");
scanf("%d",&n);
fr[0]=seq[0];
pf++;
printf("%d\t",fr[0]);
i=1;
while(count<n)
{
flag=1;
p++;
for(j=0;j<i;j++)
{
if(seq[i]==seq[j])
flag=0;
}
if(flag!=0)
{
fr[count]=seq[i];

St.Joseph’s College of Engineering ISO 9001:2008


53
CS8461-Operating systems Lab Department of IT 2019-2020

printf("%d\t",fr[count] );
count++;
pf++;
}
i++;
}
printf("\n");
for(i=p;i<max;i++)
{
flag=1;
for(j=0;j<n;j++)
{
if(seq[i]==fr[j])
flag=0;
}
if(flag!=0)
{
for(j=0;j<n;j++)
{
m=fr[j];
for(k=i;k<max;k++)
{
if(seq[k]==m)
{
pos[j]=k;
break;
}
else
pos[j]=-1;
}
}
for(k=0;k<n;k++)
{
if(pos[k]==-1)
flag=0;
}
if(flag!=0)
s=findmax(pos);
if(flag==0)
{
for(k=0;k<n;k++)
{
if(pos[k]==-1)
{
s=k;
break;
}
}
}
pf++;
fr[s]=seq[i];

St.Joseph’s College of Engineering ISO 9001:2008


54
CS8461-Operating systems Lab Department of IT 2019-2020

for(k=0;k<n;k++)
printf("%d\t",fr[k]);
printf("\n");

}
}
pfr=(float)pf/(float)max;
printf("\n theno of page faults are:%d",pf);
printf("\n page fault rate:%f",pfr);

}
int findmax(int a[])
{
int max,i,k=0;
max=a[0];
for(i=0;i<n;i++)
{
if(max<a[i])
{
max=a[i];
k=i;
}
}
return k;
}

OUTPUT

[IT@localhost ~]$ ./a.out

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


55
CS8461-Operating systems Lab Department of IT 2019-2020

Ex.No:14 FILE ORGANIZATION TECHNIQUES

AIM: To simulate file organization techniques.

ALGORITHM:

1. Start the program.


2. To implement single level tree structure get the main directories and subdirectories name.
3. Get the file names to be created within directories.
4. To implement the other level of directories run the program using –p option.
5. With –p option get the main directories and sub directories name to be created in runtime.
6. Create main and sub directories using mkdir() system call.
7. Inside the main directory and sub directory get the files name to be created
8. Create the file using fopen() system call.
9. Simulate the directory level and display the structure.
10. To simulate Directed Acyclic Graph(DAG) get the source file and destination path where the file to
be created.
11. Create the link between source and destination files.
12. Stop the program.

PROGRAM
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>

void tokenizer(char *path);


void DAG();
main(int ac,char *av[])
{

int result,i;
if (strcmp(av[1],"-p")!=0)
{
if (mkdir(av[1],0777)==-1)
{
perror("cant make it");
exit(1);
}
else
{
if (chdir(av[1])==-1)
printf("not right\n");
fopen("sample1.txt","w");
}

St.Joseph’s College of Engineering ISO 9001:2008


56
CS8461-Operating systems Lab Department of IT 2019-2020

}
else if (strcmp(av[1],"-p")==0)
{
for(i=2;i<4;i++)
{
tokenizer(av[i]);
if (chdir("/root")==-1)
printf("not right\n");
}
printf("\n Simulating DAG... \n");
DAG();
}
return EXIT_SUCCESS;
}
void tokenizer(char *path)
{
char *dir;
const char *fname[10];
if (mkdir(path, 0777)==-1)
{
dir=strtok(path,"/");
while (dir!=NULL)
{
printf("%s\n",dir);
mkdir(dir, 0777);
printf("\n Enter the file name to be created within %s directory ",dir);
scanf("%s",&fname);

if (chdir(dir)==-1)
printf("not right\n");
fopen(fname,"w");
dir=strtok(NULL,"/");

}
}

void DAG()
{
//const char fname[]="sharedfile";
const char *pt1[10];
const char *pt2[10];
char cwd[1024];
printf("Sharing file between two different directories\n");
printf("\n Enter the source and destination path from where the file to be shared \n ");

St.Joseph’s College of Engineering ISO 9001:2008


57
CS8461-Operating systems Lab Department of IT 2019-2020

scanf("%s",&pt1);
scanf("%s",&pt2);

/* chdir("/root");
if(getcwd(cwd,sizeof(cwd))!=NULL)
{
printf("current working dir %s \n",cwd);
}
else
{
perror("getcwd() error");
}*/
if(link(pt1,pt2)<0)
{
printf(" not done");
}
else
printf("\n link created between %s and %s \n",&pt1,&pt2);
}

OUTPUT

[IT@localhost ~]$ ./a.out hook


Enter the file name to be created within hook directory
file1

[IT@localhost ~]$ ./a.out –p two/pot/mat


Enter the file name to be created within two directory
file2
Enter the file name to be created within pot directory
file3
Enter the file name to be created within mat directory
file4

Simulating DAG

Sharing file between two different directories


Enter the source and destination path from where the file to be shared
/root/two/pot/file3 /root/two/pot/mat/file5
link created between /root/two/pot/file3 /root/two/pot/mat/file5

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


58
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 15A CONTIGOUS FILE ALLOCATION TECHNIQUE

AIM:
To write a C program to implementation contiguous file allocation techniques.

ALGORITHM:
Step 1: Start.
Step 2: Memory before allocation is displayed.
Step 3: The file Id is entered by the user.
Step 4: the number of blocks memory required and the starting address of the file is given by the user..
Step 5: If starting address and length of block is greater than 20 print error message.
Else , the memory address is replaced by the id.
Display memory after allocation.
Step 6: Stop.

PROGRAM:
#include<stdio.h>
#include<conio.h>
int a[20],num=0;
int fid[10],length[10],start[10];
void filedescriptor();
void display();
void filedescriptor()
{
int i;
printf("\n file id \t starting address \t length \n");
for(i=0;i<num;i++)
printf("%d\t\t\t %d\t\t%d\n",fid[i],start[i],length[i]);
}
void display()
{
int i;
for(i=0;i<20;i++)
printf("%2d",i);
printf("\n");
for(i=0;i<20;i++)
printf("%2d", a[i]);
}
void main()
{
int i,n,k,temp,st,l,id,flag=0,cho;
for(i=0;i<20;i++)
a[i]=0;
clrscr();
printf("\n memory before allocation:\n");
display();
while(1)
{
printf("\n enter the file id:");
scanf("%d",&id);

St.Joseph’s College of Engineering ISO 9001:2008


59
CS8461-Operating systems Lab Department of IT 2019-2020

printf("\n enter the number of blocks the file occupies:");


scanf("%d", &l);
fid[num]=id;
length[num]=l;
l:printf("\n enter the starting address:");
scanf("%d", &st);
flag=0;
if((st+1)>20)
{
printf("\n sorry the given memory goes out of space:");
goto l; }
for(i=st;i<(st+1);i++)
{
if(a[i]!=0)
{
flag=1;
break;
}}
if(flag==0)
{
start[num]=st;
for(i=st;i<(st+1);i++)
a[i]=id;
}
else
{
printf("\n sorry the given blocks are already occupied: Enter new starting
address");
goto l;
}
flag=0;
num++;
filedescriptor();
printf("\n memory after allocation \n");
display();
printf("\n want to continue? \n1.yes \n2.no");
scanf("%d",&cho);
if(cho==2)
exit(0);
}}

St.Joseph’s College of Engineering ISO 9001:2008


60
CS8461-Operating systems Lab Department of IT 2019-2020

OUTPUT:

[IT@localhost ~]$
memory before allocation:
0 1 2 3 4 5 6 7 8 910111213141516171819
00000000000000000000
enter the file id:9
enter the number of blocks the file occupies:4
enter the starting address:4
file id starting address length
9 4 4
memory after allocation
0 1 2 3 4 5 6 7 8 910111213141516171819
00 09999000000000000
want to continue?
1.yes
2.no

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


61
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 15B LINKED LIST FILE ALLOCATION TECHNIQUE

AIM:
To write a C program to implementation linked list file allocation techniques.

ALGORITHM:
1. Start.
2. Get the number of blocks already allocated and its block numbers as input from user.
3. Add that block numbers to a list as allocated block number list and mark that block numbers are
allocated.
4. To perform allocation .Get the starting block number and length of the input file
5. From the starting block check whether each block is in allocated block number list
6. If so Print block is already allocated. Else allocate file to the block number.
7. Continue the loop if the processes want to be repeated.
8. Stop.

PROGRAM
#include<stdio.h>

void main()
{
int f[50],p,i,j,k,a,st,len,n,c;

for(i=0;i<50;i++)
f[i]=0;
printf("enter how many blocks already allocated");
scanf("%d",&p);
printf("\nenter the blocks nos");
for(i=0;i<p;i++)
{
scanf("%d",&a);
f[a]=1;
}
X:
printf("enter index sarting block & length");
scanf("%d%d",&st,&len);
k=len;
if(f[st]==0)
{
for(j=st;j<(k+st);j++)
{
if(f[j]==0)
{
f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("\n %d->file is already allocated",j);
k++;

St.Joseph’s College of Engineering ISO 9001:2008


62
CS8461-Operating systems Lab Department of IT 2019-2020

}
}
}
else
printf("\nif u enter one more (yes-1/no-0)");
scanf("%d",&c);
if(c==1)
goto X;
else
exit();

OUTPUT:
[IT@localhost ~]$
enter how many blocks already allocated 4
enter the blocks nos 2 4 5 8
enter index starting block & length 1 8
11
2file is already allocated
31
4file is already allocated
5file is already allocated
61
71
8 file is already allocated
91
101
111
121

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


63
CS8461-Operating systems Lab Department of IT 2019-2020

Ex No: 15C INDEXED FILE ALLOCATION TECHNIQUE

AIM:
To write a C program to implementation indexed file allocation techniques.

ALGORITHM:
1. Start.
2. Get the index block number and number of files in the index block as input from user.
3. Get the file numbers (i.e referred block numbers holding file) as input .
4. Check whether that the input block number is already allocated if so print block allocated
a. Else increase the count and allocate the file.
5. Continue the loop to enter another index block.
6. Stop

PROGRAM
#include<stdio.h>

int main()
{
int f[50],indblk,i,k,j,index[50],n,c,count=0;

for(i=0;i<50;i++)
f[i]=0;
X:
printf("enter index block");
scanf("%d",&indblk);
if(f[indblk]!=1)
{
f[indblk]=1;
printf("enter no of files on index");
scanf("%d",&n);
}
Y:
for(i=0;i<n;i++)
{
scanf("%d",&index[i]);
if(f[index[i]]==0)
{
count++;
}
}
if(count==n)
{
for(j=0;j<n;j++)
f[index[j]]=1;
printf("\nallocated");
printf("\n file indexed");
for(k=0;k<n;k++)
printf("\n%d->%d:%d",indblk,index[k],f[index[k]]);
}

St.Joseph’s College of Engineering ISO 9001:2008


64
CS8461-Operating systems Lab Department of IT 2019-2020

else
{
printf("\n file in the index already allocation");
printf("\nenter another file indexed");
goto Y;
}
printf("\n index is already allocated");
count=0;
printf("\n if u enter one more block(1/0)");
scanf("%d",&c);
if(c==1)
goto X;

OUTPUT:
[IT@localhost ~]$
enter index block 3
enter no of files on index 4
5678

allocated
file indexed
3  5:1
3  6:1
3 7:1
3 8:1
index is already allocated
if u enter one or more block(1/0)

RESULT:

St.Joseph’s College of Engineering ISO 9001:2008


65
CS8461-Operating systems Lab Department of IT 2019-2020

Ex.No:16 MEMORYMANAGEMENT SCHEME - SEGMENTATION

AIM

To implement memory management segmentation scheme using C.

ALGORITHM

1. Start.
2. Get Segment number, base and limit address.
3. Define insert function to create segments and add segmentation details for each.
4. Define find function to search and get the segment details for the given segment number.
5. To display the segment details get segment number and offset.
6. Segment details are displayed when offset is less than limit of the given segment number
7. calculate physical memory address as

phyaddr=base+offset

8. Display the physical address in the segment of the given offset.


9. Stop.

St.Joseph’s College of Engineering ISO 9001:2008


66
CS8461-Operating systems Lab Department of IT 2019-2020

PROGRAM
#include<stdio.h>
structlist
{
intseg;
intbase;
intlimit;
structlist *next;
}*p;
voidinsert(struct list *q,int base,int limit,int seg)
{
if(p==NULL)
{
p=malloc(sizeof(structlist));
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(structlist));
q->next->limit=limit;
q->next->base=base;
q->next->seg=seg;
q->next->next=NULL;
}
}
intfind(struct list *q,int seg)
{
while(q->seg!=seg)
{
q=q->next;
}
returnq->limit;
}
intsearch(struct list *q,int seg)
{
while(q->seg!=seg)
{
q=q->next;
}
returnq->base;
}
main()
{

St.Joseph’s College of Engineering ISO 9001:2008


67
CS8461-Operating systems Lab Department of IT 2019-2020

p=NULL;
intseg,offset,limit,base,c,s,physical;
printf("Entersegment table/n");
printf("Enter-1 as segment value for termination\n");
do
{
printf("Entersegment number");
scanf("%d",&seg);
if(seg!=-1)
{
printf("Enterbase value:");
scanf("%d",&base);
printf("Entervalue for limit:");
scanf("%d",&limit);
insert(p,base,limit,seg);
}
}while(seg!=-1);
printf("Enteroffset:");
scanf("%d",&offset);
printf("Enterbsegmentation number:");
scanf("%d",&seg);
c=find(p,seg);
s=search(p,seg);
if(offset<c)
{
physical=s+offset;
printf("Addressin physical memory %d\n",physical);
}
else
{
printf("error");
}
}
OUTPUT
[IT@localhost]# a.out
Entersegment table/nEnter -1 as segment value for termination
Entersegment number1
Enterbase value:2000
Entervalue for limit:500
Entersegment number2
Enterbase value:3000
Entervalue for limit:600
Entersegment number-1
Enteroffset:50
Enterbsegmentation number:2
Addressin physical memory 3050

RESULT

St.Joseph’s College of Engineering ISO 9001:2008


68
CS8461-Operating systems Lab Department of IT 2019-2020

VIVA QUESTIONS
1. Define program and process?
i. A Program is a passive entity, such as the contents of a file stored on disk, whereas a
process is an active entity, with a program counter specifying the next instruction
to execute.
2. What are the activities performed by the main-memory management?
a. Keeping track of which parts of memory are currently being used and by whom.
b. Deciding which processes are to be loaded into memory when memory space becomes
available.
c. Allocating and deal locating memory space as needed.
3. Define file?
i. Is a collection of related information defined by its creator.
4. What are the components consists in I/O- system management?
a. A memory- management component that included buffering, caching, and spooling
b. A general device-driver interface
c. Drivers for specific hardware devices.
5. Define protection?
i. Is any mechanism for controlling the access of programs, processes, or users to the
resources defined by he computer system. This mechanism must provide means for
specification of the controls to be imposed and means of enforcement.
6. What are the services given by the operating system?
a. Program execution
b. I/o operations
c. File-system manipulation
d. Communications
e. Error detection
7. Define system call?
i. It provides the interface between a process and the operating system. Its categories
are process control, file management, device management, information maintenance,
and communications.
8. Define process state?
i. The state of a process is defined in part by the current activity of that process. Each
process may be in one of the following states:
1. New, running, waiting, ready and terminated.
9. Define IPC?It provides a mechanism to allow processes to communicate and to synchronize their
actions without sharing the same address space.
1. Example: Chat program
10. What are the two possibilities exist in terms of execution while creating a process?
a. The parent continues to execute concurrently with its execution
b. The parent waits until some or all of its children have terminated.
11. Define control statements?
i. When a new job is started in a batch system, or when a user logs on to a time-shared
system, a program that reads and interprets control statements is executed
automatically
12. Give the use of critical-section problem?
i. Is to design a protocol that the processes can use to operate.
13. What are the 3 requirements to solve critical-section problem?
i. Mutual exclusion
ii.Progress
iii. Bounded waiting.

St.Joseph’s College of Engineering ISO 9001:2008


69
CS8461-Operating systems Lab Department of IT 2019-2020

14. Define Semaphores?


i. A semaphores S is an integer variable that, apart from initialization is accessed only
through two standard atomic operations: Wait and signal
15. Define monitors?
i. A monitor is characterized by a set of programmer-defined operators
16. How will you represent the monitors?
i. It consists of declaration of variables whose values define the state of an instance of
the type, as well as the bodies of procedures or functions that implements operations
on the type.
17. List the advantages of thread?
i. Thread minimizes context switching time.
ii.Use of threads provides concurrency within a process.
iii. Efficient communication.
iv. Utilization of multiprocessor architecture.
18. Define starvation?
i. Also called as indefinite blocking, a situation where processes wait indefinitely
within the semaphores
19. What is logical address space and physical address space?
i. The set of all logical addresses generated by a program is called a logical address
space; the set of all physical addresses corresponding to these logical addresses is a
physical address space.
20. What is the main function of the memory-management unit?
i. The runtime mapping from virtual to physical addresses is done by a hardware
device called a memory management unit (MMU).
21. What are overlays?
i. To enable a process to be larger than the amount of memory allocated to it, overlays
are used. The idea of overlays is to keep in memory only those instructions and data
that are needed at a given time. When other instructions are needed, they are loaded
into space occupied previously by instructions that are no longer needed.
22. Define swapping.
i. A process needs to be in memory to be executed. However a process can be
swapped temporarily out of memory to a backing store and then brought back into
memory for continued execution. This process is called swapping.
23. What are the common strategies to select a free hole from a set of available holes?
a. The most common strategies are
b. First fit
c. Best fit
d. Worst fit
24. What do you mean by best fit?
Best fit allocates the smallest hole that is big enough. The entire list has to be searched,
unless it is sorted by size. This strategy produces the smallest leftover hole.
25. What do you mean by first fit?
First fit allocates the first hole that is big enough. Searching can either start at the beginning
of the set of holes or where the previous first-fit search ended. Searching can be stopped as soon as a
free hole that is big enough is found.
26. Define Paging
Paging is a scheme that allows the logical address space of a process to be non-contiguous.
Paging avoids the considerable problem of fitting the varying sized memory chunks onto the backing
store.

St.Joseph’s College of Engineering ISO 9001:2008


70
CS8461-Operating systems Lab Department of IT 2019-2020

27. What do you mean by frames and pages?


Physical memory is broken into fixed size blocks called frames. Logical address is also
broken into blocks of same size called pages.
28. Define Page table
The page table contains the base address of each page in physical memory. This base address
is combined with the page offset to define the physical memory address that is sent to the
memory unit. The page number is used as an index into the page table.
29. Define Inverted Page table?
An inverted page table has one entry for each real page of memory. Each entry consists of
the virtual address of the page stored in that real memory.
30. Define Segmentation?
Segmentation is a memory management scheme that supports the user view of memory. A
logical address space is a collection of segments. Each segment has a name and length.
31. Define UFD and MFD.
i. In the two-level directory structure, each user has her own user file directory (UFD).
Each UFD has a similar structure, but lists only the files of a single user. When a job
starts the system’s master file directory (MFD) is searched. The MFD is indexed by
the user name or account number, and each entry points to the UFD for that user.
32. What is a path name?
i. A pathname is the path from the root through all subdirectories to a specified file. In
a two-level directory structure a user name and a file name define a path name.
33. Define Path-Name Translation.
a. It is done by breaking the path into component names and performing a separate NFS lookup
call for every pair of component name and directory vnode.
b. Nonmaskable interrupt is reserved for events such as unrecoverable memory errors.
34. Define Partition Control Block.
a. It contains partition details, such as the number of blocks in the partition, size of the blocks,
free-block count and free-block pointers, and free FCB count and FCB pointers.
b. A spool is a buffer that holds output for a device, such as printer, that cannot accept
interleaved data streams.
35.
What are the advantages of Indexed allocation?
solves external-fragmentation problem
solves the size-declaration problems.
Supports direct access
36. What are the various layers of a file system?
a. Application programs
b. Logical file system
c. File-organization module
d. Basic file system
e. I/O control
f. Devices
37. Define UFD and MFD.
In the two-level directory structure, each user has her own user file directory (UFD). Each UFD has a
similar structure, but lists only the files of a single user. When a job starts the system’s master file
directory (MFD) is searched. The MFD is indexed by the user name or account number, and each
entry points to the UFD for that user.
38. What is Marshalling?
Marshalling is a process that is used to communicate to remote objects with an
object(serialized object - serialization). It simplifies complex communication, using
custom/complex objects to communicate - instead of primitives.

St.Joseph’s College of Engineering ISO 9001:2008


71
CS8461-Operating systems Lab Department of IT 2019-2020

39. Define and explain COM?


COM (Component Object Model) technology in the Microsoft Windows-family of
Operating Systems enables software components to communicate. COM is used by
developers to create re-usable software components, link components together to build
applications, and take advantage of Windows services.
40. Difference - Loading and Linking
a. loading refers to storing large amt of data into the system.linking means one
program or page is related to another page or program.
b. What are different functions of Syntax phase, Sheduler?
c. Syntax phase sheduler deals with the problem of deciding which of the process in ready
queue is to allocate the CPU time for processing.
41. What are different tasks of Lexical analysis
The purpose of the lexical analyzer is to partition the input text, delivering a
sequence of comments and basic symbols. Comments are character sequences
to be ignored, while basic symbols are character sequences that correspond to
terminal symbols of the grammar defining the phrase structure of the input
42. What are main difference : Micro-Controller and Micro- Processor?
a. microprocessor:
b. 1 general purpose digital computer
c. 2 many operational codes for moving data from external memory to cpu
d. 3 rapid movement of code and data from external address to chip
43. microcontroller
a. 1 specific purpose digital computer
b. 2 one or two codes for moving data from external memory to cpu
c. 3 rapid movements of bits within the chip
44. What do you mean by deadlock?
Deadlock is a situation where the resources are not allocated to the process because they are
already used by another process..ie../suppose P1 requests resources of P2 which is already
used by P3 and so on. this is not the only case for occurrence of deadlock. for a dead lock to
occur there are 3 necessary conditions 1)Mutual Exclusion 2)Non-Preemption 3)Hold and
wait
45. How does Windows NT supports Multitasking?
a. Windows NT support multitasking by using extra memory and it also support multitasking
by using the network. It is especially designed for that cause.
b. in Microsoft Windows
46. Explain the Unix Kernel?
The kenel is a control core of UNIX. It is the part of operating system that interacts directly
with the hardware of the computer system , throuth device driver that are built into the
kernel.
47. What is Context Switch?
Switching the CPU to another process requires saving the state of the old process and
loading the saved state for the new process. This task is known as a context switch. Context-
switch time is pure overhead, because the system does no useful work while switching. Its
speed varies from machine to machine, depending on the memory speed, the number of
registers which must be copied, the existed of special instructions(such as a single
instruction to load or store all registers).
48. What is cache memory?
Cache memory is random access memory (RAM) that a computer microprocessor can access
more quickly than it can access regular RAM. As the microprocessor processes data, it looks

St.Joseph’s College of Engineering ISO 9001:2008


72
CS8461-Operating systems Lab Department of IT 2019-2020

first in the cache memory and if it finds the data there (from a previous reading of data), it
does not have to do the more time-consuming reading of data from larger memory.
49. What is a Safe State and what is its use in deadlock avoidance?
When a process requests an available resource, system must decide if immediate allocation
leaves the system in a safe state. System is in safe state if there exists a safe sequence of all
processes. Deadlock Avoidance: ensure that a system will never enter an unsafe state.
50. What is a Real-Time System?
A real time process is a process that must respond to the events within a certain time period.
A real time operating system is an operating system that can run real time processes
successfully.
51. Explain the concept of Reentrancy?
A reentrant procedure can be interrupted and called by an interrupting program, and still execute
correctly on returning to the procedure.
52. Explain Belady's Anomaly?
Also called FIFO anomaly. Usually, on increasing the number of frames allocated to a process
virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the
reverse happens, i.e., the execution time increases even when more frames are allocated to the
process. This is Belady's Anomaly.
53. What is a binary semaphore? What is its use?
A binary semaphore is one, which takes only 0 and 1 as values. They are used to implement mutual
exclusion and synchronize concurrent processes.
54. What is thrashing?
It is a phenomenon in virtual memory schemes when the processor spends most of its time swapping
pages, rather than executing instructions. This is due to an inordinate number of page faults.
55. List the Coffman's conditions that lead to a deadlock.
1. Mutual Exclusion: Only one process may use a critical resource at a time.
2. Hold & Wait: A process may be allocated some resources while waiting for others.
3. No Pre-emption: No resource can be forcible removed from a process holding it.
4. Circular Wait: A closed chain of processes exist such that each process holds at least one resource
needed by another process in the chain.

56. What is the resident set and working set of a process?


Resident set is that portion of the process image that is actually in real-memory at a particular
instant. Working set is that subset of resident set that is actually needed for execution.
57. When is a system in safe state?
The set of dispatchable processes is in a safe state if there exists at least one temporal order in which
all processes can be run to completion without resulting in a deadlock.
58. What is cycle stealing?
We encounter cycle stealing in the context of Direct Memory Access (DMA). Either the DMA
controller can use the data bus when the CPU does not need it, or it may force the CPU to temporarily
suspend operation. The latter technique is called cycle stealing. Note that cycle stealing can be done only
at specific break points in an instruction cycle.
59. What are the advantages of a multiprocessor system?
With an increased number of processors, there is considerable increase in throughput. It can also
save more money because they can share resources. Finally, overall reliability is increased as well.
60. What is kernel?
Kernel is the core of every operating system. It connects applications to the actual processing of data.
It also manages all communications between software and hardware components to ensure usability and
reliability.

St.Joseph’s College of Engineering ISO 9001:2008


73
CS8461-Operating systems Lab Department of IT 2019-2020

61. What are real-time systems?


Real-time systems are used when rigid time requirements have been placed on the operation of a
processor. It has well defined and fixed time constraints.
62. What is virtual memory?
Virtual memory is a memory management technique for letting processes execute outside of
memory. This is very useful especially is an executing program cannot fit in the physical memory.
63. Describe the objective of multiprogramming.
The main objective of multiprogramming is to have process running at all times. With this design,
CPU utilization is said to be maximized.
64. What are time sharing systems?
In a Time sharing system, the CPU executes multiple jobs by switching among them, also known as
multitasking. This process happens so fast that users can actually interact with each program while it is
running
.65. What is SMP?
SMP is short for Symmetric MultiProcessing, and is the most common type of multiple-processor
systems. In this system, each processor runs an identical copy of the operating system, and these copies
communicate with one another as needed.
66. How are server systems classified?
Server systems can be classified as either computer-server systems or file server systems. In the first
case, an interface is made available for clients to send requests to perform an action. In the second case,
provisions are available for clients to create, access and update files.
67. What is asymmetric clustering?
In asymmetric clustering, a machine is in a state known as hot standby mode where it does nothing
but to monitor the active server. That machine takes the active server’s role should the server fails.
68. What is a thread?
A thread is a basic unit of CPU utilization. In general, a thread is composed of a thread ID, program
counter, register set and the stack.
69. Give some benefits of multithreaded programming.
– there is an increased responsiveness to the user
– resource sharing within the process
– economy
– utilization of multiprocessing architecture
70. Briefly explain FCFS.
FCFS is short for First-come, first-served, and is one type of scheduling algorithm. In this scheme,
the process that requests the CPU first is allocated the CPU first. Implementation is managed by a FIFO
queue.
71. What is RR scheduling algorithm?
RR (round-robin) scheduling algorithm is primarily aimed for time-sharing systems. A circular
queue is setup in such a way that the CPU scheduler goes around that queue, allocating CPU to each
process for a time interval of up to around 10 to 100 milliseconds.
72. What is fragmentation?
Fragmentation is memory wasted. It can be internal if we are dealing with systems that have fixed-
sized allocation units, or external if we are dealing with systems that have variable-sized allocation units.
73. How does swapping result in better memory management?
During regular intervals that are set by the operating system, processes can be copied from main
memory to a backing store, and then copied back later. Swapping allows more processes to be run that
can fit into memory at one time.
74. What is busy waiting?
The repeated execution of a loop of code while waiting for an event to occur is called busy-waiting.
The CPU is not engaged in any real productive activity during this period, and the process does not
progress toward completion.

St.Joseph’s College of Engineering ISO 9001:2008


74
CS8461-Operating systems Lab Department of IT 2019-2020

75. When does the condition 'rendezvous' arise?


In message passing, it is the condition in which, both, the sender and receiver are blocked until the
message is delivered.
76. What is a trap and trapdoor?
Trapdoor is a secret undocumented entry point into a program used to grant access without normal
methods of access authentication. A trap is a software interrupt, usually the result of an error condition.
77. What is a socket?
A socket provides a connection between two applications. Each endpoint of a communication is a
socket.
78. What is Direct Access Method?
Direct Access method is based on a disk model of a file, such that it is viewed as a numbered
sequence of blocks or records. It allows arbitrary blocks to be read or written. Direct access is
advantageous when accessing large amounts of information.
79. When does trashing occur?
Trashing refers to an instance of high paging activity. This happens when it is spending more time
paging instead of executing.
80. Describe the Buddy system of memory allocation.
Free memory is maintained in linked lists, each of equal sized blocks. Any such block is of size 2^k.
When some memory is required by a process, the block size of next higher order is chosen, and broken
into two. Note that the two such pieces differ in address only in their kth bit. Such pieces are called
buddies. When any used block is freed, the OS checks to see if its buddy is also free. If so, it is rejoined,
and put into the original free-block linked-list.
81. What is page cannibalizing?
Page swapping or page replacements are called page cannibalizing.
82. What are the four layers that Windows NT have in order to achieve independence?
1. Hardware abstraction layer
2. Kernel
3. Subsystems
4. System Services.
83. What is SMP?
To achieve maximum efficiency and reliability a mode of operation known as symmetric
multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor.
84. What are the key object oriented concepts used by Windows NT?
Encapsulation, Object class and instance.
85. What is a drawback of MVT?
It does not have the features like
1. ability to support multiple processors
2. virtual storage
3. source level debugging
86. What is process spawning?
When the OS at the explicit request of another process creates a process, this action is called process
spawning.
87.What is process spawning?
When the OS at the explicit request of another process creates a process, this action is called process
spawning.
88. List out some reasons for process termination.
1. Normal completion
2. Time limit exceeded
3. Memory unavailable
4. Bounds violation
5. Protection error

St.Joseph’s College of Engineering ISO 9001:2008


75
CS8461-Operating systems Lab Department of IT 2019-2020

89. What are the reasons for process suspension?


1. swapping
2. interactive user request
3. timing
4. parent process request
90.What is process migration?
It is the transfer of sufficient amount of the state of process from one machine to the target machine.
91. What is mutant?
In Windows NT a mutant provides kernel mode or user mode mutual exclusion with the notion of
ownership.
92. What is an idle thread?
The special thread a dispatcher will execute when no ready thread is found.
93. What is FtDisk?
It is a fault tolerance disk driver for Windows NT.
94. What are the possible threads a thread can have?
1. Ready
2. Standby
3. Running
4. Waiting
5. Transition
6. Terminated
95. What are DDks? Name an operating system that includes this feature.
DDks are device driver kits, which are equivalent to SDKs for writing device drivers. Windows NT
includes DDks.
96. What is Executive in Windows NT?
In Windows NT, executive refers to the operating system code that runs in kernel mode.
97. Explain Booting the system and Bootstrap program in operating system.
The procedure of starting a computer by loading the kernel is known as booting the system.
When a user first turn on or booted the computer, it needs some initial program to run. This initial
program is known as Bootstrap Program. It is stored in read-only memory (ROM) or electrically
erasable programmable read-only memory (EEPROM). Bootstrap program locates the kernel and
loads it into main memory and starts its execution.
98. What are the different types of Kernel?
Kernels are basically of two types:
a.) Monolithic Kernels - In this architecture of kernel, all the system services were packaged into a
single system module which lead to poor maintainability and huge size of kernel.
b.) Microkernels - They follow the modular approach of architecture. Maintainability became easier
with this model as only the concerned module is to be altered and loaded for every function. This
model also keeps a tab on the ever growing code size of the kernel.
99. What is a daemon?
- Daemon - Disk and execution monitor, is a process that runs in the background without user’s
interaction. They usually start at the booting time and terminate when the system is shut down.
100. Explain condition variable.
- These are synchronization objects which help threads wait for particular conditions to occur.
- Without condition variable, the thread has to continuously check the condition which is very costly
on the resources.
- Condition variable allows the thread to sleep and wait for the condition variable to give it a signal.

St.Joseph’s College of Engineering ISO 9001:2008


76

Vous aimerez peut-être aussi