0% found this document useful (0 votes)
18 views

Os Record

Uploaded by

Krisha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Os Record

Uploaded by

Krisha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 81

CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

SUB CODE : CS1407


SUB : OPERATING SYSTEMS LABORATORY
SEM/YEAR: IV SEM & II YEAR
BRANCH: IT, AML

St.Joseph’s College of Engineering


1
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

CS1407 OPERATING SYSTEMS LABORATORY LTPC 0042

OBJECTIVES

● To learn basic Unix commands, shell programming and to implement various Process Management
functions such as IPC and Scheduling
● To implement Process Synchronization, Deadlock Detection and Avoidance and Memory Allocation
methods
● To implement Paging Techniques and File Management Techniques

LIST OF EXPERIMENTS

1. Simulation of Unix Commands like cp, ls, grep, cd, mkdir, cat, rm etc.,
2. Implementation of Shell Programs.
3. Implementation of CPU Scheduling Algorithms.
4. Implementation of Producer Consumer problem using Semaphore.
5. Implementation of Inter-process Communication using Shared memory.
6. Implementation of Threading and Synchronization Applications
7. Implementation of Bankers Algorithm for Deadlock Avoidance.
8. Implementation of Deadlock Detection Algorithm.
9. Implementation of Contiguous Memory Allocation.
10. Implementation of Memory Management scheme using Paging.
11. Implementation of Page Replacement Algorithms.
12. Implementation of Directory Structures.
13. Implementation of File Allocation Strategies.

TOTAL: 60 PERIODS
OUTCOMES:
● Develop simple applications with shell programming and Scheduling mechanisms

● Design and develop applications for synchronization, deadlock avoidance and detection

● Develop applications for implementing Paging and File management concepts

St.Joseph’s College of Engineering


2
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

St.Joseph’s College of Engineering


3
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

LIST OF EXPERIMENTS

OPERATING SYSTEMS LAB

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

PAGE
S.NO NAME OF THE PROGRAM
NO

a) Basics of UNIX commands.


1.
b) Simulation of UNIX commands

2.
Implementation of Shell Programs.
Implementation of CPU Scheduling Algorithms.
a. FCFS
3.
b. SJF
c. Priority
d. Round Robin
4.
Implementation of Producer Consumer problem using Semaphore
5.
Implementation of Inter-process Communication using Shared memory
6.
Implementation of Threading and Synchronization Applications
7.
Implementation of Bankers Algorithm for Deadlock Avoidance.
8.
Implementation of Deadlock Detection Algorithm.
Implementation of Contiguous Memory Allocation.
9. a) First Fit
b) Best Fit
c) Worst Fit
10.
Implementation of Memory Management scheme using Paging.

Implementation of Page Replacement Algorithms.


11. a) FIFO
b) LRU
c) Optimal
12. Implementation of Directory Structures.

Implementation of File Allocation Strategies.


13. a) Contiguous
b) Linked
c) Indexed
14. Implement Segmentation Technique of memory management

St.Joseph’s College of Engineering


4
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

St.Joseph’s College of Engineering


5
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex No: 1a
Date : Basics of UNIX commands.

1.pwd
Display the full path of the current working directory
user@sys246:~$ pwd
/home/user

2.ls
This command displays the list of files in current working directory
$ls -l list the files in long format
$ls -t list in order of last modification time
$ls -d Lists directory instead of contents
$ls -u Lists in order of last access
user@sys246:~$ ls
f1.c f2.c f3.txt f4.txt CSEal

3.cd
This command is used to change from working directory to any other directory specified
$cd directoryname
user@sys107:~$ cd Desktop
user@sys107:~/Desktop$

4. cd..
This command is used to come out of the current working directory.
$cd..
user@sys107:~/Desktop $ cd
user@sys107:~$

5.mkdir
This command helps us to make a directory
$mkdir directoryname
user@sys246:~$ mkdir cse.

6.rmdir
This command is used to remove a directory specified in command line.
$rmdir directoryname
user@sys246:~$ rmdir cse
user@sys246:~$ ls
f1.c f2.c f3.txt f4.txt f4.c f5.c

7.cat
This command helps us to list the contents of the file we specify.
$cat[option][file]
cat>filename - This is used to create a new file
cat>>filename - This is used to append the contents of the file
user@sys246:~$ cat f4.c
India is good country

St.Joseph’s College of Engineering


6
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

8.cp
This command helps us to create duplicate copies of ordinary files.
$cp source destination
user@sys246:~$ cp f1.c f5.c
user@sys246:~$ ls
f1.c f2.c f3.txt f4.txt f5.c CSEal

