Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

Programs:

1. a)Write a shell script that accepts a filename, starting and ending line numbers as arguments and
displays all the lines between the given line numbers.
b)Write a shell script that deletes all lines containing a specific word in one or more files supplied as
arguments to it.
c)Write a shell script that displays a list of all the files in the current directory to which the user has
read, write and execute permissions.

a. Write a Shell script that accepts a filename, starting and ending line numbers as
arguments and displays all the lines between the given line numbers?

THEORY:

Cat: cat command is used to create the file

Syntax: cat > file name for creation

Syntax: cat file name for displaying a file

Sed: sed means stream editor it can be used for editing the main program by using sed

echo "enter the filename"


read fname
echo "enter the starting line number"
read s
echo "enter the ending line number"
read n
sed -n $s,$n\p $fname | cat > newline
cat newline
OUTPUT:
b. Write a Shell script that deletes all lines containing a specified word in one or more files
supplied as arguments to it?

## for this program we have to create one or more files (optional),


## I am creating two files names are del ,delll. (we can create 2 files
using cat command also)
[root@localhost ~]# vi del
unix is os
dos is also os
here using unix
unix is powerful os
~
[root@localhost ~]# vi delll
windowsnt is also os
Unix is an os
android

## after creation two files now we have to write sed script file name is del.sed using vi editor.
[root@localhost ~]# vi del.sed
{
/os/d
}
OUTPUT:
C)Write a shell script that displays a list of all the files in the current directory to which the user has read,
write and execute permissions.

Code: create a file : vi program2.sh

# Shell script to display list of file names


# having read, Write and Execute permission

echo "The name of all files having all permissions :"

# loop through all files in current directory


for file in *
do

# check if it is a file
if [ -f $file ]
then

# check if it has all permissions


if [ -r $file -a -w $file -a -x $file ]
then

# print the complete file name with -l option


ls -l $file

# closing second if statement


fi

# closing first if statement


fi

done
output:
2 a)Write a shell script that receives any number of filenames as arguments and checks if every
argument supplied is a file or a directory, and reports accordingly. Whenever the argument is a file,
the number of lines on it is also reported.
b)Write a shell script that accepts a list of filenames as its argument, counts and reports the accuracy
of each word that is present in the first argument file on another argument file.
c)Write a shell script to list all of the directory files in a directory.

a)Write a shell script that receives any number of filenames as arguments and checks if every
argument supplied is a file or a directory, and reports accordingly. Whenever the argument is a file,
the number of lines on it is also reported.

ALGORITHM:
Step1:check files and directories in the current directory by ls command
Step2:create a shell script vi prg3.sh
step3: Check the no of arguments for shell script
if 0 arguments then print no arguments
for fname in $*
for every filename in given files
if it is a file if [ -f $fname ] then
print it is a regular file
count=`wc -l $fname`
wc is used to count no of lines words characters
-l is used only to print lines.
print count
else
print it is a directory file.

Code: vi 2apg.sh
if [ $# -eq 0 ]
then
echo NO ARGUMENTS
else
for fname in $*
do
if [ -f $fname ]
then
echo $fname IS A REGULAR FILE
count=`wc -l $fname`
echo NUMBER OF LINES IN $fname ARE :
echo $count
else
echo $fname IS A DIRECTORY FILE
fi
done
fi
Output:
b)Write a shell script that accepts a list of filenames as its argument, counts and reports the accuracy
of each word that is present in the first argument file on another argument file.

The tr command in UNIX is a command line utility for translating or deleting characters. It supports a
range of transformations including uppercase to lowercase, squeezing repeating characters, deleting
specific characters and basic find and replace. It can be used with UNIX pipes to support more complex
translation. tr stands for translate.

Syntax :
$ tr [OPTION] SET1 [SET2]

Code: pr2b.sh

if [ $# -ne 2 ]
then
echo "Error : Invalid number of arguments."
exit
fi
str=`cat $1 | tr '\n' ' '`
for a in $str
do
echo "Word = $a, Count = `grep -c "$a" $2`"
done
Output:
C) Write a shell script to list all of the directory files in a directory.
egrep is a pattern searching command which belongs to the family of grep functions. It works the
same way as grep -E does. It treats the pattern as an extended regular expression and prints out the
lines that match the pattern. If there are several files with the matching pattern, it also displays the
file names for each line.

Syntax:
egrep [ options ] 'PATTERN' files

Code: vi pg2c.sh
echo "enter directory name"
read dir
if[ -d $dir]
then
echo "list of files in the directory"
ls –l $dir|egrep ‘^d’
else
echo "enter proper directory name"
fi

Output:
3. a)Write a shell script to find the factorial of a given integer.
b)Write an awk script to count the number of lines in a file that do not contain vowels.
c)Write an awk script to find the number of characters, words and lines in a file.

a)Write a shell script to find the factorial of a given integer.

Using While loop: vi fact.sh


#shell script for factorial of a number
#factorial using while loop

echo "Enter a number"


read num

fact=1

while [ $num -gt 1 ] # gt = greater than (>)


do
fact=$((fact * num)) #fact = fact * num
num=$((num - 1)) #num = num - 1
done

echo $fact

(or)
Using For loop – vi fact1.sh
#shell script for factorial of a number
#factorial using for loop

echo "Enter a number"


read num

fact=1

for((i=2;i<=num;i++))
{
fact=$((fact * i)) #fact = fact * i
}

echo $fact
Output:
b)Write an awk script to count the number of lines in a file that do not contain vowels.
Awk is a scripting language used for manipulating data and generating reports.The awk command
programming language requires no compiling, and allows the user to use variables, numeric functions,
string functions, and logical operators.
Awk is a utility that enables a programmer to write tiny but effective programs in the form of statements
that define text patterns that are to be searched for in each line of a document and the action that is to be
taken when a match is found within a line. Awk is mostly used for pattern scanning and processing. It
searches one or more files to see if they contain lines that matches with the specified patterns and then
performs the associated actions.
Awk is abbreviated from the names of the developers – Aho, Weinberger, and Kernighan.
1. AWK Operations:
(a) Scans a file line by line
(b) Splits each input line into fields
(c) Compares input line/fields to pattern
(d) Performs action(s) on matched lines
2. Useful For:
(a) Transform data files
(b) Produce formatted reports
3. Programming Constructs:
(a) Format output lines
(b) Arithmetic and string operations
(c) Conditionals and loops

4. Syntax:

5. awk options 'selection _criteria {action }' input-file > output-file


Options:

-f program-file : Reads the AWK program source from the file


