0% found this document useful (0 votes)
395 views113 pages

Cs6413-Os Lab Manual-Backup 2 New

The document describes experiments conducted to learn basic UNIX commands and process management using system calls. Experiment 1 covers basic UNIX commands like pwd, ls, cd, mkdir, rmdir, cat, cp, mv, ln, rm, who, date, echo. Experiment 1a implements process creation using fork(), getpid(), execvp(), wait() and termination using exit(). Experiment 1b covers directory management using opendir() and readdir(). Experiment 2 uses I/O system calls like open(), read(), write(), stat() to copy files. Experiment 3 aims to simulate UNIX commands like ls and grep.

Uploaded by

jegadeepa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
395 views113 pages

Cs6413-Os Lab Manual-Backup 2 New

The document describes experiments conducted to learn basic UNIX commands and process management using system calls. Experiment 1 covers basic UNIX commands like pwd, ls, cd, mkdir, rmdir, cat, cp, mv, ln, rm, who, date, echo. Experiment 1a implements process creation using fork(), getpid(), execvp(), wait() and termination using exit(). Experiment 1b covers directory management using opendir() and readdir(). Experiment 2 uses I/O system calls like open(), read(), write(), stat() to copy files. Experiment 3 aims to simulate UNIX commands like ls and grep.

Uploaded by

jegadeepa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 113

CS8461 OPERATING SYSTEMS LAB

EX NO: 1 BASICS OF UNIX COMMANDS


DATE :

AIM
To execute the commands in unix.

GENERAL COMMANDS
 pwd
o This command prints the current working directory
 ls
o This command displays the list of files in the current working directory.
 $ls –l Lists the files in the long format
 $ls –t Lists in the order of last modification time
 $ls –d Lists directory instead of contents
 $ls -u Lists in order of last access time
 cd
o This command is used to change from the working directory to any other
directory specified.
 $cd directoryname
 cd ..
o This command is used to come out of the current working directory.
 $cd ..
 mkdir
o This command helps us to make a directory.
 $mkdir directoryname
 rmdir
o This command is used to remove a directory specified in the command line. It
requires the specified directory to be empty before removing it.
 $rmdir directoryname
 cat
o This command helps us to list the contents of a 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
 cp
o This command helps us to create duplicate copies of ordinary files.
 $cp source destination
 mv
o This command is used to move files.
 $mv source destination
 ln
o This command is to establish an additional filename for the same ordinary file.
 $ln firstname secondname
 rm
o 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.

KINGS COLLEGE OF ENGINEERING 5


CS8461 OPERATING SYSTEMS LAB

 $rm –r Recursively delete the entire contents of the directory as well as


the
 directory itself.

PROCESS AND STATUS INFORMATION COMMANDS


 who
o This command gives the details of who all have logged in to the UNIX system
currently.
 $ who

 who am i
o This command tells us as to when we had logged in and the system’s name
for the
o connection being used.
 $who am i
 date
o This command displays the current date in different formats.
 echo
o This command will display the text typed from the keyboard.
 $echo, Eg: $echo Have a nice day

RESULT
Thus the basic unix commands were executed and verified.

KINGS COLLEGE OF ENGINEERING 6


CS8461 OPERATING SYSTEMS LAB

VIVA QUESTIONS

1. What is a directory?

2. Differentiate cmp command from diff command.

3. Differentiate cat command from more command.

4. Enumerate some of the most commonly used network commands in UNIX.

5. How to get last line from a file?

KINGS COLLEGE OF ENGINEERING 7


CS8461 OPERATING SYSTEMS LAB

EX. NO: 1(a) PROCESS MANAGEMENT USING SYSTEM CALLS OF UNIX


OPERATING SYSTEM: FORK, EXEC, GETPID, EXIT, WAIT, CLOSE.
DATE :

AIM
To write a program for implementing process management using the following
system calls of UNIX operating system: fork, exec, getpid, exit, wait, close.

ALGORITHM:
1. Start the program.
2. Read the input from the command line.
3. Use fork() system call to create process, getppid() system call used to get the parent
process ID and getpid() system call used to get the current process ID
4. execvp() system call used to execute that command given on that command line
argument
5. execlp() system call used to execute specified command.
6. Open the directory at specified in command line input.
7. Display the directory contents.
8. Stop the program.

PROGRAM:
#include
main(int arc,char*ar[])
{
int pid;
char s[100];
pid=fork();
if(pid0)
{
wait(NULL);
printf("\n Parent Process:\n");
printf("\n\tParent Process id:%d\t\n",getpid());
execlp("cat","cat",ar[1],(char*)0); error("can’t execute cat %s,",ar[1]);
} else {
printf("\nChild process:");
printf("\n\tChildprocess parent id:\t %d",getppid());
sprintf(s,"\n\tChild process id :\t%d",getpid());
write(1,s,strlen(s));
printf(" ");
printf(" ");
printf(" ");
execvp(ar[2],&ar[2]); error("can’t execute %s",ar[2]);
}
}

OUTPUT: [root@localhost ~]# ./a.out tst date


Child process:

KINGS COLLEGE OF ENGINEERING 8


CS8461 OPERATING SYSTEMS LAB

Child process id : 3137 Sat Apr 10 02:45:32 IST 2010


Parent Process:
Parent Process id:3136
sd
dsaASD[root@localhost ~]# cat tst
sd
dsaASD

RESULT: Thus the program for process management was written and successfully
executed.

EX NO:1 (b) Implementation of directory management using the following system calls of
UNIX operating system: opendir, readdir.

AIM: To write a program for implementing Directory management using the following
system calls of UNIX operating system: opendir, readdir.

ALGORITHM:
1.Start the program.
2. Open the directory at specified in command line input.
3. Display the directory contents.
4. Stop the program.

PROGRAM:
#include
#include
#include
main(int c,char* arg[])
{
DIR *d;
struct dirent *r;
int i=0; d=opendir(arg[1]);
printf("\n\t NAME OF ITEM \n");
while((r=readdir(d)) != NULL)
{
printf("\t %s \n",r->d_name);
i=i+1;
}
printf("\n TOTAL NUMBER OF ITEM IN THAT DIRECTORY IS %d \n",i);
}

OUTPUT: [root@localhost ~]# cc dr.c


[root@localhost ~]# ./a.out lab_print
NAME OF ITEM
pri_output.doc
sjf_output.doc
fcfs_output.doc

KINGS COLLEGE OF ENGINEERING 9


CS8461 OPERATING SYSTEMS LAB

rr_output.doc
ipc_pipe_output.doc
pro_con_prob_output.doc
TOTAL NUMBER OF ITEM IN THAT DIRECTORY IS 8

RESULT: Thus the program for directory management was written and successfully
executed

EX NO:2 I/O system calls of UNIX operating system


(open,read, write, etc)

AIM:
To write a program using the I/O system calls of UNIX operating system (open,
read, write, etc)

ALGORITHM:
1. Start the program.
2. Read the input from user specified file.
3. Write the content of the file to newly created file.
4. Show the file properties (access time, modified time, & etc,.)
5. Stop the program.

PROGRAM:
#include<stdio.h>
#include<sys/stat.h>
#include<time.h>
main(int ag,char*arg[])
{
char buf[100];
struct stat s;
int fd1,fd2,n;
fd1=open(arg[1],0);
fd2=creat(arg[2],0777);
stat(arg[2],&s);
if(fd2==-1)
printf("ERROR IN CREATION");
while((n=read(fd1,buf,sizeof(buf)))>0)
{
if(write(fd2,buf,n)!=n)
{
close(fd1);
close(fd2);
}
}
printf("\t\n UID FOR FILE.......>%d \n FILE ACCESS TIME.....>%s \n FILE
MODIFIED TIME........>%s \n FILE I-NODE NUMBER......>%d \n
PERMISSION FOR FILE.....>%o\n\n",s.st_uid,ctime
(&s.st_atime),ctime(&s.st_mtime),s.st_mode);
close(fd1);
close(fd2);
}

KINGS COLLEGE OF ENGINEERING 10


CS8461 OPERATING SYSTEMS LAB

OUTPUT:
[root@localhost ~]# cc iosys.c
[root@localhost ~]# ./a.out
UID FOR FILE.......>0
FILE ACCESS TIME.....>Thu Apr 8 01:23:54 2011
FILE MODIFIED TIME........>Thu Apr 8 01:23:54 2011
FILE I-NODE NUMBER......>33261
PERMISSION FOR FILE.....>1001101014

RESULT:
Thus the program using the I/O system calls was written and successfully
executed.

EX NO:3 SIMULATE UNIX COMMANDS LIKE LS, GREP

AIM:
To write a program to simulate UNIX commands like ls, grep, etc.

ALGORITHM:
1. Start the program.
2. Read the input through command line.
3. Open the specified file.
4. Options (c & i) are performed.
5. Stop the program.

PROGRAM:
#include<stdio.h>
#include<string.h>
main(int ag,char* arg[])
{
char buf[200],line[200];
int i,j,n,fd1,count=0,opt;
if(ag==4)
{
fd1=open(arg[3],0);
if(strcmp(arg[1],"-c")==0)
opt=2;
if(strcmp(arg[1],"-i")==0)
opt=3;
}
else if(ag==3)
{
fd1=open(arg[2],0);
opt=1;
}
if(fd1==-1)
printf("error in opening");
j=0;
switch(opt)
{
case 1:
while((n=read(fd1,buf,sizeof(line)))>0)
{
for(i=0;i<n;i++,j++)

KINGS COLLEGE OF ENGINEERING 11


CS8461 OPERATING SYSTEMS LAB

{
if(buf[i]!='\n') line[j]=buf[i];
else
{
line[j]='\n';
if(strstr(line,arg[1])!=0)
write(1,line,j+1);
}
}
}
break;
case 2:
while((n=read(fd1,buf,sizeof(line)))>0)
{
for(i=0;i<n;i++,j++)
{
if(buf[i]!='\n') line[j]=buf[i];
else
{
line[j]='\n';
if(strstr(line,arg[2])!=0)
count=count+1;
j=-1;
}
}
}
printf("%d \n",count);
break;
case 3:
while((n=read(fd1,buf,sizeof(line)))>0)
{
for(i=0;i<n;i++,j++)
{
if(buf[i]!='\n') line[j]=buf[i];
else
{
line[j]='\n';
if(strcasestr(line,arg[2])!=0)
write(1,line,j+1);
j=-1;
}
}
}
break;
}
close(fd1);
}

OUTPUT:
[root@localhost ~]# cat tst sd
dsaASD[root@localhost ~]# ./a.out -i a tst
aA[root@localhost ~]# ./a.out -c a tst 1[root@localhost ~]# ./a.out -c A tst
1[root@localhost ~]# ./a.out -c sd tst 1[root@localhost ~]# ./a.out -c s tst 2

KINGS COLLEGE OF ENGINEERING 12


CS8461 OPERATING SYSTEMS LAB

RESULT:
Thus the program to stimulate the UNIX commands was written and
successfully executed.

KINGS COLLEGE OF ENGINEERING 13


CS8461 OPERATING SYSTEMS LAB

EX.NO:2 SHELL PROGRAMMING


DATE :

EVEN OR ODD
AIM
To write a shell program to find whether a number is even or odd.
PROCEDURE
1. Read the input number.
2. Perform modular division on input number by 2.
3. If remainder is 0 print the number is even.
4. Else print number is odd.
5. Stop the program.
PROGRAM
echo "Enter the number"
read num echo "enter the number"
read num if [ `expr $num % 2` -eq 0 ] then
echo "number is even"
else echo "number is odd"
fi

OUTPUT
Enter the number: 5
the number is odd.

RESULT
Thus the shell program was executed and verified successfully.

BIGGEST OF TWO NUMBERS


AIM
To write a program to find the biggest of two numbers.
PROCEDURE
1. Read the two numbers.
2. If value of A is greater than B .
3. Print is A is big
4. Else print B Is Big.
5. Stop the program.
PROGRAM
echo "enter the number"
read a b if [ $a -gt $b ] then
echo "A is big"
else
echo "B is big" fi
OUTPUT
Enter the two number: 23 67
B is big
RESULT
Thus the shell program was executed and verified successfully.

KINGS COLLEGE OF ENGINEERING 14


CS8461 OPERATING SYSTEMS LAB

FACTORIAL OF NUMBER
AIM
To write a program to find the factorial of given number
PROCEDURE
1. Read a number
2. Initialize fact as 1
3. Initialize I as 1
4. While I is lesser than or equal to number
5. Multiply the value of I and fact and assign to fact
6. Increment the value of I by 1.
7. Print the result.
8. Stop the program.
PROGRAM
echo "enter the number"
read n
fact=1, i=1
while [ $i -le $n ]
do
fact=`expr $i \* $fact`
i=`expr $i + 1`
done
echo "the factorial number of $n is $fact”

OUTPUT
Enter the number : 4
The factorial of 4 is 24.

RESULT
Thus the shell program was executed and verified successfully.

KINGS COLLEGE OF ENGINEERING 15


CS8461 OPERATING SYSTEMS LAB

VIVA QUESTIONS:

1. How do you access command line arguments from a shell script?

2. Write down the syntax for all loops in shell scripting.

3. How do you terminate a shell script if statement?

4. How to count the words in a string without wc command?

5. What are the symbols used in bash shell scripting?

EX. NO: 3. IMPLEMENTATION OF A CPU SCHEDULING ALGORITHMS


DATE :
THEORY
Scheduling is a fundamental operating system function. CPU scheduling is the basis of
multi programming operating system. CPU scheduling algorithm determines how the CPU
will be allocated to the process. These are of two types.
1. Primitive scheduling algorithms
KINGS COLLEGE OF ENGINEERING 16
CS8461 OPERATING SYSTEMS LAB