9.mv
This command is used to move or rename the files.
$mv source destination
user@sys246:~$ mv f1.c f4.c
user@sys246:~$ ls
f2.c f3.txt f4.txt f5.c f4.c CSEal
user@sys246:~$

10.ln
This command is to establish an additional filename for the same ordinary file.
$ln firstName secondName
user@sys246:~$ ls
f1.c f2.c f4.c f5.c f3.txt f4.txt IT
user@sys246:~$ ln -t CSE f5.c
user@sys246:~$ cd CSE
user@sys246:~$ ls
F5.c

11.rm
This command is used to delete one or more files from the directory.
$rm [option] filename
$rm -i : Asks the user if he wants to delete the file mentioned.
$rm -r : Recursively delete the entire contents of directory as well as the directory itself
user@sys246:~$ rm f3.txt
user@sys246:~$ ls
f2.c f4.txt f5.c f4.c CSEal
user@sys246:~$

PROCESS AND STATUS INFORMATION COMMANDS:

1.who
This command gives the details of who all have logged into the UNIX system currently.
$who
user@sys246:~$ who
guest-lpdjsy tty7 2023-03-07 08:56 (:0)
user tty8 2023-03-07 09:30 (:1)

2.who am i

St.Joseph’s College of Engineering


7
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

This command tells us as to when we had logged in and the system’s name for the connection being used.
$whoami
user@sys246:~$ whoami
user

3.date
This command displays the current date in different formats.
+%D mm/dd/yy +%w Day of the week
+%H hr-00 to 23 +%a Abbr Weekday
+%M min-00 to 59 +%h Abbr Month
+%S sec-00 to 59 +%r Time in AM/PM
user@sys246:~$ date
Tue Mar 7 09:45:00 IST 2023
user@sys246:~$ date +%m
03

4.echo
This command will display the text typed from keyboard.
$echo
user@sys246:~$ echo SJCE
SJCE

TEXT RELATED COMMANDS


1.head
Displays the initial part of the text file. By default, it displays the first 10 lines of a file.
user@sys246:~$ head -1 f3.txt
Hi this is Unix Lab

2.tail
Displays the last part of he text file. By default, it displays the last 10 lines of a file.
user@sys246:~$ tail -1 f3.txt
I am studying B.E CSE in SJCE.

3.wc
This command is used to count the no.of lines,words, characters in a file.
$wc[-lwc]filename
user@sys246:~$ wc f1.txt
8 26 150 f4.txt

4.find
The find command is used to locate files in a directory and in a subdirectory.
user@sys246:~$ find
.
./1.c
./asd.bak
./f1.txt
./file_copy.c
./f2.c
./a.out

St.Joseph’s College of Engineering


8
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

FILE PERMISSION COMMANDS


1.chmod

Change the file/directory permission mode $chmod777 file 1. Give full permission to owner, groups, and
others $chmod o-w file 1. Remove write permission for others.

user@sys246:~$chmod777 welcome.txt.

USEFUL COMMANDS:
1.exit
Ends your work on the UNIX system.
user@sys246:~$ exit

2.clear
Clears the screen
user@sys246:~$ clear

3.Ctrl-z
Pauses the currently running program
user@sys246:~$ pause

4. man COMMAND
Looks up the UNIX command in online manual pages.
user@sys246:~$ man
What manual page do you want?
user@sys246:~$ man ls
NAME
ls - list directory contents

SYNOPSIS
ls [OPTION]... [FILE]...

DESCRIPTION
List information about the FILEs (the current direc‐
tory by default). Sort entries alphabetically if none
of -cftuvSUX nor --sort is specified.

Mandatory arguments to long options are mandatory for


short options too.
5. Ctrl-c
Stops the program currently running

6.history
Lists all the commands typed so far.
user@sys246:~$ history
10 mkdir os
11 ls
12 who
13 who am i
14 date

St.Joseph’s College of Engineering


9
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

15 whoami
16 echo
17 echo hello
7. more FILE

Display the contents of FILE, pausing after each screenful. There are several keys that control the output
once a screenful has been printed. <enter> will advance the output one line at a time. <spacebar> will
advance the output by another full screenful. “q” will quit and return you to the UNIX prompt.

user@sys246:~$more message1
Hello
Welcome
8.less FILE

“less” is a program similar to “more”, but which allows backward movement in the file as well as forward
movement.

user@sys246:~$less message1
Hello
Message
message1(end).

RESULT

St.Joseph’s College of Engineering


