0% found this document useful (0 votes)
24 views66 pages

Record Os 18mar

Uploaded by

sulochanat7851
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views66 pages

Record Os 18mar

Uploaded by

sulochanat7851
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Exercise1:Steps to install Windows 10

Step 1: Download Windows 10 ISO image from http://windows.microsoft.com/en-us/windows/preview-iso. Read more


about Windows 10 technical preview ISO images.

Step 2: Mount the ISO image as a drive or burn it into a DVD. Optionally, you can create a Windows 10 bootable USB drive.

Step 3: Launch your virtual machine software and create a new virtual machine. You can read more details on how to install
Windows 10 on VMWare Workstation.

Step 4: After you create the virtual machine, follow the steps below to install Windows 10.

Step 5: In the welcome screen, choose your language settings and click the "Next" button to proceed.

Step 6: Accept the license terms and click "Next" to proceed.


Step 7: In the next step, you have to select the drive to install. If you have multiple drives on your computer, you will see them all
there. Choose the correct drive to install. If you are installing Windows 10 over an existing Windows, you may install side by
side on another drive.

Step 8: Installer will copy all the necessary files to the computer and continue with the installation. Depending on your system
configuration, it may take a while (10-20 minutes) to complete the installation.
After successful installation, you will see the Windows welcome screen, which is similar to the Windows 8 theme.

You will be presented with an option to select the Settings. Unless you want to make custom configuration, you can choose
"Express Settings" and proceed.
In the next step, you will be prompted to select One Drive option. If you don't want to integrate One Drive storage for this
computer, you can Turn Off the One Drive options.

The next step is installing some basic apps for your Windows 10 computer. No intervention from your side is necessary.
Windows will automatically install the apps for you. It may take several minutes to complete the installation.

As part of installation, you will need to connect your Microsoft account with your OS to access various services like Microsoft
App Store. You will need to use the same Microsoft account to login to your Windows.

You are all set. In a few minutes, Windows 10 will be configured and will be ready for you to use.
Exercise 2:A-Z Index of the Bash command line for Linux
a

alias Create an alias •

apropos Search Help manual pages (man -k)

apt-get Search for and install software packages (Debian/Ubuntu)

aptitude Search for and install software packages (Debian/Ubuntu)

aspell Spell Checker

awk Find and Replace text, database sort/validate/index

b
basename Strip directory and suffix fromfilenames

bash GNU Bourne-Again SHell

bc Arbitrary precision calculatorlanguage

bg Send to background

bind Set or display readline key and function bindings•

break Exit from a loop •

builtin Run a shell builtin

bzip2 Compress or decompress named file(s)

c
cal Display a calendar

case Conditionally perform a command

cat Concatenate and print (display) the content offiles

cd Change Directory

cfdisk Partition table manipulator for Linux

chattr Change file attributes on a Linux filesystem


chgrp Change group ownership

chmod Change access permissions

chown Change file owner andgroup

chroot Run a command with a different rootdirectory

chkconfig System services (runlevel)

cksum Print CRC checksum and bytecounts

clear Clear terminal screen

cmp Compare two files

comm Compare two sorted files line by line

command Run a command - ignoring shell functions

continue Resume the next iteration of a loop

cp Copy one or more files to another location

cron Daemon to execute scheduled commands

crontab Schedule a command to run at a later time

csplit Split a file into context-determined pieces

curl Transfer data from or to a server

cut Divide a file into several parts

d
date Display or change the date &time

dc Desk Calculator

dd Convert and copy a file, write disk headers, bootrecords

ddrescue Data recovery tool

declare Declare variables and give them attributes•

df Display free disk space

diff Display the differences between twofiles

diff3 Show differences among three files

dig DNS lookup


dir Briefly list directorycontents

dircolors Colour setup for `ls'

dirname Convert a full pathname to just a path

dirs Display list of remembered directories

dmesg Print kernel & driver messages

du Estimate file space usage

echo Display message on screen

egrep Search file(s) for lines that match an extendedexpression

eject Eject removable media

enable Enable and disable builtin shell commands

env Environment variables

eval Evaluate severalcommands/arguments

exec Execute a command

exit Exit the shell

expect Automate arbitrary applications accessed over aterminal

expand Convert tabs to spaces

export Set an environment variable

expr Evaluate expressions

false Do nothing, unsuccessfully

fdformat Low-level format a floppydisk

fdisk Partition table manipulator forLinux

fg Send job to foreground

fgrep Search file(s) for lines that match a fixedstring

file Determine file type


find Search for files that meet a desiredcriteria
fmt Reformat paragraph text

fold Wrap text to fit a specified width.

for Expand words, and execute commands

format Format disks or tapes

free Display memory usage

fsck File system consistency check andrepair

ftp File Transfer Protocol

function Define FunctionMacros

fuser Identify/kill the process that is accessing a file

gawk Find and Replace text withinfile(s)

getopts Parse positional parameters

grep Search file(s) for lines that match a givenpattern

groupadd Add a user security group

groupdel Delete a group

groupmod Modify a group

groups Print group names a user is in

gzip Compress or decompress named file(s)

hash Remember the full pathname of a nameargument

head Output the first part of file(s)

help Display help for a built-in command

history Command History

hostname Print or set system name

iconv Convert the character set of afile


id Print user and group id's
if Conditionally perform acommand

ifconfig Configure a network interface

install Copy files and set attributes

ip Routing, devices and tunnels

jobs List active jobs

join Join lines on a common field

kill Kill a process by specifying its PID

killall Kill processes by name

let Perform arithmetic on shell variables

link Create a link to a file

ln Create a symbolic link to afile

local Create a function variable

locate Find files

logname Print current loginname

logout Exit a login shell

look Display lines beginning with a givenstring

lpc Line printer control program

lpr Off line print

lprint Print a file

lprintd Abort a print job

lprintq List the print queue

ls List information aboutfile(s)\


lsof List open files
m
make Recompile a group ofprograms

man Help manual

mkdir Create new folder(s)

mkfifo Make FIFOs (namedpipes)

mkfile Make a file

mktemp Make a temporary file

more Display output one screen at atime

most Browse or page through a textfile


mount Mount a file system
mtools Manipulate MS-DOS files
mtr Network diagnostics(traceroute/ping)
mv Move or rename files or directories
mmv Mass Move and rename (files)

nc Netcat, read and write data acrossnetworks

netstat Networking connections/stats

nice Set the priority of a command or job

nl Number lines and write files

nohup Run a command immune tohangups

notify-send Send desktopnotifications

nslookup Query Internet name servers interactively

open Open a file in its defaultapplication

op Operator access

passwd Modify a user password


paste Merge lines of files
ping Test a networkconnection

pgrep List processes by name

pkill Kill processes by name

popd Restore the previous value of the currentdirectory

pr Prepare files for printing

printcap Printer capability database

printenv Print environment variables

printf Format and print data

ps Process status

pushd Save and then change the current directory

pv Monitor the progress of data through apipe

pwd Print Working Directory

q
quota Display disk usage and limits

quotacheck Scan a file system for diskusage

ram ram disk device

rar Archive files with compression

rcp Copy files between two machines

read Read a line from standard input

readarray Read from stdin into an array variable

readonly Mark variables/functions as readonly

reboot Reboot the system

rename Rename files

renice Alter priority of running processes

remsync Synchronize remote files via email

return Exit a shell function


rev Reverse lines of a file

rm Remove files

rmdir Remove folder(s)

screen Multiplex terminal, run remote shells viassh

scp Secure copy (remote file copy)

sdiff Merge two files interactively

sed Stream Editor

select Accept keyboard input

seq Print numericsequences

set Manipulate shell variables andfunctions

sftp Secure File Transfer Program

shift Shift positionalparameters


shopt Shell Options

shutdown Shutdown or restart linux

sleep Delay for a specifiedtime

slocate Find files

sort Sort text files

source Run commands from a file '.'

split Split a file into fixed-size pieces

ss Socket Statistics

ssh Secure Shell client (remote loginprogram)

su Substitute user identity

sudo Execute a command as anotheruser

sum Print a checksum for a file


suspend Suspend execution of this shell
t

tail Output the last part of file

tar Store, list or extract files in anarchive

tee Redirect output to multiple files

test Evaluate a conditionalexpression

time Measure Program running time

timeout Run a command with a time limit

times User and system times

touch Change file timestamps

top List processes running on the system

tput Set terminal-dependent capabilities, color,position

traceroute Trace Route to Host

trap Execute a command when the shell receives a signal•

tr Translate, squeeze, and/or delete characters

true Do nothing, successfully

tsort Topological sort

tty Print filename of terminal onstdin

type Describe a command

ulimit Limit user resources

umask Users file creation mask

umount Unmount a device

Unalias Remove an alias

uniq Uniquify files

units Convert units from one scale to another

until Execute commands (until error)

uptime Show uptime


useradd Create new user account

userdel Delete a user account

usermod Modify user account

users List users currently logged in

V
v Verbosely list directory contents (`ls -l -b')