program-file, instead of from the
first command line argument.
Awk’s built-in variables include the field variables—$1, $2, $3, and so on ($0 is the entire line) — that
break a line of text into individual words or pieces called fields.
NR: NR command keeps a current count of the number of input records. Remember that records are
usually lines. Awk command performs the pattern/action statements once for each record in a file.
NF: NF command keeps a count of the number of fields within the current input record.
Code:
STEP1: Create a file called input

$cat >input4novowels
123
dgjlp
This is no vowel in awk
ctrl + d

STEP2: Create novowels.awk script file

$cat >novowels.awk
BEGIN{count=0}
!/[aeiou]/ {count++;print}
END{print "Number of lines="count}
Ctrl+d

STEP3: execute awk program

$awk –f novowels.awk input4novowels

Output:
c)Write an awk script to find the number of characters, words and lines in a file.
STEP1: Create a file called cwlinput
$cat >cwlinput
This is 1st line
2nd line
Last line
Ctrl + d

STEP2: Create awk script file

$cat >count4.awk
BEGIN{words=0;characters=0}
{
character+=length($0);
words+=NF;
}
END{print "lines=",NR," words=",words," Characters=",character}
Ctrl + d

STEP3: execute awk program


$awk -f count4.awk cwlinput

Output:
4. a) Write a C program that makes a copy of a file using standard I/O and system calls.
b) Implement in C the following LINUX commands using system calls
a. Cat (b) mv
c) Write a C program to list files in a directory.

a) Write a C program that makes a copy of a file using standard I/O and system calls.

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
void typefile (char *filename)
{
int fd, nread;
char buf[1024];
fd = open (filename, O_RDONLY);
if (fd == -1) {
perror (filename);
return;
}
while ((nread = read (fd, buf, sizeof (buf))) > 0)
write (1, buf, nread);
close (fd);
}
int
main (int argc, char **argv)
{
int argno;
for (argno = 1; argno < argc; argno )
typefile (argv[argno]);
exit (0);
}
b. Implement in C the following Unix commands using system calls
A) cat B)mv
A)cat
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[3] )
{
int fd,i;
char buf[2];
fd=open(argv[1],O_RDONLY,0777);
if(fd==-argc)
{
printf("file open error");
}
else
{
while((i=read(fd,buf,1))>0)
{
printf("%c",buf[0]);
}
close(fd);
}
}
B) mv
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[] )
{
int i,fd1,fd2;
char *file1,*file2,buf[2];
file1=argv[1];
file2=argv[2];
printf("file1=%s file2=%s",file1,file2);
fd1=open(file1,O_RDONLY,0777);
fd2=creat(file2,0777);
while(i=read(fd1,buf,1)>0)
write(fd2,buf,1);
remove(file1);
close(fd1);
close(fd2);
}
C) Write a C program to list files in a directory.
1. /*
2. * C Program to List Files in Directory
3. */
4. #include <dirent.h>
5. #include <stdio.h>
6.
7. int main(void)
8. {
9. DIR *d;
10. struct dirent *dir;
11. d = opendir(".");
12. if (d)
13. {
14. while ((dir = readdir(d)) != NULL)
15. {
16. printf("%s\n", dir->d_name);
17. }
18. closedir(d);
19. }
20. return(0);
21. }
5 (a) Write a C program to copy the contents of one file to another file using system calls.

Create biodata.txt file beside main.c, write some text in biodata.txt file, resume.txt will be automatically
created by program.

// copy the content from one file to another file


#include<stdio.h>
int main()
{
FILE *p1, *p2;
char ch;
p1 = fopen("biodata.txt", "r");
p2 = fopen("resume.txt", "w");
while((ch=getc(p1))!=EOF)
{
putc(ch,p2);
}
printf("File is copied");
fclose(p1);
fclose(p2);
return 0;
}
OUTPUT:
(b) Write C programs to simulate the following CPU scheduling algorithms:
i) FCFS ii) SJF

AIM: Write a C program to implement the various process scheduling mechanisms such as FCFS scheduling
algorithm.
DESCRIPTION: The process that arrives first is executed first.
ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Set the waiting of the first process as ‘0’ and its burst time as its turn around time
Step 5: for each process in the Ready Q calculate
(a) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-1)
(b) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)
Step 6: Calculate
(a) Average waiting time = Total waiting Time / Number of process
(b) Average Turnaround time = Total Turnaround Time / Number of process
Step 7: Stop the process

PROGRAM:/* FCFS */

#include<stdio.h>
void main()
{
int i,j,n,b[10],p[10],w[10],t[10];
float tw=0,tt=0,avgw,avgt;
printf("enter no.of process");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("enter process id:");
scanf("%d",&p[i]);
printf("enter burst time:");
scanf("%d",&b[i]);
}
b[0]=0,w[0]=0;
for(i=1;i<=n;i++)
{
w[i]=w[i-1]+b[i-1];
tw=tw+w[i];
t[i]=w[i]+b[i];
tt=tt+t[i];
}
avgw=tw/n;
avgt=tt/n;
printf("pid \t bt \t wt \t tat \n");
for(i=1;i<=n;i++)
{
printf("p[%d]\t %d\t %d\t %d\n",i,b[i],w[i],t[i]);
}
printf("average waiting time is %f\n average turn around time is %f",avgw,avgt);
}

OUTPUT SCREENS:

SJF:
AIM: To write a C program to implement the various process scheduling mechanisms such
as SJF Scheduling .
DESCRIPTION:The job which has shortest burst time is executed first.
ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Start the Ready Q according the shortest Burst time by sorting according to lowest to
highest burst time.
Step 5: Set the waiting time of the first process as ‘0’ and its turnaround time as its burst time.
Step 6: For each process in the ready queue, calculate
(c) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-1)
(d) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)
Step 6: Calculate
(c) Average waiting time = Total waiting Time / Number of process
(d) Average Turnaround time = Total Turnaround Time / Number of process
Step 7: Stop the process
PROGRAM:/* SJF */
#include<stdio.h>
int main()
{
int n,j,temp,temp1,temp2,pr[10],b[10],t[10],w[10],p[10],i;
float att=0,awt=0;
for(i=0;i<10;i++)
{
b[i]=0;w[i]=0;
}
printf("enter the number of process");
scanf("%d",&n);
printf("enter the burst times");
for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
p[i]=i;
}
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
if(b[i]>b[j])
{
temp=b[i];
temp1=p[i];
b[i]=b[j];
p[i]=p[j];
b[j]=temp;
p[j]=temp1;
}
}
}
w[0]=0;
for(i=0;i<n;i++)
w[i+1]=w[i]+b[i];
for(i=0;i<n;i++)
{
t[i]=w[i]+b[i];
awt=awt+w[i];
att=att+t[i];
}
awt=awt/n;
att=att/n;
printf("\n\t process \t waiting time \t turn around time \n");
for(i=0;i<n;i++)
printf("\t\t p[%d] \t\t %d \t\t %d \n",p[i],w[i],t[i]);
printf("the average waitingtimeis %f\n",awt);
printf("the average turn around time is %f\n",att);
return 1;
}
OUTPUT SCREENS:
6. a)Write C programs to simulate the following CPU scheduling algorithms:
i) Round Robin ii) Priority