2. Non-Primitive scheduling algorithms

1) Primitive Scheduling algorithms: In this, the CPU can release the process even in the
middle of execution. For example: the CPU executes the process p1, in the middle of
execution the CPU received a request signal from process p2, then the OS compares the
priorities of p1&p2. If the priority p1 is higher than the p2 then the CPU continue the
execution of process p1. Otherwise the CPU preempts the process p1 and assigned to
process p2.

2) Non-Primitive Scheduling algorithm: In this, once the CPU assigned to a process the
processor does not release until the completion of that process. The CPU will assign to
some other job only after the previous job has finished.

Scheduling Criteria
Scheduling may use in attempting to maximum system performance. The scheduling
policy determines the importance of each of the criteria some commonly used criteria are.
• CPU utilization
It is the function of time, during which the processor is busy. The load on the system
affects the level of utilization that can be achieved. It may range from 0% to 100% on large
and expensive system. Time shared system, CPU utilization may be the primary
consideration.
• Throughput
It refers to the amount of work completed in a unit of time. The number of processes
the system can execute in a period of time. The higher the number, the work is done by the
system.
• Turnaround time
From the point of view of a particular process, the important criterion is how long it
takes to execute that process. The interval from the time of submission of a process to the
time of completion is the turnaround time. Turnaround time is the sum of the periods spent
waiting to get into memory, waiting in the ready queue, executing on the CPU, and doing
I/O.
• Waiting time
The CPU-scheduling algorithm does not affect the amount of time during which a
process executes or does I/O. It affects only the amount of time that a process spends
waiting in the ready queue. Waiting time is the sum of the periods spent waiting in the ready
queue.
• Response time
In an interactive system, turnaround time may not be the best criterion. Often, a
process can produce some output fairly early and can continue computing new results while
previous results are being output to the user. Thus, another measure is the time from the
submission of a request until the first response is produced. This measure, called response
time, is the time it takes to start responding, not the time it takes to output the response.
The turnaround time is generally limited by the speed of the output device.

EX.NO:3(a) CPU SCHEDULING: ROUND ROBIN SCHEDULING

AIM
To write a program for implement the round robin scheduling algorithm.

ALGORITHM
1. Start the process

KINGS COLLEGE OF ENGINEERING 17


CS8461 OPERATING SYSTEMS LAB

2. Declare the array size


3. Get the number of processes involved and its burst time (time interval)
4. Get the quantum value
5. Set the time sharing system with preemption
6. Declare the queue as a circular
7. Make the CPU scheduler goes around the ready queue allocating CPU to each
process for the time interval specified
9. Make the CPU scheduler picks the first process and sets time to interrupt after
quantum expired, dispatches the process
10. If the process has burst less than the time quantum than the process releases
the CPU
PROGRAM
import java.io.DataInputStream;
import java.io.IOException;
import java.util.List;
public class RoundRobin {
public static void main(String args[]) throws IOException {
DataInputStream in = new DataInputStream(System.in);
int i, j, k, q, sum = 0;
System.out.println("Enter number of process:");
int n = Integer.parseInt(in.readLine());
int bt[] = new int[n];
int wt[] = new int[n];
int tat[] = new int[n];
int a[] = new int[n];
System.out.println("Enter burst Time:");
for (i = 0; i < n; i++) {
System.out.println ("Enter burst Time for " + (i + 1));
bt[i] = Integer.parseInt(in.readLine());
}
System.out.println ("Enter time quantum:");
q = Integer.parseInt (in.readLine ());
for (i = 0; i < n; i++) {
a[i] = bt[i];
}
for (i = 0; i < n; i++) {
wt[i] = 0;
}
do {
for (i = 0; i < n; i++) {
if (bt[i] > q) {
bt[i] -= q;
for (j = 0; j < n; j++) {
if ((j != i) && (bt[j] != 0)) {
wt[j] += q;
}
}

KINGS COLLEGE OF ENGINEERING 18


CS8461 OPERATING SYSTEMS LAB

} else {
for (j = 0; j < n; j++) {
if ((j != i) && (bt[j] != 0)) {
wt[j] += bt[i];
}
}
bt[i] = 0;
}
}
sum = 0;
for (k = 0; k < n; k++) {
sum = sum + bt[k];
}
} while (sum != 0);
for (i = 0; i < n; i++) {
tat[i] = wt[i] + a[i];
}
System.out.println("process\t\tBT\tWT\tTAT");
for (i = 0; i < n; i++) {
System.out.println("process" + (i + 1) + "\t" + a[i] + "\t" + wt[i] + "\t" + tat[i]);
}
float avg_wt = 0;
float avg_tat = 0;
for (j = 0; j < n; j++) {
avg_wt += wt[j];
}
for (j = 0; j < n; j++) {
avg_tat += tat[j];
}
System.out.println("Average wating time " + (avg_wt / n) + "\nAverage turn around
time" + (avg_tat / n));
}
}

OUTPUT
Enter number of process:
3
Enter burst Time:
Enter burst Time for 1
30 millisec

KINGS COLLEGE OF ENGINEERING 19


CS8461 OPERATING SYSTEMS LAB

Enter burst Time for 2


20 millisec
Enter burst Time for 3
40 millisec
Enter Time quantum:
10 millisec
process BT WT TAT
process1 30 40 70
process2 20 30 50
process3 40 50 90
Average waiting time 40.0 millisec
Average turnaround time 70 millisec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23RESULT
24 Thus the round robin program was executed and verified successfully.
25

26
27EX.NO:3(b) CPU SCHEDULING: SHORTEST JOB FIRST(SJF)
SCHEDULING
28DATE :
29
30AIM
31 To write a program to implement the CPU scheduling algorithm for shortest job first.

KINGS COLLEGE OF ENGINEERING 20


CS8461 OPERATING SYSTEMS LAB

32
33ALGORITHM
0 1. Start the program
1 2. Declare the array size
2 3. Get the number of processes and their burst time
3 4. Processes will be executed based on minimal burst time
4 5. Other processes will be preempted
5 6. For the processes preempted, waiting time will be calculated
6 7. Display the process burst time and their waiting time
7 8. Stop the program
34
35PROGRAM
import java.util.Scanner;
public class SJF {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n, BT[], WT[], TAT[];
System.out.println("Enter no of process");
n = sc.nextInt();
BT = new int[n + 1];
WT = new int[n + 1];
TAT = new int[n + 1];
float AWT = 0;
System.out.println("Enter Burst time for each process");
for (int i = 0; i < n; i++) {
System.out.println("Enter BT for process " + (i + 1));
BT[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
WT[i] = 0;
TAT[i] = 0;
}
int temp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (BT[j] > BT[j + 1]) {
temp = BT[j];
BT[j] = BT[j + 1];
BT[j + 1] = temp;
temp = WT[j];
WT[j] = WT[j + 1];
WT[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
TAT[i] = BT[i] + WT[i];

KINGS COLLEGE OF ENGINEERING 21


CS8461 OPERATING SYSTEMS LAB

WT[i + 1] = TAT[i];
}

TAT[n] = WT[n] + BT[n];


System.out.println(" PROCESS BT WT TAT ");
for (int i = 0; i < n; i++) {
System.out.println(" " + i + " " + BT[i] + " " + WT[i] + " " + TAT[i]);
}
for (int j = 0; j < n; j++) {
AWT += WT[j];
}
AWT = AWT / n;
System.out.println("***********************************************");
System.out.println("Avg waiting time=" + AWT +
"\n***********************************************");
}
}

OUTPUT
Enter no of process
3
Enter Burst time for each process
Enter BT for process 1
10 millisec
Enter BT for process 2
30 millisec
Enter BT for process 3
20 millisec
PROCESS BT WT TAT
1 10 0 10
2 20 10 30
3 30 30 60
***********************************************
Avg waiting time=13.333333 millisec
36 ***********************************************
37
38
39RESULT
40 Thus the shortest job first program was executed and verified successfully.

EX.NO:3(c) CPU SCHEDULING: FIRST COME FIRST SERVE (FCFS) SCHEDULING


DATE:

AIM
To write a program to implement the first come first serve CPU scheduling algorithm

KINGS COLLEGE OF ENGINEERING 22


CS8461 OPERATING SYSTEMS LAB

41ALGORITHM
1. Start the process
2. Declare the array size
3. Get the number of processes and their burst time
4. Processes will be executed based on arrival priority
5. First process will be executed first and followed by others
6. Total waiting time and turnaround time will be calculated
7. Display the values
8. Stop the process

PROGRAM
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class FCFS {
public static void main(String args[]) throws Exception {
int n, AT[], BT[], WT[], TAT[];
float AWT = 0;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter no of process");
n = Integer.parseInt(br.readLine());
BT = new int[n];
WT = new int[n];
TAT = new int[n];
AT = new int[n];
System.out.println("Enter Burst time for each
process\n******************************");
for (int i = 0; i < n; i++) {
System.out.println("Enter BT for process " + (i + 1));
BT[i] = Integer.parseInt(br.readLine());
}
System.out.println("***********************************************");
for (int i = 0; i < n; i++) {
System.out.println("Enter AT for process" + i);
AT[i] = Integer.parseInt(br.readLine());
}
System.out.println("***********************************************");
WT[0] = 0;
for (int i = 1; i < n; i++) {
WT[i] = WT[i - 1] + BT[i - 1];
WT[i] = WT[i] - AT[i];
}
for (int i = 0; i < n; i++) {
TAT[i] = WT[i] + BT[i];
AWT = AWT + WT[i];
}
System.out.println(" PROCESS BT WT TAT ");

KINGS COLLEGE OF ENGINEERING 23


CS8461 OPERATING SYSTEMS LAB

for (int i = 0; i < n; i++) {


System.out.println(" " + i + " " + BT[i] + " " + WT[i] + " " + TAT[i]);
}
AWT = AWT / n;
System.out.println("***********************************************");
System.out.println("Avg waiting time=" + AWT +
"\n***********************************************");
}
}

OUTPUT
Enter no of process
3
Enter Burst time for each process
******************************
Enter BT for process 1
20 millisec
Enter BT for process 2
30 millisec
Enter BT for process 3
10 millisec
***********************************************
Enter AT for process0
10 millisec
Enter AT for process1
20 millisec
Enter AT for process2
10 millisec
***********************************************
PROCESS BT WT TAT
0 20 0 20
1 30 0 30
2 10 20 30
***********************************************
Avg waiting time=6.6666665 millisec

42
43RESULT
44 Thus the FCFS program was executed and verified successfully.

EX.NO:3(d) CPU SCHEDULING: PRIORITY SCHEDULING


DATE :

AIM
To write a C program to implement the CPU scheduling algorithm for priority.

KINGS COLLEGE OF ENGINEERING 24


CS8461 OPERATING SYSTEMS LAB

ALGORITHM
1. Start the program
2.Declare the array size
3. Get the number of process arrival time, execution time and priority
4. Start with the higher priority process from its initial position, let other process
enter the queue
5. Calculate the total waiting time for each process, average waiting time
6. Display the values
7. Stop the program

PROGRAM
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() {
int et[20], at[10], n, i, j, temp, p[10], st[10], ft[10], wt[10], ta[10];
int totwt = 0, totta = 0;
float awt, ata;
char pn[10][10], t[10];
printf("Enter the number of process:");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter process name,arrivaltime,execution time & priority:");
flushall();
scanf("%s%d%d%d", pn[i], &at[i], &et[i], &p[i]);
}
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
if (p[i] < p[j]) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
temp = at[i];
at[i] = at[j];
at[j] = temp;
temp = et[i];
et[i] = et[j];
et[j] = temp;
strcpy(t, pn[i]);
strcpy(pn[i], pn[j]);
strcpy(pn[j], t);
}
}
for (i = 0; i < n; i++) {
if (i == 0) {
st[i] = at[i];
wt[i] = st[i] - at[i];

KINGS COLLEGE OF ENGINEERING 25


CS8461 OPERATING SYSTEMS LAB

ft[i] = st[i] + et[i];


ta[i] = ft[i] - at[i];
} else {
st[i] = ft[i - 1];
wt[i] = st[i] - at[i];
ft[i] = st[i] + et[i];
ta[i] = ft[i] - at[i];
}
totwt += wt[i];
totta += ta[i];
}
awt = (float) totwt / n;
ata = (float) totta / n;
printf("\nPname\tarrivaltime\texecutiontime\tpriority\twaitingtime\ttatime");
for (i = 0; i < n; i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d\t\t%5d", pn[i], at[i], et[i], p[i], wt[i], ta[i]);
printf("\nAverage waiting time is:%f", awt);
printf("\nAverage turnaroundtime is:%f", ata);
getch();
}

OUTPUT
Enter the number of process:3
Enter process name, arrivaltime, execution time & priority: 1 2 3
Enter process name, arrivaltime, execution time & priority: 1 3 4
Enter process name, arrivaltime, execution time & priority: 5 4 3
Pname arrivaltime executiontime priority waitingtime tatime
1 2 3 1 0 3
2 3 1 3 2 3
4 5 4 3 1 5
Average waiting time is:1.000000 millisec
Average turnaroundtime is:3.666667 millisec

1
2
3
4
5RESULT
Thus the priority program for CPU scheduling algorithms were successfully executed
and verified.

VIVA QUESTIONS:
1. What is CPU Scheduler?

KINGS COLLEGE OF ENGINEERING 26


CS8461 OPERATING SYSTEMS LAB

2. Define race condition.

3. List the different job scheduling in operating systems?

4. Define non-preemptive scheduling.

5. Define dispatcher and its functions.

KINGS COLLEGE OF ENGINEERING 27


CS8461 OPERATING SYSTEMS LAB

EX.NO: 5 IMPLEMENTATION OF SEMAPHORES


DATE :

AIM
To write a java program to implement producer consumer relationship using
semaphore.

ALGORITHM
1. The Semaphore mutex, full & empty are initialized.
2. In the case of producer process
i) Produce an item in to temporary variable.
ii) If there is empty space in the buffer check the mutex value for enter into the critical
section.
iii) If the mutex value is 0, allow the producer to add value in the temporary variable
to the buffer.
3. In the case of consumer process
i) It should wait if the buffer is empty
ii) If there is any item in the buffer check for mutex value, if the mutex==0, remove
item from buffer
iii) Signal the mutex value and reduce the empty value by 1.
iv) Consume the item.
4. Print the result