10
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex No: 1b SIMULATION OF UNIX COMMANDS


Date :

AIM:
To write a ‘C’ program for implementing ls, cp, grep, cat command

// ls command
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 The 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
user@sys246:~$ gcc pg2.c
user@sys246:~$ ./a.out

Enter The Directory Name: os


chap1.c
chap2.c
user@sys246:~$

St.Joseph’s College of Engineering


11
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

//cp command

ALGORITHM:

Step 1: Get the name of the source and destination file from the command line.
Step 2: Open the source file in read-only mode using the open system call. If the file could not be open, print
an error message.
Step 3: Create the destination file using creat system call. If the file could not be open, print an error
message.
Step 4: Read from the source file using the read system call and store the content in the buffer.
Step 5: From the buffer write to the destination file using the write system call.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int f1,f2,n;
char buf[512];
if(argc!=3)
{
printf("Error in the number of argument");
exit(1);
}
if((f1=open(argv[1],0))<0)
{
printf("Can't open %s",argv[1]);
exit(1);
}
if((f2=creat(argv[2],0))<0)
{
printf("Can't create %s",argv[2]);
exit(1);
}
n=read(f1,buf,512);
write(f2,buf,n);
close(f1);
close(f2);
}
OUTPUT
user@sys246:~$ gcc pg4.c
user@sys246:~$ ./a.out samp.txt s1.txt
user@sys246:~$ cat samp.txt
hello welcome to Chennai.
user@sys246:~$ cat s1.txt
hello welcome to Chennai.
user@sys246:~$
user@sys246:~$ ./a.out
Error in the number of argument

St.Joseph’s College of Engineering


12
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

// SIMULATION OF GREP COMMAND

ALGORITHM:
Step 1: Include the header files essential to simulate CAT command.
Step 2: Create a file with some contents in it.
Step 3: Give two choices
( i ) To print the similar pattern word.
( ii ) To print the entire line of the specified pattern.
Step 4: Define the two cases using Switch cases.
Step 5: Print the lines of similar pattern depending upon the choice of selection.
Step 6: Close the file and exit.

PROGRAM:
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<string.h>
#define bs 1024
void main()
{
FILE *f1;
char *ptr,file1[bs],str[bs],pat[bs];
printf("Enter the file name :");
scanf("%s",file1);
printf("Enter the pattern to be searched :");
scanf("%s",pat);
f1=fopen(file1,"r");
while(!feof(f1))
{
fscanf(f1,"%s",str);
if((strstr(str,pat))!=NULL)
{
printf("The substring is %s\n",str);
}
}
}

OUTPUT
user@sys246:~$ gcc pg7.c
user@sys246:~$ ./a.out
Enter the file name :pg6.c
Enter the pattern to be searched :%
The substring is printf("%s\n",et->d_name);
user@sys246:~$ ./a.out
Enter the file name :pg5.c
Enter the pattern to be searched :#
The substring is #include<stdio.h>
The substring is #include<sys/stat.h>
The substring is #include<fcntl.h>
The substring is #define
user@sys246:~$

St.Joseph’s College of Engineering


13
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

// SIMULATION OF CAT COMMAND


ALGORITHM:

Step 1: Include the header files essential to simulate CAT command.


Step 2: Define Buffer size of 1024 which can be used as the standard size for file and buffer.
Step 3: Create a source file with some contents in it.
Step 4: Open the source file in READ mode.
Step 5: Print the contents of the file that was opened in READ mode.
Step 6: Close the file and exit.

PROGRAM:
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#define bs 1024
main()
{
FILE *f;
char fil1[bs], buf[bs];
printf("Enter the filename:\n");
scanf("%s", &file1);
f=open(fil1, O_RDONLY, bs);
if(read(f, buf, bs)>0)
{
printf("%s", buf);
}
else
{
printf("File does not exists");

}
close(f);
}

OUTPUT
user@sys246:~$ gcc pg5.c
user@sys246:~$ ./a.out
Enter the filename:
samp.txt
hello welcome to Chennai.
user@sys246:~

RESULT

St.Joseph’s College of Engineering


14
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex No: 2a SHELL PROGRAMMING


Date :
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:
user@sys246:~$ 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

RESULT

St.Joseph’s College of Engineering


15
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex No: 2b IMPLEMENTATION OF UNIX COMMANDS USING CASE


Date :
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:
Enter the total number of elements
4
Enter the element one by one
20
25
50
10
The largest of all the elements is 50
RESULT:

Ex No: 3A FCFS SCHEDULING


Date :

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

ALGORITHM:

St.Joseph’s College of Engineering


16
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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++)
{
printf(" P%d |",i+1);
}
printf("\n");
for(i=0;i<n;i++)
{
printf("--------");

St.Joseph’s College of Engineering


17
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

}
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
user@sys49:~/Desktop/prog$ ./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


18
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex No: 3B SJF SCHEDULING


Date :

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];

St.Joseph’s College of Engineering


19
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

} 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]);
} 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
user@sys49:~/Desktop/prog$ ./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 |

St.Joseph’s College of Engineering


20
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

------------------------
0 1 3 6
Total waiting time :4

Total turnaround time :10

Average waiting time :1.33

Average turn around time :3.33

RESULT:

Ex No: 3C PRIORITY SCHEDULING


Date :
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++)

St.Joseph’s College of Engineering


21
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

{
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;
}}}
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;

St.Joseph’s College of Engineering


22
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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

OUTPUT
user@sys49:~/Desktop/prog$ ./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

St.Joseph’s College of Engineering


23
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

RESULT:

St.Joseph’s College of Engineering


24
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex No: 3D ROUND ROBIN SCHEDULING


Date :

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 2 nd 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;

St.Joseph’s College of Engineering


25
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

else
x++;
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++)

St.Joseph’s College of Engineering


26
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

{
wat[i]=k[i]-bur1[i];
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
user@sys246:~$ ./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


27
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex No: 4 PRODUCER CONSUMER PROBLEM USING SEMAPHORES


Date :

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.

PROGRAM:
#include<stdio.h> #include<string.h>
#define SIZE 3
struct process
{
char a[5];
}buffer[SIZE];
int mutex=1,full=0,empty=SIZE,f=0;
int main()
{
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;
}
mutex=signal(mutex);

St.Joseph’s College of Engineering


28
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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:
69 of 190

//Thread created and called for execution

printf("Enter Correct Option");


break;
}}}
int wait(int s)
{
if(s==0)
f=1;
else
s--;
return s;
}
int signal(int s)
{

St.Joseph’s College of Engineering


29
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

s++;
return s;
}
OUTPUT
user@sys246:~$ ./a.out
Producer Consumer Problem:
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

St.Joseph’s College of Engineering


30
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

3.Buffer Contents
4.Exit
Enter your Choice:3
Buffer is empty
RESULT:

Ex No: 5 INTER PROCESS COMMUNICATION USING SHARED MEMORY


Date :

AIM:
To write a program to implement inter process communication using 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.
PROGRAM:

#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

St.Joseph’s College of Engineering


31
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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

}
exit(0);
}

OUTPUT
user@sys246:~$ ./a.out
abcdefghijklmnopqrstuvwxyz
user@sys246:~$ ipcs

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


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

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


key semid owner perms nsems

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


key msqid owner perms used-bytes messages

RESULT:

St.Joseph’s College of Engineering


32
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex.No:6 PTHREADS & ITS SYNCHRONIZATION


Date :

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


33
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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

user@sys246:~$ cc –pthread filename.c

Job 1 started
Job 2 started

Job 1 finished
Job 2 finished

RESULT

St.Joseph’s College of Engineering


34
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex.No:7 DEAD LOCK AVOIDANCE USING BANKERS ALGORITHM


Date :

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


35
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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++)
{

St.Joseph’s College of Engineering


36
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

need[i][j]= max[i][j]-allocation[i][j];
printf("\t %d",need[i][j]);
}
printf("\n");
}
do{
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


37
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

OUTPUT

Input the number of processes running ( <10 )..3

Input the number of resources ( <5 )..3

Input the allocation matrix for the processes in row major order..

Process 0

Resource 0
121

Resource 1

Resource 2

Process 1

Resource 0
323

Resource 1

Resource 2

Process 2

Resource 0
123

Resource 1

Resource 2

Input the no. of resources that a process can maximum have..

Process 0

Resource 0
232

St.Joseph’s College of Engineering


38
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Resource 1

Resource 2

Process 1

Resource 0
434

Resource 1

Resource 2

Process 2

Resource 0
234

Resource 1

Resource 2

Input the no. of available instances of each resource..

Resource 0 : 2 1 2

Resource 1 :
Resource 2 :
The need matrix is as follows :
1 1 1
1 1 1
1 1 1

*******************IT'S A SAFE STATE*******************


The safe sequence is....
P0 P1 P2

The available matrix is now : 7 7 9

RESULT

St.Joseph’s College of Engineering


39
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex.No:8 DEAD LOCK DETECTION USING BANKERS ALGORITHIM


Date :

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++)
{

St.Joseph’s College of Engineering


40
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

scanf("%d",&ins[i]);
}
//To calculate resource availability vector
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)
{

St.Joseph’s College of Engineering


41
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

count++;
}
}
}
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