AIM:To write a C program to implement the various process scheduling mechanisms such
as Round Robin Scheduling.
DESCRIPTION: The processes are executed in a round fashioned way with a fixed time slice.
ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue and time quantum (or) time slice
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Calculate the no. of time slices for each process where
No. of time slice for process(n) = burst time process(n)/time slice
Step 5: If the burst time is less than the time slice then the no. of time slices =1.
Step 6: Consider the ready queue is a circular Q, calculate
(a) Waiting time for process(n) = waiting time of process(n-1)+ burst time of process(n-1 ) + the time
difference in getting the CPU from process(n-1)
(b) Turn around time for process(n) = waiting time of process(n) + burst time of process(n)+ the time
difference in getting CPU from process(n).
Step 7: Calculate
(e) Average waiting time = Total waiting Time / Number of process
(f) Average Turnaround time = Total Turnaround Time / Number of process
Step 8: Stop the process

PROGRAM:/* ROUND ROBIN */


#include<stdio.h>
void main()
{
int st[10],bt[10],wt[10],tat[10],n,tq;
int i,count=0,swt=0,stat=0,temp,sq=0;
float awt=0.0,atat=0.0;
printf("Enter number of processes:");
scanf("%d",&n);
printf("Enter burst time for sequences:");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
st[i]=bt[i];
}
printf("Enter time quantum:");
scanf("%d",&tq);
while(1)
{
for(i=0,count=0;i<n;i++)
{
temp=tq;
if(st[i]==0)
{
count++;
continue;
}
if(st[i]>tq)
st[i]=st[i]-tq;
else
if(st[i]>=0)
{
temp=st[i];
st[i]=0;
}
sq=sq+temp;
tat[i]=sq;
}
if(n==count)
break;
}
for(i=0;i<n;i++)
{
wt[i]=tat[i]-bt[i];
swt=swt+wt[i];
stat=stat+tat[i];
}
awt=(float)swt/n;
atat=(float)stat/n;
printf("\tProcess_no \tBurst time\t Wait time \tTurn around time\n ");
for(i=0;i<n;i++)
printf("\t%d\t\t %d\t\t %d\t\t %d\n ",i+1,bt[i],wt[i],tat[i]);
printf("Avg wait time is %f Avg turn around time is %f",awt,atat);
}
OUTPUT SCREENS:
AIM: To write a C program to implement the various process scheduling mechanisms such as Priority Scheduling.
DESCRIPTION: The process which ha highest priority(lowest number or vice versa) is executed first.
ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Sort the ready queue according to the priority number.
Step 5: Set the waiting of the first process as ‘0’ and its burst time as its turn around time
Step 6: For each process in the Ready Q calculate
(e) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-1)
(f) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)
Step 7: Calculate
(g) Average waiting time = Total waiting Time / Number of process
(h) Average Turnaround time = Total Turnaround Time / Number of process
Step 8: Stop the process
PROGRAM: /* priority */
#include<stdio.h>
void main()
{
int i,j,n,b[10],p[10],w[10],t[10],pr[10];
float tw=0,tt=0,avgw,avgt,temp1,temp2,temp3;
printf("enter no.of process");
scanf("%d",&n);
for(i=1;i<=n;i++){
printf("enter process id:");
scanf("%d",&p[i]);
printf("enter burst time:");
scanf("%d",&b[i]);
printf(" enter priority:");
scanf("%d",&pr[i]);
}
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(pr[i]>=pr[j])
{
temp1=b[i];
b[i]=b[j];
b[j]=temp1;
temp2=p[i];
p[i]=p[j];
p[j]=temp2;
temp3=pr[i];
pr[i]=pr[j];
pr[j]=temp3;
}
}
}
b[0]=0,w[0]=0;
for(i=1;i<=n;i++){
w[i]=w[i-1]+b[i-1];
tw=tw+w[i];
t[i]=w[i]+b[i];
tt=tt+t[i];
}
avgw=tw/n;
avgt=tt/n;
printf("pid \t bt \t wt \t pr \t tat \n");
for(i=1;i<=n;i++){
printf("p[%d]\t %d\t %d\t %d\t %d\n",p[i],b[i],w[i],pr[i],t[i]);
}
printf("average waiting time is %f\n average turn around time is %f",avgw,avgt);}
OUTPUT SCREENS:

b) Write a C program to implement the ls| sort command (Use unnamed Pipe)

Source Code:
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int fd[2],pid,k;
k=pipe(fd);
if(k==-1)
{
perror("pipe");
exit(1);
}
pid=fork();
if(pid==0)
{
close(fd[0]);
dup2(fd[1],1);
close(fd[1]);
execlp(argv[1],argv[1],NULL);
perror("execl");
}
else
{
wait(2);
close(fd[1]);
dup2(fd[0],0);
close(fd[0]);
execlp(argv[2],argv[2],NULL);
perror("execl");
}
}

Output:
7. a)Write C program to implement ipc between two unrelated processes using named pipe.
b)Write a C program to solve the Dining- Philosopher problem using semaphores.

a) Write C program to implement ipc between two unrelated processes using named pipe.

#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
Int main()
{
int file1,file2;
int fd;
char str[256];
char temp[4]="how";
char temp1[4];
file1 = mkfifo("fifo_server",0666);
if(file1<0) {
printf("Unable to create a fifo");
exit(-1);
}

file2 = mkfifo("fifo_client",0666);

if(file1<0) {
printf("Unable to create a fifo");
exit(-1);
}
printf("fifos server and child created successfuly");
}

Compile fifo.c
Cc fifo.c –o fifo
./fifo
Next check out ls –l

Server.c
#include<stdio.h>
#include<fcntl.h>
main()
{
FILE *file1;
int fifo_server,fifo_client;
int choice;
char *buf;
fifo_server = open("fifo_server",O_RDWR);
if(fifo_server<1) {
printf("Error opening file");
}
read(fifo_server,&choice,sizeof(int));
sleep(10);
fifo_client = open("fifo_client",O_RDWR);

if(fifo_server<1) {
printf("Error opening file");
}
switch(choice) {

case 1:
buf="Linux";
write(fifo_client,buf,10*sizeof(char));
printf("\n Data sent to client \n");
break;
case 2:

buf="ubuntu";
write(fifo_client,buf,10*sizeof(char));
printf("\nData sent to client\n");
break;
case 3:
buf="2.6.32";
write(fifo_client,buf,10*sizeof(char));
printf("\nData sent to client\n");
}

close(fifo_server);
close(fifo_client);
}