vdir Verbosely list directory contents (`ls -l -b')

vi Text Editor

vmstat Report virtual memory statistics

w
w Show who is logged on and what they are doing

wait Wait for a process to complete

watch Execute/display a program periodically

wc Print byte, word, and line counts

whereis Search the user's $path, man pages and source files

for a program
which Search the user's $path for a program file
while Execute commands
who Print all usernames currently logged in
whoami Print the current user id and name (`id -un')
wget Retrieve web pages or files via HTTP, HTTPS or FTP
write Send a message to another user

x
xargs Execute utility, passing constructed argument list(s)
xdg-open Open a file or URL in the user's preferred application
xz Compress or decompress .xz and .lzma files

yes Print a string until interrupted


zip Package and compress (archive) files.
. Run a command script in the current shell

!! Run the last command again


### Comment / Remark
Exercise 3:Process Management using system
calls:Fork,Exit,Getpid,Wait,Close

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
pid_t pid;

// Fork a child process


pid = fork();

if (pid < 0) { // Error occurred


fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) { // Child process
printf("Child process:\n");
printf("PID: %d\n", getpid());
printf("Parent PID: %d\n", getppid());
printf("Exiting child process\n");
exit(0);
} else { // Parent process
printf("Parent process:\n");
printf("PID: %d\n", getpid());
printf("Child PID: %d\n", pid);
printf("Waiting for child process to finish...\n");

// Wait for the child process to finish


int status;
wait(&status);

printf("Child process finished\n");


}

printf("Exiting parent process\n");


return 0;
}

Output:
Child process:
PID: [child_pid]
Parent PID: [parent_pid]
Exiting child process
Parent process:
PID: [parent_pid]
Child PID: [child_pid]
Waiting for child process to finish...
Child process finished
Exiting parent process
Exercise 4:
CPU SCHEDULINGALGORITHMS

A. FIRST COME FIRST SERVE:


AIM: To write a c program to simulate the CPU scheduling algorithm First Come First Serve
(FCFS)

DESCRIPTION:
To calculate the average waiting time using the FCFS algorithm first the waiting time of the first process
is kept zero and the waiting time of the second process is the burst time of the first process and the
waiting time of the third process is the sum of the burst times of the first and the second process and so
on. After calculating all the waiting times the average waiting time is calculated as the average of all
the waiting times. FCFS mainly says first come first serve the algorithm which camefirst will be served
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 name and the burst time
Step 4: Set the waiting of the first process as ‗0‘and its burst time as its turnaround
timeStep 5: for each process in the Ready Q calculate a).Waiting
time (n) = waiting time (n-1) + Burst time (n-1)b). Turnaround
time (n)= waiting time(n)+Burst time(n)
Step 6: Calculate
a) Average waiting time = Total waiting Time / Number of process
b) Average Turnaround time = Total Turnaround Time / Number ofprocess
Step 7: Stop the process

SOURCE CODE :

#include<stdio.h>
int main()
{
int bt[20], wt[20], tat[20], i, n;
float wtavg, tatavg;
printf("\n Enter the number of processes -- ");
scanf("%d", &n);

for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\t PROCESS \t BURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i], tat[i]);
printf("\n Average Waiting Time --%f", wtavg/n);
printf("\n Average Turnaround Time -- %f", tatavg/n);
}
INPUT:
Enter the number of processes – 3
Enter Burst Time for Process 0 -- 24
Enter Burst Time for Process 1 -- 3
Enter Burst Time for Process 2 – 3

Expected Output:
PROCESS BURST TIME WAITING TIME TURNAROUND TIME

P0 24 0 24
P1 3 24 27
P2 3 27 30
Average Waiting Time --17.000000
Average Turnaround Time -- 27.000000
OUTPUT:
B. SHORTEST JOB FIRST:
AIM: To write a program to stimulate the CPU scheduling algorithm Shortest job first (Non- Preemption)

DESCRIPTION:
To calculate the average waiting time in the shortest job first algorithm the sorting of the process based on
their burst time in ascending order then calculate the waiting time of each process as the sum of the bursting
times of all the process previous or before to that process.

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: Sort the processes names based on their Burt time
Step 7: For each process in the ready queue, calculate
A) Waiting time(n)= waiting time (n-1) + Burst time (n-1)

B) Turnaround time (n)= waiting time(n)+Burst time(n)


Step 8: Calculate
A)Average waiting time = Total waiting Time / Number of process
a) Average Turnaround time = Total Turnaround Time / Number ofprocessStep 9: Stop
the process

SOURCE CODE :
#include<stdio.h>

int main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp;
float wtavg, tatavg;
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
for(i=0;i<n;i++) for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=p[i];
p[i]=p[k];
p[k]=temp;
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);

}
INPUT:
Enter the number of processes --4
Enter Burst Time for Process 0 --6
Enter Burst Time for Process 1 --8
Enter Burst Time for Process 2 --7
Enter Burst Time for Process 3 –3
Expected Output:
PROCESS BURST TIME WAITING TIME TURNAROUND TIME
P0 6 3 9
P1 8 16 24
P2 7 9 16
P3 3 0 3

Average Waiting Time -- 7.000000

Average Turnaround Time -- 13.000000

