Professional Documents
Culture Documents
All OS Programs - Manual
All OS Programs - Manual
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:
Sed: sed means stream editor it can be used for editing the main program by using sed
## 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.
# check if it is a file
if [ -f $file ]
then
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.
fact=1
echo $fact
(or)
Using For loop – vi fact1.sh
#shell script for factorial of a number
#factorial using for loop
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:
$cat >input4novowels
123
dgjlp
This is no vowel in awk
ctrl + d
$cat >novowels.awk
BEGIN{count=0}
!/[aeiou]/ {count++;print}
END{print "Number of lines="count}
Ctrl+d
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
$cat >count4.awk
BEGIN{words=0;characters=0}
{
character+=length($0);
words+=NF;
}
END{print "lines=",NR," words=",words," Characters=",character}
Ctrl + d
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.
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
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
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:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
sem_t room;
sem_t chopstick[5];
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);
}
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);
}
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);
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
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
#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:
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
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);
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:
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
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
#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:
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
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.
Ouput:
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.
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
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
HIR
OBJ
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:
ROOT
USER1 USER2
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 RequestiNeedigo to step 2.
Otherwise, raise error condition, since process has exceeded its maximum claim.
Step 2:If RequestiAvailable, 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
(bRequestiWork
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 in,
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;