Compile server.c
Cc server.c –o server
./server

Open another terminal and run client program


client.c
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
main()
{
FILE *file1;
int fifo_server,fifo_client;
char str[256];
char *buf;
int choice=1;
printf("Choose the request to be sent to server from options below");
printf("\n\t\t Enter 1 for O.S.Name \n \
Enter 2 for Distribution \n \
Enter 3 for Kernel version \n");
scanf("%d",&choice);

fifo_server=open("fifo_server",O_RDWR);
if(fifo_server < 0) {
printf("Error in opening file");
exit(-1);
}

write(fifo_server,&choice,sizeof(int));

fifo_client=open("fifo_client",O_RDWR);

if(fifo_client < 0) {
printf("Error in opening file");
exit(-1);
}

buf=malloc(10*sizeof(char));
read (fifo_client,buf,10*sizeof(char));
printf("\n ***Reply from server is %s***\n",buf);
close(fifo_server);
close(fifo_client);
}

Compile client.c
Cc client.c –o client
./client
Output:

b)Write a C program to solve the Dining- Philosopher problem using semaphores.

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

sem_t room;
sem_t chopstick[5];

void * philosopher(void *);


void eat(int);
int main()
{
int i,a[5];
pthread_t tid[5];
sem_init(&room,0,4);

for(i=0;i<5;i++)
sem_init(&chopstick[i],0,1);

for(i=0;i<5;i++){
a[i]=i;
pthread_create(&tid[i],NULL,philosopher,(void *)&a[i]);
}
for(i=0;i<5;i++)
pthread_join(tid[i],NULL);
}

void * philosopher(void * num)


{
int phil=*(int *)num;

sem_wait(&room);
printf("\nPhilosopher %d has entered room",phil);
sem_wait(&chopstick[phil]);
sem_wait(&chopstick[(phil+1)%5]);

eat(phil);
sleep(2);
printf("\nPhilosopher %d has finished eating",phil);

sem_post(&chopstick[(phil+1)%5]);
sem_post(&chopstick[phil]);
sem_post(&room);
}

void eat(int phil)


{
printf("\nPhilosopher %d is eating",phil);
}
Output:
8. Write C programs to simulate the following techniques of memory management:
a) Paging b) Segmentation

Aim: To implement the Memory management policy- Paging.


Description of the Program:
Paging is an efficient memory management scheme because it is non-contiguous memory allocation
method. The basic idea of paging is the physical memory (main memory) is divided into fixed sized blocks
called frames, the logical address space is divided into fixed sized blocks, called pages, but page size and
frame size should be equal. The size of the frame or a page is depending on operating system.
In this scheme the operating system maintains a data structure that is page table, it is used for
mapping purpose. The page table specifies the some useful information; it tells which frames are there and
so on. The page table consisting of two fields, one is the page number and other one is frame number. Every
address generated by the CPU divided into two parts, one is page number and second is page offset or
displacement. The pages are loaded into available free frames in the physical memory.
Algorithm for Paging:
Step 1: Read all the necessary input from the keyboard.
Step 2: Pages - Logical memory is broken into fixed - sized blocks.
Step 3: Frames – Physical memory is broken into fixed – sized blocks.
Step 4: Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
Step 5: Display the physical address.
Step 6: Stop the process.
Code:
#include <stdio.h>
#include <conio.h>
struct pstruct
{
int fno;
int pbit;
}ptable[10];

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

void info()
{
printf("\n\nMEMORY MANAGEMENT USING PAGING\n\n");
printf("\n\nEnter the Size of Physical memory: ");
scanf("%d",&pmsize);
printf("\n\nEnter the size of Logical memory: ");
scanf("%d",&lmsize);
printf("\n\nEnter the partition size: ");
scanf("%d",&psize);
frame = (int) pmsize/psize;
page = (int) lmsize/psize;
printf("\nThe physical memory is divided into %d no.of frames\n",frame);
printf("\nThe Logical memory is divided into %d no.of pages",page);
}

void assign()
{
int i;
for (i=0;i<page;i++)
{
ptable[i].fno = -1;
ptable[i].pbit= -1;
}
for(i=0; i<frame;i++)
ftable[i] = 32555;
for (i=0;i<page;i++)
{
printf("\n\nEnter the Frame number where page %d must be placed: ",i);
scanf("%d",&frameno);
ftable[frameno] = i;
if(ptable[i].pbit == -1)
{
ptable[i].fno = frameno;
ptable[i].pbit = 1;
}
}

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

// clrscr();
printf("\n\n\n\tProcess to create the Physical Address\n\n");
printf("\nEnter the Base Address: ");
scanf("%d",&baddr);
printf("\nEnter theLogical Address: ");
scanf("%d",&laddr);

paddr = laddr / psize;


disp = laddr % psize;
if(ptable[paddr].pbit == 1 )
phyaddr = baddr + (ptable[paddr].fno*psize) + disp;
printf("\nThe Physical Address where the instruction present: %d",phyaddr);
}
void main()
{
info();
assign();
cphyaddr();
}
Output:
b) Aim: To implement the memory management policy-segmentation.
Description of the program:
Memory segmentation is the division of computer's primary memory into segments or sections. In a
computer system using segmentation, a reference to a memory location includes a value that identifies a
segment and an offset within that segment. Segments or sections are also used in object files of
compiled programs when they are linked together into a program image and when the image is loaded
into memory.
Algorithm:
Step 1: Start the program.
Step 2: Get the number of segments.
Step 3: get the base address and length for each segment.
Step 4: Get the logical address.
Step 5: check whether the segment number is within the limit, if not display the error
message.
Step 6: Check whether the byte reference is within the limit, if not display the error
message.
Step 7: Calculate the physical memory and display it.
Step 8: Stop the program.

Source program:

#include<stdio.h>
#include<conio.h>
struct list
{
int seg;
int base;
int limit;
struct list *next;
} *p;
void insert(struct list *q,int base,int limit,int seg)
{
if(p==NULL)
{
p=malloc(sizeof(Struct list));
p->limit=limit;
p->base=base;
p->seg=seg;
p->next=NULL;
}
else
{
while(q->next!=NULL)
{
Q=q->next;
Printf(“yes”)
}
q->next=malloc(sizeof(Struct list));
q->next ->limit=limit;
q->next ->base=base;
q->next ->seg=seg;
q->next ->next=NULL;
}
}
int find(struct list *q,int seg)
{
while(q->seg!=seg)
{
q=q->next;
}
return q->limit;
}
int search(struct list *q,int seg)
{
while(q->seg!=seg)
{
q=q->next;
}
return q->base;
}
main()
{
p=NULL;
int seg,offset,limit,base,c,s,physical;
printf(“Enter segment table/n”);
printf(“Enter -1 as segment value for termination\n”);
do
{
printf(“Enter segment number”);
scanf(“%d”,&seg);
if(seg!=-1)
{
printf(“Enter base value:”);
scanf(“%d”,&base);
printf(“Enter value for limit:”);
scanf(“%d”,&limit);
insert(p,base,lmit,seg);
}
}
while(seg!=-1)
printf(“Enter offset:”);
scanf(“%d”,&offset);
printf(“Enter bsegmentation number:”);
scanf(“%d”,&seg);
c=find(p,seg);
s=search(p,seg);
if(offset<c)
{
physical=s+offset;
printf(“Address in physical memory %d\n”,physical);
}
else
{
printf(“error”);
}
}
OUTPUT:
[examuser56@localhost ~]$ cc seg.c
[examuser56@localhost ~]$ ./a.out

Enter segment table


Enter -1 as segmentation value for termination
Enter segment number:1
Enter base value:2000
Enter value for limit:100
Enter segment number:2
Enter base value:2500
Enter value for limit:100
Enter segmentation number:-1
Enter offset:90
Enter segment number:2
Address in physical memory 2590

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

Enter segment table


Enter -1 as segmentation value for termination
Enter segment number:1
Enter base value:2000
Enter value for limit:100
Enter segment number:2
Enter base value:2500
Enter value for limit:100
Enter segmentation number:-1
Enter offset:90
Enter segment number:1
Address in physical memory 2090
9. Write C programs to simulate the following page replacement algorithms:

a) FIFO b)LRU c)LFU (optimal)

a) FIFO PAGE REPLACEMENT ALGORITHM

AIM: To implement page replacement algorithms


FIFO (First In First Out)

ALGORITHM:

FIFO:
Step 1: Create a queue to hold all pages in memory
Step 2: When the page is required replace the page at the head of the queue
Step 3: Now the new page is inserted at the tail of the queue

/* FIFO Page Replacement Algorithm */

#include<stdio.h>
#include<conio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
void main()
{
printf("\n \t\t\t FIFO PAGE REPLACEMENT ALGORITHM");
printf("\n Enter no.of frames....");
scanf("%d",&nof);
printf("Enter number of reference string..\n");
scanf("%d",&nor);
printf("\n Enter the reference string..");
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
printf("\nThe given reference string:");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=1;i<=nof;i++)
frm[i]=-1;
printf("\n");
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\t Reference np%d->\t",ref[i]);
for(j=0;j<nof;j++)
{
if(frm[j]==ref[i])
{
flag=1;
break;
}}
if(flag==0)
{
pf++;
victim++;
victim=victim%nof;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
}
}
printf("\n\n\t\t No.of pages faults...%d",pf);
getch();
}

OUTPUT:

FIFO PAGE REPLACEMENT ALGORITHM

Enter no.of frames....4


Enter number of reference string..
6

Enter the reference string..


564123

The given reference string:


...................................... 5 6 4 1 2 3

Reference np5-> 5 -1 -1 -1
Reference np6-> 5 6 -1 -1
Reference np4-> 5 6 4 -1
Reference np1-> 5 6 4 1
Reference np2-> 2 6 4 1
Reference np3-> 2 3 4 1

No.of pages faults...6


(b) LRU PAGE REPLACEMENT ALGORITHM

AIM: To implement page replacement algorithm


LRU (Least Recently Used)

LRU (Lease Recently Used)


Here we select the page that has not been used for the longest period of time.

ALGORITHM:

Step 1: Create a queue to hold all pages in memory


Step 2: When the page is required replace the page at the head of the queue
Step 3: Now the new page is inserted at the tail of the queue
Step 4: Create a stack
Step 5: When the page fault occurs replace page present at the bottom of the stack

/* LRU Page Replacement Algorithm */

#include<stdio.h>
#include<conio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
int recent[10],lrucal[50],count=0;
int lruvictim();

void main()
{
printf("\n\t\t\t LRU PAGE REPLACEMENT ALGORITHM");
printf("\n Enter no.of Frames....");
scanf("%d",&nof);

printf(" Enter no.of reference string..");


scanf("%d",&nor);

printf("\n Enter reference string..");


for(i=0;i<nor;i++)
scanf("%d",&ref[i]);

printf("\n\n\t\t LRU PAGE REPLACEMENT ALGORITHM ");


printf("\n\t The given reference string:");
printf("\n………………………………..");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=1;i<=nof;i++)
{
frm[i]=-1;
lrucal[i]=0;
}

for(i=0;i<10;i++)
recent[i]=0;
printf("\n");
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\t Reference NO %d->\t",ref[i]);
for(j=0;j<nof;j++)
{

if(frm[j]==ref[i])
{
flag=1;
break;
}
}

if(flag==0)
{
count++;
if(count<=nof)
victim++;
else
victim=lruvictim();
pf++;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
}
recent[ref[i]]=i;
}
printf("\n\n\t No.of page faults...%d",pf);
getch();
}
int lruvictim()
{
int i,j,temp1,temp2;
for(i=0;i<nof;i++)
{
temp1=frm[i];
lrucal[i]=recent[temp1];
}
temp2=lrucal[0];
for(j=1;j<nof;j++)
{
if(temp2>lrucal[j])
temp2=lrucal[j];
}
for(i=0;i<nof;i++)
if(ref[temp2]==frm[i])
return i;
return 0;
}
OUTPUT:

LRU PAGE REPLACEMENT ALGORITHM

Enter no.of Frames....3


Enter no.of reference string..6

Enter reference string..


654231

LRU PAGE REPLACEMENT ALGORITHM


The given reference string:
…………………. 6 5 4 2 3 1

Reference NO 6-> 6 -1 -1
Reference NO 5-> 6 5 -1
Reference NO 4-> 6 5 4
Reference NO 2-> 2 5 4
Reference NO 3-> 2 3 4
Reference NO 1-> 2 3 1

No.of page faults...6


(c) OPTIMAL(LFU) PAGE REPLACEMENT ALGORITHM

AIM: To implement page replacement algorithms


Optimal (The page which is not used for longest time)

ALGORITHM:

Optimal algorithm
Here we select the page that will not be used for the longest period of time.

OPTIMAL:
Step 1: Create a array
Step 2: When the page fault occurs replace page that will not be used for the longest
period of time