OUTPUT:
C.ROUND ROBIN:
AIM: To simulate the CPU scheduling algorithm round-robin.

DESCRIPTION:
To aim is to calculate the average waiting time. There will be a time slice, each process should be executed
within that time-slice and if not it will go to the waiting state so first check whether the burst time is
less than the time-slice. If it is less than it assign the waiting time to the sum of the total times. If it is
greater than the burst-time then subtract the time slot from the actual burst time and increment it by time-
slot and the loop continues until all the processes are completed.

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 timeof process(n-1 ) + the
time difference in getting the CPU fromprocess(n-1)
b) Turnaround 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
a) Average Turnaround time = Total Turnaround Time / Number ofprocessStep 8: Stop the process
SOURCE CODE

#include<stdio.h>

int main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
printf("Enter the no of processes -- ");
scanf("%d",&n);for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i]) max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i]; att+=tat[i];
awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is --%f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
}

INPUT:
Enter the no of processes – 3
Enter Burst Time for process 1 – 24Enter
Burst Time for process 2 -- 3 Enter Burst
Time for process 3 – 3 Enter the size of
time slice – 3 Expected Output:
The Average Turnaround time is -- 15.000000The
Average Waiting time is --5.000000

PROCESS BURST TIME WAITING TIME TURNAROUND TIME


1 24 6 30
2 3 3 6
3 3 6 9
D.PRIORITY:
AIM: To write a c program to simulate the CPU scheduling priority algorithm.

DESCRIPTION:
To calculate the average waiting time in the priority algorithm, sort the burst times according to their
priorities and then calculate the average waiting time of the processes. The waiting time ofeach process
is obtained by summing up the burst times of all the previous processes.

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 timeStep 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 turnaround timeStep 6:Arrange the
processes based on process priority
Step 7: For each process in the Ready Q calculate
a) Waiting time(n)= waiting time (n-1) + Burst time (n-1)
b) Turnaround time (n)= waiting time(n)+Burst time(n)
Step 8: Calculate
a) Average waiting time = Total waiting Time / Number of process
Average Turnaround time = Total Turnaround Time / Number of process Print theresults in an order.
Step9:Stop

SOURCE CODE :

#include<stdio.h>int

main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;float
awt=0,att=0,temp=0;
printf("Enter the no of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0]; for(i=1;i<n;i++)
if(max<bu[i]) max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++) if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];
att+=tat[i]; awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is --%f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
}
INPUT:
Enter the no of processes – 3
Enter Burst Time for process 1 – 24Enter
Burst Time for process 2 -- 3 Enter Burst
Time for process 3 – 3 Enter the size of
time slice – 3

Expected Output:
The Average Turnaround time is -- 15.000000The
Average Waiting time is --5.000000
PROCESS BURST TIME WAITING TIME TURNAROUND TIME
1 24 6 30
2 3 3 6
3 3 6 9
Exercise 5:Illustrate the inter process communication strategy
Program code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

#define BUFFER_SIZE 25

int main() {
int pipefds[2];
pid_t pid;
char buffer[BUFFER_SIZE];
char message[] = "Hello, IPC!";

// Create pipe
if (pipe(pipefds) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}

// Fork a child process


pid = fork();

if (pid < 0) { // Error occurred


perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) { // Child process
// Close the write end of the pipe in the child
close(pipefds[1]);

// Read from the pipe


read(pipefds[0], buffer, BUFFER_SIZE);
printf("Child process received: %s\n", buffer);

// Close the read end of the pipe in the child


close(pipefds[0]);

exit(EXIT_SUCCESS);
} else { // Parent process
// Close the read end of the pipe in the parent
close(pipefds[0]);

// Write to the pipe


write(pipefds[1], message, sizeof(message));
// Close the write end of the pipe in the parent
close(pipefds[1]);

// Wait for the child process to finish


wait(NULL);
}

return 0;
}

Output:
Child process received: Hello, IPC!
Exercise 6:
AIM: To Write a C program to simulate producer-consumer problem using semaphores.

DESCRIPTION
Producer consumer problem is a synchronization problem. There is a fixed size buffer where the
producer produces items and that is consumed by a consumer process. One solution to the producer-
consumer problem uses shared memory. To allow producer and consumer processes to run
concurrently, there must be available a buffer of items that can be filled by the producer and emptied
by the consumer. This buffer will reside in a region of memory that is shared by the producer and
consumer processes. The producer and consumer must be synchronized, so that the consumer does not
try to consume an item that has not yet been produced.

