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

Ex.

No : 1 UNIX BASIC COMMANDS

Date :

AIM :

To study and execute the commands in UNIX.

CONTENT:

a)date–used to check the date and time

Syn:$date

Format Purpose Example Result

+%m To display only month $date+%m 06


+%h To display month name $date+%h June
+%d To display day of month $date+%d O1
+%y To display last two digits of years $date+%y 09
+%H To display hours $date+%H 10
+%M To display minutes $date+%M 45
+%S To display seconds $date+%S 55

b)cal –used to display the calendar

Syn:$cal 2 2009

c) echo –used to print the message on the screen. Syn:$echo “text”

d)ls –used to list the files.


Your files are kept in a directory.
Syn:$lsls–s All files (include files with prefix)
ls–lLodetai (provide file statistics)
ls–t Order by creation time
ls– u Sort by access time (or show when last accessed together with –l)
ls–s Order by size
ls–r Reverse order
ls–f Mark directories with /,executable with* , symbolic links with @, local sockets with =,
named pipes(FIFOs)with ls–s Show file size ls– h“ Human Readable”,
show file size in Kilo Bytes & Mega Bytes (h can be used together with –l or)
ls[a-m]*List all the files whose name begin with alphabets From „a‟ to „m‟ ls[a]*List all the
files whose name begins with „a‟ or „A‟
Eg:$ls>my list Output of „ls‟ command is stored to disk file named „my list‟

e)lp –used to take printouts


Syn:$lp filename
f)man –used to provide manual help on every UNIX commands.
Syn:$man unix command
$man cat
g) who&whoami –it displays data about all users who have logged into the system currently.
The next command displays about current user only.
Syn:$who$whoami
h)uptime –tells you how long the computer has been running since its last reboot or power-off.
Syn:$uptime
i)uname –it displays the system information such as hardware platform, system name and
processor, OS type.
Syn:$uname–a
j)hostname –displays and set system host name
Syn:$ hostname
k)bc
–stands for „best calculator”
$bc $ bc$ bc $ bc
10/2*3 scale =1 ibase=2 sqrt(196)
15 2.25+1 obase=16 14 quit
3.35 11010011
quit89275
1010
Ā
Quit
$bc $bc-1
For(i=1;i<3;i=i+1) scale=2
1 s(3.14)
2 0
3 quit

FILE MANIPULATION COMMANDS

a)cat–this create, view and concatenate files.

Creation: Syn:$cat>filename

Viewing: Syn:$cat filename

Add text to an existing file: Syn:$cat>>filename


Concatenate: Syn:$catfile1file2>file3

$catfile1file2>>file3 (no over writing of file3)

b)grep–used to search a particular word or pattern related to that word from the file.

Syn:$grep search word filename

Eg:$grepanu student

c)rm–deletes a file from the file system

Syn:$rm filename

d)touch–used to create a blank file.

Syn:$touch file names

e)cp–copies the files or directories

Syn:$cpsource file destination file

Eg:$cp student stud

f)mv–to rename the file or directory

syn:$mv old file new file

Eg:$mv–i student student list(-i prompt when overwrite)

g)cut–it cuts or pickup a given number of character or fields of the file.

Syn:$cut <option><filename>

Eg: $cut –c filename

$cut–c1-10emp

$cut–f 3,6emp

$ cut –f 3-6 emp

-c cutting columns

-f cutting fields

h)head–displays10 lines from the head(top)of a given file


Syn:$head filename

Eg:$head student

To display the top two lines:

Syn:$head-2student

i)tail–displays last 10 lines of the file

Syn:$tail filename

Eg:$tail student

To display the bottom two lines;

Syn:$ tail -2 student

j)chmod–used to change the permissions of a file or directory.

Syn:$ch mod category operation permission file

Where, Category–is the user type

Operation–is used to assign or remove permission

Permission–is the type of permission

File–are used to assign or remove permission all

Examples: $chmodu-wx student

Removes write and execute permission for users

$chmodu+rw,g+rwstudent

Assigns read and write permission for users and groups

$chmodg=rwx student

Assigns absolute permission for groups of all read, write and execute permissions

k)wc–it counts the number of lines, words, character in a specified file(s) with the options as –
l,-w,-c

Category Operation Permission