/*OPTIMAL(LFU) page replacement algorithm*/

#include<stdio.h>
#include<conio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
int recent[10],optcal[50],count=0;
int optvictim();
void main()
{
printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHN");
printf("\n.................................");
printf("\nEnter the no.of frames");
scanf("%d",&nof);
printf("Enter the no.of reference string");
scanf("%d",&nor);
printf("Enter the reference string");
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHM");
printf("\n................................");
printf("\nThe given string");
printf("\n....................\n");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=0;i<nof;i++)
{
frm[i]=-1;
optcal[i]=0;
}
for(i=0;i<10;i++)
recent[i]=0;
printf("\n");
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\tref no %d ->\t",ref[i]);
for(j=0;j<nof;j++)
{
if(frm[j]==ref[i])
{
flag=1;
break;
}
}
if(flag==0)
{
count++;
if(count<=nof)
victim++;
else
victim=optvictim(i);
pf++;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
}
}
printf("\n Number of page faults: %d",pf);
getch();
}
int optvictim(int index)
{
int i,j,temp,notfound;
for(i=0;i<nof;i++)
{
notfound=1;
for(j=index;j<nor;j++)
if(frm[i]==ref[j])
{
notfound=0;
optcal[i]=j;
break;
}
if(notfound==1)
return i;
}
temp=optcal[0];
for(i=1;i<nof;i++)
if(temp<optcal[i])
temp=optcal[i];
for(i=0;i<nof;i++)
if(frm[temp]==frm[i])
return i;
return 0;
}
OUTPUT:

OPTIMAL PAGE REPLACEMENT ALGORITHM

Enter no.of Frames....3


Enter no.of reference string..6

Enter reference string..


654231

OPTIMAL PAGE REPLACEMENT ALGORITHM


The given reference string:
…………………. 6 5 4 2 3 1

Reference NO 6-> 6 -1 -1
Reference NO 5-> 6 5 -1
Reference NO 4-> 6 5 4
Reference NO 2-> 2 5 4
Reference NO 3-> 2 3 4
Reference NO 1-> 2 3 1

No.of page faults...6


10. Simulate all file allocation strategies
a) Sequential b) Indexed c) Linked
4.a) Sequential/Contiguous file allocation strategy:
Description of the Program:
In this type of strategy, the files are allocated in a sequential manner such that there is a continuity
among the various parts or fragments of the file. The contiguous allocation method requires each file to
occupy a set of contiguous address on the disk. Disk addresses define a linear ordering on the disk. Notice
that, with this ordering, accessing block b+1 after block b normally requires no head movement. When head
movement is needed (from the last sector of one cylinder to the first sector of the next cylinder), it is only
one track. Thus, the number of disk seeks required for accessing contiguous allocated files in minimal, as is
seek time when a seek is finally needed. Contiguous allocation of a file is defined by the disk address and
the length of the first block. If the file is n blocks long, and starts at location b, then it occupies blocks b,
b+1, b+2, …, b+n-1. The directory entry for each file indicates the address of the starting block and the
length of the area allocated for this file.
Algorithm For Sequential/Contiguous:
Step 1: Start the program.
Step 2: Check number of available free blocks in memory.
Step 3: Get the name of the file, Starting block & length.
Step 3: Get the number of processes and values of block size for each process.
Step 4: Analyses all the three memory Placement techniques and display the best algorithm
which utilizes the memory resources effectively and efficiently.
Step 5: If the blocks are free then it will allocate the files contiguously otherwise files are not
being allocated.
Step 6: Finally, retrieve FAT to know allocated and free blocks
Step 7: Stop the program.
Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int m[48], b[10][2], n,i,j,ch,k;
int f[10];
clrscr();
printf("enter the number of blocks available: \n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
m[i]=0;
}
i=0;
do
{
printf("enter name of file:\n");
scanf("%d", &f[i]);
printf("enter starting block and length: \n");
scanf("%d%d",&b[i][0], &b[i][1]);
for(j=b[i][0];j<(b[i][0]+b[i][1]);j++)
{
if(m[j]==0)
{
printf(".....allocating.....\n");
m[j]=f[i];
}
else
{
printf("allocation is not possible\n");
k=j;
for(j=b[i][0];j<=k;j++)
m[j]=0;
i--;
break;
}
}
printf("Is ther any another file to be allocated(1/0):\n");
scanf("%d", &ch);
i++;
}
while(ch==1);
printf("\t file allocation table\n");
printf("file name starting block length\n");
for(j=0;j<i;j++)
{
printf("%d\t%d\t%d\t",f[j],b[j][0],b[j][1]);
printf("\n");
}
getch();
}

Output:
b)Linked File Allocation strategy:
AIM: To write a Program to implement Linked file allocation strategy
Description of the Program:
In this type of strategy, the files are allocated in a linked list format where each and
every fragment is linked to the other file through either addresses or pointers. Thus, the starting location of
the file serves for the purpose of extraction of the entire file because every fragment is linked to each other.

In linked allocation, each file is a linked list of disk blocks. The directory contains a pointer to the
first and (optionally the last) block of the file. For example, a file of 5 blocks which starts at block 4, might
continue at block 7, then block 16, block 10, and finally block 27. Each block contains a pointer to the next
block and the last block contains a NIL pointer. The value -1 may be used for NIL to differentiate it from
block 0.

Algorithm for Linked File Allocation Strategy:


Step 1: Start the program.
Step 2: Get the name of the file, Starting block & length.
Step 3:The directory contains a pointer to the first and last block of the file.
Step 4: Analyses all the three memory Placement techniques and display the best algorithm
which utilizes the memory resources effectively and efficiently.
Step 5: A write to a file removes the first free block and writes to that block.
Step 6: If the blocks are free then it will allocate the files in a linked manner otherwise files
are not being allocated.
Step 7: Finally, retrieve File Allocation Table to know allocated and free blocks
Step 8: Stop the program.
Source Code:
#include<stdio.h>
#include<conio.h>
struct file
{
char fname[10];
int start,size,block[10];
}f[10];
main()
{
int i,j,n;
clrscr();
printf("Enter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter file name:");
scanf("%s",&f[i].fname);
printf("Enter starting block:");
scanf("%d",&f[i].start);
f[i].block[0]=f[i].start;
printf("Enter no.of blocks:");
scanf("%d",&f[i].size);
printf("Enter block numbers:");
for(j=1;j<=f[i].size;j++)
{
scanf("%d",&f[i].block[j]);
}
}
printf("File\tstart\tsize\tblock\n");
for(i=0;i<n;i++)
{
printf("%s\t%d\t%d\t",f[i].fname,f[i].start,f[i].size);
for(j=1;j<=f[i].size-1;j++)
printf("%d--->",f[i].block[j]);
printf("%d",f[i].block[j]);
printf("\n");
}
getch();
}