PROGRAM
#include<stdio.h>
int main()
{
int buffer[10], bufsize, in, out, produce, consume,
choice=0; in = 0;
out = 0;
bufsize = 10;
while(choice !=3)
{
printf(“\n1. Produce \t 2. Consume \t3. Exit”);
printf(“\nEnter your choice: ”);
scanf(“%d”,&choice);
switch(choice) {
case 1: if((in+1)%bufsize==out)
printf(“\nBuffer is Full”);
else
{
printf(“\nEnter the value: “);
scanf(“%d”, &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
break;;;

case 2: if(in == out)


printf(“\nBuffer is Empty”);
else
{
consume = buffer[out];
printf(“\nThe consumed value is %d”, consume);
out = (out+1)%bufsize;
}
break;
} } }
OUTPUT
1. Produce 2. Consume 3. ExitEnter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. ExitEnter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. ExitEnter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. ExitEnter your choice: 3
Exercise 7:
DEAD LOCK AVOIDANCE

AIM: Simulate bankers algorithm for Dead Lock Avoidance (Banker‘s Algorithm)

DESCRIPTION:
Deadlock is a situation where in two or more competing actions are waiting f or the other to finish, and

thus neither ever does. When a new process enters a system, it must declare the maximum number of
instances of each resource type it needed. This number may exceed the total number of resources in the
system. When the user request a set of resources, the system must determine whether the allocation of
each resources will leave the system in safe state. If it will the resources are allocation; otherwise the
process must wait until some other process release the resources.
Data structures Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj Need: If
Need[I, j]=k, Pi may need k more instances of resource type Rj, Need[I, j]=Max[I, j]- Allocation[I, j];
Safety Algorithm

Work and Finish be the vector of length m and n respectively, Work=Available and Finish[i] =False.

1. Find an i such that both


2. Finish[i] =False Need<=Work If no such I exists go to step 4.
3. work= work + Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state. Resource request algorithm
Let Request i be request vector for the process Pi, If request i=[j]=k, then process Pi wants k
instances of resource type Rj.

1. if Request<=Need I go to step 2. Otherwise raise an error condition.


2. if Request<=Available go to step 3. Otherwise Pi must since the resources are available.

3. Have the system pretend to have allocated the requested resources to process Pi by modifying the
state as follows;
Available=Available-Request I; Allocation I=Allocation +Request I; Need i=Need i- Request I;
If the resulting resource allocation state is safe, the transaction is completed and process Pi is
allocated its resources. However if the state is unsafe, the Pi must wait for Request i and the old
resource-allocation state is restored.

ALGORITHM:
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safestate.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety.
9. or not if we allow the request.
10. stop the program.
11. End.
SOURCE CODE :

#include <stdio.h>

#define MAX_PROCESSES 10
#define MAX_RESOURCES 10

int available[MAX_RESOURCES];
int maximum[MAX_PROCESSES][MAX_RESOURCES];
int allocation[MAX_PROCESSES][MAX_RESOURCES];
int need[MAX_PROCESSES][MAX_RESOURCES];
int num_processes, num_resources;

// Function to check if the current state is safe or not


int isSafe(int processes[], int available[], int max[][MAX_RESOURCES], int alloc[][MAX_RESOURCES]) {
int work[MAX_RESOURCES];
int finish[MAX_PROCESSES] = {0}; // Initialize finish array to false

// Copy available array to work


for (int i = 0; i < num_resources; i++) {
work[i] = available[i];
}

int count = 0;
while (count < num_processes) {
int found = 0;
for (int i = 0; i < num_processes; i++) {
if (finish[i] == 0) {
int j;
for (j = 0; j < num_resources; j++) {
if (need[i][j] > work[j]) {
break;
}
}
if (j == num_resources) {
for (int k = 0; k < num_resources; k++) {
work[k] += alloc[i][k];
}
finish[i] = 1;
processes[count++] = i;
found = 1;
}
}
}
if (!found) {
break; // If no process found, break the loop
}
}

if (count == num_processes) {
return 1; // If all processes are finished, return true (safe state)
} else {
return 0; // If some processes are unfinished, return false (unsafe state)
}
}

// Function to request resources


void requestResources(int process_num, int request[]) {
// Check if the request is within need and available resources
for (int i = 0; i < num_resources; i++) {
if (request[i] > need[process_num][i] || request[i] > available[i]) {
printf("Error: Requested resources exceed the need or available resources.\n");
return;
}
}

// Simulate allocation of resources


for (int i = 0; i < num_resources; i++) {
available[i] -= request[i];
allocation[process_num][i] += request[i];
need[process_num][i] -= request[i];
}

// Check if the current state is still safe after allocation


int processes[MAX_PROCESSES];
if (isSafe(processes, available, maximum, allocation)) {
printf("Request granted. New available resources:\n");
for (int i = 0; i < num_resources; i++) {
printf("%d ", available[i]);
}
printf("\n");
} else {
// If the state is unsafe after allocation, rollback changes
for (int i = 0; i < num_resources; i++) {
available[i] += request[i];
allocation[process_num][i] -= request[i];
need[process_num][i] += request[i];
}
printf("Request denied. Granting the request will result in an unsafe state.\n");
}
}

int main() {
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
printf("Enter the number of resources: ");
scanf("%d", &num_resources);

printf("Enter the maximum resources that each process can claim:\n");


for (int i = 0; i < num_processes; i++) {
printf("For process %d: ", i);
for (int j = 0; j < num_resources; j++) {
scanf("%d", &maximum[i][j]);
need[i][j] = maximum[i][j];
}
}

printf("Enter the available resources: ");


for (int i = 0; i < num_resources; i++) {
scanf("%d", &available[i]);
}

printf("Enter the current allocation of resources for each process:\n");


for (int i = 0; i < num_processes; i++) {
printf("For process %d: ", i);
for (int j = 0; j < num_resources; j++) {
scanf("%d", &allocation[i][j]);
need[i][j] -= allocation[i][j];
}
}

// Interactive resource request handling


int choice;
do {
printf("\nEnter the process number to request resources (-1 to exit): ");
scanf("%d", &choice);
if (choice != -1) {
int request[MAX_RESOURCES];
printf("Enter the requested resources for process %d: ", choice);
for (int i = 0; i < num_resources; i++) {
scanf("%d", &request[i]);
}
requestResources(choice, request);
}
} while (choice != -1);

return 0;
}

Expected Output:
Enter the number of processes: 3
Enter the number of resources: 4

Enter the maximum resources that each process can claim:


For process 0: 7 5 3 2
For process 1: 3 2 2 1
For process 2: 9 0 2 2
Enter the available resources: 3 3 2 2

Enter the current allocation of resources for each process:


For process 0: 0 1 0 0
For process 1: 2 0 0 1
For process 2: 3 0 2 0

Enter the process number to request resources (-1 to exit): 0


Enter the requested resources for process 0: 0 1 1 0
Request granted. New available resources:
3212

Enter the process number to request resources (-1 to exit): 1


Enter the requested resources for process 1: 0 1 0 1
Request denied. Granting the request will result in an unsafe state.

Enter the process number to request resources (-1 to exit): 2


Enter the requested resources for process 2: 3 0 2 0
Request denied. Granting the request will result in an unsafe state.

Enter the process number to request resources (-1 to exit): -1

Exercise 8: Write a C program to implement Deadlock Detection


Algorithm.

Program code:
#include <stdio.h>

#define MAX_PROCESSES 10
#define MAX_RESOURCES 10

int n_processes, n_resources;


int allocation[MAX_PROCESSES][MAX_RESOURCES];
int request[MAX_PROCESSES][MAX_RESOURCES];
int available[MAX_RESOURCES];
int marked[MAX_PROCESSES];

void initialize() {
printf("Enter the number of processes: ");
scanf("%d", &n_processes);
printf("Enter the number of resources: ");
scanf("%d", &n_resources);

printf("Enter the allocation matrix:\n");


for (int i = 0; i < n_processes; ++i) {
for (int j = 0; j < n_resources; ++j) {
scanf("%d", &allocation[i][j]);
}
}

printf("Enter the request matrix:\n");


for (int i = 0; i < n_processes; ++i) {
for (int j = 0; j < n_resources; ++j) {
scanf("%d", &request[i][j]);
}
}

printf("Enter the available resources: ");


for (int i = 0; i < n_resources; ++i) {
scanf("%d", &available[i]);
}
}

void detect_deadlock() {
int work[MAX_RESOURCES];
int finish[MAX_PROCESSES] = {0};

// Initialize work to available


for (int i = 0; i < n_resources; ++i) {
work[i] = available[i];
}

// Find an unfinished process that can be satisfied with current resources


int count = 0;
while (count < n_processes) {
int found = 0;
for (int i = 0; i < n_processes; ++i) {
if (!finish[i]) {
int j;
for (j = 0; j < n_resources; ++j) {
if (request[i][j] > work[j])
break;
}
if (j == n_resources) {
// Process i can be satisfied
finish[i] = 1;
found = 1;
++count;
for (int k = 0; k < n_resources; ++k) {
work[k] += allocation[i][k];
}
}
}
}
if (!found) {
printf("Deadlock detected!\n");
return;
}
}

printf("No deadlock detected.\n");


}

int main() {
printf("Deadlock Detection Algorithm\n");
initialize();
detect_deadlock();
return 0;
}

Output:
Number of processes: 3
Number of resources: 3
Allocation matrix:
201
010
121
Request matrix:
100
002
000
Available resources: 1 1 1

Now, the program will output:

Deadlock detected!
Exercise 9:Write C program to implement Threading.

Program code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // Header file for sleep()
#include <pthread.h>

// Function executed by the thread


void *myThreadFun(void *vargp) {
sleep(1); // Sleep for 1 second
printf("Printing GeeksQuiz from Thread\n");
return NULL;
}

int main() {
pthread_t thread_id;
printf("Before Thread\n");

// Create a new thread


pthread_create(&thread_id, NULL, myThreadFun, NULL);

// Wait for the thread to finish


pthread_join(thread_id, NULL);
printf("After Thread\n");
exit(0);
}

Output:
Before Thread
Printing GeeksQuiz from Thread
After Thread

Exercise 10:Implement the paging technique using C program

Program code:
#include <stdio.h>
#include <stdlib.h>

#define NUM_FRAMES 4
#define NUM_PAGES 10
#define PAGE_SIZE 1024 // Page size in bytes

int main() {
int frames[NUM_FRAMES] = {-1, -1, -1, -1}; // Represents frames, -1 indicates empty frame
int pages[NUM_PAGES]; // Represents pages
int i, j, page, frame, offset, physical_address;

// Initialize pages with data


for (i = 0; i < NUM_PAGES; i++) {
pages[i] = i * PAGE_SIZE;
}

// Accessing pages
printf("Page\tFrame\tOffset\tPhysical Address\n");
for (i = 0; i < NUM_PAGES; i++) {
page = i;
frame = page % NUM_FRAMES;
offset = page * PAGE_SIZE % PAGE_SIZE;
physical_address = frames[frame] * PAGE_SIZE + offset;

if (frames[frame] == -1) {
frames[frame] = i; // Allocate frame for page
}
printf("%d\t%d\t%d\t%d\n", page, frame, offset, physical_address);
}

return 0;
}

Output:

Page Frame Offset Physical Address


0 0 0 0
1 1 1024 1024
2 2 2048 2048
3 3 3072 3072
4 0 0 4096
5 1 1024 5120
6 2 2048 6144
7 3 3072 7168
8 0 0 8192
9 1 1024 9216

Exercise 11:
MEMORY ALLOCATION TECHNIQUES

AIM: To Write a C program to simulate the following contiguous memory allocation techniques
a) Worst-fit b) Best-fit c) First-fit