PROGRAM
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
Semaphore binary = new Semaphore(1);
public static void main(String args[]) {
final SemaphoreTest test = new SemaphoreTest();
new Thread(){
@Override
public void run(){
test.mutualExclusion();
}
}.start();
new Thread(){
@Override
public void run(){
test.mutualExclusion();
}
}.start();
}
private void mutualExclusion() {
try {
binary.acquire();

//mutual exclusive region


System.out.println(Thread.currentThread().getName() + " inside mutual exclusive
region");

KINGS COLLEGE OF ENGINEERING 28


CS8461 OPERATING SYSTEMS LAB

Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
binary.release();
System.out.println(Thread.currentThread().getName() + " outside of mutual exclusive
region");
}
}}

OUTPUT
Thread-0 inside mutual exclusive region
Thread-0 outside of mutual exclusive region
Thread-1 inside mutual exclusive region
Thread-1 outside of mutual exclusive region

RESULT
Thus the program for semaphore was successfully executed and verified.

KINGS COLLEGE OF ENGINEERING 29


CS8461 OPERATING SYSTEMS LAB

VIVA QUESTIONS:
1. What is a semaphore?

2. Find the category of java thread in java?

3. What is a thread?

4. What is a P-thread?

15. What is bounded-buffer problem?

KINGS COLLEGE OF ENGINEERING 30


CS8461 OPERATING SYSTEMS LAB

EX.NO:10 IMPLEMENTATION OF SHARED MEMORY AND IPC


DATE :

AIM
To write a program for interprocess communication using shared memory.

ALGORITHM
SERVER
1. Define shared memory size of 30 bytes
2. Define the key to be 5600
3. Create a shared memory using shmget () system calls and gets the shared memory
id in variable shmid.
4. Attach the shared memory to server data space
5. Get the content to be placed in the shared memory from the user of the server.
6. Write the content in the shared memory, which will read out by the client.
7. Stop the program
CLIENT
1. Define the key to be 5600
2. Attach the client to the shared memory created by the server.
3. Read the content from the shared memory.
4. Display the content on the screen.
5. Stop the program
PROGRAM
#include<stdio.h>
#include<unistd.h>
#include<string.h>
void main() {
int pid[2], pid1[2], pid2[2], pid3[2], pid4[2];
int a[20], i, l, s = 0;
char str[20];
pipe(pid);
pipe(pid1);
pipe(pid2);
pipe(pid3);
pipe(pid4);
if (fork() == 0) {
sleep(5);
close(pid[1]);
read(pid[0], str, sizeof (str));
for (i = 0, l = 0; str[i] != '\0'; i++)
l = l + 1;
close(pid3[0]);
write(pid3[1], &l, sizeof (l));
sleep(6);
printf("Enter %d array elementz:", l);
for (i = 0; i < l; i++)
scanf("%d", &a[i]);

KINGS COLLEGE OF ENGINEERING 31


CS8461 OPERATING SYSTEMS LAB

close(pid1[0]);
write(pid1[1], a, sizeof (a));
close(pid4[0]);
write(pid4[1], &l, sizeof (l));
}
else if (fork() == 0) {
sleep(2);
close(pid1[1]);
close(pid4[1]);
read(pid4[0], &l, sizeof (l));
read(pid1[0], a, sizeof (a));
for (i = 0; i < l; i++)
s = s + a[i];
close(pid2[0]);
write(pid2[1], &s, sizeof (s));
}
else {
printf("\nEnter string:");
scanf("%s", str);
close(pid[0]);
write(pid[1], str, sizeof (str));
sleep(7);
close(pid3[1]);
read(pid3[0], &l, sizeof (l));
printf("\nThe string length=%d", l);
sleep(8);
close(pid2[1]);
read(pid2[0], &s, sizeof (s));
printf("\nSum=%d", s);
}
}
OUTPUT
Enter string:KINGS
Enter 5 array elements:
The string length=5
HELLO
Sum=-2110358802

RESULT
Thus the program for shared memory and IPC was successfully executed
and verified.

KINGS COLLEGE OF ENGINEERING 32


CS8461 OPERATING SYSTEMS LAB

VIVA QUESTIONS:

1. What do you know about a pipe? When is it used?

2. What is a named pipe?

3. Define shared memory.

4. Define IPC.

5. What is fork?

KINGS COLLEGE OF ENGINEERING 33


CS8461 OPERATING SYSTEMS LAB

EX. NO: 7 IMPLEMENTATION OF BANKERS ALGORITHM FOR DEAD LOCK


DATE : AVOIDANCE

AIM
To implement deadlock avoidance by using banker’s algorithm.

ALGORITHM
Safety algorithm
1. Start the program
2. Initialize a temporary vector W (Work) to equal the available vector A.
3. Find an index i (row i) such that
Need i : = W
If no such row exists, the system will deadlock, since no process can run to
completion.
4. If such a row is found, mark this process as finished, and add all its resources to
W Vector i, W = W + Ci
Go to step 2, until either all processes are marked terminated (in this case
initial state is safe), or until a deadlock occurs, in which the state is not safe.

Resource – request algorithm


1. If Request i < = Needi , go to step 2. Otherwise, error
2. If Request i < = Available, go to step 3. Otherwise, Pi must wait, since resources
are not available
3. Modify the state (the system pretend to have allocated the requested resources to
process Pi)
Available = Available - Requesti
Allocationi = Allocationi + Requesti
Needi = Needi - Requesti
4. If the resulting state is safe, the transaction is completed and process Pi is
allocated its resources. If new state is unsafe, then Pi must wait for Requesti and the
old state is restored.
5. Stop the program

PROGRAM
import java.util.Scanner;
public class Bankers {
int claim[][], alloc[][], av[], need[], p, r, alsum[], sum, temp[][];
int a = 0, b = 0, c;
boolean flag;
Scanner src = new Scanner(System.in);

Bankers(int p, int r) {
this.p = p;
this.r = r;
claim = new int[p][r];
alloc = new int[p][r];
av = new int[r];
KINGS COLLEGE OF ENGINEERING 34
CS8461 OPERATING SYSTEMS LAB

need = new int[r];


alsum = new int[r];
temp = new int[p][r];
System.out.println("ENTER THE " + r + " VALUES IN AVAILABLE VECTOR");
for (int i = 0; i < r; i++) {
av[i] = src.nextInt();
}
System.out.println("ENTER THE CLAIM MATRIX OF" + p + " X " + r);
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
claim[i][j] = src.nextInt();
}
}
System.out.println("ENTER THE ALLOCATION MATRIX OF " + p + " X " + r);
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
alloc[i][j] = src.nextInt();
}
}
}

public void calNeed() {


for (int i = 0; i < r; i++) {
for (int j = 0; j < p; j++) {
sum = sum + alloc[j][i];
}
alsum[i] = sum;
sum = 0;
}
for (int i = 0; i < r; i++) {
need[i] = av[i] - alsum[i];
System.out.print("Initial Need Vector ");
System.out.print(need[i]);
System.out.println();
System.out.println();
}
}

public void checkNeed() {


for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
temp[i][j] = claim[i][j] - alloc[i][j];
}
}
}

public void compareNeed() {

KINGS COLLEGE OF ENGINEERING 35


CS8461 OPERATING SYSTEMS LAB

while (b < p) {
flag = false;
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
if (temp[i][0] == 89) {
break;
}
if (temp[i][j] <= need[j]) {
a++;
} else {
break;
}
}
if (a == r) {
System.out.println("Process P" + (i + 1) + " is Completed");
addtoNeed(i);
temp[i][0] = 89;
a = 0;
c++;
flag = true;
}
if (flag == true) {
break;
}
}
b++;
}
}

public void addtoNeed(int k) {


int n = k;
for (int j = 0; j < r; j++) {
need[j] = need[j] + alloc[n][j];
}
if (c == p) {
System.out.println("SYSTEM IS IN SAFE STATE");
} else {
System.out.println("SYSTEM IS NOT IN SAFE STATE");
}
}
}
class BankerExp1 {
public static void main(String args[]) {
Scanner src = new Scanner(System.in);
System.out.println("ENTER THE NO. OF PROCESS");
int p = src.nextInt();
System.out.println("ENTER THE NO. OF RESOURCES");

KINGS COLLEGE OF ENGINEERING 36


CS8461 OPERATING SYSTEMS LAB

int r = src.nextInt();
Bankers obj = new Bankers(p, r);
obj.calNeed();
obj.checkNeed();
obj.compareNeed();
}
}

OUTPUT
ENTER THE NO. OF PROCESS
5
ENTER THE NO. OF RESOURCES
3
ENTER THE 3 VALUES IN AVAILABLE VECTOR
3
3
2
ENTER THE CLAIM MATRIX OF5 X 3
0
1
0
2
0
0
3
0
2
2
1
1
0
0
2
ENTER THE ALLOCATION MATRIX OF 5 X 3
7
5
3
3
2
2
9
0
2
2
2
2
4

KINGS COLLEGE OF ENGINEERING 37


CS8461 OPERATING SYSTEMS LAB

3
3
Initial Need Vector -22
Initial Need Vector -9
Initial Need Vector -10

RESULT

Thus the program to implement banker’s algorithm for dead lock avoidance was
executed successfully.

KINGS COLLEGE OF ENGINEERING 38


CS8461 OPERATING SYSTEMS LAB

VIVA QUESTIONS:
1. What is a deadlock?

2. What are the necessary conditions for deadlock to occur?

3. Define mutual exclusion.

1 4. What are privileged instructions?

5. Define safe state and a safe sequence?

EX. NO: 8 IMPLEMENTATION OF DEAD LOCK DETECTION


DATA :

KINGS COLLEGE OF ENGINEERING 39


CS8461 OPERATING SYSTEMS LAB

AIM
To write a C program to implement deadlock detection algorithm

ALGORITHM
1. Start the process
2. Obtain the processes and resource availability details
3. Resources will be allocated to processes if processes do not compete for same
resource
4. Resource will be released by process if job completes
5. Before job completion if resource is required, process enters into deadlock state
6. Status of resource allocated helps deadlock detection
7. Display the process, resource details
8. Stop the process
PROGRAM
#include<stdio.h>
#include<conio.h>
int max[100][100];
int alloc[100][100];
int need[100][100];
int avail[100];
int n, r;
void input();
void show();
void cal();
int main() {
int i, j;
printf("********** Deadlock Detection Algo ************\n");
input();
show();
cal();
getch();
return 0;
}
void input() {
int i, j;
printf("Enter the no of Processes\t");
scanf("%d", &n);
printf("Enter the no of resource instances\t");
scanf("%d", &r);
printf("Enter the Max Matrix\n");
for (i = 0; i < n; i++) {
for (j = 0; j < r; j++) {
scanf("%d", &max[i][j]);
}
}
printf("Enter the Allocation Matrix\n");

KINGS COLLEGE OF ENGINEERING 40


CS8461 OPERATING SYSTEMS LAB

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


for (j = 0; j < r; j++) {
scanf("%d", &alloc[i][j]);
}
}
printf("Enter the available Resources\n");
for (j = 0; j < r; j++) {
scanf("%d", &avail[j]);
}
}
void show() {
int i, j;
printf("Process\t Allocation\t Max\t Available\t");
for (i = 0; i < n; i++) {
printf("\nP%d\t ", i + 1);
for (j = 0; j < r; j++) {
printf("%d ", alloc[i][j]);
}
printf("\t");
for (j = 0; j < r; j++) {
printf("%d ", max[i][j]);
}
printf("\t");
if (i == 0) {
for (j = 0; j < r; j++)
printf("%d ", avail[j]);
}
}
}
void cal() {
int finish[100], temp, need[100][100], flag = 1, k, c1 = 0;
int dead[100];
int safe[100];
int i, j;
for (i = 0; i < n; i++) {
finish[i] = 0;
}
for (i = 0; i < n; i++) {
for (j = 0; j < r; j++) {
need[i][j] = max[i][j] - alloc[i][j];
}
}
while (flag) {
flag = 0;
for (i = 0; i < n; i++) {
int c = 0;
for (j = 0; j < r; j++) {

KINGS COLLEGE OF ENGINEERING 41


CS8461 OPERATING SYSTEMS LAB

if ((finish[i] == 0) && (need[i][j] <= avail[j])) {


c++;
if (c == r) {
for (k = 0; k < r; k++) {
avail[k] += alloc[i][j];
finish[i] = 1;
flag = 1;
}
//printf("\nP%d",i);
if (finish[i] == 1) {
i = n;
}
}
}
}
}
}
j = 0;
flag = 0;
for (i = 0; i < n; i++) {
if (finish[i] == 0) {
dead[j] = i;
j++;
flag = 1;
}
}
if (flag == 1) {
printf("\n\nSystem is in Deadlock and the Deadlock process are\n");
for (i = 0; i < n; i++) {
printf("P%d\t", dead[i]);
}
} else {
printf("\nNo Deadlock Occur");
}
}

