21CSC202J OPERATING SYSTEMS LAB MANUAL Ver01
21CSC202J OPERATING SYSTEMS LAB MANUAL Ver01
LAB MANUAL
Bachelor of Technology
Semester III
1
21CSC202J-Operating Systems Lab
LIST OF EXPERIMENTS
2 Process Creation using fork() and Usage of getpid(), getppid(), wait() functions
3 Multithreading
5 Reader-Writer problem
15 File organization schemes for single level and two level directory
2
21CSC202J-Operating Systems Lab
OPERATING SYSTEM
Ex.No:1 INSTALLATION
3
21CSC202J-Operating Systems Lab
4
21CSC202J-Operating Systems Lab
5
21CSC202J-Operating Systems Lab
Click on Install
6
21CSC202J-Operating Systems Lab
7
21CSC202J-Operating Systems Lab
8
21CSC202J-Operating Systems Lab
9
21CSC202J-Operating Systems Lab
Finally you will get the prompt on successful installation of Ubuntu in windows 10 64 bit
21CSC202J-Operating Systems Lab
AIM:
To study about the basics of LINUX
UNIX:
It is a multi-user operating system. Developed at AT & T Bell Industries, USA in 1969.
Ken Thomson along with Dennis Ritchie developed it from MULTICS (Multiplexed
Information and Computing Service) OS.
By1980, UNIX had been completely rewritten using C language.
LINUX:
It is similar to UNIX, which is created by Linus Torualds. All UNIX commands works
in Linux. Linux is a open source software. The main feature of Linux is coexisting with other
OS such as windows and UNIX.
a) UNIX kernel
b) Shells
c) Tools and Applications
UNIX KERNEL:
Kernel is the core of the UNIX OS. It controls all tasks, schedule all Processes and
carries out all the functions of OS.
SHELL:
Shell is the command interpreter in the UNIX OS. It accepts command from the user
and analyses and interprets them
21CSC202J-Operating Systems Lab
AIM:
To study of Basic UNIX Commands and various UNIX editors such as vi, ed, ex
and EMACS.
CONTENT:
Note: Syn->Syntax
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–l Lodetai (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)
21CSC202J-Operating Systems Lab
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 p ro vi d e manual help on eve r y UNIX c o m m a n d s .
Syn:$man unix command
$man cat
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
quit 89275
1010
Ā
Quit
$bc $ bc-l
for(i=1;i<3;i=i+1)I scale=2
1 s(3.14)
2 0
3 quit
21CSC202J Operating Systems Lab
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:$grep anu student
Examples:
$chmodu-wx student
Removes write and execute permission for users
$ch modu+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
Aim :
To write a program for process Creation using fork() and usage of getpid(), getppid(),
wait() function.
Program :
• Process creating using fork()
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int
main(){
fork();
fork();
printf("Hello World\n");
}
Output
• Usage of wait()
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
int main()
{
pid_t cpid;
if (fork()== 0)
exit(0); /* terminate child */
else
cpid = wait(NULL); /* reaping parent */
printf("Parent pid = %d\n", getpid());
printf("Child pid = %d\n", cpid);
return 0;
}
lO M oA R cP S D| 2 81 1 40 20
Output:
Result :
Thus Successfully completed Process Creation using fork() and Usage of getpid(),
getppid(), wait() functions.
lO M oA R cP S D| 2 81 1 40 20
Aim :
for (int i = thread_part * (MAX / 4); i < (thread_part + 1) * (MAX / 4); i++)
{
sum[thread_part] += array[i];
}
}
void testSum()
{
pthread_t threads[MAX_THREAD];
// joining threads
for (int i = 0; i < MAX_THREAD; i++)
{
pthread_join(threads[i], NULL);
}
}
void readfile(char* file_name)
{
char ch;
FILE *fp;
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
int i=0;
i++;
}
lO M oA R cP S D| 2 81 1 40 20
fclose(fp);
if (argc != 2) {
fprintf(stderr,"usage: a.out <file name>\n");
/*exit(1);*/
return -1;
}
readfile(argv[1] );
return 0;
}
Output :
Result :
Aim :
To implement Mutual Exclusion using semaphore and monitor
Program :
USING SEMAPHORE
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
#include<errno.h>
#include <stdlib.h>
#include<sched.h>
int philNo[5] = { 0, 1, 2, 3, 4 };
// my_semaphore structure
typedef struct {
}
my_semaphore;
// The case when pshared == 1 is not implemeted as it was not required because the
philosphers are implemented using threads and not processes.
lO M oA R cP S D| 2 81 1 40 20
if(pshared == 1){
printf("Cannot handle semaphores shared between processes!!! Exiting\n");
return -1;
}
return 0;
}
//This locks the mutex so that only thread can access the critical section at a time
pthread_mutex_lock(&sema->mutex);
sema->cnt = sema->cnt + 1;
pthread_cond_signal(&sema->conditional_variable);
lO M oA R cP S D| 2 81 1 40 20
// A woken thread must acquire the lock, so it will also have to wait until we call unlock
return 0;
}
// While the semaphore count variable value is 0 the mutex is blocked on the conditon
variable
while (!(sema->cnt))
pthread_cond_wait(&sema->conditional_variable, &sema->mutex);
// unlock mutex, wait, relock mutex
sema->cnt = sema->cnt - 1;
return 0;
}
// Print semaphore value for debugging
void signal1(my_semaphore *sema) {
printf("Semaphore variable value = %d\n", sema->cnt);
}
// Declaring the semaphore variables which are the shared resources by the threads
my_semaphore forks[5], bowls;
while(1) {
int* i = arg;
// This puts a wait condition on the bowls to be used by the current philospher so
that the philospher can access these forks whenever they are free
wait(&bowls);
lO M oA R cP S D| 2 81 1 40 20
// This puts a wait condition on the forks to be used by the current philospher so
that the philospher can access these forks whenever they are free
wait(&forks[*i]);
wait(&forks[(*i+4)%5] );
sleep(1);
//Print the philospher number, its thread ID and the number of the forks it uses for
eating printf("Philosopher %d with ID %ld eats using forks %d and %d\n", *i+1,
pthread_self(), *i+1, (*i+4)%5+1);
// This signals the other philospher threads that the bowls are available for
eating signal(&bowls);
// This signals the other philospher threads that these forks are available for
eating and thus other threads are woken up
signal(&forks[*i]);
signal(&forks[(*i+4)%5]);
sched_yield();
}
}
void main() {
int i = 0;
// Initialising the forks (shared variable) semaphores
while(i < 5){
init(&forks[i], 0, 1);
i++;
}
i = 0;
// Creating the philospher threads
while(i < 5) {
i++;
}
i = 0;
// Waits for all the threads to end their execution before ending
while(i < 5) {
pthread_join(phil[i], NULL);
i++;
}}
Output :
USING MONITOR
monitor DP
{
status state[5];
condition self[5];
// Pickup chopsticks
Pickup(int i)
{
// indicate that I’m hungry
state[i] = hungry;
// signaling R’s CV
test((i + 1) % 5);
test((i + 4) % 5);
}
test(int i)
{
if (state[(i + 1) % 5] != eating
&& state[(i + 4) % 5] != eating
&& state[i] == hungry) {
// indicate that I’m eating
state[i] = eating;
Output :
Result :
Aim :
Program :
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
sem_t wrt;
pthread_mutex_t
int numreader = 0;
void *writer(void *wno)
{
sem_wait(&wrt);
cnt = cnt*2;
printf("Writer %d modified cnt to %d\n",(*((int *)wno)),cnt);
sem_post(&wrt);
}
void *reader(void *rno)
{
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
numreader++;
if(numreader == 1) {
sem_wait(&wrt); // If this id the first reader, then it will block the writer
}
pthread_mutex_unlock(&mutex);
// Reading Section
printf("Reader %d: read cnt as %d\n",*((int *)rno),cnt);
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
numreader--;
if(numreader == 0) {
}
int main()
{
pthread_t read[10],write[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt,0,1);
int a[10] = {1,2,3,4,5,6,7,8,9,10}; //Just used for numbering the producer and consumer
for(int i = 0; i < 10; i++) {
pthread_join(write[i], NULL);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);
return 0;
}
Output:
Result:
Thus Successfully provided a solution to Reader – Writer using mutex and semaphore.
EX:NO:6 Dining Philosopher’s Problem
Aim:
Program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
//Function declarations
void *pickup_forks(void * philosopher_number); void *return_forks(void *
philosopher_number); void test(int philosopher_number);
int left_neighbor(int philosopher_number); int right_neighbor(int
philosopher_number); double think_eat_time(void);
void think(double think_time);
void eat(double eat_time);
//Mutex lock.
pthread_mutex_t mutex;
//Condition variables.
pthread_cond_t cond_vars[PHILOSOPHER_NUM];
//Initialize arrays.
int i;
for(i = 0; i < PHILOSOPHER_NUM; i++)
{
state[i] = THINKING;
pthread_cond_init(&cond_vars[i], NULL);
meals_eaten[i] = 0;
}
//Initialize the mutex lock.
pthread_mutex_init(&mutex, NULL);
//Join the threads.
for(i = 0; i < PHILOSOPHER_NUM; i++)
{
pthread_join(philos_thread_ids[i], NULL);
}
//Create threads for the philosophers.
for(i = 0; i < PHILOSOPHER_NUM; i++)
{
pthread_create(&philos_thread_ids[i], NULL, pickup_forks, (void *)&i);
}
sleep(run_time);
for(i = 0; i < PHILOSOPHER_NUM; i++)
{
pthread_cancel(philos_thread_ids[i]);
}
//Print the number of meals that each philosopher ate.
for(i = 0; i < PHILOSOPHER_NUM; i++)
{
printf("Philosopher %d: %d meals\n", i, meals_eaten[i]);
}
}
return 0;
}
void *pickup_forks(void * philosopher_number)
{
int loop_iterations = 0;
int pnum = *(int *)philosopher_number;
while(meals_eaten[pnum] < MAX_MEALS)
{
printf("Philosoper %d is thinking.\n", pnum);
think(think_eat_time());
pthread_mutex_lock(&mutex);
state[pnum] = HUNGRY;
test(pnum);
while(state[pnum] != EATING)
{
pthread_cond_wait(&cond_vars[pnum], &mutex);
}
pthread_mutex_unlock(&mutex);
(meals_eaten[pnum])++;
eat(think_eat_time());
return_forks((philosopher_number));
loop_iterations++;
}
}
void *return_forks(void * philosopher_number)
{
pthread_mutex_lock(&mutex);
int pnum = *(int *)philosopher_number;
state[pnum] = THINKING;
test(left_neighbor(pnum));
test(right_neighbor(pnum));
pthread_mutex_unlock(&mutex);
}
int left_neighbor(int philosopher_number)
{
return ((philosopher_number + (PHILOSOPHER_NUM - 1)) % 5);
}
int right_neighbor(int philosopher_number)
{
return ((philosopher_number + 1) % 5);
}
void test(int philosopher_number)
{
if((state[left_neighbor(philosopher_number)] != EATING) &&
(state[philosopher_number] == HUNGRY) &&
(state[right_neighbor(philosopher_number)] != EATING))
{
state[philosopher_number] = EATING;
pthread_cond_signal(&cond_vars[philosopher_number]);
}
}
double think_eat_time(void)
{
return ((double)rand() * (MAX_THINK_EAT_SEC - 1)) / (double)RAND_MAX + 1;
}
void think(double think_time)
{
sleep(think_time);
}
Output:
Result:
Thus Successfully implemented the concepts of Dining Philosophers Problem.
EX:NO:7 Bankers Algorithm for Deadlock avoidance
Aim :
To implement and study Bankers Algorithm for Deadlock Avoidance Problem
Program :
Banker’s Algorithm
#include <stdio.h>
int m, n, i, j, al[10][10], max[10][10], av[10], need[10][10], temp, z, y, p, k;
void main() {
printf("\n Enter no of processes : ");
scanf("%d", &m); // enter numbers of processes
printf("\n Enter no of resources : ");
scanf("%d", &n); // enter numbers of resources
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("\n Enter instances for al[%d][%d] = ", i,j); // al[][] matrix is for allocated
instances scanf("%d", &al[i][j]);
al[i][j]=temp;
}
}
for (i = 0; i < m;
i++) {
for (j = 0; j < n; j++) {printf("\n Enter instances for max[%d][%d] = ", i,j); // max[][]
matrix is for max instances
scanf("%d", &max[i][j]);
}
}
for (i = 0; i < n; i++) {
printf("\n Available Resource for av[%d] = ",i); // av[] matrix is for available instances
scanf("%d", &av[i] );
}
// Print allocation values
printf("Alocation Values :\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {printf(" \t %d", al[i][j]); // printing allocation matrix
}
printf("\n");
}
printf("\n\n");
printf("\n\n");
Output :
lO M oA R cP S D| 2 81 1 40 20
Result :
Aim :
Program :
FCFS Scheduling
#include <stdio.h>
typedef struct fcfs
{
int process; //Process
Number int burst; //Burst
Time
int arrival; //Arrival Time
int tat; //Turn Around
Time int wt; //Waiting
Time
}fcfs;
int sort(fcfs [], int);
int main()
{
int n, i, temp = 0, AvTat = 0, AvWt = 0;
printf ("Enter the number of processes: ");
scanf ("%d", &n);
fcfs arr[n]; //Array of type
fcfs int tct[n];
for (i = 0; i < n; i++)
{
arr[i].process = i;
printf ("Enter the process %d data\n", arr[i].process);
printf ("Enter CPU Burst: ");
scanf ("%d", &(arr[i].burst));
printf ("Enter the arrival time:
"); scanf ("%d",
&(arr[i].arrival));
}
//Sorting the processes according to their arrival
time sort(arr, n);
printf ("Process\t\tBurst Time\tArrival Time\tTurn Around Time\tWaiting
Time\n");
for (i = 0; i < n; i++)
{
tct[i] = temp + arr[i].burst;
temp = tct[i];
lO M oA R cP S D| 2 81 1 40 20
//Bubble Sort
int sort(fcfs arr[], int n)
{
int i, j;
fcfs k;
SJF Scheduling
#include <stdio.h>
int main()
{
int A[100][4]; // Matrix for storing Process Id, Burst
// Time, Average Waiting Time & Average
// Turn Around
Time. int i, j, n, total = 0,
index, temp; float avg_wt,
avg_tat;
printf("Enter number of process: ");
scanf("%d", &n);
printf("Enter Burst Time:\n");
// User Input Burst Time and alloting Process
Id. for (i = 0; i < n; i++) {
printf("P%d: ", i + 1);
scanf("%d",
&A[i][1]); A[i][0]
= i + 1;
}
// Sorting process according to their Burst
Time. for (i = 0; i < n; i++) {
index = i;
for (j = i + 1; j < n; j++)
if (A[j][1] < A[index][1])
index = j;
temp = A[i][1];
A[i][1] = A[index][1];
A[index][1] = temp;
temp = A[i][0];
lO M oA R cP S D| 2 81 1 40 20
A[i][0] = A[index][0];
A[index][0] = temp;
}
A[0][2] = 0;
// Calculation of Waiting Times for
(i = 1; i < n; i++) {
A[i][2] = 0;
for (j = 0; j < i; j++)
A[i][2] += A[j][1];
total += A[i][2];
}
avg_wt = (float)total / n;
total = 0;
printf("P BT WT TAT\n");
// Calculation of Turn Around Time and printing the
// data.
for (i = 0; i < n; i++) {
A[i][3] = A[i][1] + A[i][2];
total += A[i][3];
printf("P%d %d %d %d\n", A[i][0],
A[i][1], A[i][2], A[i][3]);
}
avg_tat = (float)total / n;
printf("Average Waiting Time= %f", avg_wt);
printf("\nAverage Turnaround Time= %f", avg_tat);
}
Output :
Result :
Priority Scheduling
#include<stdio.h>
#define max 10
int main()
{
int i,j,n,bt[max],p[max],wt[max],tat[max],pr[max],total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter Total Number of Process:");
scanf("%d",&n);
printf("\nEnter Burst Time and Priority For ");
for(i=0;i<n;i++)
{
printf("\nEnter Process %d: ",i+1);
scanf("%d",&bt[i]);
scanf("%d",&pr[i]);
p[i]=i+1;
}
for(i=0;i<n;i++)
{ pos=i;
for(j=i+1;j<n;j++)
{
if(pr[j]<pr[pos])
pos=j;
} temp=pr[i];
pr[i]=pr[pos];
pr[pos]=temp;
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=total/n;
total=0;
lO M oA R cP S D| 2 81 1 40 20
Output :
lO M oA R cP S D| 2 81 1 40 20
#include<stdio.h>
int main()
{
//Input no of processed
int n;
printf("Enter Total Number of Processes:");
scanf("%d", &n);
int wait_time = 0, ta_time = 0, arr_time[n], burst_time[n], temp_burst_time[n];
int x = n;
Output :
Result :
Aim :
Program :
#include <stdio.h>
int a[100],b[100],i,n,z,f,j,pf,h,temp;
void main(){
printf("\nEnter the no. of pages : "); // no. of page
referencing scanf("%d",&n);
printf("\nEnter the size of frame : "); // no. of page
frames scanf("%d",&f);
printf("\n Enter the pages value :\n"); // values of page
referencing for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(i=0;i<f;i++){ // assign values of
page frames 1 innitially
b[i]=-1;
}
i=0;j=0;h=0; // i , j used for loop, h for hit count all initialized to 0
while(i<n){
if(b[i]=-1 && i<f ){ // when frames are empty so for starting
enquee b[i]=a[i];
pf++; // page fault counter
}
else
{
z=0
;
for(j=0;j<f;j++){
temp=b[j];
b[j]=b[j+1]
;
b[j+1]=tem
p;
}
b[f-1]=a[i]; // insert new values
}
} // end else
printf("\n Current Frame: %d \t %d \t %d \n",b[2],b[1],b[0]); // frames value for
every iteration
i++;
} //end while
printf("\n frame at the end :");
for(i=0;i<f;i++){
printf("\n b[%d] = %d",i,b[i]); // frame values at the end
}
printf("\n Page Fault = %d ",pf); // no. of page
faults printf("\n Hit = %d ",h); //
no. of hitS
printf("\n");
}
lO M oA R cP S D| 2 81 1 40 20
Output :
Result :
Aim :
Output :
LFU
st.append(ind)
pf = 'Yes'
fault += 1
else:
st.append(st.pop(st.index(f.index(i))))
pf = 'No'
print(" %d\t\t"%i,end='')
for x in f:
print(x,end=' ')
for x in range(capacity-len(f)):
print(' ',end=' ')
print(" %s"%pf)
print("\nTotal Requests: %d\nPage Faults: %d"%(len(s),fault))
print("Page Hit: ",len(st))
Output
Result :
Aim :
To implement and study Best fit and Worst fit memory management policies
in C.
Program :
# Function to allocate memory to
blocks
# as per Best fit
algorithm
def bestFit(blockSize, m, processSize,
n):
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocated")
# Driver code
if name == ' main ':
print("Enter the Process Size")
l=input()
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)
bestFit(blockSize, m, processSize, n)
Outp
ut :
Algorithm :
1- Input memory blocks and processes with sizes.
2- Initialize all memory blocks as free.
3- Start by picking each process and find the minimum block size that can be assigned to
current process i.e., find min(bockSize[1], blockSize[2],.....blockSize[n]) >
processSize[current], if found then assign it to the current process.
5- If not then leave that process and keep checking the further processes.
Program :
wstIdx = j
elif blockSize[wstIdx] < blockSize[j]:
wstIdx = j
# Driver code
if name == ' main ':
print("Enter the Process Size")
l=input()
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)
worstFit(blockSize, m, processSize, n)
lO M oA R cP S D| 2 81 1 40 20
Output :
Result :
Successfully implemented and studied Best fit and Worst fit memory management policies in
C.
lO M oA R cP S D| 2 81 1 40 20
FCFS(hp,requests):
time = 0
n = len(requests)
pos = hp
time += abs(request-pos)
pos = request
avg_seek_time = time / n
return avg_seek_time
def SSTF(hp,reqs):
requests = reqs.copy()
time = 0
position = hp
n = len(requests)
heap=[]
while len(requests)>0:
for r in requests:
lO M oA R cP S D| 2 81 1 40 20
heappush(heap,(abs(position-r),r))
x=heappop(heap)[1]
time+=abs(position-x)
position=x
requests.remove(x)
heap=[]
avg_seek_time = time/n
return avg_seek_time
def SCAN(hp,reqs):
requests = reqs.copy()
pos = hp
time = 0
end=200
start=0
for i in range(pos,end+1):
if i in requests:
time+=abs(pos-i)
pos=i
requests.remove(i)
time+=abs(pos-end)
pos=end
for i in range(end,start-1,-1):
lO M oA R cP S D| 2 81 1 40 20
if i in requests:
time+=abs(pos-i)
# print(time)
pos=i
requests.remove(i)
print(time)
avg_seek_time = time/n
return avg_seek_time
def C_SCAN(hp,reqs):
requests = reqs.copy()
pos = hp
time = 0
end=200
start=0
for i in range(pos,end+1):
if i in requests:
time+=abs(pos-i)
pos=i
requests.remove(i)
time+=abs(pos-end)
lO M oA R cP S D| 2 81 1 40 20
pos=end
for i in range(start,hp+1):
if i in requests:
time+=abs(pos-i)
pos=i
requests.remove(i)
avg_seek_time
reqs.copy() pos = hp
time = 0 end=max(requests)
start=min(requests)
if i in requests: time+=abs(pos-i)
pos=i
requests.remove(i)
lO M oA R cP S D| 2 81 1 40 20
for i in range(end,start-1,-1):
if i in requests: time+=abs(pos-i)
pos=i
requests.remove(i)
print(time)
= hp
time = 0 end=max(requests)
start=min(requests)
requests.remove(i)
time+=abs(pos-start)
pos=start
for i in range(start,hp+1):
if i in requests:
time+=abs(pos-i)
pos=i
requests.remove(i)
lO M oA R cP S D| 2 81 1 40 20
= int(input())
hp = int(input())
while hp>200:
hp = int(input())
print("Provide positions to visit : max is 200")
requests = []
for i in range(n): req = int(input()) requests.append(req)
print(requests)
#calling the functions
print(" ********** FCFS *********")
print("Avg seek time for fcfs was ", FCFS(hp,requests))
C_SCAN(hp,requests))
LOOK(hp,requests))
C_LOOK(hp,requests))
Output :
Result :
Aim :
To implement and study Sequential and Indexed File Allocation
Algorithm :
Step 1: Start the program.
Step 2: Get the number of memory partition and their sizes.
Step 3: Get the number of processes and values of block size for each process.
Step 4: First fit algorithm searches all the entire memory block until a hole which is big
enough is encountered. It allocates that memory block for the requesting process.
Step 5: Best-fit algorithm searches the memory blocks for the smallest hole which can be
allocated to requesting process and allocates it.
Step 6: Worst fit algorithm searches the memory blocks for the largest hole and allocates it to
the process.
Step 7: Analyses all the three memory management techniques and display the best algorithm
which utilizes the memory resources effectively and efficiently.
Step 8: Stop the program.
Program :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TOTAL_DISK_BLOCKS 32
#define TOTAL_DISK_INODES 8
#ifndef MAX
#define MAX 15
#endif
count = 0;
while (count < Size) {
nextBlock = (rand() % (allocEndBlock - allocStartBlock + 1)) + allocStartBlock;
count = count + 1;
else { count =
0; break;
}
}
}
blockStart = nextBlock;
for (int i = 0; i < Size; i++) {
blockStatus[blockStart + i] = 1;
}
if (count == Size)
return nextBlock; // success
else
return 1; // not successful
}
void main() {
int i = 0, j = 0, numFiles = 0, nextBlock = 0, ret = 1, totalFileSize = 0;
char s[20];
//-- -
char *header[] = {"FILE_fileName", "FILE_SIZE", "BLOCKS_OCCUPIED"};
//numFiles = 3;
for (i = 0; i < numFiles; i++) {
//-- -
printf("\nEnter the name of file #%d: ", i+1);
scanf("%s", fileTable[i].fileName); printf("Enter
the size (kB) of file #%d: ", i+1); scanf("%d",
&fileTable[i].fileSize);
//strcpy(fileTable[i].fileName, "testfile");
srand(1234);
ret = AllocateBlocks(fileTable[i].fileSize);
//-- -
if (ret == 1) {
exit(0);
} else {
fileTable[i].startBlock = ret;
}
}
//-- -
printf("\n%*s %*s %*s\n", -MAX, header[0], -MAX, header[1], MAX, header[2]);
//Seed the pseudo-random number generator used by rand() with the value seed
srand(1234);
//-- -
for (j = 0; j < numFiles; j++) {
printf("\n%*s %*d ", -MAX, fileTable[j].fileName, -MAX, fileTable[j].fileSize);
for(int k=0;k<fileTable[j].fileSize;k++) {
printf("%d%s", fileTable[j].startBlock+k, (k == fileTable[j].fileSize-1) ? "" : "-");
}
}
printf("\nFile allocation completed. Exiting.\n");
}
Output :
lO M oA R cP S D| 2 81 1 40 20
}
}
else{
cout << "\n File in the index is already allocated";
cout << "\n Enter another file to index"; Allotment();
}
cout << "\n Do you want to enter more files?";
cin >> Choice;
if (Choice == 1)
IndexedAllocation();
else
exit(0);
return;
}
int main()
{ cout<<"\n Simulation of Indexed Allocation";
for(int i=0;i<MaximumSizeAvailable;i++){
BlockFiles[i]=0;
BlockIndex[i]=0;
}
IndexedAllocation();
return 0;
}
Output :
Result :
Successfully implemented and studied Sequential and Indexed File Allocation.
lO M oA R cP S D| 2 81 1 40 20
Aim :
To implement and study file organization schemes for single and two level directory
Single-level directory
Program :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct file
{
char fileName[15][20];
char dirName[10];
int fno;
};
struct file dir;
int i, n;
void InsertFile()
{
printf("\n Enter the File name ");
scanf("%s", dir.fileName[dir.fno]);
dir.fno++;
}
void DisplayFiles()
{
printf("\n\n\n\n");
printf("+------------------------+");
printf("\n Directorytfiles \n");
printf("+------------------------+");
printf("\n %s", dir.dirName);
for (i = 0; i < dir.fno; i++)
{
printf("\n tt%s", dir.fileName[i]);
}
printf("\n+------------------------+");
printf("\n\n\n\n");
}
void DeleteFile()
{
char name[20];
printf("\n Enter the file to be deleted : ");
scanf("%s", name);
for (i = 0; i < dir.fno; i++)
{
if (strcmp(dir.fileName[i], name) == 0)
lO M oA R cP S D| 2 81 1 40 20
{
printf("%s is deleted t", dir.fileName[i]);
strcpy(dir.fileName[i], dir.fileName[dir.fno - 1]);
dir.fno--;
}
}
}
void SearchFile()
{
char name[20];
int found = -1;
printf("\n Enter the file to be searched :");
scanf("%s", name);
for (i = 0; i < dir.fno; i++)
{
if (strcmp(dir.fileName[i], name) == 0)
{
printf("\n The File is found at position %d", i + 1);
found = 1;
break;
}
}
if (found == -1)
printf("n the file is not found ");
}
int main()
{
int op;
dir.fno = 0;
printf("\n Enter the directory name : ");
scanf("%s", dir.dirName);
while (1)
{
printf("\n choose the option \n1:Insert a file\n2:Display Files\n3:Delete File\n4:Search
File\n5:Exitn>>");
scanf("%d", &op);
switch (op)
{
case 1:
InsertFile();
break;
case 2:
DisplayFiles();
break;
case 3:
DeleteFile();
break;
lO M oA R cP S D| 2 81 1 40 20
case 4:
SearchFile();
break;
case 5:
exit(0);
}
}
return 0;
}
Output :
lO M oA R cP S D| 2 81 1 40 20
Two-level directory
Program :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir[10];
void main()
{
int i,ch,dcnt,k; char
f[30], d[30]; dcnt=0;
while(1)
{
printf("\n\n 1. Create Directory\t 2. Create File\t 3. Delete File"); printf("\n 4.
Search File \t \t 5. Display \t 6. Exit \t Enter your choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n Enter name of directory -- ");
scanf("%s", dir[dcnt].dname); dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created");
break;
case 2: printf("\n Enter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",dir[i].fname[dir[i].fcnt]);
dir[i].fcnt++;
printf("File created");
break;
}
if(i==dcnt)
printf("Directory %s not found",d);
break;
case 3: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
lO M oA R cP S D| 2 81 1 40 20
Output
Result :
Successfully implemented file organization schemes for single level and two level directory.