PROGRAM

WORST-FIT
#include <stdio.h>
#include <stdlib.h>

#define MAX_BLOCKS 100


#define MAX_PROCESS 100

// Structure to represent a block of memory


typedef struct Block {
int id;
int size;
int allocated;
} Block;

// Structure to represent a process


typedef struct Process {
int id;
int size;
} Process;
// Function prototypes
void worstFit(Block blocks[], int m, Process processes[], int n);
void printAllocation(Block blocks[], int m, Process processes[], int n);

int main() {
Block blocks[MAX_BLOCKS];
Process processes[MAX_PROCESS];
int m, n;

// Input for number of blocks


printf("Enter the number of memory blocks: ");
scanf("%d", &m);

// Input for memory blocks


printf("Enter the size of memory blocks:\n");
for (int i = 0; i < m; i++) {
printf("Block %d: ", i + 1);
scanf("%d", &blocks[i].size);
blocks[i].id = i + 1;
blocks[i].allocated = 0;
}

// Input for number of processes


printf("Enter the number of processes: ");
scanf("%d", &n);

// Input for processes


printf("Enter the size of processes:\n");
for (int i = 0; i < n; i++) {
printf("Process %d: ", i + 1);
scanf("%d", &processes[i].size);
processes[i].id = i + 1;
}

// Perform worst fit allocation


worstFit(blocks, m, processes, n);

// Print allocation
printf("\nMemory allocation after worst fit:\n");
printAllocation(blocks, m, processes, n);

return 0;
}

// Function to perform worst fit memory allocation


void worstFit(Block blocks[], int m, Process processes[], int n) {
for (int i = 0; i < n; i++) {
int worstIdx = -1;
for (int j = 0; j < m; j++) {
if (blocks[j].allocated == 0 && blocks[j].size >= processes[i].size) {
if (worstIdx == -1 || blocks[j].size > blocks[worstIdx].size) {
worstIdx = j;
}
}
}
if (worstIdx != -1) {
blocks[worstIdx].allocated = 1;
printf("Process %d allocated to Block %d\n", processes[i].id, blocks[worstIdx].id);
} else {
printf("Process %d cannot be allocated\n", processes[i].id);
}
}
}

// Function to print memory allocation


void printAllocation(Block blocks[], int m, Process processes[], int n) {
printf("Block\tSize\tProcess\n");
for (int i = 0; i < m; i++) {
printf("%d\t%d\t", blocks[i].id, blocks[i].size);
if (blocks[i].allocated) {
printf("%d", processes[blocks[i].id - 1].id);
} else {
printf("Not Allocated");
}
printf("\n");
}
}

Output:
Enter the number of memory blocks: 3
Enter the size of memory blocks:
Block 1: 100
Block 2: 200
Block 3: 300
Enter the number of processes: 4
Enter the size of processes:
Process 1: 50
Process 2: 100
Process 3: 250
Process 4: 150

Memory allocation after worst fit:


Block Size Process
1 100 Process 4
2 200 Process 3
3 300 Process 2

BEST-FIT
Program code:
#include <stdio.h>

#define MAX_BLOCKS 100


#define MAX_REQUESTS 100

// Structure to represent a memory block


struct MemoryBlock {
int size;
int allocated;
};

// Function to allocate memory using best-fit algorithm


void bestFit(struct MemoryBlock blocks[], int m, int requests[], int n) {
for (int i = 0; i < n; i++) {
int bestIdx = -1;
for (int j = 0; j < m; j++) {
if (!blocks[j].allocated && blocks[j].size >= requests[i]) {
if (bestIdx == -1 || blocks[j].size < blocks[bestIdx].size) {
bestIdx = j;
}
}
}
if (bestIdx != -1) {
blocks[bestIdx].allocated = 1;
printf("Request %d: Allocated block of size %d at index %d\n", i+1, requests[i], bestIdx);
} else {
printf("Request %d: Not enough memory available\n", i+1);
}
}
}

int main() {
struct MemoryBlock blocks[MAX_BLOCKS];
int requests[MAX_REQUESTS];
int m, n;

printf("Enter the number of memory blocks: ");


scanf("%d", &m);

printf("Enter the size of each memory block:\n");


for (int i = 0; i < m; i++) {
scanf("%d", &blocks[i].size);
blocks[i].allocated = 0;
}

printf("Enter the number of memory allocation requests: ");


scanf("%d", &n);

printf("Enter the size of each memory allocation request:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}

bestFit(blocks, m, requests, n);

return 0;
}

Output:
Enter the number of memory blocks: 3
Enter the size of each memory block:
10
20
30
Enter the number of memory allocation requests: 2
Enter the size of each memory allocation request:
15
10
Request 1: Allocated block of size 15 at index 1
Request 2: Allocated block of size 10 at index 0

FIRST-FIT
Program code:
#include <stdio.h>

#define MAX_MEMORY_SIZE 100


#define MAX_PROCESS_SIZE 10

int main() {
int memory[MAX_MEMORY_SIZE], process[MAX_PROCESS_SIZE];
int n, m, i, j;

// Input the number of memory blocks and processes


printf("Enter the number of memory blocks: ");
scanf("%d", &n);
printf("Enter the number of processes: ");
scanf("%d", &m);

// Input memory block sizes


printf("Enter memory block sizes:\n");
for (i = 0; i < n; i++) {
printf("Memory block %d: ", i + 1);
scanf("%d", &memory[i]);
}

// Input process sizes


printf("Enter process sizes:\n");
for (i = 0; i < m; i++) {
printf("Process %d: ", i + 1);
scanf("%d", &process[i]);
}

// Allocation using First Fit algorithm


for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
if (memory[j] >= process[i]) {
printf("Process %d allocated to Memory block %d\n", i + 1, j + 1);
memory[j] -= process[i];
break;
}
}
if (j == n) {
printf("Process %d cannot be allocated\n", i + 1);
}
}