OUTPUT
********** Deadlock Detection Alg ************

KINGS COLLEGE OF ENGINEERING 42


CS8461 OPERATING SYSTEMS LAB

Enter the no. of Processes 3


Enter the no. of resource instances 2
Enter the Max Matrix
2
2
2
2
2
2
Enter the Allocation Matrix
2
2
2
2
2
2
Enter the available Resources
2
2
Process Allocation Max Available
P1 22 22 22
P2 22 22
P3 22 22
No Deadlock Occur

RESULT
Thus the program for deadlock detection was successfully executed and verified.

1. Define deadlock avoidance.


VIVA QUESTIONS:

KINGS COLLEGE OF ENGINEERING 43


CS8461 OPERATING SYSTEMS LAB

2. Define hold and wait.

3. What are the methods for handling deadlocks?

4. How memory is protected in OS?

5. What is a safe state and write its’ use in deadlock avoidance?

KINGS COLLEGE OF ENGINEERING 44


CS8461 OPERATING SYSTEMS LAB

EX.NO:12 IMPLEMENTATION OF THREADING & SYNCHRONIZATION APPLICATIONS


DATE :

AIM
To write a program to implement threading and synchronization.

ALGORITHM
1. Create a Bank Database
2. Create functions for adding a new user, depositing the amt, withdrawing the
amt & viewing the customer
3. Create a thread for each functionality
4. Implement the concurrency control among the threads
5. Function - add new user
a. Get the user details namely, Acno, Name & Bank Balance
b. Write the user details to the bank database
6. Function -Deposit
a. Get the Acno & Amt
b. Update the Bank balance for the given Acno
7. Function- Withdraw
a. Get the Acno & Amt
b. Update the Bank balance for the given Acno
8. Function- View
a. Get the Acno
b. Display the account details

PROGRAM
import java.util.*;
public class BankingMain {
public static final int a_maxi = 10; // number of accounts
public static long[] balance = new long[a_maxi];
public static Random r_number;
private static final int t_maxi = 5; // number of threads
private static BankingThread[] t_list = new BankingThread[t_maxi];
private static long t_step;
private static Object o_lock;
private static Object[] a_lock = new Object[a_maxi];
public static void main(String[] a) {
o_lock = new Object();
for (int i = 0; i < a_maxi; i++) {
a_lock[i] = new Object();
}
t_step = 1; // using doTransaction1();
System.out.println("No synchronization:");
testATM();
printResult();
t_step = 2; // using doTransaction2();
System.out.println("Synchronized method:");
testATM();
printResult();
t_step = 3; // using doTransaction3();

KINGS COLLEGE OF ENGINEERING 45


CS8461 OPERATING SYSTEMS LAB

System.out.println("Synchronized statements:");
testATM();
printResult();
t_step = 4; // using doTransaction4();
System.out.println("Synchronized statements per account:");
testATM();
printResult();
}
private static void testATM() {
for (int i = 0; i < a_maxi; i++) {
balance[i] = 0;
}
r_number = new Random();
ThreadGroup g = new ThreadGroup("ATM");
for (int i = 0; i < t_maxi; i++) {
BankingThread t = new BankingThread(g, String.valueOf(i));
t.start();
t_list[i] = t;
}
try {
Thread.sleep(5 * 1000); // working period
} catch (InterruptedException e) {
System.out.println("Interrupted in the mainthread.");
}
g.interrupt();
while (g.activeCount() > 0); // wait for all threads to end
}
private static void printResult() {
System.out.print("Account");
for (int i = 0; i < t_maxi; i++) {
System.out.print(", ATM " + i);
}
System.out.print(", Transaction Sum, Balance");
for (int j = 0; j < a_maxi; j++) {
System.out.print("\n" + j);
long sum = 0;
for (int i = 0; i < t_maxi; i++) {
sum += t_list[i].getBalance(j);
System.out.print(", " + getCurrency(t_list[i].getBalance(j)));
}
System.out.print(", " + getCurrency(sum) +
", " + getCurrency(balance[j]));
}
System.out.print("\n# of Transactions");
for (int i = 0; i < t_maxi; i++) {
System.out.print(", " + t_list[i].transactionCount());
}

KINGS COLLEGE OF ENGINEERING 46


CS8461 OPERATING SYSTEMS LAB

System.out.print("\n");
}
private static String getCurrency(long d) {
long i = d / 100;
long f = Math.abs(d) % 100;
String fs = String.valueOf(f);
if (f < 10) {
fs = "0" + fs;
}
return String.valueOf(i) + "." + fs;
}
public static long getStep() {
return t_step;
}

public static int accountCount() {


return a_maxi;
}

public static Random getRandom() {


return r_number;
}

public static long getBalance(int i) {


return balance[i];
}

public static boolean doTransaction1(int i, long a) {


boolean ok = false;
long c = balance[i]; // get current balance
ok = c + a > 0;
if (ok) { // stop accout balance going negative
try {
Thread.sleep(1); // slow down the process
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // re-set the flag
}
balance[i] = c + a; // set current balance
}
return ok;
}

public synchronized static boolean doTransaction2(int i, long a) {


boolean ok = false;
long c = balance[i]; // get current balance
ok = c + a > 0;
if (ok) { // stop accout balance going negative

KINGS COLLEGE OF ENGINEERING 47


CS8461 OPERATING SYSTEMS LAB

try {
Thread.sleep(1); // slow down the process
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // re-set the flag
}
balance[i] = c + a; // set current balance
}
return ok;
}

public static boolean doTransaction3(int i, long a) {


boolean ok = false;
synchronized (o_lock) {
long c = balance[i]; // get current balance
ok = c + a > 0;
if (ok) { // stop accout balance going negative
try {
Thread.sleep(1); // slow down the process
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // re-set the flag
}
balance[i] = c + a; // set current balance
}
}
return ok;
}

public static boolean doTransaction4(int i, long a) {


boolean ok = false;
synchronized (a_lock[i]) {
long c = balance[i]; // get current balance
ok = c + a > 0;
if (ok) { // stop accout balance going negative
try {
Thread.sleep(1); // slow down the process
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // re-set the flag
}
balance[i] = c + a; // set current balance
}
}
return ok;
}
}

class BankingThread extends Thread {

KINGS COLLEGE OF ENGINEERING 48


CS8461 OPERATING SYSTEMS LAB

private long[] t_balance; // acount balance


private long t_count; // number of transactions done so far

public BankingThread(ThreadGroup g, String n) {


super(g, n);
t_count = 0;
int m = BankingMain.accountCount();
t_balance = new long[m];
for (int i = 0; i < m; i++) {
t_balance[i] = 0;
}
}

public long transactionCount() {


return t_count;
}

public long getBalance(int i) {


return t_balance[i];
}

public void run() {


while (!isInterrupted()) {
t_count++;
Random r = BankingMain.getRandom();
long t_step = BankingMain.getStep();
int m = BankingMain.accountCount();
int n = r.nextInt(m); // account number
int t = 2 * r.nextInt(2) - 1; // type of transaction
long a = (long) t * r.nextInt(10000); // amount of transaction
if (t_step == 1) {
if (BankingMain.doTransaction1(n, a)) {
t_balance[n] += a;
}
}
if (t_step == 2) {
if (BankingMain.doTransaction2(n, a)) {
t_balance[n] += a;
}
}
if (t_step == 3) {
if (BankingMain.doTransaction3(n, a)) {
t_balance[n] += a;
}
}
if (t_step == 4) {
if (BankingMain.doTransaction4(n, a)) {

KINGS COLLEGE OF ENGINEERING 49


CS8461 OPERATING SYSTEMS LAB

t_balance[n] += a;
}
}
try {
sleep(10); // wait for the next customer
} catch (InterruptedException e) {
break;
}}} }

OUTPUT
No synchronization:
Account, ATM 0, ATM 1, ATM 2, ATM 3, ATM 4, Trans. Sum, Bal
0, -169.92, -200.43, 43.72, 268.13, 112.82, 54.32, 215.56

RESULT:
Thus the program for threading and synchronization is successfully executed.

KINGS COLLEGE OF ENGINEERING 50


CS8461 OPERATING SYSTEMS LAB

VIVA QUESTIONS:

1. What is dual-mode operation?

2. What is fragmentation?

3. What is process synchronization?

4. Explain Segmentation with paging?

5. Why thread is called as a lightweight process?

KINGS COLLEGE OF ENGINEERING 51


CS8461 OPERATING SYSTEMS LAB

EX NO: 8 Implement first fit algorithm for memory management


AIM:
To write a program to implement first fit algorithm for memory management.
ALGORITHM
1. Start the process.
2. Declare the size.
3. Get the number of processes to be inserted.
4. Allocate the first hole that is big enough searching.
5. Start at the beginning of the set of holes.
6. If not start at the hole that is sharing the pervious first fit search end.
7. If large enough then stop searching in the procedure.
8. Display the values.
9. Stop the process.
PROGRAM:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct allocate
{
int pid;
int st_add;
int end_add;
struct allocate *next;
};
struct free_list
{
int st_add;
int end_add;
struct free_list *next;
};
struct process
{
int pid;
int size;
};
struct process pro[10];
struct free_list *flist=NULL;
struct allocate *alot=NULL;
void display_alot(struct allocate *temp_a)
{
printf("\n\n allocated list:");
printf("\n================");
while(temp_a!=NULL)
{
printf("\n process:%d st_add:%d end_add:%d ",temp_a->pid,
temp_a- >st_add,temp_a->end_add);

KINGS COLLEGE OF ENGINEERING 52


CS8461 OPERATING SYSTEMS LAB

temp_a=temp_a->next;
}
}
void display_free(struct free_list *temp_f)
{
printf("\n\n free list:");
printf("\n=================");
while(temp_f!=NULL)
{
printf("\n st_add:%d end_add:%d",temp_f->st_add,
temp_f->end_add);
temp_f=temp_f->next;
}
}
void insert(int p)
{
struct free_list *temp_f;
struct allocate *temp_a,*pre_a;
int i,n;
do
{
srand((unsigned int)time((time_t*)NULL));
n=rand()%5;
}
while(n==0);
printf("\n\n no. of process:%d",n);
for(i=0;i<n;i++)
{
pro[i].pid=i+p;
do
{
pro[i].size=rand()%300;
}
while(pro[i].size==0);
}
for(i=0;i<n;i++)
{
printf("\n\n process to be inserted:%d size:%d",pro[i].pid,pro[i].size);
temp_f=flist;
temp_a=alot;
while(temp_f!=NULL && temp_f->end_add-temp_f->st_add
< pro[i].size)
{
temp_f=temp_f->next;
}
if(temp_f!=NULL)
{

KINGS COLLEGE OF ENGINEERING 53


CS8461 OPERATING SYSTEMS LAB

pre_a=(struct allocate*)malloc(sizeof(struct allocate));


pre_a->st_add=temp_f->st_add;
pre_a->end_add=temp_f->st_add=temp_f->st_add+pro[i].size;
pre_a->pid=pro[i].pid;
if(temp_a==NULL)
{
alot=pre_a;
pre_a->next=NULL;
}
else
{
while(temp_a->next!=NULL)
{
temp_a=temp_a->next;
}
temp_a->next=pre_a;
pre_a->next=NULL;
}
}
else
printf("\n there is not enough space");
display_alot(alot);
display_free(flist);
getch();
}
}
void main()
{
int no,n,i,nod,ndpid;
struct process pro[10];
struct free_list *temp_f,*free_alot,*pre_f;
struct allocate *temp_a,*pre_a;
clrscr();
alot=NULL;
flist=(struct free_list*)malloc(sizeof(struct free_list));
flist->st_add=0;
flist->end_add=1024;
flist->next=NULL;
insert(0);
do
{
srand((unsigned int)time((time_t*)NULL));
nod=rand()%2;
}
while(nod==0);
printf("\n\n no.of process deletion:%d",nod);
for(i=0;i<nod;i++)

KINGS COLLEGE OF ENGINEERING 54


CS8461 OPERATING SYSTEMS LAB

{
printf("\n\n\n process to be deleted:");
scanf("%d",&ndpid);
temp_a=alot;
temp_f=flist;
while(temp_a!=NULL && temp_a->pid!=ndpid)
{
pre_a=temp_a;
temp_a=temp_a->next;
}
if(temp_a!=NULL)
{
if(alot==temp_a)
alot=temp_a->next;
else
pre_a->next=temp_a->next;
pre_f=NULL;
while(temp_f!=NULL && temp_f->st_add < temp_a->st_add)
{
pre_f=temp_f;
temp_f=temp_f->next;
}
if(pre_f!=NULL && pre_f->end_add==temp_a->st_add)
pre_f->end_add=temp_a->end_add;
else if(pre_f!=NULL&&temp_f!=NULL&&
temp_f- >st_add==temp_a->end_add)
temp_f->st_add=temp_a->st_add;
else
{
free_alot=(struct free_list*)malloc(sizeof
(struct free_list));
free_alot->st_add=temp_a->st_add;
free_alot->end_add=temp_a->end_add;
if(pre_f!=NULL)
pre_f->next=free_alot;
free_alot->next=temp_f;
if(flist==temp_f)
{
flist=free_alot;
}
}
free(temp_a);
}
else printf("\n process not in memory");
temp_f=flist;
while(temp_f!=NULL)
{

KINGS COLLEGE OF ENGINEERING 55


CS8461 OPERATING SYSTEMS LAB

if(temp_f->end_add==temp_f->next->st_add)
{
temp_f->end_add=temp_f->next->end_add;
temp_f->next=temp_f->next->next;
}
temp_f=temp_f->next;
}
display_alot(alot);
display_free(flist);
getch();
}
insert(10);
}
OUTPUT:
no. of process:3
process to be inserted:0 size:120
allocated list:
================
process:0 st_add:0 end_add:120
free list:
=================
st_add:120 end_add:1024
process to be inserted:1 size:185
allocated list:
================
process:0 st_add:0 end_add:120
process:1 st_add:120 end_add:305
free list:
=================
st_add:305 end_add:1024
process to be inserted:2 size:246
allocated list:
================
process:0 st_add:0 end_add:120
process:1 st_add:120 end_add:305
process:2 st_add:305 end_add:551
free list:
=================
st_add:551 end_add:1024
no.of process deletion:1
process to be deleted:0
allocated list:
================
process:1 st_add:120 end_add:305
process:2 st_add:305 end_add:551
free list:
=================