user@sys246:~$

RESULT

St.Joseph’s College of Engineering


42
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex.No: 9 MEMORY ALLOCATION METHODS


Date :

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;
}

St.Joseph’s College of Engineering


43
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

//display allocation details


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;

St.Joseph’s College of Engineering


44
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

static int barray[20],parray[20];


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


45
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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++)
{
St.Joseph’s College of Engineering
46
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

if(part[j]<part[i])
{
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


47
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

{
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


48
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex.No:10 MEMORY MANAGEMENT USING PAGING TECHNIQUE


Date :

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


49
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

}
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


50
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

OUTPUT

user@sys246:~$ ./a.out

RESULT

St.Joseph’s College of Engineering


51
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex.No:11A FIFO PAGE REPLACEMENT ALGORITHM


Date :

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


52
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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

OUTPUT

user@sys246:~$ ./a.out

RESULT

St.Joseph’s College of Engineering


53
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex No:11B LRU PAGE REPLACEMENT ALGORITHM


Date :

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>
int 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++;

St.Joseph’s College of Engineering


54
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

for(j=0;j<k;j++)
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


55
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

OUTPUT

user@sys246:~$ ./a.out

RESULT

St.Joseph’s College of Engineering


56
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex No:11C OPTIMAL PAGE REPLACEMENT ALGORITHM


Date :

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)

St.Joseph’s College of Engineering


57
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

{
fr[count]=seq[i];
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;
}
}
}

St.Joseph’s College of Engineering


58
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

pf++;
fr[s]=seq[i];
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

user@sys246:~$ ./a.out

RESULT

St.Joseph’s College of Engineering


59
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex.No:12 DIRECTORY STRUCTURES


Date :

AIM: To write a C program to implement Directory Structures

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

St.Joseph’s College of Engineering


60
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

fopen("sample1.txt","w");
}
}
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];

St.Joseph’s College of Engineering


61
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

printf("Sharing file between two different directories\n");


printf("\n Enter the source and destination path from where the file to be shared \n ");
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

user@sys246:~$ ./a.out hook


Enter the file name to be created within hook directory
file1

user@sys246:~$ ./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


62
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex No: 13A CONTIGOUS FILE ALLOCATION STRATEGIES


Date :

AIM:
To write a C program to implement 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<stdlib.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;

printf("\n memory before allocation:\n");


display();
while(1)

St.Joseph’s College of Engineering


63
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

{
printf("\n enter the file id:");
scanf("%d",&id);
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


64
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

OUTPUT:

user@sys246:~$
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

St.Joseph’s College of Engineering


65
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

RESULT

Ex No: 13B LINKED LIST FILE ALLOCATION STRATEGIES


Date :

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>
#include<stdlib.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:

St.Joseph’s College of Engineering


66
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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++;
}
}
}
else
printf("\nif u enter one more (yes-1/no-0)");
scanf("%d",&c);
if(c==1)
goto X;
else
exit(0);

OUTPUT:
user@sys246:~$
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

St.Joseph’s College of Engineering


67
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

10🡪1

11🡪1

12🡪1

RESULT

Ex No: 13C INDEXED FILE ALLOCATION STRATEGIES


Date :

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;

St.Joseph’s College of Engineering


68
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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]]);
}
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:
user@sys43:~$ cc 13c.c
user@sys43:~$ ./a.out
enter index block3
enter no of files on index4
5678

allocated
file indexed

St.Joseph’s College of Engineering


69
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

3->5:1
3->6:1
3->7:1
3->8:1
index is already allocated
if u enter one more block(1/0)

RESULT:

St.Joseph’s College of Engineering


70
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

Ex.No:14 MEMORYMANAGEMENT SCHEME – SEGMENTATION


Date :

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.

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)

St.Joseph’s College of Engineering


71
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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

St.Joseph’s College of Engineering


72
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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


73
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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


74
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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


75
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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. WWhat 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.
39. Define and explain COM?

St.Joseph’s College of Engineering


76
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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
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.
St.Joseph’s College of Engineering
77
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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.
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.

St.Joseph’s College of Engineering


78
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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.
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.

St.Joseph’s College of Engineering


79
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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


80
CS1407-Operating systems Laboratory Department of IT &AML 2022-2023

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


81

You might also like