u-users +assign r-read

g-group -remove w-write

o-others =assign absolutely x-execute

Syn: $wc –l filename

$wc –w filename

$wc–c filename

RESULT :
Ex.no : 2 SHELL PROGRAMMING (using looping, control constructs etc.,)

Date :

AIM :

To write a shell program for looping and control statements

ALGORITHM :

Step 1- Open vi editor and start the program and go to the insert mode for entering the
code.
Step 2- Read the inputs file use conditional statement like while ,if,if then, switch case.
Step 3- Print the output by checking whether the condition is true or false
Step 4 – Enter into the escape mode for the execution of the result and verify the output.
PROGRAMS :

i) Addition, subtraction, Multiplication and Division.

#!/bin/bash
echo "Enter the a value"
read a
echo " Enter the b value"
read b
c=$ (expr "$a" + "$b")
echo "sum: $c"
d = & (expr "$a" - "$b")
echo "Sub: $d"
e=$ (expr "$a" /* "$b")
echo "mul: $e"
f = $ (expr "$a" % "b")
echo "div: $f"
ii) While Statement

#!/bin/bash
a=1
while [ "$a" -lt 11]
do
Echo "$a"
a = $(expr "$a" + 1)
done
iii) IF Statement

#!/bin/bash
a=10
b=20
if [ "$a" =="$b"]
then
echo "a is equal to b"
fi
if [ "$a" != "$b"]
Then
echo "a is not equal to b"
fi
iv) Switch Statement

#!/bin/bash
CARS = " bmw"
case "$CARS" in
# case 1
"mercedes") echo "headquatres-affaliserbach,germany" ;;
# case 2
"audi") echo "headquatres - Ingelstak, germary" ;;
# case 3
"bmw") echo "headquatres -chennai, Tamilnadu, India";;
Esac
v) IF-THEN Statement

#!/bin/bash
a = 20
b=20
if [ "$a" == "$b"]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi

RESULT:
Ex.No :3a SYSTEM CALLS PROCESS CREATION

Date :

AIM :

To write a program to create a process in UNIX.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare pid as integer.

STEP 3: Create the process using Fork command.

STEP 4: Check pid is less than 0 then print error else if pid is equal to 0 then execute
command else parent process wait for child process.

STEP 5: Stop the program.

PROGRAM:
void main()
{
intpid;
pid=fork();
if(pid<0)
{
Printf("cannot create the file");
Exit(-1);
}
if(pid==0)
{
Printf("child process");
Exit(0);
}
else
{
Printf("parent process");
}
}

RESULT:
Ex.No : 3b EXECUTING A COMMAND

Date :

AIM :

To write a program to executing a command

ALGORITHM :

STEP 1 : Start the program

STEP 2 : Execute the command in the shell program using exec.

STEP 3 : Stop the execution

PROGRAM :

Echo program for executing UNIX command using Shell programming.

echo welcome
ps
exec wc el

RESULT :
Ex.No : 3c SLEEP COMMAND USING GETPID

Date :

AIM:

To create child with sleep command using getpid.

ALGORITHM:

STEP 1: Start the execution and create a process using fork() command.

STEP 2: Make the parent process to sleep for 10 seconds.

STEP 3:In the child process print it pid and it corresponding pid.

STEP 4: Make the child process to sleep for 5 seconds.

STEP 5: Again print it pid and it parent pid.

STEP 6: After making the sleep for the parent process for 10 seconds print it pid.

STEP 7: Stop the execution.

PROGRAM:

Void main ()
{
intpid;
pid=fork();
if (pid==0)
{
printf("\nChild process\n");
printf("\nChild process id is %d",getpid());
printf("\nIts parent process 1 is %d",getppid());
sleep (5);
printf("\nChild process after sleep=5\n");
printf("\nChild process id is %d", getpid());
Printf("\nIts parent process id is %d",getppid());
}
else
{
printf("\nparent process");
sleep (10);
printf("\nChild process id is %d", getpid());
printf("\nIts parent process id is %d", getppid());
printf("\nParent terminates");
}
}

RESULT:
Ex.No : 4a READING FROM A FILE

Date :

AIM:

To create the file,read data from the file,update the file.

ALGORITHM:

1.Get the data from the user.

2.Open a file.

3.Read from the file.

4.Close the file.

PROGRAM :
#include<stdio.h>
int main()
{
charstr[100];
FILE *fp;
fp=fopen("file1.dat","r");
while(!feof(fp))
{
fscanf(fp,"%s",str);
printf("%s",str);
}
fclose(fp);
}

RESULT:
Ex.No : 4b WRITING INTO A FILE

Date :

AIM:

To write a C program to write the data into a file.

ALGORITHM:

Step1.Get the data from the user.

Step2.Open a file.

Step3.Write the data from the file.

Step4.Get the data and update the file.

PROGRAM:

#include<stdio.h>
int main ()
charstr[100];
FILE *fp;
printf ("enter the string");
gets (str);
fp=fopen("filel.dat", "w+");
while (!feof (fp))
{
fscanf(fp,"%s", str);
}
fprintf(fp,"%s", str);
return 0;
}

RESULT:
Ex.No : 4c FILE CREATION

Date :

AIM:

To write a C program to create a file.

ALGORITHM:

Step1:Start the program.

Step2:Create the file using create function and assign a variable to it.

Step3:If the value of the variable is less then print file cannot be created ,otherwise print
file is created.

Step4:Stop the program.

PROGRAM :
Void main ()
{
int id;
if (id=creat ("z.txt",0)==-1)
{
printf ("cannot create the file");
exit (1);
}
else
{
printf("file is create");
exit (1);
}}

RESULT:
Ex.No : 5a FIRST COME FIRST SERVE (FCFS)

Date :

AIM :

To write an implementation of CPU scheduling algorithm in FCFS.

ALGORITHM :

STEP 1 : Create the number of process.

STEP 2 : Get the ID card service time for each process.

STEP 3 : Initially, waiting time of first process is zero and total time for first process is
starting

time of that process.

STEP 4 : Calculate the total time and processing time for remaining process.

STEP 5 : Waiting time of one process is the total time of previous process.

STEP 6 : Total time of process is calculated by adding waiting time for lack process.

STEP 7 : Calculate average waiting time by dividing total waiting time by total no of
process.

STEP 8 : Calculate average turnaround time by dividing total turnaround by total no.of
process

STEP 9 : Display Result.

PROGRAM :

#include<stdio.h>
// Function to find the waiting time for all processes
intwaitingtime(intproc[],int n,
intburst_time[],intwait_time[]){
// waiting time for first process is 0
wait_time[0]=0;
// calculating waiting time
for(int i =1; i < n ; i++)
wait_time[i]=burst_time[i-1]+wait_time[i-1];
return0;
}
// Function to calculate turn around time
intturnaroundtime(intproc[],int n,
intburst_time[],intwait_time[],int tat[]){
// calculating turnaround time by adding
// burst_time[i] + wait_time[i]
int i;
for( i =0; i < n ; i++)
tat[i]=burst_time[i]+wait_time[i];
return0;
}
//Function to calculate average time
intavgtime(intproc[],int n,intburst_time[]){
intwait_time[n], tat[n],total_wt=0,total_tat=0;
int i;
//Function to find waiting time of all processes
waitingtime(proc, n,burst_time,wait_time);
//Function to find turn around time for all processes
turnaroundtime(proc, n,burst_time,wait_time, tat);
//Display processes along with all details
printf("Processes Burst Waiting Turn around \n");
// Calculate total waiting time and total turn
// around time
for( i=0; i<n; i++){
total_wt=total_wt+wait_time[i];
total_tat=total_tat+ tat[i];
printf(" %d\t %d\t\t %d \t%d\n", i+1,burst_time[i],wait_time[i], tat[i]);
}
printf("Average waiting time = %f\n",(float)total_wt/(float)n);
printf("Average turn around time = %f\n",(float)total_tat/(float)n);
return0;
}
// main function
int main(){
//process id's
intproc[]={1,2,3};
int n =sizeofproc/sizeofproc[0];
//Burst time of all processes
intburst_time[]={5,8,12};
avgtime(proc, n,burst_time);
return0;
}

RESULT:
Ex.No : 5b IMPLEMENTATION OF SJF SCHEDULING

Date :

AIM :

To write a C program to implement CPU Scheduling algorithm for Shortest Job First.

ALGORITHM :

STEP 1 : Create the number of process.

STEP 2 : Get the ID card service time for each process.

STEP 3 : Initially, waiting time of first process is zero and total time for first process is
starting

time of that process.

STEP 4 : Calculate the total time and processing time for remaining process.

STEP 5 : Waiting time of one process is the total time of previous process.

STEP 6 : Total time of process is calculated by adding waiting time for lack process.

STEP 7 : Calculate average waiting time by dividing total waiting time by total no of
process.

STEP 8 : Calculate average turnaround time by dividing total turnaround by total no.of
process

STEP 9 : Display Result.

PROGRAM :

#include<stdio.h>
int main()
{
intbt[20],p[20],wt [20], tat [20],i,j,n, total=0,pos, temp;
floatavg_wt, avg_tat;
printf("enter number of process :");
scanf("%d", &n);
printf("\nEnter burst time:n");
for (i=0;i<n;i++)
{
printf("p%d: ",i+1);
scanf("%d", &bt [i]);
p[i]=i+1;
}
for (i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n; j++)
{
if (bt [j]<bt [pos])
pos=j;
}
temp=bt [i];
bt [i]=bt [pos];
bt [pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt [0]=0;
for (i-1;i<n;i++)
{
wt [i]=0;
for (j=0;j<i;j++)
wt[i]+=bt [j];
total+ =wt [i];
}
avg_wt=(float) total/n:
total=0;

printf("\nprocessbursttimewaitingtimeturnaroundtime");
for (i=0;i<n;i++)
{
tat [i]=bt [i]+wt [i];
total +=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t %d",p[i], bt[i], wt [i],tat[i]);
avg_tat=(float) total/n;
printf("\nAverage waiting time=%f",avg_wt);
printf("\nAverageturnround time=%f",avg_tat);
}

RESULT:
Ex.No : 6a IMPLEMENTATION OF PRIORITY SCHEDULING

Date :

AIM:

To write the program to stimulate priority program.

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 :

#include<stdio.h>
#include<conio.h>
void main()
{
inti,j,n,bt[10],p[10],compt[10], wt[10],tat[10],temp1,temp2;
floatsumwt=0.0,sumtat=0.0,avgwt,avgtat;
clrscr();
printf("Enter number of processes: ");
scanf("%d",&n);
printf("Enter the burst time of %d process\n", n);
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
printf("Enter the priority of %d process\n", n);
for(i=0;i<n;i++)
scanf("%d",&p[i]);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(p[i]>p[j])
{
temp1=bt[i];
bt[i]=bt[j];
bt[j]=temp1;
temp2=p[i];
p[i]=p[j];
p[j]=temp2;
}
compt[0]=bt[0]; wt[0]=0;
for(i=1;i<n;i++)
compt[i]=bt[i]+compt[i-1];
for(i=0;i<n;i++)
{
tat[i]=compt[i];
wt[i]=tat[i]-bt[i];
sumtat+=tat[i];
sumwt+=wt[i];
}
avgwt=sumwt/n; avgtat=sumtat/n;
printf("------------------------------\n");
printf("Bt\tCt\tTat\tWt\n");
printf("------------------------------\n");
for(i=0;i<n;i++)
{
printf("%2d\t%2d\t%2d\t%2d\n",bt[i],compt[i],tat[i],wt[i]);
}
printf("------------------------------\n");
printf(" Avgwt = %.2f\tAvgtat = %.2f\n",avgwt,avgtat);
printf("-------------------------------\n");
getch();
}

RESULT :
Ex.No : 6b IMPLEMENTATION OF RR SCHEDULING

Date :

AIM:

To write the program t stimulate Round Robin program.

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

(a) Average waiting time = Total waiting Time / Number of process

(b) Average Turnaround time = Total Turnaround Time / Number of process

Step 8: Stop the process

PROGRAM :

#include<stdio.h>
#include<conio.h>
struct process
{
charpn[10];
intbt,ct,time;
}p[10];
void main()
{
inti,full,n,tq,wt[10],tat[10], time1=0;
floatavgwt=0.0;
clrscr();
printf("Enter number of processes:");
scanf("%d",&n);
printf("Enter process name and burst time of %d process\n", n);
for(i=0;i<n;i++)
{
scanf("%s%d",&p[i].pn,&p[i].bt);
p[i].time=p[i].bt;
}
printf("Enter quantum:");
scanf("%d",&tq);
full=n;
while(full)
{
for(i=0;i<n;i++)
{
if(p[i].bt>=tq)
{
p[i].bt-=tq;
time1=time1+tq;
}
else if(p[i].bt!=0)
{
time1+=p[i].bt;
p[i].bt=0;
}
else
continue;
if(p[i].bt==0)
{
full=full-1;
tat[i]=time1;
}
}
}
for(i=0;i<n;i++)
{
p[i].ct=tat[i];
wt[i]=tat[i]-p[i].time;
}
printf("----------------------------------\n");
printf("PN\tBt\tCt\tTat\tWt\n");
printf("----------------------------------\n");
for(i=0;i<n;i++)
{
printf("%2s\t%2d\t%2d\t%2d\t%2d\n",p[i].pn,p[i].time,p[i].ct,tat[i],wt[i]);
avgwt+=wt[i];
}
printf("----------------------------------\n");
avgwt=avgwt/n;
printf(" Average waiting time = %.2f\n",avgwt);
printf("-----------------------------------\n");
getch();
}

RESULT :
Ex.No : 7 PRODUCER- CONSUMER PROBLEM USING

Date : SEMAPHORES

AIM:

To write a C-program to implement the producer – consumer problem using


semaphores.

ALGORITHM :

1. Start the program.


2. Declare the variables in the type of pthread_t as tid_producetid_consume.
3. Declare a structure for semaphore variables.
4. During run time read the number of items to be produced and consumed.
5. Declare and define semaphore function for creation and destroy.
6. Define producer function.
7. Define consumer function.
8. Call producer and consumer function.
9. Stop the execution
PROGRAM :

#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include<stdlib.h>
#define buffersize 10
pthread_mutex_tmutex;
pthread_ttidP[20],tidC[20];
sem_tfull,empty; int counter; int buffer[buffersize];
void initialize()
{
pthread_mutex_init(&mutex,NULL);
sem_init(&full,1,0);
sem_init(&empty,1,buffersize);
counter=0;
}
void write(int item)
{
buffer[counter++]=item;
}
int read()
{
return(buffer[--counter]);
}
void * producer (void * param)
{
intwaittime,item,i;
item=rand()%5; waittime=rand()%5;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
printf("\nProducer has produced item: %d\n",item);
write(item);
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
void * consumer (void * param)
{
intwaittime,item;
waittime=rand()%5;
sem_wait(&full);
pthread_mutex_lock(&mutex);
item=read();
printf("\nConsumer has consumed item: %d\n",item);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
int main()
{
int n1,n2,i; initialize();
printf("\nEnter the no of producers: ");
scanf("%d",&n1);
printf("\nEnter the no of consumers: ");
scanf("%d",&n2);
for(i=0;i <n1;i++)
pthread_create(&tidP[i],NULL,producer,NULL);
for(i=0;i<n2;i++)
pthread_create(&tidC[i],NULL,consumer,NULL);
for(i=0;i<n1;i++)
pthread_join(tidP[i],NULL);
for(i=0;i<n2;i++)
pthread_join(tidC[i],NULL);
//sleep(5);
exit(0); }

RESULT :
Ex.No : 8 IMPLEMENTATION OF BANKER’S ALGORITHM

Date :

AIM:

To write a C program to implement banker‟s algorithm for deadlock avoidance.

ALGORITHM:

Step-1: Start the program.

Step-2: Declare the memory for the process.

Step-3: Read the number of process, resources, allocation matrix and available matrix.

Step-4: Compare each and every process using the banker‟s algorithm.

Step-5: If the process is in safe state then it is a not a deadlock process otherwise it is a
deadlock process

Step-6: produce the result of state of process

Step-7: Stop the program

PROGRAM:
#include <stdio.h>
int current[5][5], maximum_claim[5][5], available[5];
int allocation[5] = {0, 0, 0, 0, 0};
intmaxres[5], running[5], safe = 0;
int counter = 0, i, j, exec, resources, processes, k = 1;
int main()
{
printf("\nEnter number of processes: ");
scanf("%d", &processes);

for (i = 0; i < processes; i++)


{
running[i] = 1;
counter++;
}

printf("\nEnter number of resources: ");


scanf("%d", &resources);
printf("\nEnter Claim Vector:");
for (i = 0; i < resources; i++)
{
scanf("%d", &maxres[i]);
}

printf("\nEnter Allocated Resource Table:\n");


for (i = 0; i < processes; i++)
{
for(j = 0; j < resources; j++)
{
scanf("%d", &current[i][j]);
}
}

printf("\nEnter Maximum Claim Table:\n");


for (i = 0; i < processes; i++)
{
for(j = 0; j < resources; j++)
{
scanf("%d", &maximum_claim[i][j]);
}
}

printf("\nThe Claim Vector is: ");


for (i = 0; i < resources; i++)
{
printf("\t%d", maxres[i]);
}

printf("\nThe Allocated Resource Table:\n");


for (i = 0; i < processes; i++)
{
for (j = 0; j < resources; j++)
{
printf("\t%d", current[i][j]);
}
printf("\n");
}

printf("\nThe Maximum Claim Table:\n");


for (i = 0; i < processes; i++)
{
for (j = 0; j < resources; j++)
{
printf("\t%d", maximum_claim[i][j]);
}
printf("\n");
}

for (i = 0; i < processes; i++)


{
for (j = 0; j < resources; j++)
{
allocation[j] += current[i][j];
}
}

printf("\nAllocated resources:");
for (i = 0; i < resources; i++)
{
printf("\t%d", allocation[i]);
}

for (i = 0; i < resources; i++)


{
available[i] = maxres[i] - allocation[i];
}

printf("\nAvailable resources:");
for (i = 0; i < resources; i++)
{
printf("\t%d", available[i]);
}
printf("\n");

while (counter != 0)
{
safe = 0;
for (i = 0; i < processes; i++)
{
if (running[i])
{
exec = 1;
for (j = 0; j < resources; j++)
{
if (maximum_claim[i][j] - current[i][j] >available[j])
{
exec = 0;
break;
} }
if (exec)
{
printf("\nProcess%d is executing\n", i + 1);
running[i] = 0;
counter--;
safe = 1;

for (j = 0; j < resources; j++)


{ available[j] += current[i][j]; }
break;
}
}
}
if (!safe)
{ printf("\nThe processes are in unsafe state.\n");
break;
}
else
{
printf("\nThe process is in safe state");
printf("\nAvailable vector:");

for (i = 0; i < resources; i++)


{
printf("\t%d", available[i]);
}

printf("\n");
}
}
return 0;
}

RESULT:
Ex.No : 9a IMPLEMENTATION OF MEMORY MANAGEMENT SCHEMES

Date :

AIM:

To write the program to implement first fit memory management scheme.

ALGORITHM :

Step 1: START.
Step 2: At first get the no of processes and blocks.
Step 3: Allocate the process by if(size of block>=size of the process) then allocate the
process else move to the next block.
Step 4: Now Display the processes with blocks and allocate to respective process.
Step 5: STOP.
PROGRAM
#include<stdio.h>
void main()
{
intbsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j;
for(i = 0; i < 10; i++)
{
flags[i] = 0;
allocation[i] = -1;
}
printf("Enter no. of blocks: ");
scanf("%d", &bno);
printf("\nEnter size of each block: ");
for(i = 0; i <bno; i++)
scanf("%d", &bsize[i]);
printf("\nEnter no. of processes: ");
scanf("%d", &pno);
printf("\nEnter size of each process: ");
for(i = 0; i <pno; i++)
scanf("%d", &psize[i]);
for(i = 0; i <pno; i++) //allocation as per first fit
for(j = 0; j <bno; j++)
if(flags[j] == 0 &&bsize[j] >= psize[i])
{
allocation[j] = i;
flags[j] = 1;
break;
}
//display allocation details
printf("\nBlock no.\tsize\t\tprocess no.\t\tsize");
for(i = 0; i <bno; i++)
{
printf("\n%d\t\t%d\t\t", i+1, bsize[i]);
if(flags[i] == 1)
printf("%d\t\t\t%d",allocation[i]+1,psize[allocation[i]]);
else
printf("Not allocated");
}
}

RESULT :
Ex.No : 9b IMPLEMENTATION OF MEMORY MANAGEMENT SCHEMES

Date : (BEST FIT )

AIM :

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

ALGORITHM :

1. Start the process

2. Declare the size

3. Get the number of processes to be inserted

4. Allocate the first hole that is big enough searching

5. Start at the beginning of the set of holes

6. If not start at the hole that is sharing the pervious first fit search end

7. Compare the hole

8. if large enough then stop searching in the procedure

9. Display the values

10. Stop the process

PROGRAM :

#include<stdio.h>
#include<process.h>
void main()
{
int a[20],p[20],i,j,n,m;
printf("Enter no of Blocks.\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %dst Block size:",i);
scanf("%d",&a[i]);
}
printf("Enter no of Process.\n");
scanf("%d",&m);
for(i=0;i<m;i++)
{
printf("Enter the size of %dst Process:",i);
scanf("%d",&p[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(p[j]<=a[i])
{
printf("The Process %d allocated to %d\n",j,a[i]);
p[j]=10000;
break;
}
}
}
for(j=0;j<m;j++)
{
if(p[j]!=10000)
{
printf("The Process %d is not allocated\n",j);
}
}
}

RESULT :
Ex.No : 9c IMPLEMENTATION OF MEMORY MANAGEMENT SCHEMES

Date : (WORST FIT )

AIM :

To write a c program to implement worst fit algorithm for memory management.

ALGORITHM:

Step 1: Input memory block with a size.

Step 2: Input process with size.

Step 3: Initialize by selecting each process to find the maximum block size that can be
assigned to the current process.

Step 4: If the condition does not fulfill, they leave the process.

Step 5: If the condition is not fulfilled, then leave the process and check for the next
process.

Step 6: Stop.

PROGRAM :
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme - First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
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();
}

RESULT :
Ex.No : 10a IMPLEMENTATION OF PAGE REPLACEMENT ALGORITHM

Date : (FIFO)

AIM :

To write a c program to implement FIFO algorithm for page replacement.

ALGORITHM:

Step 1. Start to traverse the pages.

Step 2. If the memory holds fewer pages, then the capacity else goes to step 5.

Step 3. Push pages in the queue one at a time until the queue reaches its maximum
capacity or all page requests are fulfilled.

Step 4. If the current page is present in the memory, do nothing.

Step 5. Else, pop the topmost page from the queue as it was inserted first.

Step 6. Replace the topmost page with the current page from the string.

Step 7. Increment the page faults.

Step 8. Stop

PROGRAM :
#include <stdio.h>
int main()
{
int incomingStream[] = {4, 1, 2, 4, 5};
int pageFaults = 0;
int frames = 3;
int m, n, s, pages;

pages = sizeof(incomingStream)/sizeof(incomingStream[0]);

printf("Incoming \t Frame 1 \t Frame 2 \t Frame 3");


int temp[frames];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;

for(n = 0; n < frames; n++)


{
if(incomingStream[m] == temp[n])
{
s++;
pageFaults--;
}
}
pageFaults++;

if((pageFaults <= frames) && (s == 0))


{
temp[m] = incomingStream[m];
}
else if(s == 0)
{
temp[(pageFaults - 1) % frames] = incomingStream[m];
}

printf("\n");
printf("%d\t\t\t",incomingStream[m]);
for(n = 0; n < frames; n++)
{
if(temp[n] != -1)
printf(" %d\t\t\t", temp[n]);
else
printf(" - \t\t\t");
}
}

printf("\nTotal Page Faults:\t%d\n", pageFaults);


return 0;
}

RESULT :
Ex.No : 10b IMPLEMENTATION OF PAGE REPLACEMENT ALGORITHM

Date : (LRU)

AIM :

To Simulate LRU page replacement algorithms

ALGORITHM:

1. Start

2. Read the number of frames

3. Read the number of pages

4. Read the page numbers

5. Initialize the values in frames to -1

6. Allocate the pages in to frames by selecting the page that has not been used for the
longest period of time.

7. Display the number of page faults.

8. stop

PROGRAM :

#include<stdio.h>
#include<coniio.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()
{
clrscr(); 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<=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++)
{
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++)
}
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;
}

RESULT:

You might also like