return 0;
}

Output:
Enter the number of memory blocks: 4
Enter the number of processes: 3
Enter memory block sizes:
Memory block 1: 50
Memory block 2: 20
Memory block 3: 30
Memory block 4: 40
Enter process sizes:
Process 1: 25
Process 2: 10
Process 3: 35
Process 1 allocated to Memory block 1
Process 2 allocated to Memory block 1
Process 3 allocated to Memory block 4

Exercise 12: Write C program to implement the various page


replacement algorithms.
Program code:

#include<stdio.h>
#include<stdlib.h>

#define MAX_FRAMES 3

void FIFO(int pages[], int n, int frames);


void LRU(int pages[], int n, int frames);
void optimal(int pages[], int n, int frames);

int main() {
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int n = sizeof(pages) / sizeof(pages[0]);
int frames = MAX_FRAMES;

printf("FIFO Page Replacement Algorithm:\n");


FIFO(pages, n, frames);

printf("\nLRU Page Replacement Algorithm:\n");


LRU(pages, n, frames);

printf("\nOptimal Page Replacement Algorithm:\n");


optimal(pages, n, frames);

return 0;
}

void FIFO(int pages[], int n, int frames) {


int frame[frames];
int count = 0, hit = 0, i, j;
int page_faults = 0;

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


frame[i] = -1;

for(i = 0; i < n; i++) {


int flag = 0;
for(j = 0; j < frames; j++) {
if(frame[j] == pages[i]) {
hit++;
flag = 1;
break;
}
}
if(flag == 0) {
frame[count] = pages[i];
count = (count + 1) % frames;
page_faults++;
}
}

printf("Page Faults: %d\n", page_faults);


}

void LRU(int pages[], int n, int frames) {


int frame[frames];
int count = 0, hit = 0, i, j;
int page_faults = 0;
int counter[frames];

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


frame[i] = -1;

for(i = 0; i < n; i++) {


int flag = 0;
for(j = 0; j < frames; j++) {
if(frame[j] == pages[i]) {
hit++;
flag = 1;
counter[j] = i;
break;
}
}
if(flag == 0) {
int min = 0;
for(j = 1; j < frames; j++) {
if(counter[j] < counter[min])
min = j;
}
frame[min] = pages[i];
counter[min] = i;
page_faults++;
}
}

printf("Page Faults: %d\n", page_faults);


}

void optimal(int pages[], int n, int frames) {


int frame[frames];
int count = 0, hit = 0, i, j;
int page_faults = 0;
int temp[frames];

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


frame[i] = -1;

for(i = 0; i < n; i++) {


int flag = 0;
for(j = 0; j < frames; j++) {
if(frame[j] == pages[i]) {
hit++;
flag = 1;
break;
}
}
if(flag == 0) {
int x;
if(count < frames) {
frame[count++] = pages[i];
} else {
for(x = 0; x < frames; x++)
temp[x] = -1;
for(x = i + 1; x < n; x++) {
for(j = 0; j < frames; j++) {
if(pages[x] == frame[j]) {
temp[j] = x;
break;
}
}
}
int pos = 0;
for(j = 1; j < frames; j++) {
if(temp[j] == -1)
pos = j;
else if(temp[j] > temp[pos])
pos = j;
}
frame[pos] = pages[i];
page_faults++;
}
}
}

printf("Page Faults: %d\n", page_faults);


}
Output:
FIFO Page Replacement Algorithm:
Page Faults: 9

LRU Page Replacement Algorithm:


Page Faults: 10

Optimal Page Replacement Algorithm:


Page Faults: 7

Exercise 13:Write C program to implement the various file organization


techniques.
Program code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_RECORDS 100

// Structure to represent a record


typedef struct {
int id;
char name[50];
float salary;
} Record;

// Function prototypes
void sequential();
void indexed();
void direct();

// Function to add a record to the file


void addRecord(FILE *file, Record record);

// Function to search for a record by ID


int searchRecord(FILE *file, int id);

// Function to delete a record by ID


void deleteRecord(FILE *file, int id);