KINGS COLLEGE OF ENGINEERING 56


CS8461 OPERATING SYSTEMS LAB

st_add:0 end_add:120
st_add:551 end_add:1024
no. of process:3
process to be inserted:10 size:195
allocated list:
================
process:1 st_add:120 end_add:305
process:2 st_add:305 end_add:551
process:10 st_add:551 end_add:746
free list:
=================
st_add:0 end_add:120
st_add:746 end_add:1024
process to be inserted:11 size:96
allocated list:
================
process:1 st_add:120 end_add:305
process:2 st_add:305 end_add:551
process:10 st_add:551 end_add:746
process:11 st_add:0 end_add:96
free list:
=================
st_add:96 end_add:120
st_add:746 end_add:1024
process to be inserted:12 size:148
allocated list:
================
process:1 st_add:120 end_add:305
process:2 st_add:305 end_add:551
process:10 st_add:551 end_add:746
process:11 st_add:0 end_add:96
process:12 st_add:746 end_add:894
free list:
=================
st_add:96 end_add:120
st_add:894 end_add:1024
RESULT:
Thus the program for Implement first fit algorithm for memory management is
written and successfully executed.
EX NO: 9 (a) Implement Best fit algorithm for memory management
AIM :
To write a program for Implement best fit memory management
ALGORITHM:
1.Start the program.
2. Declare the size.
3. Get the number of processes to be inserted.
4. Allocate the best hole that is small enough searching.

KINGS COLLEGE OF ENGINEERING 57


CS8461 OPERATING SYSTEMS LAB

5. Start at the best of the set of holes.


6. If not start at the hole that is sharing the pervious best fit search end.
7. Compare the hole in the list.
8. If small enough then stop searching in the procedure.
9. Display the values.
10. Stop the program.
PROGRAM:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct allocate
{
int pid;
int st_add;
int end_add;
struct allocate *next;
};
struct free_list
{
int st_add;
int end_add;
struct free_list *next;
};
struct process
{
int pid;
int size;
};
struct process pro[10];
struct free_list *flist=NULL;
struct allocate *alot=NULL;
void display_alot(struct allocate *temp_a)
{
printf("\n\n allocated list:");
printf("\n================");
while(temp_a!=NULL)
{
printf("\n process:%d st_add:%d end_add:%d ",temp_a->pid,
temp_a->st_add,temp_a->end_add);
temp_a=temp_a->next;
}
}
void display_free(struct free_list *temp_f)
{
printf("\n\n free list:");
printf("\n=================");

KINGS COLLEGE OF ENGINEERING 58


CS8461 OPERATING SYSTEMS LAB

while(temp_f!=NULL)
{
printf("\n st_add:%d end_add:%d",temp_f->st_add,
temp_f->end_add);
temp_f=temp_f->next;
}
}
void insert(int p)
{
struct free_list *temp_f;
struct allocate *temp_a,*pre_a;
int i,n;
do
{
srand((unsigned int)time((time_t*)NULL));
n=rand()%10;
}
while(n==0);
printf("\n\n no. of process:%d",n);
for(i=0;i<n;i++)
{
pro[i].pid=i+p;
do
{
pro[i].size=rand()%550;
}
while(pro[i].size==0);
}
for(i=0;i<n;i++)
{
printf("\n\n process to be inserted:%d size:%d",pro[i].pid,pro[i].size);
temp_f=flist;
temp_a=alot;
while(temp_f!=NULL && temp_f->end_add-temp_f->
st_add < pro[i].size)
{
temp_f=temp_f->next;
}
if(temp_f!=NULL)
{
pre_a=(struct allocate*)malloc(sizeof(struct allocate));
pre_a->st_add=temp_f->st_add;
pre_a->end_add=temp_f->st_add=temp_f->st_add+pro[i].size;
pre_a->pid=pro[i].pid;
if(temp_a==NULL)
{
alot=pre_a;

KINGS COLLEGE OF ENGINEERING 59


CS8461 OPERATING SYSTEMS LAB

pre_a->next=NULL;
}
else
{
while(temp_a->next!=NULL)
{
temp_a=temp_a->next;
}
temp_a->next=pre_a;
pre_a->next=NULL;
}
}
else
printf("\n there is not enough space");
display_alot(alot);
display_free(flist);
getch();
}
}
void bestfit(int p)
{
struct free_list *temp_f,*enough_hole;
struct allocate *temp_a,*pre_a;
int i,n,rem_space;
do
{
srand((unsigned int)time((time_t*)NULL));
n=rand()%10;
}
while(n==0);
printf("\n no of processes:%d",n);
for(i=0;i<n;i++)
{
pro[i].pid=i+p;
do
{
pro[i].size=rand()%200;
}
while(pro[i].size==0);
}
for(i=0;i<n;i++)
{
printf("\n process to be inserted:%d size:%d",pro[i].pid,pro[i].size);
temp_f=flist;
temp_a=alot;
enough_hole=NULL;
rem_space=1024;

KINGS COLLEGE OF ENGINEERING 60


CS8461 OPERATING SYSTEMS LAB

while(temp_f!=NULL)
{
if(temp_f->end_add - temp_f->st_add >= pro[i].size)
{
if(temp_f->end_add - temp_f->
st_add - pro[i].size<rem_space)
{
rem_space=temp_f->end_add - temp_f->
st_add - pro[i].size;
enough_hole=temp_f;
}
}
temp_f=temp_f->next;
}
if(enough_hole!=NULL)
{
pre_a=(struct allocate*)malloc(sizeof(struct allocate));
pre_a->st_add=enough_hole->st_add;
pre_a->end_add=enough_hole->st_add=
enough_hole->st_add + pro[i].size;
pre_a->pid=pro[i].pid;
if(temp_a==NULL)
{
alot=pre_a;
pre_a->next=NULL;
}
else
{
while(temp_1->next!=NULL)
{
temp_a=temp_a->next;
}
temp_a->next=pre_a;
pre_a->next=NULL;
}
}
else
printf("\n there is not enough space");
display_alot(alot);
display_free(flist);
getch();
}
}
void main()
{
int no,n,i,nod,ndpid;
struct process pro[10];

KINGS COLLEGE OF ENGINEERING 61


CS8461 OPERATING SYSTEMS LAB

struct free_list *temp_f,*free_alot,*pre_f;


struct allocate *temp_a,*pre_a;
clrscr();
alot=NULL;
flist=(struct free_list*)malloc(sizeof(struct free_list));
flist->st_add=0;
flist->end_add=1024;
flist->next=NULL;
insert(0);
do
{
srand((unsigned int)time((time_t*)NULL));
nod=rand()%5;
}
while(nod==0);
printf("\n\n no.of process deletion:%d",nod);
for(i=0;i<nod;i++)
{
printf("\n\n\n process to be deleted:");
scanf("%d",&ndpid);
temp_a=alot;
temp_f=flist;
while(temp_a!=NULL && temp_a->pid!=ndpid)
{
pre_a=temp_a;
temp_a=temp_a->next;
}
if(temp_a!=NULL)
{
if(alot==temp_a)
alot=temp_a->next;
else
pre_a->next=temp_a->next;
pre_f=NULL;
while(temp_f!=NULL && temp_f->st_add < temp_a->st_add)
{
pre_f=temp_f;
temp_f=temp_f->next;
}
if(pre_f!=NULL && pre_f->end_add==temp_a->st_add)
pre_f->end_add=temp_a->end_add;
else if(pre_f!=NULL&&temp_f!=NULL&&
temp_f->st_add==temp_a->end_add)
temp_f->st_add=temp_a->st_add;
else
{
free_alot=(struct free_list*)malloc(sizeof

KINGS COLLEGE OF ENGINEERING 62


CS8461 OPERATING SYSTEMS LAB

(struct free_list));
free_alot->st_add=temp_a->st_add;
free_alot->end_add=temp_a->end_add;
if(pre_f!=NULL)
pre_f->next=free_alot;
free_alot->next=temp_f;
if(flist==temp_f)
{
flist=free_alot;
}
}
free(temp_a);
}
else printf("\n process not in memory");
temp_f=flist;
while(temp_f!=NULL)
{
if(temp_f->end_add==temp_f->next->st_add)
{
temp_f->end_add=temp_f->next->end_add;
temp_f->next=temp_f->next->next;
}
temp_f=temp_f->next;
}
display_alot(alot);
display_free(flist);
getch();
}
bestfit(10);
}
OUTPUT:
no. of process:7
process to be inserted:0 size:351
allocated list:
================
process:0 st_add:0 end_add:351
free list:
=================
st_add:351 end_add:1024
process to be inserted:1 size:466
allocated list:
================
process:0 st_add:0 end_add:351
process:1 st_add:351 end_add:817
free list:
=================
st_add:817 end_add:1024

KINGS COLLEGE OF ENGINEERING 63


CS8461 OPERATING SYSTEMS LAB

process to be inserted:2 size:337


there is not enough space
allocated list:
================
process:0 st_add:0 end_add:351
process:1 st_add:351 end_add:817
free list:
=================
st_add:817 end_add:1024
process to be inserted:3 size:410
there is not enough space
allocated list:
================
process:0 st_add:0 end_add:351
process:1 st_add:351 end_add:817
free list:
=================
st_add:817 end_add:1024
process to be inserted:4 size:542
there is not enough space
allocated list:
================
process:0 st_add:0 end_add:351
process:1 st_add:351 end_add:817
free list:
=================
st_add:817 end_add:1024
process to be inserted:5 size:547
there is not enough space
allocated list:
================
process:0 st_add:0 end_add:351
process:1 st_add:351 end_add:817
free list:
=================
st_add:817 end_add:1024
process to be inserted:6 size:89
allocated list:
================
process:0 st_add:0 end_add:351
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
free list:
=================
st_add:906 end_add:1024
no.of process deletion:4
process to be deleted:0

KINGS COLLEGE OF ENGINEERING 64


CS8461 OPERATING SYSTEMS LAB

allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
free list:
=================
st_add:0 end_add:351
st_add:906 end_add:1024
process to be deleted:2
process not in memory
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
free list:
=================
st_add:0 end_add:351
st_add:906 end_add:1024
process to be deleted:3
process not in memory
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
free list:
=================
st_add:0 end_add:351
st_add:906 end_add:1024
process to be deleted:4
process not in memory
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
free list:
=================
st_add:0 end_add:351
st_add:906 end_add:1024
no of processes:9
process to be inserted:10 size:155
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
free list:
=================

KINGS COLLEGE OF ENGINEERING 65


CS8461 OPERATING SYSTEMS LAB

st_add:155 end_add:351
st_add:906 end_add:1024
process to be inserted:11 size:43
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
free list:
=================
st_add:155 end_add:351
st_add:949 end_add:1024
process to be inserted:12 size:188
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
process:12 st_add:155 end_add:343
free list:
=================
st_add:343 end_add:351
st_add:949 end_add:1024
process to be inserted:13 size:7
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
process:12 st_add:155 end_add:343
process:13 st_add:343 end_add:350
free list:
=================
st_add:350 end_add:351
st_add:949 end_add:1024
process to be inserted:14 size:160
there is not enough space
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
process:12 st_add:155 end_add:343

KINGS COLLEGE OF ENGINEERING 66


CS8461 OPERATING SYSTEMS LAB

process:13 st_add:343 end_add:350


free list:
=================
st_add:350 end_add:351
st_add:949 end_add:1024
process to be inserted:15 size:100
there is not enough space
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
process:12 st_add:155 end_add:343
process:13 st_add:343 end_add:350
free list:
=================
st_add:350 end_add:351
st_add:949 end_add:1024
process to be inserted:16 size:198
there is not enough space
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
process:12 st_add:155 end_add:343
process:13 st_add:343 end_add:350
free list:
=================
st_add:350 end_add:351
st_add:949 end_add:1024
process to be inserted:17 size:51
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
process:12 st_add:155 end_add:343
process:13 st_add:343 end_add:350
process:17 st_add:949 end_add:1000
free list:
=================
st_add:350 end_add:351
st_add:1000 end_add:1024

KINGS COLLEGE OF ENGINEERING 67


CS8461 OPERATING SYSTEMS LAB

process to be inserted:18 size:42


there is not enough space
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
process:12 st_add:155 end_add:343
process:13 st_add:343 end_add:350
process:17 st_add:949 end_add:1000
free list:
=================
st_add:350 end_add:351
st_add:1000 end_add:1024
RESULT:
Thus the program for Implement best fit algorithm for memory management is
written and successfully executed.

EX NO: 9 (b) Implement worst fit algorithm for memory management