Ouput:

c) Indexed file allocation


AIM: To write a Program to implement Indexed file allocation strategy
Description of the Program:
In this type of strategy, the files are allocated based on the indexes that are created for each fragment
of the file such that each and every similar indexed file is maintained by the primary index thereby
providing flow to the file fragments.
The indexed allocation method is the solution to the problem of both contiguous and linked
allocation. This is done by bringing all the pointers together into one location called the index block. Of
course, the index block will occupy some space and thus could be considered as an overhead of the method.
In indexed allocation, each file has its own index block, which is an array of disk sector of
addresses. The ith entry in the index block points to the ith sector of the file. The directory contains the
address of the index block of a file. To read the ith sector of the file, the pointer in the ith index block entry
is read to find the desired sector.
Algorithm for Indexed file Allocation Strategy:
Step 1: Start the program.
Step 2: Bring all the pointers together into one location called the index block, which is an
array of disk sector of addresses.
Step 3: Get the index block and number of files on index block.
Step 4:The directory contains a pointer to the first and last block of the file.
Step 5: Analyses all the three memory Placement techniques and display the best algorithm
which utilizes the memory resources effectively and efficiently.
Step 6: If the blocks are free then it will allocate the files based on the index block otherwise
files are not being allocated.
Step 7: The directory contains the address of the index block of a file.
Step 8: Finally, To read the ith sector of the file, the pointer in the ith index block entry is
read to find the desired sector.
Step 9: Stop the program.

Source Code:
#include<stdio.h>
int f[50],i,k,j,inde[50],n,c,count=0,p;
main()
{
clrscr();
for(i=0;i<50;i++)
f[i]=0;
x:
printf("enter index block\t");
scanf("%d",&p);
if(f[p]==0)
{
f[p]=1;
printf("enter no of files on index\t");
scanf("%d",&n);
}
else
{
printf("Block already allocated\n");
goto x;
}
for(i=0;i<n;i++)
scanf("%d",&inde[i]);
for(i=0;i<n;i++)
if(f[inde[i]]==1)
{
printf("Block already allocated");
goto x;
}
for(j=0;j<n;j++)
f[inde[j]]=1;
printf("\n allocated");
printf("\n file indexed");
for(k=0;k<n;k++)
printf("\n %d->%d:%d",p,inde[k],f[inde[k]]);
printf(" Enter 1 to enter more files and 0 to exit\t");
scanf("%d",&c);
if(c==1)
goto x;
else
exit();
getch();
}
Output:
11. Simulate file organization techniques
a) Single Level Directory
b) Two Level Directory
c) Hierarchical

Description:
The directory contains information about the files, including attributes, location and
ownership.Sometimes the directories consisting of subdirectories also. The directory is itself a file, owned
by the o.s and accessible by various file management routines.

a)Single Level Directories: It is the simplest of all directory structures, in this the directory system having
only one directory, it consisting of the all files. Sometimes it is said to be root directory. It has the
simplicity and ability to locate files quickly. it is not used in the multi-user system, it is used on small
embedded system.

b) Two Level Directory: The problem in single level directory is different users may be accidentally using
the same names for their files. To avoid this problem, each user need a private directory. In this way names
chosen by one user don’t interface with names chosen by a different user.

c) Hierarchical Directory: The two level directories eliminate name conflicts among users but it is not
satisfactory for users but it is not satisfactory for users with a large no of files. To avoid this, create the
subdirectory and load the same type of the files into the subdirectory. So, in this method each can have as
many directories are needed.This directory structure looks like tree, that’s why it is also said to be tree-level
directory structure.

(a) Single Level Directory Structure


Aim: To write a program to implement Single Level Directory Structure.
Description of the program:
In a single-level directory system, all the files are placed in one directory. This is very common on
single-user OS's.
A single-level directory has significant limitations, however, when the number of files increases or
when there is more than one user. Since all files are in the same directory, they must have unique names. If
there are two users who call their data file "test", then the unique-name rule is violated. Although file names
are generally selected to reflect the content of the file, they are often quite limited in length.

Source Code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm,count,i,j,mid,cir_x;
char fname[10][20];
clrscr();
initgraph(&gd,&gm,"c:\\tc\\bgi");
cleardevice();
setbkcolor(GREEN);
puts("Enter no of files do u have?");
scanf("%d",&count);
for(i=0;i<count;i++)
{
cleardevice();
setbkcolor(GREEN);
printf("Enter file %d name",i+1);
scanf("%s",fname[i]);
setfillstyle(1,MAGENTA);
mid=640/count;
cir_x=mid/3;
bar3d(270,100,370,150,0,0);
settextstyle(2,0,4);
settextjustify(1,1);
outtextxy(320,125,"Root Directory");
setcolor(BLUE);
for(j=0;j<=i;j++,cir_x+=mid)
{
line(320,150,cir_x,250);
fillellipse(cir_x,250,30,30);
outtextxy(cir_x,250,fname[j]);
}
getch();
}
}

OUTPUT:
ROOT

1.C
ROOT

1.C 2.C

ROOT

1.C
2.C 3.C
(b) Two Level Directory Structure

Aim: To implement Two Level Directory Structure


Description of the program:
In the two-level directory system, the system maintains a master block that has one entry for each
user. This master block contains the addresses of the directory of the users.
There are still problems with two-level directory structure. This structure effectively isolates one
user from another. This is an advantage when the users are completely independent, but a disadvantage
when the users want to cooperate on some task and access files of other users. Some systems simply do not
allow local files to be accessed by other users.

Source Code:
#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,"null",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);
if(lev==0||lev==1)
(*root)->ftype=1;
else
(*root)->ftype=2;
(*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)
{
if(lev==0||lev==1)
{
if((*root)->level==0)
printf("How many users");
else
printf("hoe many files");
printf("(for%s):",(*root)->name);
scanf("%d",&(*root)->nc);
}
else
(*root)->nc=0;
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 null):sld
How many users(forsld):2
enter name of dir/file(under sld):tld
hoe many files(fortld):2
enter name of dir/file(under tld):hir
enter name of dir/file(under tld):dag
enter name of dir/file(under sld):bin
hoe many files(forbin):2
enter name of dir/file(under bin):exe
enter name of dir/file(under bin):obj

SLD

TLD DAG BIN


EXE

HIR
OBJ

c) Hierarchical Level Directory Structure


