1-15_OS_record
1-15_OS_record
BACHELOR OF TECHNOLOGY
SECOND YEAR
Name :
University Reg.No :
Semester :
Branch :
Year :
2B UNIX COMMANDS
2C Shell Programming
6 Implementation of Semaphores
9 Implementation of Thread in C
Aim
Procedure
1. Boot your PC using Windows 7 DVD/USB drive and press any key if you see Press any key to
continue message.
2. Next select your language, keyboard type (Generally the US) and time format.
5. In the next screen, click on the Custom (advanced) option. I hope you are not upgrading here. If you
are doing an upgrade then just click on the Upgrade option.
6. This is an important step as you need to select the drive where you would like to install Windows 7.
Note that selecting a wrong partition will wipe out the data. Also, note that Windows 7 creates another
small partition of about 200 MB if you are installing Windows 7 on an empty hard drive. The hidden
200MB partition will not be shown in the Windows Explorer!
7. You can also format the selected partition by opening drive option and then choosing
the Format option.
8. Click on the Next button to start the Windows 7 installation. Windows may restart many times during
the installation and you need not worry about that.
9. After completing the installation, Windows will give you the below screen to enter your username
and password.
10. In the next step you will be asked to enter the Product Key. Enter the key that you have got and click
the Next button.
11. Here you need to select the Windows 7 update option. Click Use recommended settings option.
10. In the next screen, you need to select the type of network. That is, choose between Home network,
Work network and Public network.
11. Finally, the setup will ask you to create a group depending on the type of Network you have chosen.
If you are not sure, just skip as you can do it later as well.
12. You will see the Windows 7 desktop. That is, you have successfully installed Windows 7 on your PC.
Don’t forget to read 10 things to do soon after installing Windows 7 to make your Windows 7 secure.
Result :
Thus the installation of Windows Operating System has been completed successfully.
Ex.no:2(a)
Date: Study of UNIX Operating System
Aim
Operating System
o Acts as resource management through orderly and controlled allocation of the processors,
memories, and I/O devices among the programs competing for it.
UNIX Features
1. Multi-user system—Multi-user capability of UNIX allows several users to use the same
computer to perform their tasks. Several terminals [Keyboards and Monitors] are connected to a
single powerful server.
3. Programming Facility—the UNIX shell has all the necessary ingredients like conditional and
control structures, etc.
4. Security—Every user must have a single login name and password. So, accessing another user’s
data is impossible without his permission.
Apart from these features, UNIX has an extensive Tool kit, exhaustive system calls and Libraries and
enhanced GUI (X Window).
Organization of UNIX
1. The kernel is the heart of the system, a collection of programs written in C that directly
communicate with the hardware. It manages the system resources, allocates time between user and
processes, decides process priorities, and performs all other tasks. The kernel, in traditional
parlance, is often called the Operating system.
2. The shell, on the other hand, is the "sleeping beauty" of UNIX. It is actually the interface
between the user and the kernel. The shell is the agency which takes care of the features of
redirection and has a programming capability of its own.
3. The Tools and Applications consist of Application Software, Compilers, Database Package,
Internet tools, UNIX commands, etc.
File System
All files in UNIX are related to one another. The file system of UNIX resembles a tree that grows
from top to bottom as shown in the figure. The file system begins with a directory called root (at the
top). The root directory is denoted by a slash (\). Branching from root there are several directories
such as bin, lib, etc, tmp, dev. Each of these directories contains several sub-directories and files.
Result :
Thus the study of UNIX Operating System has been completed successfully.
Ex.no:2(b)
Date: UNIX Commands
Aim
Login
User has to authenticate himself by providing username and password. Once verified, a greeting and
$ prompt appears. The shell is now ready to receive commands from the user. Options suffixed with
a hyphen (–) and arguments are separated by space.
General commands
commands functions
Date Used to display the current system date and time.
Date+%D Displays date only
Date+%T Displays time only
Date +% Y Displays the year part of date
date +% H Displays the hour part of time
Cal Calendar of the current month
cal year Displays calendar for all months of the specified year
cal month year Displays calendar for the specified month of the year
Who Login details of all users such as their IP, Terminal No, User name,
who am i Used to display the login details of the user
Uname Displays the Operating System
uname –r Shows version number of the OS (kernel).
uname –n Displays domain name of the server
echo $HOME Displays the user's home directory
Bc Basic calculator. Press Ctrl+d to quit
lp file Allows the user to spool a job along with others in a print queue
man cmdname Manual for the given command. Press q to exit
history To display the commands used by the user since log on.
exit Exit from a process. If shell is the only process then logs out
Directory commands
Command Function
Pwd Path of the present working directory
mkdir dir A directory is created in the given name under the current directory
mkdir dir1 dir2 A number of sub-directories can be created under one stroke
Change Directory. If the subdir starts with / then path starts from root
cd subdir (absolute) otherwise from current working directory
cd To switch to the home directory.
cd / To switch to the root directory.
cd .. To move back to the parent directory
rmdir subdir Removes an empty sub-directory.
File commands
Commands Functions
To create a file with some contents. To end typing press Ctrl+d.
cat > filename The > symbol means redirecting output to a file. (< for input)
cat filename Displays the file contents
cat >> filename Used to append contents to a file
cp src des Copy files to given location. If already exists, it will be overwritten
cp –i src des Warns the user prior to overwriting the destination file
cp –r src des Copies the entire directory, all its sub-directories and files
mv old new To rename an existing file or directory. –i option can also be used
mv f1 f2 f3 dir To move a group of files to a directory
mv –v old new Display name of each file as it is moved
rm file Used to delete a file or group of files. –i option can also be used
rm * To delete all the files in the directory
rm –r * Deletes all files and sub-directories
rm –f * To forcibly remove even write-protected files
Ls Lists all files and subdirectories (blue colored) in sorted manner.
Is name To check whether a file or directory exists
ls name* Short-hand notation to list out filenames of a specific pattern
ls –a Lists all files including hidden files (files beginning with .)
ls –x dirname To have specific listing of a directory.
ls –R Recursive listing of all files in the subdirectories
ls –l Long listing showing file access rights (read/write/executerwx for
user/group/others-ugo)
cmp file1 file2 Used to compare two files. Displays nothing if files are identical
wc file it produces a statistics of lines (l), words(w), and characters(c).
chmod perm file Changes permission for the specified file. (r=4, w=2, x=1) chmod 740
file sets all rights for user, read only for groups and no rights for others
For example:
number of users logged in can be obtained as. who | wc -l Finally to terminate the unix session
execute the command exit or logout.
Output
$ date
$ date +%D
04/09/11
$ date +%T
13:05:33
$ date +%Y
2011
$ date +%H
13
$ cal 08 1998
August 1998
Su Mo Tu We Th Fr Sa
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
$ who
root : 0 Apr 9 08:41
$ uname
Linux
$ uname -r
2.4.20-8smp
$ uname -n
localhost.localdomain
$ echo $HOME
/home/vijai
$ echo $USER
vijai
$ bc
3+5
$ pwd
/home/vijai/shellscripts/loops
$ mkdir filter
$ ls
$ cd shellscripts/loops/
$ cd
$ cd /
[vijai@localhost /]$
[vijai@localhost shellscripts]$
$ rmdir filter
$ ls
hi cse
$ cat greet
hi ece-a
Bye
$ cat greet
hi cse
$ ls
$ ls -a
$ ls -l
$ cp greet ./regexpr/
$ ls
$ ls ./regexpr
demo greet
$ cp -i greet ./regexpr/
$ mv greet greet.txt
$ mv greet.txt ./regexpr/
$ ls
$ rm -i *.sh
$ ls
$ wc list.sh
4 9 30 list.sh
$ wc -l list.sh
4 list.sh
$ ls -l list.sh
$ ls - l list.sh
$ ls - l list.sh
Result:
Illustration of UNIX command has been executed successfully.
En.no:2(c)
Date: Shell Programming
Aim
The activities of a shell are not restricted to command interpretation alone. The shell also has
rudimentary programming features. Shell programs are stored in a file (with extension .sh). Shell
programs run in interpretive mode. Bourne shell (sh), C shell (csh) and Korn shell (ksh) are also
widely used. Linux offers Bash shell (bash) .
Preliminaries
2. Shell variables are loosely typed i.e. not declared. Variables in an expression or output must be
prefixed by $.
3. The read statement is shell's internal tool for making scripts interactive.
5. Expressions are computed using the expr command. Arithmetic operators are + - * / %. Meta
characters * ( ) should be escaped with a \.
$ sh filename
Decision-making
if [ condition ]
then
statements
else
statements
fi
if [condition ]
then
statements
elif [ condition ]
then
statements .. .
else
statements
fi
The set of relational operators are –eq –ne –gt –ge –lt –le and logical operators used in
conditional expression are –a –o !
Multi-way branching
The case statement is used to compare a variables value against a set of constants. If it matches
a constant, then the set of statements followed after ) is executed till a ;; is encountered. The
optional default block is indicated by *. Multiple constants can be specified in a single pattern
separated by |.
case variable in
constant1)
statements ;;
constant2)
statements ;;
. . . *)
Statements
Esac
Loops
Shell supports a set of loops such as for, while and until to execute a set of statements
repeatedly. The body of the loop is contained between do and done statement.
The for loop doesn't test a condition, but uses a list instead.
do
statements
done
The while loop executes the statements as long as the condition remains true.
while [ condition ]
do
statements
done
The until loop complements the while construct in the sense that the statements are executed as
long as the condition remains false.
until [ condition ]
do
statements
done
Result
Thus shell scripts were executed using different programming construct
Ex.no:3 Process Management using System Calls : Fork, Exit,
Date: Getpid, Wait, Close
(a) (Fork, Getpid, Exit)
Aim:
To create a new child process using fork system call.
Algorithm :
1. Declare a variable x to be shared by both child and parent.
Output
$ gcc fork.c
$ ./a.out Child
Value of x is 6
Parent process:
Process id is 19498
Value of x is 6
Result Thus a child process is created with copy of its parent's address spac
b) (wait system call)
Aim
To block a parent process until child completes using wait system call.
Algorithm
a. Suspend parent process until child completes using wait system call
6. Stop
Program
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include<sys/wait.h>
#include <sys/types.h>
main()
pid;
pid = fork();
if (pid < 0)
{ wait(NULL);
for (i=2;i<=10;i+=2)
printf ("%3d",i);
else if (pid == 0)
printf(“%3d”,i);
printf(“/nchild ends\n”);
Output
$ gcc wait.c
$ ./a.out
Child Starts
Parent starts
Result
Thus using wait system call zombie child processes were avoided.
(c)open&close system call
Aim
Algorithm
3. Create a file with the given name using open system call with O_CREAT and O_TRUNC options.
a) Read 100 bytes (max.) from console and store onto buf using read system call
7. Stop
Program
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <fcntl.h>
char buf[100];
if (argc != 2)
if(fd < 0)
close(fd);
Output
$ gcc fcreate.c
I/O
Open system call is used to either open or create a file. creat system call is used to create a file. It is
seldom used. ^
Result
Thus a file has been created with input from the user. The process can be verified by using cat
command
Ex.no: 4 Write C programs to implement the various CPU
Date: Scheduleing Algorithm
a) FCFS Scheduling
Aim
Process Scheduling
By switching CPU among processes, efficiency of the system can be improved. Some scheduling
algorithms are FCFS, SJF, Priority, Round-Robin, etc. Gantt chart provides a way of visualizing CPU
scheduling and enables to understand better.
Process that comes first is processed first FCFS scheduling is non-preemptive Not efficient as it
results in long average waiting time. Can result in starvation, if processes at beginning of the queue
have long bursts.
Algorithm
1. Define an array of structure process with members pid, btime, wtime & ttime.
5. Compute wtime and ttime for each process as: a. wtimei+1 = wtimei + btimei b. ttimei = wtimei +
btimei
6. Compute average waiting time awat and average turnaround time atur
10. Stop
Program
#include <stdio.h>
struct process
int pid;
int btime;
int wtime;
int ttime;
p[10];
main()
int i,j,k,n,ttur,twat;
float awat,atur;
scanf("%d", &n);
for(i=0; i<n;i++)
scanf("%d", &p[i].btime);
p[i].pid = i+1;
p[0].wtime = 0;
for(i=0; i<n;i++)
ttur = twat = 0;
for(i=0; i<28;i++)
ttur += p[i].ttime;
twat += p[i].wtime;
awat = (float)twat / n;
atur = (float)ttur / n;
printf("\n FCFS Scheduling\n\n");
for(i=0; i<28;i++)
printf("-");
for(i=0; i<28;i++)
printf("-");
for(i=0; i<n;i++)
for(i=0; i<28;i++)
printf("-");
printf("\n\nGANTT Chart\n");
printf("-");
for(i=0; i<(p[n-1].ttime+2”n);i++)
printf("-");
printf("\n");
printf("|");
for(i=0; i<n;i++)
k = p[i].btime/2;
for(j=0; j<k;j++)
printf(" ");
printf("P%d",p[i].pid);
for(j=k+1; j<p[i].btime;j++)
printf(“ ”);
printf("|");
printf("\n");
printf("-");
for(i=0; i<(p[n-1].ttime+2”n);i++)
printf("-");
printf("\n");
printf("0");
for(i=0; i<n;i++)
{for(j=0;j<p[i].btime;j++)
printf(" ");
printf("%2d",p[i].ttime);
}
}
Output
FCFS Scheduling -
P1 10 10 0
P2 4 14 10
P3 11 25 14
P4 6 31 25 -- -
GANTT Chart
- -
| P1 | P2 | P3 | P4 |
- -
0 10 14 25 31
Result
Thus waiting time & turnaround time for processes based on FCFS scheduling was computed and the
average waiting time was determined
b) SJF Scheduling
Aim:
Process that requires smallest burst time is processed first. SJF can be preemptive or non–
preemptive When two processes require same amount of CPU utilization, FCFS is used to break the
tie. Generally efficient as it results in minimal average waiting time. Can result in starvation, since
long critical processes may not be processed.
Algorithm
1. Define an array of structure process with members pid, btime, wtime & ttime.
4. Sort the processes according to their btime in ascending order. a. If two process have same
btime, then FCFS is used to resolve the tie.
6. Compute wtime and ttime for each process as: a. wtimei+1 = wtimei + btimei b. ttimei = wtimei +
btimei
7. Compute average waiting time awat and average turn around time atur.
11. Stop
Program
#include<stdio.h>
struct process
int pid;
int btime;
int wtime;
int ttime;
p[10], temp;
main()
int i,j,k,n,ttur,twat;
float awat,atur;
scanf("%d", &n);
p[0].wtime = 0;
for(i=0; i<n;i++)
scanf("%d", &p[i].btime);
p[i].pid = i+1;
for(i=0; i<n-1;i++)
for(j=i+1;j<n;j++)
p[0].wtime = 0;
for(i=0; i<n;i++)
{
ttur = twat = 0;
for(i=0; i<n;i++)
awat = (float)twat / n;
atur = (float)ttur / n;
for(i=0; i<28;i++)
printf("-");
for(i=0; i<28;i++)
printf(“-“);
for(i=0;i<n;i++)
printf("\n");
for(i=0; i<28;i++)
printf("-");
printf("\n\nGANTT Chart\n");
printf("-");
for(i=0; i<(p[n-1].ttime+2*n);i++)
printf(“-“)4;
printf(“\n|”);
for(i=0;i<n;i++)
K=p[i].btime/2;
For(j=0;j<k;j++)
printf(" ");
printf("%2d",p[i].ttime);
Output
SJF Scheduling -- -
P3 5 5 0
P2 6 11 5
P4 6 17 11
P5 9 26 17
P1 10 36 26
GANTT Chart
| P3 | P2 | P4 | P5 | P1 |
0 5 11 17 26 36
Result
Thus waiting time & turnaround time for processes based on SJF scheduling was computed and the
average waiting time was determined
c) Priority Scheduling
Aim
Priority
Process that has higher priority is processed first. Prioirty can be preemptive or non–preemptive
When two processes have same priority, FCFS is used to break the tie. Can result in starvation, since
low priority processes may not be processed.
Algorithm
1. Define an array of structure process with members pid, btime, pri, wtime & ttime.
a. If two process have same pri, then FCFS is used to resolve the tie.
5. The wtime for first process is 0. 6. Compute wtime and ttime for each process as:
7. Compute average waiting time awat and average turn around time atur
8. Display the btime, pri, ttime and wtime for each process.
11. Stop
Program
#include <stdio.h>
struct process
int pid;
int btime;
int ttime;
p[10], temp;
main()
int i,j,k,n,ttur,twat;
float awat,atur;
scanf("%d", &n);
for(i=0; i<n;i++)
scanf("%d", &p[i].btime);
p[0].wtime = 0;
for(i=0; i<n-1;i++)
for(j=i+1;j<n;j++)
p[0].wtime = 0;
for(i=0; i<n;i++)
ttur = twat = 0;
for(i=0; i<n;i++)
ttur += p[i].ttime;
twat += p[i].wtime;
awat = (float)twat / n;
atur = (float)ttur / n;
for(i=0; i<38;i++)
printf("-");
for(i=0; i<38;i++)
printf(“-“);
for(i=0; i<38;i==)
printf("-");
printf("\n\nGANTT Chart\n");
printf("-");
for(i=0; i<(p[n-1].ttime=2*n);i++)
printf("-");
printf("\n|");
for(i=0; i<n;i++)
k = p[i].btime/2;
for(j=0; j<k;j++)
printf(" ");
printf("P%d",p[i].pid);
for(j=k+1; j<(p[n-1].ttime+2*n);i++)
printf("-");
printf("\n0");
for(i=0; i<n;i++)
for(j=0;j<p[i].btime;j++)
printf(“ “);
printf("%2d",p[i].ttime);
Output
Priority Scheduling
P5 5 2 12 7
P1 10 3 22 12
P3 6 3 28 22
P4 13 4 41 28
- -
GANTT Chart
| P2 | P5 | P1 | P3 | P4 |
0 7 12 22 28 41
Result:
Thus waiting time & turnaround time for processes based on Priority scheduling was computed and
the average waiting time was determined
d) Round Robin Scheduling
Aim:
Round Robin
All processes are processed one by one as they have arrived, but in rounds. Each process cannot take
more than the time slice per round. Round robin is a fair preemptive scheduling algorithm. A process
that is yet to complete in a round is preempted after the time slice and put at the end of the queue.
When a process is completely processed, it is removed from the queue.
Algorithm
6. If Bi > TS then process takes more than one round. Therefore turnaround and waiting time should
include the time spent for other remaining processes in the same round.
9. Display the burst time, turnaround time and wait time for each process (in order of rounds they
were processed).
11. Stop
Program:
#include<stdio.h>
main()
int i,x=-1,k[10],m=0,n,t,s=0;
int a[50],temp,b[50],p[10],bur[10],bur1[10];
int wat[10],tur[10],ttur=0,twat=0,j=0;
float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i=0; i<n;i++)
scanf("%d", &t);
for(i=0; i<n;i++)
b[i] = bur[i] / t;
if((bur[i]%t) != 0)
b[i] += 1;
m += b[i];
printf("\nGANTT Chart\n");
for(i=0; i< m)
if(x == n-1)
x = 0;
else
x++;
if(bur[x] >= t)
bur[x] -= t;
a[j+1] = a[j] + t;
if(b[x] == 1)
p[s] = x;
k[s] = a[j+1];
s++;
j++;
b[x] -= 1;
else if(bur[x] != 0)
bur[x] = 0;
if(b[x] == 1)
p[s] = x;
k[s] = a[j+1];
s++;
j++;
b[x] -= 1;
printf("\n");
for(i=0;i<=m; i++)
printf(“\n”);
for(j=0;i<n;i++)
printf("%d\t", a[j]);
for(i=0; i<n;i++)
for(j=i+1;j<n;j++)
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
temp = k[i];
k[i] = k[j];
k[j] = temp;
}}}
for(i=0; i<n;i++)
tur[i] = k[i];
for(i=0; i<n;i++)
ttur += tur[i];
twat += wat[i];
printf("\n\n");
for(i=0; i<30;i++)
printf("-");
printf("\nProcess\tBurst\tTrnd\tWait\n");
for(i=0; i<30;i++)
printf(“_”);
for(i=0;i<30;i++)
printf("-");
awat = (float)twat / n;
atur = (float)ttur / n;
}
Output
P1 | P2 | P3 | P4 | P5 | P2 | P5 | P2 |
0 10 20 23 30 40 50 52 61
- -
P1 10 10 0
P2 29 61 32
P3 3 23 20
P4 7 30 23
P5 12 52 40
Result :
Thus waiting time and turnaround time for processes based on Round robin scheduling was
computed and the average waiting time was determined.
Ex.no:5 Illustrate the Inter Process Communication (IPC)
Date: strategy
AIM:
To Write C programs to simulate Intra & Inter – Process Communication (IPC) techniques: Pipes,
Messages Queues, and Shared Memory.
DESCRIPTION:
Inter Process Communication (IPC) is a mechanism that involves communication of one process with
another process. This usually occurs only in one system.
Following are some important terms that we need to know before proceeding further on this topic.
Pipes − Communication between two related processes. The mechanism is half duplex meaning the
first process communicates with the second process. To achieve a full duplex i.e., for the second
process to communicate with the first process another pipe is required.
FIFO − Communication between two unrelated processes. FIFO is a full duplex, meaning the first
process can communicate with the second process and vice versa at the same time.
Message Queues − Communication between two or more processes with full duplex capacity. The
processes will communicate with each other by posting a message and retrieving it out of the queue.
Once retrieved, the message is no longer available in the queue.
Shared Memory − Communication between two or more processes is achieved through a shared
piece of memory among all processes. The shared memory needs to be protected from each other
by synchronizing access to all the processes.
Semaphores − Semaphores are meant for synchronizing access to multiple processes. When one
process wants to access the memory (for reading or writing), it needs to be locked (or protected)
and released when the access is removed. This needs to be repeated by all the processes to secure
data. Signals − Signal is a mechanism to communica on between mul ple processes by way of
signaling. This means a source process will send a signal (recognized by number) and the destination
process will handle it accordingly.
Note − Almost all the programs in this tutorial are based on system calls under Linux Operating
System (executed in Ubuntu).
A ) ECHOSERVER USING PIPE
SOURCE CODE:
/* Implementation of echoserver using Pipes */
#include <stdio.h>
#include<string.h>
#define msgsize 29
int main()
int ser[2],cli[2],pid;
char inbuff[msgsize];
system("clear");
pipe(ser);
pipe(cli);
pid=fork();
if(pid==0)
close(cli[0]);
close(ser[1]);
write(cli[1],msg,msgsize);
sleep(2);
read(ser[0],inbuff,msgsize);
printf("\n %s",inbuff); }
else
close(cli[1]);
close(ser[0]);
read(cli[0],inbuff,msgsize);
write(ser[1],inbuff,msgsize);
}}
OUTPUT:
$ vi echopipe.c
$ cc echopipe.c
$ ./a.out
i am in child process !
parent process
parent ended!
RESULT:
Thus the program was executed and verified successfully.
B) ECHO SERVER USING MESSAGES SOURCE CODE:
/* Implementation of echo server using messages */
#include <sys/ipc.h>
#include<stdio.h>
#include<string.h>
#include <sys/msg.h>
#include<stdlib.h>
struct
{
long mtype;
char mtext[20];
}
send,recv;
main()
int qid,pid,len;
qid=msgget((key_t)0X2000,IPC_CREAT|0666);
if(qid==-1)
exit(1);
len=strlen(send.mtext);
pid=fork();
if(pid>0)
if(msgsnd(qid,&send,len,0)==-1)
exit(1); }
printf("\n message has been posted");
sleep(2);
if(msgrcv(qid,&recv,100,2,0)==-1)
exit(1);
else
send.mtype=2;
strcpy(send.mtext,"\n hi i am child");
len=strlen(send.mtext);
if(msgrcv(qid,&recv,100,1,0)==-1)
exit(1); }
if(msgsnd(qid,&send,len,0)==-1)
{ perror("\n child message send failed"); }
}}
OUTPUT:
$ vi echomsg.c
$ cc echomsg.c
$ ./a.out
RESULT:
Thus the program was executed and verified successfully.
Ex.no:6
Date: Implementation of semaphores
Aim :
Semaphore
A semaphore is a counter used to synchronize access to a shared data amongst multiple processes.
To obtain a shared resource, the process should: o Test the semaphore that controls the resource. o
If value is positive, it gains access and decrements value of semaphore. o If value is zero, the process
goes to sleep and awakes when value is > 0.
Producer-Consumer problem
4. If choice = 1 then
5. If choice = 2 then
iii. If buffer is not empty then remove first item from the buffer
7. Stop
Program
/* Producer-Consumer problem using semaphore – pcsem.c */
#include<stdio.h>
#include<string.h>
#define size 5
struct process
{
char item[10];
p[10];
int wait(int s)
if(s==0) flag=1;
else s--;
return s;
int signal(int s)
s++;
return s;
main()
int c, i;
printf("\nProducer-Consumer Problem\n");
while(1)
scanf("%d", &c);
switch(c)
mutex = wait(mutex);
if(flag == 0)
scanf("%s", p[full].item);
full = signal(full);
else
printf("\nBuffer is FULL\n");
flag = 0;
mutex = signal(mutex);
break;
case 2:
full = wait(full);
mutex = wait(mutex);
if(flag == 0)
printf("Item %s is consumed\n",p[0].item);
for(i=0; i<size;i++)
else
mutex = signal(mutex);
empty = signal(empty);
break;
case 3:
if(full != 0)
for(i=0; i<full;i++)
printf("\n%s", p[i].item);
Else
break;
case 4:
exit(0);
break;
Output:
Producer-Consumer Problem
Result :
Thus synchronization between producer and consumer process for access to a shared memory
segment is implemented.
Exp. No:7 Implementation of deadlock detection algorithm
Date:
Aim :
To detect whether the given system is in a deadlocked state or not.
Deadlock Detection
Data structures used are Available, Allocation and Request Detection algorithm checks every
possible allocation sequence for all processes Resources allocated to deadlocked processes will be
idle until deadlock is broken Deadlocks occur only when process request cannot be granted
immediately. Deadlock eventually cripples system throughput and causes CPU utilization to drop
Algorithm:
1. See if any Processes Requests can be satisfied.
2. If so satisfy the needs and remove that Process and all the Resources it holds
Program:
/* Deadlock detection - deaddeduct.c */
#include <stdio.h>
main()
scanf("%d", &tp);
scanf("%d", &tr);
scanf("%d", &c[i][j]);
scanf("%d", &p[i][j]);
scanf("%d", &a[i]);
temp[i] = a[i];
sum = 0;
sum += p[i][j];
if(sum == 0)
m[k] = i;
k++;
if(i != m[l])
flag = 1;
flag = 0;
break;
if(flag == 1)
m[k] = i;
k++;
temp[j] += p[i][j];
found = 0;
for(i=1; i<k;i++)
found = 0;
for(i=1; i<k;i++)
if(j == m[i])
found = 1;
if(found == 0)
}
Output:
Enter No. of Processes :4
01001
00101
00001
10101
10110
11000
00010
00000
21121
00001
Result:
Thus given system is checked for deadlock and deadlocked processes are listed
out.
Exp. No: 8 Bankers Algorithm for deadlock avoidance
Date:
Aim :
To avoid deadlocks to a resource allocation system with multiple instances using bankers algorithm.
Banker’s Algorithm:
Data structures maintained are:
o Need—matrix contains remaining resource need of each process Safety algorithm is used to
determine whether system is in a safe state Resource request algorithm determines whether
requests can be safetly granted
Algorithm:
1. Read number of resources
9. Stop
Program :
/* Banker algorithm for deadlock avoidance - bankersalgo.c */
#include<stdio.h>
#include<conio.h>
main()
scanf("%d", &nor);
avail[i]=0;
printf("%c = ",(i+65));
scanf("%d", &ins[i]);
scanf("%d", &pno);
for(i=0; i<nor;i++)
printf("\t%c", (i+65));
printf("\n");
for(i=0; i<pno;i++)
{
scanf("%d", &allocated[i][j]);
avail[j] += allocated[i][j];
for(i=0; i<nor;i++)
printf("\t%c", (i+65));
printf("\n");
{
printf("P%d\t",i);
scanf("%d", &max[i][j]);
printf("\n");
for(i=0; i<nor;i++)
for(i=0; i<pno;i++)
Printf(“P%d\t”,i);
printf("%d\t", max[i][j]-allocated[i][j]);
printf("\n"); }
A:
d = -1;
for (i=0;i<pno;i++)
count = 0;
t = p[i];
if(count == nor)
output[k++] = p[i];
avail[j]+=allocated[t][j];
else
p[++d]=p[i];
}
if(d != -1)
pno = d + 1;
goto A;
printf("<");
printf(">");
Output
A = 10
B=5
C=7
A B C
P0 0 1 0
P1 2 0 0
P2 3 0 2
P3 2 1 1
P4 0 0 2
A B C
P0 7 5 3
P1 3 2 2
P2 9 0 2
P3 2 2 2
P4 4 3 3
A=3
B=3
C=2
Need matrix is :
A B C
P0 7 4 3
P1 1 2 2
P2 6 0 0
P3 0 1 1
P4 4 3 1
Result:
Thus deadlock is avoided for multiple instances of resources using ban
Ex.no:9 C Program to implement threading
Date:
AIM :
Write C programs to demonstrate various thread related concepts
PROGRAM :
Implementing a program using thread */
#include <pthread.h>
int je,jo,evensum=0,sumn=0,oddsum=0,evenarr[50],oddarr[50];
int i,n;
je=0;
n=(int)threadid;
for(i=1;i<=n;i++)
if(i%2==0)
evenarr[je]=i;
evensum=evensum+i;
je++; } } }
int i,n;
jo=0;
n=(int)threadid;
for(i=0;i<=n;i++)
if(i%2!=0)
{
oddarr[jo]=i;
oddsum=oddsum+i;
jo++;
}}
int i,n;
n=(int)threadid;
for(i=1;i<=n;i++)
sumn=sumn+i;
}}
int main()
pthread_t threads[NUM_THREADS];
int i,t;
printf("Enter a number\n");
scanf("%d",&t);
pthread_create(&threads[0],NULL,Even,(void *)t);
pthread_create(&threads[1],NULL,Odd,(void *)t);
pthread_create(&threads[2],NULL,SumN,(void *)t);
for(i=0;i<NUM_THREADS;i++)
pthread_join(threads[i],NULL);
for(i=0;i<je;i++)
printf("%d\n",evenarr[i]);
for(i=0;i<jo;i++)
printf("%d\n",oddarr[i]);
pthread_exit(NULL);
OUTPUT:
$ vi threadf.c
$ cc threadf.c -pthread
$ ./a.out
Enter a number 12
RESULT:
Thus the program was executed and verified successfully
Exp. No. 10 Implementation of paging technique of memory
Date: management
Aim:
To implement paging technique for memory management.
Paging
Paging permits physical address space of a process to be noncontiguous. It avoids external
fragmentation and the need for compaction.
Logical memory is broken into pages , where page size = frame size Address consist of two parts:
page number and page offset
Page number is used as an index into page table to obtain base address Base address is added with
offset to obtain physical memory address
Algorithm
1. Read physical memory size
9. Stop
Program
#include<stdio.h>
main()
scanf("%d", &ms);
nop = ms / ps;
scanf("%d",&np);
rempages = nop;
scanf("%d", &s[i]);
printf("\nMemory is Full");
break;
scanf("%d", &fno[i][j]);
else
pa = fno[x][y]* ps + offset;
}
}
Output:
Enter Physical memory size : 4096
Result:
Thus Paging technique of memory management has been executed successfuly
Exp. No. 11 Implementation of memory allocation methods
Date: for fixed partition
First fit
The first-fit, best-fit, or worst-fit strategy is used to select a free hole from the set of available
holes. Allocate the first hole that is big enough. Searching starts from the beginning of set of
holes.
Algorithm
1. Declare structures hole and process to hold information about set of holes and processes
respectively.
7. Print the list of process and their allocated holes or unallocated status.
9. Stop
Program
/* First fit allocation - ffit.c */
#include<stdio.h>
struct process
int size;
int flag;
int holeid;
p[10];
struct hole
int size;
int actual;
h[10];
main()
scanf("%d", &nh);
p[i].flag = 1;
p[i].holeid = j;
h[j].size -= p[i].size;
}}}}
printf("\n\tFirst fit\n");
printf("\nProcess\tPSize\tHole");
for(i=0; i<np;i++)
if(p[i].flag != 1)
else
printf("\n\nHole\tActual\tAvailable");
for(i=0; i<nh;i++)
printf("\n");
Output:
Enter the number of Holes : 5
First fit
Process PSize Hole
P0 212 H1
P1 417 H4
P2 112 H1
H0 100 100
H1 500 176
H2 200 200
H3 300 300
H4 600 183
Result:
Thus processes were allocated memory using first fit method.
b) Best Fit Allocation
Aim :
To allocate memory requirements for processes using best fit allocation.
Best fit
Allocate the smallest hole that is big enough. The list of free holes is kept sorted according to
size in ascending order. This strategy produces smallest leftover holes
Worst fit
Allocate the largest hole. The list of free holes is kept sorted according to size in descending
order. This strategy produces the largest leftover hole.
Algorithm :
1. Declare structures hole and process to hold information about set of holes and processes
respectively.
2. 8Get number of holes, say nh.
3. Get the size of each hole
4. Get number of processes, say np.
5. Get the memory requirements for each process.
6. Allocate processes to holes, by examining each hole as follows:
a. Sort the holes according to their sizes in ascending order
b. If hole size > process size then
i. Mark process as allocated to that hole.
ii. Decrement hole size by process size.
c. Otherwise check the next from the set of sorted hole
7. Print the list of process and their allocated holes or unallocated status.
8. Print the list of holes, their actual and current availability.
9. Stop
Program:
/* Best fit allocation - bfit.c */
#include<stdio.h>
struct process
{
int size;
int flag;
int holeid;
}
p[10];
struct hole
{
int hid;
int size;
int actual;
}
h[10];
main()
{
int i, np, nh, j;
void bsort(struct hole[], int);
printf("Enter the number of Holes : ");
scanf("%d", &nh);
for(i=0; i<nh;i++)
{
printf("Enter size for hole H%d : ",i);
scanf("%d", &= h[j].size);
h[i].actual=h[i].size;
h[i].hid = i;
}
printf("\nEnter number of process : " );
scanf("%d",&np);
for(i=0;i<np;i++)
{
bsort(h, nh);
for(j=0; j<nh;j++)
{
If(p[i].flag!=1)
{
If(p[i].size<= h[j].size)
{
p[i].flag = 1;
p[i].holeid = h[j].hid;
h[j].size -= p[i].size;
printf("\n\tBest fit\n");
printf("\nProcess\tPSize\tHole");
for(i=0; i bh[j].size)
temp = bh[i];
bh[i] = bh[j];
bh[j] = temp;
}
Output:
Enter the number of Holes : 5
Best fit
Process PSize Hole
P0 212 H3
P1 417 H1
P2 112 H2
P3 426 H4
H1 500 83
H3 300 88
H2 200 88
H0 100 100
H4 600 174
Result:
Thus processes were allocated memory using best fit method.
c) Worst Fit Allocation
Aim:
C Program To implement the Worst Fit Allocation.
Program:
#include<stdio.h>
#include< conio.h>
#define max
void main()
int frag[max],b[max],f[max],i,j,nb,nf,temp;
clrscr();
scanf("%d",&nb);
scanf("%d",&nf);
for(i=1;i<=nb;i++)
printf("Block %d:",i);
scanf("%d",&b[i]);
for(i=1;i<=nf;i++)
printf("File %d:",i);
scanf("%d",&f[i) ;
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
if(bf[j]!=1)
temp=b[j]- f[i];
if(temp>=0 )
ff[i]=j;
break;
}}}
frag[i]=temp;
bf[ff[i]]=1; }
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
INPUT
OUTPUT
File No File Size Block No Block Size Fragment
1 1 1 5 4
2 4 3 7 3
Result:
Program to implement the worst fit allocation has been executed successfully.
Exp. No. 12 Implementation of page replacement algorithms
Date:
a) FIFO Page Replacement
Aim:
To implement demand paging for a reference string using FIFO method.
FIFO
Page replacement is based on when the page was brought into memory. When a page should be
replaced, the oldest one is chosen. Generally, implemented using a FIFO queue. Simple to
implement, but not efficient. Results in more page faults. The page-fault may increase, even if frame
size is increased (Belady's anomaly)
Algorithm
1. Get length of the reference string, say l.
8. Print count.
9. Stop
Program
/* FIFO page replacement - fifopr.c */
#include<stdio.h>
main()
{
int i,j,l,rs[50],frame[10],nf,k,avail,count=0;
scanf("%d", &l);
scanf("%d", &rs[i]);
scanf("%d", &nf);
for(i=0; i<nf;i++)
frame[i] = -1; j = 0;
printf("\n%4d\t", rs[i]);
avail = 0;
for(k=0; k<nf;k++)
if(frame[k] == rs[i])
avail = 1;
if(avail == 0)
frame[j] = rs[i];
j = (j+1) % nf;
count++;
for(k=0; k<nf;k++)
Output :
Enter length of ref. string : 20
1 1 -1 -1 -1 -1
2 1 2 -1 -1 -1
3 1 2 3 -1 -1
4 1 2 3 4 -1
5 1 2 3 4 5
6 6 2 3 4 5
1 6 1 3 4 5
2 6 1 2 4 5
3 6 1 2 3 5
7 6 1 2 3 7
3
6
Result:
Thus page replacement was implemented using FIFO algorithm
b) LRU Page Replacement
Aim
To implement demand paging for a reference string using LRU method.
LRU
Pages used in the recent past are used as an approximation of future usage. The page that has not
been used for a longer period of time is replaced. LRU is efficient but not optimal. Implementation of
LRU requires hardware support, such as counters/stack.
Algorithm:
1. Get length of the reference string, say len.
4. Create access array to store counter that indicates a measure of recent usage.
5. Create a function arrmin that returns position of minimum of the given array.
10. For each page in reference string in the given order, examine:
ii. If there is an empty frame, Assign that frame to the page Store incremented freq for that page
position in access array. Increment count.
iii. If there is no free frame then Determine page to be replaced using arrmin function. Store
incremented freq for that page position in access array. Increment count.
12. Stop
Program
/* LRU page replacement - lrupr.c */
#include <stdio.h>
main()
{
int i,j,len,rs[50],frame[10],nf,k,avail,count=0;
scanf("%d", &len);
scanf("%d", &rs[i]);
scanf("%d", &nf);
frame[i] = -1;
j = 0;
printf("\n%4d\t", rs[i]);
avail = 0;
for(k=0; k<nf;k++)
if(frame[k] == rs[i])
avail = 1;
access[k] = ++freq;
break;
}}
if(avail == 0)
dm = 0; for(k=0; k<nf;k++)
if(frame[k] == -1)
dm = 1;
break;
if(dm == 1)
frame[k] = rs[i];
access[k] = ++freq;
count++;
else
j = arrmin(access, nf);
frame[j] = rs[i];
access[j] = ++freq;
count++; }
for(k=0; k<nf;k++)
printf("%4d", frame[k]);
}}
for(i=1; i<n;i++)
if(min>a[i])
min = a[i];
for(i=0; i<n;i++)
if min==a[i]
return I;}
Output
Length of Reference string : 20
2 1 2 -1 -1 -1
3 1 2 3 -1 -1
4 1 2 3 4 -1
5 1 2 3 4 5
6 1 2 6 4 5
3 1 2 6 3 5
7 1 2 6 3 7
3
6
Result
Thus page replacement was implemented using LRU algorithm.
C ) Implementation Of LFU Page Replacement Algorithm
AIM:
To write a c program to implement LFU page replacement algorithm
ALGORITHM :
1. Start the process
3. Get the number of pages to be inserted and enter the reference string
PROGRAM
#include<stdio.h>
main()
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf("Enter no of pages:");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;
k++;
for(i=1;i<n;i++)
{c1=0;
for(j=0;j<f;j++)
if(p[i]!=q[j])
c1++; }
if(c1==f)
c++;
if(k <f)
q[k]=p[i];
k++;
for(j=0;j<k;j++)
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"); } } }
Output:
Enter no of pages:10
Enter no of frames:3
7
7 5
7 5 9
4 5 9
4 3 9
4 3 7
9 3 7
9 6 7
9 6 2
1 6 2
*/
Result
Thus page replacement was implemented using LFU algorithm
Exp. No. 13 Implementation of various file organization techniques
Date:
a) Single-Level Directory
Aim :
To create directory structure as a single level directory structure.
Single-Level Directory
All files are contained in the same directory, Easy to implement Filenames must be unique within a
directory Difficult to remember all filenames Leads to anamoly in a multi-user system
Algorithm :
1. Read number of directories
4. Stop
Program:
/* Single Level Directory - singlev.c */
#include<stdio.h>
char file[20][20][20];
char dir[20][20];
int i,j;
main()
scanf("%d", &nod);
for(i=0; i<nod;i++)
scanf("%s", &dir[i]);
printf("No. of Files in the directory : ");
scanf("%d", &nof[i]);
for(j=0; j<nof[i];j++)
scanf("%s", &file[i][j]);}
printf("\nDirectory Filenames\n");
for(i=0; i<nod;i++)
{printf("%s\t", dir[i]);
for(j=0; j<nof[i];j++)
printf("\n"); } }
Output :
No. of Directories : 3
Directory Name : os
swing.java
Directory Filenames
pds2 inherit.cpp poly.cpp ovld.cpp
Result:
Thus single-level directory structure has been demonstrated
b) Two-Level Directory :
Aim:
To create directory structure as a two-level directory structure.
Two-Level Directory:
Each user has a user file directory (UFD) that lists folders and files of that user When a user refers to
a particular file, only his own UFD is searched. The two-level directory structure solves the
namecollision problem It isolates one user from another.
Algorithm :
1. Read number of users
4. Stop
Program:
/* Two-level directory */
#include<stdio.h>
#include<conio.h>
struct st
char uname[10];
char dname[10][10];
char fname[10][10][15];
int ds,sds[10];
dir[10];
int main()
int i,j,k,n;
for(i=0; i <n;i++)
scanf("%s", &dir[i].uname);
scanf("%d", &dir[i].ds);
for(j=0; j<dir[i].dss;j++)
scanf("%s", &dir[i].dname[j]);
scanf("%d", &dir[i].sds[j]);
printf("Enter filenames:\n");
for(k=0; k<dir[i].sds[j];k++)
scanf("%s", &dir[i].fname[j][k]);
}}
printf("\nUser\tFolders\tFiles\n\n");
for(i=0; i<n;i++)
printf("%s", dir[i].uname);
for(j=0; j<dir[i].ds;j++)
printf("\t%s\t", dir[i].dname[j]);
for(k=0; k<dir[i].sds[j];k++)
printf("\n");
printf("\n");
}}
Output:
No. of Users : 2
No. of folders : 2
No. of files : 2
No. of files : 2
No. of folders : 2
No. of files : 3
No. of files : 2
Result :
Thus two-level directory structure has been demonstrated
c) Hirearchical Directory Structure
Aim:
To demonstrate tree-like hierarchical directory structure graphically.
Tree-Structured Directories:
A tree is the most common directory structure. Extends two-level directory structure to a tree of
arbitrary height. It allows users to create their own subdirectories and organize their files. The tree
has a root directory, and every file in the system has a unique path name. A directory (or
subdirectory) contains a set of files or subdirectories. Current directory contains files that are
required for that process. Path names can be of two types: absolute and relative.
Algorithm :
1. Define tree structure
2. Initialize graphics
5. Stop
Program:
/* Hierarchical directory structure - treedir.c */
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
struct tree_element
char name[20];
main()
node *root;
root = NULL;
clrscr();
clrscr();
initgraph(&gd,&gm,"C:\\TurboC3\\BGI");
display(root);
getch();
closegraph();
int i, gap;
if(*root == NULL)
fflush(stdin);
gets((*root)->name);
scanf("%d", &(*root)->ftype);
(*root)->level = lev;
(*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
for(i=0;i<(*root)->nc; i++)
else
(*root)->nc = 0; } }
display(node *root)
int i;
settextstyle(2, 0, 4);
settextjustify(1, 1);
setfillstyle(1, BLUE);
setcolor(14);
if(root != NULL) {
if(root->ftype == 1)
else
display(root->link[i]); } }
Output:
Enter Name of dir/file(under root): ROOT
No of subdirectories/files(for ROOT): 2
No of subdirectories/files(for SUBDIR1): 2
No of subdirectories/files(for JAVA): 0
No of subdirectories/files(for VB): 0
No of subdirectories/files(for USER2): 2
No of subdirectories/files(for SUBDIR2): 2
No of subdirectories/files(for PPL): 2
No of subdirectories/files(for AI): 2
Aim:
To implement file allocation on free disk space in a contiguous manner.
File Allocation:
The three methods of allocating disk space are:
1. Contiguous allocation
2. Linked allocation
3. Indexed allocation
Contiguous
Each file occupies a set of contiguous block on the disk. The number of disk seeks required is
minimal. The directory contains address of starting block and number of contiguous block (length)
occupied. Supports both sequential and direct access. First / best fit is commonly used for selecting a
hole.
Algorithm:
1. Assume no. of blocks in the disk as 20 and all are free.
c. Check to see whether any block in the range (start, start + length1) is allocated. If so, then go to
step 2.
d. Allocate blocks to the file contiguously from start block to start + length – 1.
6. Stop
Program :
/* Contiguous Allocation - cntalloc.c */
#include<stdio.h>
#include<string.h>
int num=0, length[10], start[10];
void directory()
int i;
for(i=0; i 20)
continue;
for(i=st; i<num;i++)
void display()
int i;
for(i=0; i<20;i++)
printf("%4d",i);
printf("\n");
for(i=0; i<20;i++)
printf("%4s", a[i]);
main()
int i,n,k,temp,st,nb,ch,flag;
char id[4];
for(i=0; i<20;i++)
strcpy(a[i], "");
display();
do
scanf("%s", id);
scanf("%d", &st);
scanf("%d", &nb);
strcpy(fid[num], id);
length[num] = nb;
flag = 0;
if((st+nb) > 20)
continue;
for(i=st; i<st+nb);i++)
if(strcmp(a[i], "") != 0)
flag = 1;
if(flag == 1)
continue;
start[num] = st;
for(i=st; i<(st+nb);i++)
strcpy(a[i], id);;
printf("Allocation done\n");
num++;
scanf("%d", &ch);
}
while (ch == 1);
printf("\n\t\t\tContiguous Allocation\n");
printf("Directory:");
directory();
display();
printf("\n");
Output:
Disk space before allocation: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
cp 14 3
tr 10 3
mv 0 2
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
my mv ls ls ls ls tr tr tr cp cp cp
Result:
Thus contiguous allocation is done for files with the available free blocks
b) Linked Allocation:
Aim
To implement file allocation on free disk space as a linked list of disk blocks.
Linked
Each file is a linked list of disk blocks. The directory contains a pointer to first and last blocks of the
file. The first block contains a pointer to the second one, second to third and so on. File size need not
be known in advance, as in contiguous allocation. No external fragmentation. Supports sequential
access only.
Indexed
In indexed allocation, all pointers are put in a single block known as index block. The directory
contains address of the index block. The ith entry in the index block points to ith block of the file.
Indexed allocation supports direct access. It suffers from pointer overhead, i.e wastage of space in
storing pointers.
Algorithm
1. Define file table as a linked list structure
6. Stop
Program
/* Linked list file allocation */
#include<stdio.h>
struct filetable
{
char name[20];
int nob;
}
ft[30];
struct block
int bno;
};
main()
int i, j, n;
char str[20];
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\nEnter file name %d : ",i+1);
scanf("%s", ft[i].name);
scanf("%d", &ft[i].nob);
malloc(sizeof(struct block));
temp = ft[i].sb;
temp->next = NULL;
for(j=1; j<ft[i].nob;j++){
temp->next = (struct block*)malloc(sizeof(structblock));
temp = temp->next;
scanf("%d", &temp->bno); }
temp->next = NULL; }
for(i=0; i<n;i++)
if(strcmp(str, ft[i].name)==0)
break;
if(i == n)
else
temp = ft[i].sb;
for(j=0; j<ft[i].nob;j++)
temp = temp->next; }
printf("NULL"); } }
Output :
Enter no. of files: 3
Result:
Thus linked list allocation is done for files with the available free blocks.
c) Indexed Allocation
Aim:
To implement Indexed file allocation technique in C.
Algorithm:
1. Start
2. Declare the index block no. and total no.of files in a block
3. Get the index block no. and total no.of files in a block from the user.
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
PROGRAM:
#include<stdio.h>
#include<conio.h>
main()
{
int n,m[20],i,j,sb[20],s[20],b[20][20],x;
clrscr();
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d%d",&sb[i],&s[i]);
scanf("%d",&m[i]);
for(j=0;j<m[i];j++)
scanf("%d",&b[i][j]); }
printf("\nFile\t index\tlength\n");
for(i=0;i<n;i++)
printf("%d\t%d\t%d\n",i+1,sb[i],m[i]);
scanf("%d",&x);
printf("Index is:%d",sb[i]);
for(j=0;j<m[i];j++)
printf("%3d",b[i][j]);
getch(); }
OUTPUT:
Enter no. of files:2
Result :
Thus linked list allocation is done for files with the available free blocks.
Ex.no:15 Implementation Of Various Disk Scheduling Algorithm
Date:
A) FCFS
Aim :
Write C programs to simulate implementation FCFS Disk Scheduling Algorithm.
Algorithm:
1. Let Request array represents an array storing indexes of tracks that have been requested in
ascending order of their time of arrival. ‘head’ is the position of disk head.
2. Let us one by one take the tracks in default order and calculate the absolute distance of the track
from the head.
4. Currently serviced track position now becomes the new head position.
5. Go to step 2 until all tracks in request array have not been serviced.
Program:
#include<stdio.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff;
float avg;
scanf("%d",&max);
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&queue[i]);
printf("Enter the initial head position\n");
scanf("%d",&head);
queue[0]=head;
for(j=0;j<=n-1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
OUTPUT:
Enter the max range of disk:200
RESULT:
Thus the program was executed and verified successfully
B] SSTF
Aim :
Write C programs to simulate implementation SSTF Disk Scheduling Algorithm.
Algorithm :
1. Let Request array represents an array storing indexes of tracks that have been requested. ‘head’ is
the position of disk head.
2. Find the positive distance of all tracks in the request array from head.
3. Find a track from requested array which has not been accessed/serviced yet and has minimum
distance from head.
5. Currently serviced track position now becomes the new head position.
6. Go to step 2 until all tracks in request array have not been serviced.
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
int queue[100],t[100],head,seek=0,n,i,j,temp;
float avg;
// clrscr();
scanf("%d",&n);
for(i=0;it[j])
temp=t[i];
t[i]=t[j];
t[j]=temp;
temp=queue[i];
queue[i]=queue[j];
queue[j]=temp; } } }
for(i=1;i<n;i++)
scanf("%d",&queue[i]); }
scanf("%d",&head);
for(i=1;it[j])
{
temp=t[i];
t[i]=t[j];
t[j]=temp;
temp=queue[i] queue[i]=queue[j];
queue[j]=temp; } } }
for(i=1;i<n-1;i++)
{ seek=seek+abs(head-queue[i]);
head=queue[i]; }
avg=seek/(float)n;
return 0; }
OUTPUT:
*** SSTF Disk Scheduling Algorithm ***
RESULT:
Thus the program was executed and verified successfully.