AIM :
To write a program for Implement worst fit memory management.
ALGORITHM:
1. Start the program.
2. Declare the size.
3. Get the number of processes to be inserted.
4. Allocate the first hole that is small enough searching.
5. If small enough then stop searching in the procedure.
6. Display the values.
7. Stop the program.
PROGRAM:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct allocate
{
int pid; int st_add; int end_add; struct allocate *next;
};
struct free_list
{
int st_add; int end_add; struct free_list *next;
};
struct process
{
int pid; int size;
};

KINGS COLLEGE OF ENGINEERING 68


CS8461 OPERATING SYSTEMS LAB

struct process pro[10];


struct free_list *flist=NULL;
struct allocate *alot=NULL;
void display_alot(struct allocate *temp_a)
{
printf("\n\n allocated list:");
printf("\n================");
while(temp_a!=NULL)
{
printf("\n process:%d st_add:%d end_add:%d ",temp_a->pid,
temp_a->st_add,temp_a->end_add);
temp_a=temp_a->next;
}
}
void display_free(struct free_list *temp_f)
{
printf("\n\n free list:");
printf("\n=================");
while(temp_f!=NULL)
{
printf("\n st_add:%d end_add:%d",temp_f->st_add,temp_f->end_add);
temp_f=temp_f->next;
}
}
void insert(int p)
{
struct free_list *temp_f;
struct allocate *temp_a,*pre_a;
int i,n;
do
{
srand((unsigned int)time((time_t*)NULL));
n=rand()%10;
}
while(n==0);
printf("\n\n no. of process:%d",n);
for(i=0;i<n;i++)
{
pro[i].pid=i+p;
do
{
pro[i].size=rand()%550;
}
while(pro[i].size==0);
}
for(i=0;i<n;i++)
{

KINGS COLLEGE OF ENGINEERING 69


CS8461 OPERATING SYSTEMS LAB

printf("\n\n process to be inserted:%d size:%d",pro[i].pid,pro[i].size);


temp_f=flist;
temp_a=alot;
while(temp_f!=NULL && temp_f->end_add-temp_f->st_add < pro[i].size)
{
temp_f=temp_f->next;
}
if(temp_f!=NULL)
{
pre_a=(struct allocate*)malloc(sizeof(struct allocate));
pre_a->st_add=temp_f->st_add;
pre_a->end_add=temp_f->st_add=temp_f->st_add+pro[i].size;
pre_a->pid=pro[i].pid;
if(temp_a==NULL)
{
alot=pre_a;
pre_a->next=NULL;
}
else
{
while(temp_a->next!=NULL)
{
temp_a=temp_a->next;
}
temp_a->next=pre_a;
pre_a->next=NULL;
}
}
else
printf("\n there is not enough space");
display_alot(alot);
display_free(flist);
getch();
}
}
void worstfit(int p)
{
struct free_list *temp_f,*big_hole;
struct allocate *temp_a,*pre_a;
int i,n;
do
{
srand((unsigned int)time((time_t*)NULL));
n=rand()%10;
}
while(n==0);
printf("\n no.of process:%d",n);

KINGS COLLEGE OF ENGINEERING 70


CS8461 OPERATING SYSTEMS LAB

for(i=0;i<n;i++)
{
pro[i].pid=i+p;
do
{
pro[i].size=rand()%250;
}
while(pro[i].size==0);
}
for(i=0;i<n;i++)
{
printf("\n process to be inserted: %d size :%d",pro[i].pid,pro[i].size);
temp_f=flist;
temp_a=alot;
big_hole=NULL;
while(temp_f!=NULL)
{
if(temp_f->end_add-temp_f->st_add>=pro[i].size)
{
if(big_hole==NULL)
big_hole=temp_f;
else if(temp_f->end_add - temp_f->st_add > big_hole
-> end_add - big_hole-> st_add)
big_hole=temp_f;
}
temp_f=temp_f->next;
}
if(big_hole!= NULL)
{
pre_a=(struct allocate*) malloc (sizeof(struct allocate));
pre_a->st_add=big_hole->st_add;
pre_a->end_add=big_hole->st_add=big_hole->st_add + pro[i].size;
pre_a->pid=pro[i].pid;
if(temp_a==NULL)
{
alot=pre_a;
pre_a->next=NULL;
}
else
{
while(temp_a->next!=NULL)
temp_a=temp_a->next;
temp_a->next= pre_a;
pre_a->next=NULL;
}
}
else

KINGS COLLEGE OF ENGINEERING 71


CS8461 OPERATING SYSTEMS LAB

printf("\n there is not enough space");


display_alot(alot);
display_free(flist);
getch();
}
}
void main()
{
int no,n,i,nod,ndpid;
struct process pro[10];
struct free_list *temp_f,*free_alot,*pre_f;
struct allocate *temp_a,*pre_a;
clrscr();
alot=NULL;
flist=(struct free_list*)malloc(sizeof(struct free_list));
flist->st_add=0;
flist->end_add=1024;
flist->next=NULL;
insert(0);
do
{
srand((unsigned int)time((time_t*)NULL));
nod=rand()%5;
}
while(nod==0);
printf("\n\n no.of process deletion:%d",nod);
for(i=0;i<nod;i++)
{
printf("\n\n\n process to be deleted:");
scanf("%d",&ndpid);
temp_a=alot;
temp_f=flist;
while(temp_a!=NULL && temp_a->pid!=ndpid)
{
pre_a=temp_a;
temp_a=temp_a->next;
}
if(temp_a!=NULL)
{
if(alot==temp_a)
alot=temp_a->next;
else
pre_a->next=temp_a->next;
pre_f=NULL;
while(temp_f!=NULL && temp_f->st_add < temp_a->st_add)
{
pre_f=temp_f;

KINGS COLLEGE OF ENGINEERING 72


CS8461 OPERATING SYSTEMS LAB

temp_f=temp_f->next;
}
if(pre_f!=NULL && pre_f->end_add==temp_a->st_add)
pre_f->end_add=temp_a->end_add;
else if(pre_f!=NULL&&temp_f!=NULL&&
temp_f->st_add==temp_a->end_add)
temp_f->st_add=temp_a->st_add;
else
{
free_alot=(struct free_list*)malloc(sizeof(struct free_list));
free_alot->st_add=temp_a->st_add;
free_alot->end_add=temp_a->end_add;
if(pre_f!=NULL)
pre_f->next=free_alot;
free_alot->next=temp_f;
if(flist==temp_f)
{
flist=free_alot;
}
}
free(temp_a);
}
else printf("\n process not in memory");
temp_f=flist;
while(temp_f!=NULL)
{
if(temp_f->end_add==temp_f->next->st_add)
{
temp_f->end_add=temp_f->next->end_add;
temp_f->next=temp_f->next->next;
}
temp_f=temp_f->next;
}
display_alot(alot);
display_free(flist);
getch();
}
worstfit(10);
}
OUTPUT:
no. of process:9
process to be inserted:0 size:21
allocated list:
================
process:0 st_add:0 end_add:21
free list:
=================

KINGS COLLEGE OF ENGINEERING 73


CS8461 OPERATING SYSTEMS LAB

st_add:21 end_add:1024
process to be inserted:1 size:469
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
free list:
=================
st_add:490 end_add:1024
process to be inserted:2 size:30
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
free list:
=================
st_add:520 end_add:1024
process to be inserted:3 size:74
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
free list:
=================
st_add:594 end_add:1024
process to be inserted:4 size:182
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
free list:
=================
st_add:776 end_add:1024
process to be inserted:5 size:100
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776

KINGS COLLEGE OF ENGINEERING 74


CS8461 OPERATING SYSTEMS LAB

process:5 st_add:776 end_add:876


free list:
=================
st_add:876 end_add:1024
process to be inserted:6 size:183
there is not enough space
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
free list:
=================
st_add:876 end_add:1024
process to be inserted:7 size:411
there is not enough space
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
free list:
=================
st_add:876 end_add:1024
process to be inserted:8 size:292
there is not enough space
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
free list:
=================
st_add:876 end_add:1024
no.of process deletion:2
process to be deleted:0
allocated list:
================

KINGS COLLEGE OF ENGINEERING 75


CS8461 OPERATING SYSTEMS LAB

process:1 st_add:21 end_add:490


process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
free list:
=================
st_add:0 end_add:21
st_add:876 end_add:1024
process to be deleted:1
allocated list:
================
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
free list:
=================
st_add:0 end_add:490
st_add:876 end_add:1024
no.of process:6
process to be inserted: 10 size :105
allocated list:
================
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
process:10 st_add:0 end_add:105
free list:
=================
st_add:105 end_add:490
st_add:876 end_add:1024
process to be inserted: 11 size :93
allocated list:
================
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
process:10 st_add:0 end_add:105
process:11 st_add:105 end_add:198
free list:
=================
st_add:198 end_add:490
st_add:876 end_add:1024
process to be inserted: 12 size :60

KINGS COLLEGE OF ENGINEERING 76


CS8461 OPERATING SYSTEMS LAB

allocated list:
================
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
process:10 st_add:0 end_add:105
process:11 st_add:105 end_add:198
process:12 st_add:198 end_add:258
free list:
=================
st_add:258 end_add:490
st_add:876 end_add:1024
process to be inserted: 13 size :103
allocated list:
================
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
process:10 st_add:0 end_add:105
process:11 st_add:105 end_add:198
process:12 st_add:198 end_add:258
process:13 st_add:258 end_add:361
free list:
=================
st_add:361 end_add:490
st_add:876 end_add:1024
process to be inserted: 14 size :72
allocated list:
================
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
process:10 st_add:0 end_add:105
process:11 st_add:105 end_add:198
process:12 st_add:198 end_add:258 process:13 st_add:258 end_add:361 process:14
st_add:876 end_add:948
free list:
=================
st_add:361 end_add:490
st_add:948 end_add:1024
process to be inserted: 15 size :17
allocated list:
================
process:2 st_add:490 end_add:520

KINGS COLLEGE OF ENGINEERING 77


CS8461 OPERATING SYSTEMS LAB

process:3 st_add:520 end_add:594


process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
process:10 st_add:0 end_add:105
process:11 st_add:105 end_add:198
process:12 st_add:198 end_add:258
process:13 st_add:258 end_add:361
process:14 st_add:876 end_add:948
process:15 st_add:361 end_add:378
free list:
=================
st_add:378 end_add:490
st_add:948 end_add:1024
RESULT:
Thus the program for Implement best fit algorithm for memory management is
written and successfully executed.

KINGS COLLEGE OF ENGINEERING 78


CS8461 OPERATING SYSTEMS LAB

EX. NO: 11(a) IMPLEMENTATION OF PAGING TECHNIQUE OF MEMORY


DATE : MANAGEMENT
(FIRST FIT)

AIM
To write a program to implement first fit algorithm for memory management.

ALGORITHM
1. Start the process
2. Declare the size
3. Get the number of processes to be inserted
4. Allocate the first hole that is big enough
5. Display the values
6. Stop the process

PROGRAM
import java.io.DataInputStream;
import java.io.IOException;
public class FirstFit {
public static void main(String args[]) throws IOException {
int n, i, it;
DataInputStream in = new DataInputStream(System.in);
System.out.println("Enter Number of Holes");
n = Integer.parseInt(in.readLine());
int sp[] = new int[n];
for (i = 0; i < n; i++) {
System.out.println("Enter size of Hole" + (i + 1));
sp[i] = Integer.parseInt(in.readLine());
}
System.out.println("Before Insertion of new process");
System.out.println("hole\t\tsize");
for (i = 0; i < n; i++) {
System.out.println("hole" + (i + 1) + "\t\t" + sp[i]);
}
System.out.println("enter new process size to insert");
it = Integer.parseInt(in.readLine());
for (i = 0; i < n; i++) {
if (it < sp[i]) {
sp[i] = sp[i] - it;
break;
}
}
System.out.println("After Insertion of new process");
System.out.println("hole\t\tsize");
for (i = 0; i < n; i++) {
System.out.println("hole" + (i + 1) + "\t\t" + sp[i]);
}

KINGS COLLEGE OF ENGINEERING 79


CS8461 OPERATING SYSTEMS LAB

}
}
OUTPUT
Enter Number of Holes
2
Enter size of Hole1
1
Enter size of Hole2
2
Before Insertion of new process
hole size
hole1 1
hole2 2
enter new process size to insert
2
After Insertion of new process
hole size
hole1 1
hole2 2

RESULT

Thus the program for first fit algorithm for memory management was executed and
verified.

KINGS COLLEGE OF ENGINEERING 80


CS8461 OPERATING SYSTEMS LAB

EX. NO: 11(b) IMPLEMENTATION OF PAGING TECHNIQUE OF MEMORY


DATE : MANAGEMENT
(NEXT FIT)

AIM
To write a program to implement next fit algorithm for memory management.

ALGORITHM
1. Start the program.
2. Get the number of segments and size.
3. Get the memory requirement and select the option.
4. If the option is ‘1’ call next fit function.
5. Otherwise exit.
6. For first fit, allocate the process to first possible segment which is free.
7. For next fit, do the following steps.
8. Sorts the segments according to their sizes.
9. Allocate the process to the segment which is equal to or slightly greater than the
process size.
10. Stop the program.

PROGRAM
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class NextFit {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int nh, np;
System.out.println("Enter the number of Holes:");
nh = Integer.parseInt(br.readLine());
System.out.println("Enter the number of Processes:");
np = Integer.parseInt(br.readLine());
int P[] = new int[np];
int H[] = new int[nh];
System.out.println("Enter the size of holes:");
for (int i = 0; i < nh; i++) {
System.out.print("H[" + i + "]=");
H[i] = Integer.parseInt(br.readLine());
System.out.println();
}
System.out.println("Enter the size of Processes:");
for (int i = 0; i < np; i++) {
System.out.print("P[" + i + "]=");
P[i] = Integer.parseInt(br.readLine());
System.out.println();
}

KINGS COLLEGE OF ENGINEERING 81


CS8461 OPERATING SYSTEMS LAB

int h = nh;
int j = 0;

while (h > 0) {
for (int i = 0; i < nh; i++) {
if (H[i] > P[j]) {
System.out.println("Process " + j + "allocated in hole " + i);
H[i] -= P[j];
j++;

h--;

}
}
}

System.out.println("_______________");
}
}