int main() {
int choice;

do {
printf("\nFile Organization Techniques\n");
printf("1. Sequential File\n");
printf("2. Indexed File\n");
printf("3. Direct File\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
sequential();
break;
case 2:
indexed();
break;
case 3:
direct();
break;
case 4:
printf("Exiting program...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 4);

return 0;
}

void sequential() {
FILE *file;
Record record;
int choice;

file = fopen("sequential.txt", "a+");

if (file == NULL) {
printf("Error opening file.\n");
return;
}

do {
printf("\nSequential File Operations\n");
printf("1. Add Record\n");
printf("2. Search Record\n");
printf("3. Delete Record\n");
printf("4. Back to Main Menu\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter ID: ");
scanf("%d", &record.id);
printf("Enter Name: ");
scanf("%s", record.name);
printf("Enter Salary: ");
scanf("%f", &record.salary);
addRecord(file, record);
break;
case 2:
printf("Enter ID to search: ");
scanf("%d", &record.id);
if (searchRecord(file, record.id))
printf("Record found.\n");
else
printf("Record not found.\n");
break;
case 3:
printf("Enter ID to delete: ");
scanf("%d", &record.id);
deleteRecord(file, record.id);
break;
case 4:
printf("Returning to Main Menu...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 4);

fclose(file);
}

void indexed() {
// Implement indexed file organization
printf("Indexed File Organization\n");
}

void direct() {
// Implement direct file organization
printf("Direct File Organization\n");
}

void addRecord(FILE *file, Record record) {


fprintf(file, "%d %s %.2f\n", record.id, record.name, record.salary);
}

int searchRecord(FILE *file, int id) {


Record record;
rewind(file);

while (fscanf(file, "%d %s %f", &record.id, record.name, &record.salary) != EOF) {


if (record.id == id)
return 1; // Found
}

return 0; // Not found


}

void deleteRecord(FILE *file, int id) {


FILE *tempFile;
Record record;

tempFile = fopen("temp.txt", "w");

rewind(file);

while (fscanf(file, "%d %s %f", &record.id, record.name, &record.salary) != EOF) {


if (record.id != id)
fprintf(tempFile, "%d %s %.2f\n", record.id, record.name, record.salary);
}

fclose(file);
fclose(tempFile);

remove("sequential.txt");
rename("temp.txt", "sequential.txt");
}

Output:
File Organization Techniques
1. Sequential File
2. Indexed File
3. Direct File
4. Exit
Enter your choice: 1

Sequential File Operations


1. Add Record
2. Search Record
3. Delete Record
4. Back to Main Menu
Enter your choice: 1
Enter ID: 101
Enter Name: John Doe
Enter Salary: 5000

Sequential File Operations


1. Add Record
2. Search Record
3. Delete Record
4. Back to Main Menu
Enter your choice: 2
Enter ID to search: 101
Record found.

Sequential File Operations


1. Add Record
2. Search Record
3. Delete Record
4. Back to Main Menu
Enter your choice: 3
Enter ID to delete: 101

Sequential File Operations


1. Add Record
2. Search Record
3. Delete Record
4. Back to Main Menu
Enter your choice: 4
Returning to Main Menu...

File Organization Techniques


1. Sequential File
2. Indexed File
3. Direct File
4. Exit
Enter your choice: 4
Exiting program...

Exercise 14:
FILE ALLOCATION STRATEGIES

A) SEQUENTIAL:
AIM: To write a C program for implementing sequential file allocation method

SOURCE CODE :
#include <stdio.h>
#include <stdlib.h>

#define MAX_BLOCKS 100


// Function prototypes
void initializeDisk(int disk[], int size);
void displayDisk(int disk[], int size);
int allocateSequential(int disk[], int size, int fileSize);
void deallocateSequential(int disk[], int size, int startBlock, int fileSize);

int main() {
int disk[MAX_BLOCKS];
int diskSize = MAX_BLOCKS;

// Initialize disk
initializeDisk(disk, diskSize);

// Display initial disk status


printf("Initial Disk Status:\n");
displayDisk(disk, diskSize);

// Example file allocation


int fileSize = 4;
int startBlock = allocateSequential(disk, diskSize, fileSize);
if (startBlock != -1) {
printf("\nFile allocated successfully at block %d\n", startBlock);
printf("Disk Status after allocation:\n");
displayDisk(disk, diskSize);

// Deallocate the file


deallocateSequential(disk, diskSize, startBlock, fileSize);
printf("\nFile deallocated from block %d\n", startBlock);
printf("Disk Status after deallocation:\n");
displayDisk(disk, diskSize);
} else {
printf("File allocation failed. Disk space not available.\n");
}

return 0;
}

// Initialize disk with all blocks marked as free (0)


void initializeDisk(int disk[], int size) {
for (int i = 0; i < size; i++) {
disk[i] = 0;
}
}

// Display disk status


void displayDisk(int disk[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", disk[i]);
}
printf("\n");
}

// Allocate sequential blocks for a file


int allocateSequential(int disk[], int size, int fileSize) {
int startBlock = -1;
int consecutiveFree = 0;

for (int i = 0; i < size; i++) {


if (disk[i] == 0) {
consecutiveFree++;
if (consecutiveFree == fileSize) {
startBlock = i - fileSize + 1;
// Mark allocated blocks as used (1)
for (int j = startBlock; j <= i; j++) {
disk[j] = 1;
}
break;
}
} else {
consecutiveFree = 0;
}
}

return startBlock;
}

// Deallocate sequential blocks allocated for a file


void deallocateSequential(int disk[], int size, int startBlock, int fileSize) {
for (int i = startBlock; i < startBlock + fileSize; i++) {
disk[i] = 0;
}
}
OUTPUT:
Initial Disk Status:
00000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000

File allocated successfully at block 0


Disk Status after allocation:
11110000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000

File deallocated from block 0


Disk Status after deallocation:
00000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000
B) INDEXED:

AIM: To implement allocation method using chained method

Program code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_BLOCKS 100

struct IndexTable {
int blockNumber;
bool occupied;
};

void initializeIndexTable(struct IndexTable indexTable[], int numBlocks) {


for (int i = 0; i < numBlocks; ++i) {
indexTable[i].blockNumber = -1; // -1 indicates unallocated block
indexTable[i].occupied = false;
}
}

void displayIndexTable(struct IndexTable indexTable[], int numBlocks) {


printf("Index Table:\n");
printf("Block Number | Occupied\n");
for (int i = 0; i < numBlocks; ++i) {
printf("%d\t\t| %s\n", indexTable[i].blockNumber, indexTable[i].occupied ?
"Yes" : "No");
}
}

int allocateBlock(struct IndexTable indexTable[], int numBlocks) {


for (int i = 0; i < numBlocks; ++i) {
if (!indexTable[i].occupied) {
indexTable[i].occupied = true;
return i; // Return the block number/index
}
}
return -1; // Return -1 if no free block is found
}

void deallocateBlock(struct IndexTable indexTable[], int blockNum) {


if (blockNum >= 0 && blockNum < MAX_BLOCKS)
indexTable[blockNum].occupied = false;
}

int main() {
int numBlocks;
printf("Enter the number of blocks: ");
scanf("%d", &numBlocks);

if (numBlocks > MAX_BLOCKS || numBlocks <= 0) {


printf("Invalid number of blocks.\n");
return 1;
}

struct IndexTable indexTable[MAX_BLOCKS];


initializeIndexTable(indexTable, numBlocks);

int choice, blockNum;


do {
printf("\n1. Allocate Block\n");
printf("2. Deallocate Block\n");
printf("3. Display Index Table\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
blockNum = allocateBlock(indexTable, numBlocks);
if (blockNum != -1)
printf("Block allocated at index %d.\n", blockNum);
else
printf("No free blocks available.\n");
break;
case 2:
printf("Enter the block number to deallocate: ");
scanf("%d", &blockNum);
deallocateBlock(indexTable, blockNum);
printf("Block at index %d deallocated.\n", blockNum);
break;
case 3:
displayIndexTable(indexTable, numBlocks);
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 4);

return 0;
}

Output:
Enter the number of blocks: 5

1. Allocate Block
2. Deallocate Block
3. Display Index Table
4. Exit
Enter your choice: 1
Block allocated at index 0.

1. Allocate Block
2. Deallocate Block
3. Display Index Table
4. Exit
Enter your choice: 1
Block allocated at index 1.

1. Allocate Block
2. Deallocate Block
3. Display Index Table
4. Exit
Enter your choice: 1
Block allocated at index 2.

1. Allocate Block
2. Deallocate Block
3. Display Index Table
4. Exit
Enter your choice: 3
Index Table:
Block Number | Occupied
0 | Yes
1 | Yes
2 | Yes
-1 | No
-1 | No

1. Allocate Block
2. Deallocate Block
3. Display Index Table
4. Exit
Enter your choice: 2
Enter the block number to deallocate: 1
Block at index 1 deallocated.

1. Allocate Block
2. Deallocate Block
3. Display Index Table
4. Exit
Enter your choice: 3
Index Table:
Block Number | Occupied
0 | Yes
-1 | No
2 | Yes
-1 | No
-1 | No

1. Allocate Block
2. Deallocate Block
3. Display Index Table
4. Exit
Enter your choice: 4
Exiting...
C) LINKED:

AIM: To implement linked file allocation technique.

Program code:
#include <stdio.h>
#include <stdlib.h>

// Define the maximum number of memory blocks


#define MAX_BLOCKS 100

// Initialize an array to represent memory blocks (0 = free, 1 = allocated)


int pages[MAX_BLOCKS] = {0};

// Recursive function to allocate memory blocks for a file


void allocateBlocks(int fileNumber) {
int startBlock, length, k, j;
printf("Enter the index of the starting block and its length for File %d:
", fileNumber);
scanf("%d %d", &startBlock, &length);

k = length;
if (pages[startBlock] == 0) {
for (j = startBlock; j < (startBlock + k); j++) {
if (pages[j] == 0) {
pages[j] = 1;
printf("%d ------> %d\n", j, pages[j]);
} else {
printf("Block %d is already allocated.\n", j);
break;
}
}
} else {
printf("Block %d is already allocated.\n", startBlock);
}
}

int main() {
int numFiles, i;
printf("Enter the number of files: ");
scanf("%d", &numFiles);

for (i = 1; i <= numFiles; i++) {


allocateBlocks(i);
}

printf("\nFile Allocation Summary:\n");


for (i = 0; i < MAX_BLOCKS; i++) {
if (pages[i] == 1) {
printf("Block %d is allocated.\n", i);
}
}

return 0;
}

Output:
Enter the number of files: 1
Enter the index of the starting block and its length for File 1: 2
3
2 ------> 1
3 ------> 1
4 ------> 1

File Allocation Summary:


Block 2 is allocated.
Block 3 is allocated.
Block 4 is allocated.

Exercise 15:Write C program for the implementation of


various disk scheduling algorithms.

Program code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#define MAX_REQUESTS 1000

// Function to sort an array in ascending order


void sort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

// FCFS disk scheduling algorithm


void fcfs(int requests[], int n, int head) {
int total_seek = 0;
printf("FCFS Schedule:\n");
for (int i = 0; i < n; i++) {
total_seek += abs(head - requests[i]);
printf("Move from %d to %d\n", head, requests[i]);
head = requests[i];
}
printf("Total seek time: %d\n", total_seek);
}

// SSTF disk scheduling algorithm


void sstf(int requests[], int n, int head) {
int total_seek = 0;
int visited[MAX_REQUESTS] = {0};
printf("SSTF Schedule:\n");
for (int i = 0; i < n; i++) {
int min_seek = INT_MAX;
int next_index = -1;
for (int j = 0; j < n; j++) {
if (!visited[j]) {
int seek = abs(head - requests[j]);
if (seek < min_seek) {
min_seek = seek;
next_index = j;
}
}
}
total_seek += min_seek;
printf("Move from %d to %d\n", head, requests[next_index]);
visited[next_index] = 1;
head = requests[next_index];
}
printf("Total seek time: %d\n", total_seek);
}

// SCAN disk scheduling algorithm


void scan(int requests[], int n, int head, int direction) {
int total_seek = 0;
printf("SCAN Schedule:\n");
int start = direction == 1 ? 0 : head;
int end = direction == 1 ? head : 199; // assuming disk size is 200
if (direction == 1) {
for (int i = start; i <= end; i++) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
for (int i = end - 1; i >= 0; i--) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
} else {
for (int i = start; i >= end; i--) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
for (int i = end + 1; i <= 199; i++) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
}
printf("Total seek time: %d\n", total_seek);
}

// C-SCAN disk scheduling algorithm


void cscan(int requests[], int n, int head, int direction) {
int total_seek = 0;
printf("C-SCAN Schedule:\n");
int start = direction == 1 ? 0 : head;
int end = direction == 1 ? head : 199; // assuming disk size is 200
if (direction == 1) {
for (int i = start; i <= end; i++) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
for (int i = 199; i >= end; i--) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
} else {
for (int i = start; i >= end; i--) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
for (int i = 0; i <= end; i++) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
}
printf("Total seek time: %d\n", total_seek);
}

// LOOK disk scheduling algorithm


void look(int requests[], int n, int head, int direction) {
int total_seek = 0;
printf("LOOK Schedule:\n");
int start = direction == 1 ? 0 : head;
int end = direction == 1 ? head : 199; // assuming disk size is 200
if (direction == 1) {
for (int i = start; i <= end; i++) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
} else {
for (int i = start; i >= end; i--) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
}
printf("Total seek time: %d\n", total_seek);
}

// C-LOOK disk scheduling algorithm


void clook(int requests[], int n, int head, int direction) {
int total_seek = 0;
printf("C-LOOK Schedule:\n");
int start = direction == 1 ? 0 : head;
int end = direction == 1 ? head : 199; // assuming disk size is 200
if (direction == 1) {
for (int i = start; i <= end; i++) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
for (int i = 0; i < start; i++) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
} else {
for (int i = start; i >= end; i--) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
for (int i = 199; i > start; i--) {
for (int j = 0; j < n; j++) {
if (requests[j] == i) {
total_seek += abs(head - requests[j]);
printf("Move from %d to %d\n", head, requests[j]);
head = requests[j];
}
}
}
}
printf("Total seek time: %d\n", total_seek);
}

int main() {
int requests[MAX_REQUESTS];
int n, head, direction;

printf("Enter the number of requests: ");


scanf("%d", &n);

if (n > MAX_REQUESTS || n <= 0) {


printf("Invalid number of requests.\n");
return 1;
}

printf("Enter the requests: ");


for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}

printf("Enter the initial position of head: ");


scanf("%d", &head);

printf("Enter the direction of movement (1 for towards 0, 0 for away from


0): ");
scanf("%d", &direction);

sort(requests, n);

fcfs(requests, n, head);
sstf(requests, n, head);
scan(requests, n, head, direction);
cscan(requests, n, head, direction);
look(requests, n, head, direction);
clook(requests, n, head, direction);

return 0;
}

Output:
Enter the number of requests: 5
Enter the requests: 98 183 37 122 14
Enter the initial position of head: 53
Enter the direction of movement (1 for towards 0, 0 for away from 0): 1
FCFS Schedule:
Move from 53 to 37
Move from 37 to 14
Move from 14 to 98
Move from 98 to 122
Move from 122 to 183
Total seek time: 261
SSTF Schedule:
Move from 53 to 37
Move from 37 to 14
Move from 14 to 98
Move from 98 to 122
Move from 122 to 183
Total seek time: 261
SCAN Schedule:
Move from 53 to 37
Move from 37 to 14
Move from 14 to 0
Move from 0 to 98
Move from 98 to 122
Move from 122 to 183
Total seek time: 408
C-SCAN Schedule:
Move from 53 to 37
Move from 37 to 14
Move from 14 to 0
Move from 0 to 199
Move from 199 to 98
Move from 98 to 122
Move from 122 to 183
Total seek time: 484
LOOK Schedule:
Move from 53 to 37
Move from 37 to 14
Move from 14 to 0
Move from 0 to 98
Move from 98 to 122
Move from 122 to 183
Total seek time: 386
C-LOOK Schedule:
Move from 53 to 37
Move from 37 to 14
Move from 14 to 0
Move from 0 to 199
Move from 199 to 98
Move from 98 to 122
Move from 122 to 183
Total seek time: 484

Exercise 16: Install any guest operating system like linux using VMware.

You might also like