Aim: To implement Hierarchical Level Directory Structure
Description of the program:
In the tree-structured directory, the directory themselves are files. This leads to the possibility of
having sub-directories that can contain files and sub-subdirectories.
An interesting policy decision in a tree-structured directory structure is how to handle the deletion of
a directory. If a directory is empty, its entry in its containing directory can simply be deleted. However,
suppose the directory to be deleted id not empty, but contains several files, or possibly sub-directories.
Some systems will not delete a directory unless it is empty. Thus, to delete a directory, someone must first
delete all the files in that directory. If these are any sub-directories, this procedure must be applied
recursively to them, so that they can be deleted also. This approach may result in a insubstantial amount of
work. An alternative approach is just to assume that, when a request is made to delete a directory, all of that
directory's files and sub-directories are also to be deleted.
Algorithm for Hierarchical Level Directory Structure:

Source Code:
#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;
(*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 ROOT) :2
Enter Name of dir/file (under ROOT): USER 1
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for USER 1): 1
Enter Name of dir/file (under USER 1):SUBDIR
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for SUBDIR): 2
Enter Name of dir/file (under USER 1):JAVA
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for JAVA): 0
Enter Name of dir/file (under SUBDIR):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):SUBDIR 2
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for SUBDIR 2): 2
Enter Name of dir/file (under SUBDIR2):PPL
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for PPL): 2
Enter Name of dir/file (under PPL):B
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under PPL):C
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under SUBDIR):AI
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for AI): 2
Enter Name of dir/file (under AI):D
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under AI):E
Enter 1 for Dir /2 for file:2

ROOT

USER1 USER2

SUB DIR1 A SUB DIR2

JAVA VB PPL AI

B C D E
12: Write a C program to simulate Bankers Algorithm for DeadLock Avoidance.
AIM: To write a C program to implement deadlock avoidance.
DESCRIPTION:Requires that the system has some additional a priori information available.The deadlock-
avoidance algorithm dynamically examines the resource-allocation state to ensure that there can never be a
circular-wait condition.
ALGORITHM:
Requesti = request vector for process Pi.
Step 1: If Requesti[j] == k then process Pi wants k instances of resource type Rj.
1. If RequestiNeedigo to step 2.

Otherwise, raise error condition, since process has exceeded its maximum claim.
Step 2:If RequestiAvailable, go to step 3.
Otherwise Pi must wait, since resources are not available.
Step 3:Pretend to allocate requested resources to Pi
by modifying the state as follows:
Available = Available – Request;
Allocationi= Allocationi + Requesti;
Needi= Needi – Requesti;
If safe  the resources are allocated to Pi.
If unsafe  Pi must wait, and the old resource-allocation state is restored

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int Max[10][10], need[10][10], alloc[10][10], avail[10], completed[10], safeSequence[10];
int p, r, i, j, process, count;
count = 0;
printf("Enter the no of processes : ");
scanf("%d", &p);
for(i = 0; i< p; i++)
completed[i] = 0;
printf("\n\nEnter the no of resources : ");
scanf("%d", &r);
printf("\n\nEnter the Max Matrix for each process : ");
for(i = 0; i < p; i++)
{
printf("\nFor process %d : ", i + 1);
for(j = 0; j < r; j++)
scanf("%d", &Max[i][j]);
}
printf("\n\nEnter the allocation for each process : ");
for(i = 0; i < p; i++)
{
printf("\nFor process %d : ",i + 1);
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
}
printf("\n\nEnter the Available Resources : ");
for(i = 0; i < r; i++)
scanf("%d", &avail[i]);
for(i = 0; i < p; i++)
for(j = 0; j < r; j++)
need[i][j] = Max[i][j] - alloc[i][j];
do
{
printf("\n Max matrix:\tAllocation matrix:\n");
for(i = 0; i < p; i++)
{
for( j = 0; j < r; j++)
printf("%d ", Max[i][j]);
printf("\t\t");
for( j = 0; j < r; j++)
printf("%d ", alloc[i][j]);
printf("\n");
}
process = -1;
for(i = 0; i < p; i++)
{
if(completed[i] == 0)//if not completed
{
process = i ;
for(j = 0; j < r; j++)
{
if(avail[j] < need[i][j])
{
process = -1;
break;
}
}
}
if(process != -1)
break;
}
if(process != -1)
{
printf("\nProcess %d runs to completion!", process + 1);
safeSequence[count] = process + 1;
count++;
for(j = 0; j < r; j++)
{
avail[j] += alloc[process][j];
alloc[process][j] = 0;
Max[process][j] = 0;
completed[process] = 1;
}
}
}
while(count != p && process != -1);
if(count == p)
{
printf("\nThe system is in a safe state!!\n");
printf("Safe Sequence : < ");
for( i = 0; i < p; i++)
printf("%d ", safeSequence[i]);
printf(">\n");
}
else
printf("\nThe system is in an unsafe state!!");
}
OUTPUT SCREENS:
13: Write a C program to simulate Bankers Algorithm for DeadLock prevention
AIM:To write a C program to implement deadlock prevention.
DESCRIPTION:
• Allow system to enter deadlock state

• Detection algorithm

• Recovery scheme

ALGORITHM:
Step1: Let Workand Finish be vectors of length m and n, respectively. Initialize:
Work = Available
Finish [i] = false for i = 0, 1, …, n- 1.
Step2: Find and i such that both:
(a) Finish [i] = false
(bRequestiWork
If no such i exists, go to step 4.
Step 3: Work = Work + Allocationi
Finish[i] = true
go to step 2.
Step 4:If Finish[i] == false, for some i, 1 in,
then the system is in deadlock state.
Moreover, if Finish[i] == false, then Pi is deadlocked.

PROGRAM:
#include<stdio.h>
void main()
{
int cl[10][10],al[10][10],av[10],i,j,k,m,n,ne[10][10],flag=0;

printf("\nEnter the matrix");


scanf("%d %d",&m,&n);
printf("\nEnter the claim matrix:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cl[i][j]);
}
}
printf("\nEnter allocated matrix:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&al[i][j]);
}
}
printf("\nThe need matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
ne[i][j]=cl[i][j]-al[i][j];
printf("\t%d",ne[i][j]);
}
printf("\n");
}
printf("\nEnter avaliable matrix");
for(i=0;i<n;i++)
scanf("%d",&av[i]);
printf("Claim matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",cl[i][j]);
}
printf("\n");
}
printf("\n Allocated matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",al[i][j]);
}
printf("\n");
}
printf("Available matrix:\n");
for(i=0;i<n;i++)
{
printf("%d\t",av[i]);
}
//for(k=0;k<m;k++)
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(av[j]>=ne[i][j])
flag=1;
else
flag=0;
}
}
if(flag==0)
printf("Unsafe State");
else
printf("Safe State");
}
OUTPUT SCREENS:

You might also like