OUTPUT
Enter the number of Holes:
2
Enter the number of Processes:
3
Enter the size of holes:
H[0]=2
H[1]=3
Enter the size of Processes:
P[0]=2
P[1]=3
P[2]=3
Process 0 allocated in hole 1

RESULT

Thus the program for next fit algorithm for memory management was executed and
verified.

KINGS COLLEGE OF ENGINEERING 82


CS8461 OPERATING SYSTEMS LAB

EX. NO: 11(c) IMPLEMENTATION OF PAGING TECHNIQUE OF MEMORY


DATE : MANAGEMENT
(BEST FIT)

AIM
To write a program to implement best fit algorithm for memory management.

ALGORITHM
1. Start the program
2. Declare the size
3. Get the number of processes to be inserted
4. Allocate the best hole that is small enough searching
5. Start at the best of the set of holes
6. Compare the hole in the list
7. If small enough, then stop searching in the procedure
8. Display the values
9. Stop the program

PROGRAM
import java.io.DataInputStream;
import java.io.IOException;
public class best {
public static void main(String args[]) throws IOException {
int flag[] = new int[10];
int sm[] = new int[10];
int i, sr, nm;
int sp, loc = 0;
int cntrl = 1000;
DataInputStream in = new DataInputStream(System.in);
System.out.println("Enter the no of memory segments\n");
nm = Integer.parseInt(in.readLine());
System.out.println("Enter the size of memory segments\n");

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


sm[i] = Integer.parseInt(in.readLine());
}
for (i = 0; i < nm; i++) {
flag[i] = 0;
}
System.out.println("Before best fit allocation\n");
System.out.println("\nIndex\t\tMemory Segments\n");
for (i = 0; i < nm; i++) {
System.out.println((i + 1) + "\t\t" + sm[i]);
}
System.out.println("\nEnter the space requirement for new process\n");
sr = Integer.parseInt(in.readLine());
for (i = 0; i < nm; i++) {

KINGS COLLEGE OF ENGINEERING 83


CS8461 OPERATING SYSTEMS LAB

if (flag[i] == 0) {
sp = sm[i];
if (sr <= sp) {
if (cntrl > sp) {
cntrl = sp;
loc = i;
}
}
}
}
if (cntrl == 0) {
System.out.println("\n Space not available");
} else {
sm[loc] = sr;
flag[loc] = 1;
}
System.out.println("\nAfter Bestfit Allocation\n");
System.out.println("Index \t\t Memory Segment\n");
for (i = 0; i < nm; i++) {
System.out.println((i + 1) + "\t\t" + sm[i]);
}
System.out.println("\n The process allocated to the memory segments " + (loc +
1));
}
}

KINGS COLLEGE OF ENGINEERING 84


CS8461 OPERATING SYSTEMS LAB

OUTPUT
Enter the no of memory segments
3
Enter the size of memory segments
2
1
2
Before best fit allocation
Index Memory Segments

1 2
2 1
3 2

Enter the space requirement for new process


6
After Bestfit Allocation
Index Memory Segment
1 6
2 1
3 2

The process allocated to the memory segments 1

RESULT
Thus the best fit program for paging techniques was successfully executed
and verified.

KINGS COLLEGE OF ENGINEERING 85


CS8461 OPERATING SYSTEMS LAB

VIVA QUESTIONS:
1. What are the common strategies to select a free hole from a set of available
holes?

2. What do you mean by best fit?

3. What do you mean by first fit?

4. What are memory segment?

5. Define worst fit.

KINGS COLLEGE OF ENGINEERING 86


CS8461 OPERATING SYSTEMS LAB

EX NO: 9 (a) IMPLEMENTATION OF PAGE REPLACEMENT ALGORITHMS-FIFO


DATE :

AIM
To write a c program to implement FIFO (First In First Out) page replacement
algorithm

ALGORITHM
1. Start the program
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. Form a queue to hold all pages
6. Insert the page required 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 program

PROGRAM
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
clrscr();
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];

KINGS COLLEGE OF ENGINEERING 87


CS8461 OPERATING SYSTEMS LAB

j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);
getch();
return 0;
}

OUTPUT

ENTER THE NUMBER OF PAGES:


3

ENTER THE PAGE NUMBER:


1
2
3

ENTER THE NUMBER OF FRAMES: 2


Ref string Page frames
1 1 -1
2 1 2
3 3 2
Page Fault is 3

RESULT
Thus the FIFO program was successfully executed and verified.

KINGS COLLEGE OF ENGINEERING 88


CS8461 OPERATING SYSTEMS LAB

EX NO: 9 (b) IMPLEMENTATION OF PAGE REPLACEMENT ALGORITHMS-LRU


DATE :

AIM
To write a c program to implement LRU (Least Recently Used) page replacement
algorithm

ALGORITHM
1. Start the program
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 program

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

KINGS COLLEGE OF ENGINEERING 89


CS8461 OPERATING SYSTEMS LAB

{
q[k]=p[i];
k++;
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);
getch();
return 0;

KINGS COLLEGE OF ENGINEERING 90


CS8461 OPERATING SYSTEMS LAB

OUTPUT
Enter no. of pages: 3
Enter the reference string: Adithya
Enter no of frames: 1627902152
The no. of page faults is 3

RESULT
Thus the LRU program was successfully executed and verified.

KINGS COLLEGE OF ENGINEERING 91


CS8461 OPERATING SYSTEMS LAB

EX NO: 9 (c) IMPLEMENTATION OF PAGE REPLACEMENT ALGORITHMS-LFU


DATE :

AIM
To write a C program for page replacement LFU (Least Frequently Used) algorithm.
ALGORITHM
1. Start the program
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 frequently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the program
PROGRAM
#include<stdio.h>
int main() {
int f, p;
int pages[50], frame[10], hit = 0, count[50], time[50];
int i, j, page, flag, least, minTime, temp;

printf("Enter no of frames : ");


scanf("%d", &f);
printf("Enter no of pages : ");
scanf("%d", &p);

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


frame[i] = -1;
}
for (i = 0; i < 50; i++) {
count[i] = 0;
}
printf("Enter page no : \n");
for (i = 0; i < p; i++) {
scanf("%d", &pages[i]);
}
printf("\n");
for (i = 0; i < p; i++) {
count[pages[i]]++;
time[pages[i]] = i;
flag = 1;
least = frame[0];
for (j = 0; j < f; j++) {
if (frame[j] == -1 || frame[j] == pages[i]) {
if (frame[j] != -1) {
hit++;
}

KINGS COLLEGE OF ENGINEERING 92


CS8461 OPERATING SYSTEMS LAB

flag = 0;
frame[j] = pages[i];
break;
}
if (count[least] > count[frame[j]]) {
least = frame[j];
}
}
if (flag) {
minTime = 50;
for (j = 0; j < f; j++) {
if (count[frame[j]] == count[least] && time[frame[j]] < minTime) {
temp = j;
minTime = time[frame[j]];
}
}
count[frame[temp]] = 0;
frame[temp] = pages[i];
}
for (j = 0; j < f; j++) {
printf("%d ", frame[j]);
}
printf("\n");
}
printf("Page hit = %d", hit);
return 0;
}

OUTPUT
Enter no of frames : 3
Enter no of pages: 2
Enter page number :
1
2
1 -1 -1
1 2 -1
Page hit = 0

RESULT
Thus the LFU program was successfully executed and verified.

KINGS COLLEGE OF ENGINEERING 93


CS8461 OPERATING SYSTEMS LAB

VIVA QUESTIONS:

1. What are local page replacements?

2. What are global page replacements?

3. What is cache-coherency?

4. What are placement and replacement algorithms?

5. What are demand- paging and pre-paging?

EX.NO: 6 (a) IMPLEMENTATION OF ALL FILE ORGANIZATION TECHNIQUES


DATE : (SINGLE LEVEL DIRECTORY)
KINGS COLLEGE OF ENGINEERING 94
CS8461 OPERATING SYSTEMS LAB

AIM
To write a C program to implement file organization concept using the technique
single level directory.

ALGORITHM
1. Start the program
2. Declare the number, names and size of the directories and file names
3. Get the values for the declared variables
4. Display the files that are available in the directories
5. Stop the program

PROGRAM
#include<stdio.h>
#include<conio.h>
void main()
{
int master,s[20];
char f[20][20][20];
char d[20][20];
int i,j;
clrscr();
printf("enter number of directories:");
scanf("%d",&master);
printf("enter names of directories:");
for(i=0;i<master;i++)
scanf("%s",&d[i]);
printf("enter size of directories:");
for(i=0;i<master;i++)
scanf("%d",&s[i]);
printf("enter the file names :");
for(i=0;i<master;i++)
for(j=0;j<s[i];j++)
scanf("%s",&f[i][j]);
printf("\n");
printf(" directory\tsize\tfilenames\n");
printf("*************************************************\n");
for(i=0;i<master;i++)
{
printf("%s\t\t%2d\t",d[i],s[i]);
for(j=0;j<s[i];j++)
printf("%s\n\t\t\t",f[i][j]);
printf("\n");
}
printf("\t\n");
getch();
}

KINGS COLLEGE OF ENGINEERING 95


CS8461 OPERATING SYSTEMS LAB

OUTPUT
Enter number of directories:2
Enter names of directories:a1
Enter size of directories:2
Enter the file names:
b1
b2
Welcome to all
Directory size filenames
************************************
a1 2 b1
b2
a2 2 welcome to all

RESULT
Thus the single level directory program was successfully executed and verified.

EX.NO: 6 (b) IMPLEMENTATION OF ALL FILE ORGANIZATION TECHNIQUES

KINGS COLLEGE OF ENGINEERING 96


CS8461 OPERATING SYSTEMS LAB

DATE : (TWO LEVEL DIRECTORY)

AIM
To write a C program to implement file organization concept using the two level
directory.

ALGORITHM
1. Start the program
2. Declare the number, names and size of the directories and subdirectories and file
names.
3. Get the values for the declared variables.
4. Display the files that are available in the directories and subdirectories.
5. Stop the program

PROGRAM
#include<stdio.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir[10];
void main()
{
int i,ch,dcnt,k;
char f[30], d[30];
clrscr();
dcnt=0;
while(1)
{
printf("\n\n1. Create Directory\t2. Create File\t3. Delete File");
printf("\n4. Search File\t\t5. Display\t6. Exit\t
Enter your choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter name of directory -- ");
scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created");
break;
case 2: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",dir[i].fname[dir[i].fcnt]);

KINGS COLLEGE OF ENGINEERING 97


CS8461 OPERATING SYSTEMS LAB

dir[i].fcnt++;
printf("File created");
break;
}
if(i==dcnt)
printf("Directory %s not found",d);
break;
case 3: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is deleted ",f);
dir[i].fcnt--;
strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
printf("File %s not found",f);
goto jmp;
}
}
printf("Directory %s not found",d);
jmp : break;
case 4: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter the name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is found ",f);
goto jmp1;
}
}

KINGS COLLEGE OF ENGINEERING 98


CS8461 OPERATING SYSTEMS LAB

printf("File %s not found",f);


goto jmp1;
}
}
printf("Directory %s not found",d);
jmp1: break;
case 5: if(dcnt==0)
printf("\nNo Directory's ");
else
{
printf("\nDirectory\tFiles");
for(i=0;i<dcnt;i++)
{
printf("\n%s\t\t",dir[i].dname);
for(k=0;k<dir[i].fcnt;k++)
printf("\t%s",dir[i].fname[k]);
}
}
break;
default:exit(0);
}}
getch();
}
OUTPUT

1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display
6. Exit
Enter your choice -- 1

Enter name of directory -- DIR1

Directory created

1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display
6. Exit
Enter your choice -- 1
Enter name of directory -- DIR2
Directory created
1. Create Directory
2. Create File
3. Delete File
4. Search File

KINGS COLLEGE OF ENGINEERING 99


CS8461 OPERATING SYSTEMS LAB

5. Display
6. Exit
Enter your choice -- 2
Enter name of the directory – DIR1
Enter name of the file -- A1
File created

RESULT
Thus the two level directory program was executed and verified successfully.

EX.NO: 6 (c) IMPLEMENTATION OF ALL FILE ORGANIZATION TECHNIQUES


DATE: (HIERARCHICAL LEVEL DIRECTORY)

KINGS COLLEGE OF ENGINEERING


100
CS8461 OPERATING SYSTEMS LAB

AIM
To write a C program to implement file organization concept using the hierarchical
level directory.

ALGORITHM
1. Start the program
2. Declare the number, names and size of the directories and subdirectories and file
names.
3. Get the values for the declared variables by maintaining their root directory details
4. Display the files that are available in the directories and subdirectories.
5. Stop the program

PROGRAM
#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element
node; void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
clrscr();
initgraph(&gd,&gm,"c:\\tc\\BGI");
display(root);
getch();
closegraph();
}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf("Enter name of dir/file(under %s) :
",dname); fflush(stdin);
gets((*root)->name);
printf("enter 1 for Dir/2 for
file :"); scanf("%d",&(*root)->ftype); (*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
KINGS COLLEGE OF ENGINEERING
101
CS8461 OPERATING SYSTEMS LAB

(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
printf("No of sub directories/files(for %s):",(*root)->name); scanf("%d",&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else gap=(rx-lx)/(*root)->nc; for(i=0;i<(*root)->nc;i++)
create(&((*root)->link[i]),lev+1,(*root)->name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else (*root)->nc=0;
}}
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14); if(root
!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1) bar3d(root->x-20,root->y-
10,root->x+20,root->y+10,0,0); else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}
}

OUTPUT:
Enter Name of dir/file(under root): ROOT
Enter 1 for Dir//2 for File: 1 No of subdirectories/files(for USER1): 1
Enter Name of dir/file(under USER1): SUBDIR1
KINGS COLLEGE OF ENGINEERING
102
CS8461 OPERATING SYSTEMS LAB

Enter 1 for Dir/2 for File: 1


No of subdirectories/files(for SUBDIR1): 2
Enter Name of dir/file(under USER1): JAVA
Enter 1 for Dir/2 for File: 1 No of subdirectories/files(for JAVA): 0
Enter Name of dir/file(under SUBDIR1): VB
Enter 1 for Dir/2 for File: 1 No of subdirectories/files(for VB): 0
Enter Name of dir/file(under ROOT): USER2
Enter 1 for Dir/2 for File: 1
No of subdirectories/files(for USER2): 2
Enter Name of dir/file(under ROOT): A
Enter 1 for Dir/2 for File: 2
Enter Name of dir/file(under USER2): SUBDIR2
Enter 1 for Dir/2 for File: 1
No of subdirectories/files(for SUBDIR2): 2
Enter Name of dir/file(under SUBDIR2): PPL

RESULT
Thus the hierarchical level directory program was executed and verified successfully.

EX.NO: 6 (d) IMPLEMENTATION OF ALL FILE ORGANIZATION TECHNIQUES-DAG


DATE: (DIRECTED ACYCLIC GRAPH)

AIM
KINGS COLLEGE OF ENGINEERING
103
CS8461 OPERATING SYSTEMS LAB

To write a C program to implement file organization concept using DAG.

ALGORITHM
1. Start the program
2. Read the root directory and sub directory details
3. Read the common file to be shared between directories
4. Establish link for the file for the directories
5. Updation on the file will reflect on both the directories
6. Display the directory and file details
5. Stop the program.

PROGRAM
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<string.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element
node; typedef struct
{
char from[20];
char to[20];
}link; link
L[10]; int
nofl;
node * root;
void main()
{
int gd=DETECT,gm;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
read_links();
clrscr();
initgraph(&gd,&gm,"c:\\tc\\BGI");
draw_link_lines();
display(root);
getch();
closegraph();
}
read_links()
{
KINGS COLLEGE OF ENGINEERING
104
CS8461 OPERATING SYSTEMS LAB

int i;
printf("how many links");
scanf("%d",&nofl);
for(i=0;i<nofl;i++)
{
printf("File/dir:");
fflush(stdin);
gets(L[i].from);
printf("user name:");
fflush(stdin);
gets(L[i].to);
}
}
draw_link_lines()
{
int i,x1,y1,x2,y2;
for(i=0;i<nofl;i++)
{
search(root,L[i].from,&x1,&y1);
search(root,L[i].to,&x2,&y2);
setcolor(LIGHTGREEN);
setlinestyle(3,0,1);
line(x1,y1,x2,y2);
setcolor(YELLOW);
setlinestyle(0,0,1);
}
}s
earch(node *root,char *s,int *x,int *y)
{
int i;
if(root!=NULL)
{
if(strcmpi(root->name,s)==0)
{
*x=root->x;
*y=root->y;
return;
}
else
{
for(i=0;i<root->nc;i++)
search(root->link[i],s,x,y);
}
}
} create(node **root,int lev,char *
dname,int lx,int rx,int x)
{
KINGS COLLEGE OF ENGINEERING
105
CS8461 OPERATING SYSTEMS LAB

int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf("enter name of dir/file(under%s):",dname);
fflush(stdin);
gets((*root)->name);
printf("enter 1 for dir/ 2 for
file:"); scanf("%d",&(*root)->ftype); (*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
printf("no of sub directories /files (for %s):",(*root)->name); scanf("%d",&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)
create( & ( (*root)->link[i] ) , lev+1 ,
(*root)->name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else
(*root)->nc=0;
}
}
/* displays the constructed tree in graphics
mode */
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14); if(root
!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1) bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
KINGS COLLEGE OF ENGINEERING
106
CS8461 OPERATING SYSTEMS LAB

fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name); for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}
}

OUTPUT
Enter number of directories:1
Enter directory1 names:a1
Enter size of directories:2
Enter subdirectory name and size:b1
Enter file name:a11
Enter file name:a12
Enter subdirectory name and size:c1
Enter file name:b11
Dir name size subdirname size files
**************************************************************************************
a1 2 b1 2 a11
a1 2 c1 1 b11

RESULT
Thus the program for implementation of DAG was successfully executed and verified

VIVA QUESTIONS

KINGS COLLEGE OF ENGINEERING


107
CS8461 OPERATING SYSTEMS LAB

1. What is Direct Access Method?

2. When designing the file structure for an operating system, what attributes are
considered?

3. What is Sector?

4. Define UFD and MFD.

5. What is Memory-Management Unit (MMU)?

4. FILE ALLOCATION TECHNIQUES


KINGS COLLEGE OF ENGINEERING
108
CS8461 OPERATING SYSTEMS LAB

EX.NO: 4(a) FILE ALLOCATION TECHNIQUE- SEQUENTIAL ALLOCATION


DATE :

AIM
To write a C program to implement sequential file allocation method.

ALGORITHM
1. Start the program
2. Declare the starting block number and the length of the file
3. Get the starting block number and length of the file from the user
4. Allocate files sequentially until end of the file
5. Display the fragments of the file
6. Stop the program

PROGRAM
#include<stdio.h>
#include<conio.h>
#include<process.h>
struct sequence {
char n[20];
int i;
} s[20];
int create(int);
int del(int);
void
display(int);
void main() {
int
x = 0, j = 0;
clrscr();
while (1) {
printf("1.creation\n2.delete\n3.display\n4.exit");
printf("\nenter the option");
scanf("%d", &x);
switch (x) {
case 1:
j = create(j
);
break;
case 2:
j = del(j);
break;
case 3: display(j);
break;
case 4: exit(1);
default: printf("wrong option");
KINGS COLLEGE OF ENGINEERING
109
CS8461 OPERATING SYSTEMS LAB

}
}
}
int create(int j) {
int m, v;
j++;
w:
printf("\nenter the file name:");
scanf("%s", &s[j].n);
m = 1;
while (m < j) {
v = strcmp(s[j].n, s[m].n);
if (v == 0) {
printf("file is already exist\nplease enter another name");
goto w;
}
m++;
}
printf("\nenter field:");
scanf("%d", &s[j].i);
return (j);
}
int del(int j) {
j--;
return (j);
}

void display(int j) {
int l;
printf("filename\tfield");
for (l = 1; l <= j; l++)
printf("\n%s\t\t%d\n", s[l].n, s[l].i);
}

KINGS COLLEGE OF ENGINEERING


110
CS8461 OPERATING SYSTEMS LAB

OUTPUT
1. creation
2. delete
3. display
4. exit
enter the option
1
enter the file name: kk
enter field:1
1.creation
2.delete
3.display
4.exit
enter the option
3
filename field
kk 1
1.creation
2.delete
3.display
4.exit
enter one option

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25RESULT
Thus the sequential file allocation program was executed and verified.

EX.NO: 4(b) FILE ALLOCATION TECHNIQUE- INDEXED ALLOCATION


DATE :
KINGS COLLEGE OF ENGINEERING
111
CS8461 OPERATING SYSTEMS LAB

AIM
To write a C program to implement file allocation concept using indexed allocation
technique.

ALGORITHM
1. Start the program
2. Declare the index block number and total number of files in a block
3. Get the index block number and total number of files in a block from the user
4. Allocate files based on the index block number
5. Arrange the files based on indexes which are created for each fragment of the file
such that each and every similar indexed file is maintained by the primary index to
provide the flow to file fragments.
6. Stop the program

PROGRAM
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct file {
char n[20];
int fld, ind;
} s[20];
int no, i = -1, a, b, f, j = -1, fe, t;
char tem[20];
void create();
void display();
void del();
void main() {
clrscr();
while (1) {
printf("\n\n menu");
printf("\n1.create\n2.display\n3.delete\n4.exit");
printf("enter ur choice:");
scanf("%d", &no);
switch (no) {
case 1: create();
break;
case 2: display();
break;
case 3: del();
break;
case 4: exit(0);
default: printf("wrong choice");
}}
}
void create() {
KINGS COLLEGE OF ENGINEERING
112
CS8461 OPERATING SYSTEMS LAB

i++;
printf("\nenter the name of the recorded:");
scanf("%s", &s[i].n);
printf("\nenter the indexno:");
scanf("%d", &s[i].ind);
printf("\nenter the field no:");
scanf("%d", &s[i].fld);
j++;
}
void display() {
for (a = 0; a < i; a++) {
for (b = 0; b < i; b++) {
if (s[b].ind > s[b + 1].ind) {
t = s[b].ind;
s[b].ind = s[b + 1].ind;
s[b + 1].ind = t;
strcpy(tem, s[b].n);
strcpy(s[b].n, s[b + 1].n);
strcpy(s[b + 1].n, tem);
t = s[b].fld;
s[b].fld = s[b + 1].fld;
s[b + 1].fld = t;
} else
continue;
}}
printf("\n ---------------------------------");
printf("\n\t Index Recordname FieldNo");
for (i = 0; i <= j; i++) {
printf("\n\t%d\t", s[i].ind);
printf("\t%s", s[i].n);
printf("\t%d", s[i].fld);
}
i--;
printf("\n -----------------------------------\n");
}
void del() {
int de, index = -
1, k = 0, l;
if (i != -1) {
printf("enter index no to be deleted");
scanf("%d", &de);
index = de;
while (s[k].ind != de) {
k++;
printf("\n\t\t\t%d", k);
}
for (l = k; l <= j; l++)
KINGS COLLEGE OF ENGINEERING
113
CS8461 OPERATING SYSTEMS LAB

s[l] = s[l + 1];


i--;
j--;
printf("\nindex no %d file is deleted", index);
}
}
OUTPUT
menu
1.create
2.display
3.delete
4.exit
enter ur choice:1
enter the name of the recorded: rajiv
enter the indexno:1
enter the field no:1
menu
1.create
2.display
3.delete
4.exit
enter ur choice:1
enter the name of the recorded: uma
enter the indexno:2
enter the field no:2
menu
1.create
2.display
3.delete
4.exit
enter ur choice:2
---------------------------------
Index Recordname FieldNo
1 rajiv 1
2 uma 2
-----------------------------------
menu
1.create
2.display
3.delete
4.exit
enter ur choice:
26
27RESULT
Thus the indexed file allocation program was executed and verified.
EX.NO: 4(c) FILE ALLOCATION TECHNIQUE- LINKED ALLOCATION
DATE :
KINGS COLLEGE OF ENGINEERING
114
CS8461 OPERATING SYSTEMS LAB

AIM
To write a C program to implement file allocation concept using the linked list
technique.

ALGORITHM
1. Create a queue to hold all pages in memory
2. When the page is required, replace the page at the head of the queue
3. Now, the new page is inserted at the tail of the queue
4. Create a stack
5. When the page fault occurs replace page present at the bottom of the stack
6. Stop the allocation

PROGRAM
#include<stdio.h>
#include<stdlib.h>
typedef struct {
int bno, flag, next;
} block;
block b[200], b1;

void main() {
int rnum();
int i, n, s, s1, p[30], r, k[20];
clrscr();
printf("\nEnter number of programs:");
scanf("%d", &n);
printf("\nEnter the memory block request");
for (i = 1; i <= n; i++) {
printf("\nEnter program requirement");
scanf("%d", &p[i]);
}
for (i = 1; i <= n; i++) {
s = rnum();
b[s].bno = 0;
b[s].flag = 1;
k[i] = 0;
r = p[i] - 1;
while (r != 0) {
s1 = rnum();
b[s].next = s1;
b[s1].flag = 1;
b[s1].bno = 0;
s = s1;
r = r - 1;
}
b[s1].next = NULL;
KINGS COLLEGE OF ENGINEERING
115
CS8461 OPERATING SYSTEMS LAB

}
printf("\n Starting blocks for program");
for (i = 1; i <= n; i++)
printf("\n%5d%5d", i, k[i]);
printf("\n allocated blocks");
for (i = 1; i <= 200; i++) {
if (b[i].flag == 1)
printf("\n%5d%5d", b[i].bno, b[i].next);
}
}
int rnum() {
int k, i;
for (i = 1; i <= 200; i++) {
k = rand() % 200;
if (b[i].flag != 1)
break;
}
return k;
}

OUTPUT
Enter number of programs: 2
Enter the memory block request
Enter program requirement 10 20
Enter program requirement
Starting blocks for program
1 0
2 0
allocated blocks
0 149
0 105
0 172
0 119
0 129
0 180
0 108
0 108
0 193

RESULT
Thus the linked file allocation program was executed and verified successfully.
1. What is a reference string?
VIVA QUESTIONS:

KINGS COLLEGE OF ENGINEERING


116
CS8461 OPERATING SYSTEMS LAB

2. What is a file?

1
2
3. List out the
3 various file attributes.

4. What is Directory?

5. What is a device queue?

KINGS COLLEGE OF ENGINEERING


117

You might also like