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

lOMoARcPSD|38975850

OS LAB Manual

Unit operation (Madras Institute of Technology, Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Deepa S (dpa148106@gmail.com)
lOMoARcPSD|38975850

LABORATORY RECORD
for

AL3452 : OPERATING SYSTEMS


of

B.TECH (AI&DS)
(Anna University Regulation 2021)
For the Batch (2021 to 2025)

Semester: IV
Academic Year: 2022-2023

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA


SCIENCE
KCG COLLEGE OF TECHNOLOGY, CHENNAI – 600 097

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

LABORATORY RECORD

Reg No ………………………………………………………

Course Code :

Name of the Course :

Program :

It is certified that this is the bonafide record of the work carried out by

of _class during the

year 2022 – 2023.

Faculty In-Charge: HoD: _

Int.Examiner: Ext. Examiner:

Date of the Examination: _

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

VISION OF THE COLLEGE

KCG College of Technology aspires to become a globally recognized centre of excellence for
science, technology & engineering education, committed to quality teaching, learning, and research
while ensuring for every student a unique educational experience which will promote leadership,
job creation, social commitment and service to nation building

MISSION OF THE COLLEGE

• Disseminate knowledge in a rigorous and intellectually stimulating environment

• Facilitate socially responsive research, innovation and entrepreneurship

• Foster holistic development and professional competency

• Nurture the virtue of service and an ethical value system in the young minds

VISION OF THE DEPARTMENT


The Department of Artificial Intelligence and Data Science desires to become a: prominent Centre
of Excellence for producing competent Data Architect for providing quality education by using the
latest tools.

MISSION OF THE DEPARTMENT

➢ Provide quality education in the field of Artificial Intelligence and Data Science
related domains.
➢ Facilitate Skill based value added education.
➢ Inculcate professional performance, an essence of entrepreneurship and promise
to the growth of the country.
➢ Providing varying software development tools and required implementation
facilities.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

PROGRAMME EDUCATIONAL OBJECTIVES


The graduates of B.TECH/ AI&DS will

PEO 1 To provide graduates with the proficiency to utilize the fundamental knowledge of basic sciences,
mathematics, Artificial Intelligence, data science and statistics to build systems that require management
and analysis of large volume of data.

To enrich graduates with necessary technical skills to pursue pioneering research in the field of AI and
PEO 2
Data Science and create disruptive and sustainable solutions for the welfare of ecosystems..

To enable graduates to think logically, pursue lifelong learning and collaborate with an ethical attitude in a
PEO 3 multidisciplinary team.

PROGRAMME OUTCOMES AND PROGRAMME SPECIFIC OUTCOMES


After successful completion of B.TECH (Artificial Intelligence and Data Science) Programme, the
students will be able to:

PO No. Description of the PO

Engineering Knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
PO 1
engineering specialization to the solution of complex engineering problems.
Problem Analysis: Identify, formulate, review research literature, and analyze complex engineering
PO 2 problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
Design / Development of Solutions: Design solutions for complex engineering problems and design system
PO 3 components or processes that meet the specified needs with appropriate consideration for the public health and
safety, and the cultural, societal, and environmental considerations.
Conduct Investigations of Complex Problems: Use research based knowledge and research methods
PO 4 including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and modern engineering
PO 5 and IT tools including prediction and modeling to complex engineering activities with an understanding of
the limitations.
The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess societal,
PO 6 health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and Sustainability: Understand the impact of the professional engineering solutions in
PO 7 societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
PO 8
engineering practice.
Individual and Team Work: Function effectively as an individual, and as a member or leader in diverse
PO 9
teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the engineering
PO 10 community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
Project Management and Finance: Demonstrate knowledge and understanding of the engineering and
PO 11 management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
Lifelong Learning: Recognize the need for, and have the preparation and ability to engage in independent
PO 12
and lifelong learning in the broadest context of technological change.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

PSO No. Description of PSO

Graduates should be able to evolve AI based efficient domain specific processes for effective decision
PSO 1
making in several domains such as business and governance domains.
.
Graduates should be able to arrive at actionable Fore sight, Insight , hind sight from data for solving business
PSO 2
and engineering problems

Graduates should be able to create, select and apply the theoretical knowledge of AI and Data Analytics
PSO 3
along with practical industrial tools and techniques to manage and solve wicked societal problems

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

AL3452 OPERATING SYSTEM LABORATORY

INDEX
Expt.
Name of the Experiment Page No Date Signature
No.

1 Installation of Operating system : Windows/ Linux

2 Illustrate UNIX commands and Shell Programming

Process Management using System Calls : Fork, Exec, Getpid,


3 Exit, Wait, Close
Write C programs to implement the various CPU Scheduling
4 Algorithms

5 Illustrate the inter process communication strategy

6 Implement mutual exclusion by Semaphores

7 Write a C program to avoid Deadlock using Banker's Algorithm

Write a C program to Implement Deadlock Detection


8 Algorithm

9 Write C program to implement Threading

10 Implement the paging Technique using C program

Write C programs to implement the following Memory


11 Allocation Methods a. First Fit b. Worst Fit c. Best Fit

Write C programs to implement the various Page


12 Replacement Algorithms

Write C programs to Implement the various File


13 Organization Techniques

Implement the following File Allocation Strategies


14 using C programs a. Sequential b. Indexed c. Linked

Write C programs for the implementation of various


15 disk scheduling algorithms

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Basic of C Language

C is a programming language developed by Dennis Ritchie in 1972 at bell laboratories of AT&T (American
Telephone & Telegraph), located in U.S.A. C inherited many behavior from its ancestor programming
languages. Along with the inherited features, some more unique features were developed in C that made it the
most basic programming language and the mother of all programming languages.

Features of C:
Some unique features of C are:

• Extensible
• Fast Speed
• Machine Independent or Portable
• Mid-level programming language
• Memory Management
• Pointers
• Rich Library
• Recursion
• Simple to Learn
• Structured programming language
• Procedure-oriented programming language
C as a mother language:
C language is used to write most of the compilers. Also the syntax of C, including its unique features and
concepts of array, strings, functions, file handling, pointers, etc are used even today in almost all languages in
some way or now. This made it to be considered as the mother language of all the programming languages.

C as a System Programming Language and a Mid Level Language:


C is a high level language as it can be easily developed by a user. However, C can also be used as a low level
programming language to develop some system applications such as kernel, driver etc. Thus, it can be better
called as a mid-level language, instead of a high level language.

C as a Structured Programming Language:


A structured programming language is the one which can be broken into smaller parts. C supports this feature
using multiple functions and is thus called as a Structured Programming Language.

C Compilers:
For executing a C file in a system, C compiler is a must. Various C compilers are available for downloading.
Turbo C++ is among some common C compilers.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

First C Program:

Lets print “Hello C” as the first C program and than understand it in detail.

Description:

#include <stdio.h> :
“#include” is a preprocessor directive used to include a library file in the code. The header file
“stdio.h” is included in the source code to use the pre-defined functions “printf” and “scanf”.

void main() :
Void represents the data type of the main function which is a must for every C program.

{} :
{} represents the opening and closing of the main function.

printf (“Hello C!”); :


The printf function outputs the string on the console screen.

Compilation and Execution:


Click on Compile menu and then on Run menu or click ctrl+F9 directly, both for compile and
run.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

GOBAL VARIABLE

LOCAL VARIABLE

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Installation of Operating system : Windows/ Linux

Exp.no: 1

Date:

Aim:

To study Installation of Operating system: Windows/ Linux.

Study :

Installing an operating system (OS) is a process that typically involves creating a bootable drive
with the installation files and then booting from that drive to start the installation process. Here
are the basic steps for installing Windows and Linux operating systems:

Installing Windows:

1. Obtain the installation media (e.g. a Windows installation USB drive or DVD).
2. Connect the installation media to your computer and restart the machine.
3. Boot the machine from the installation media by changing the boot order in the BIOS or
UEFI settings.
4. Follow the on-screen instructions to install Windows. You will need to accept the license
agreement, select the installation type (e.g. custom or upgrade), choose the installation
location (e.g. which hard drive and partition), and configure basic settings such as
language, time and currency format, and keyboard input method.
5. Once the installation is complete, the machine will restart and guide you through the
initial setup process.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Installing Linux:

1. Obtain the installation media (e.g. a Linux distribution ISO file).


2. Create a bootable drive with the installation media.
3. Connect the bootable drive to your computer and restart the machine.
4. Boot the machine from the bootable drive by changing the boot order in the BIOS or
UEFI settings.
5. Follow the on-screen instructions to install the Linux distribution. You will need to select
the language, keyboard layout, and time zone. You may also need to partition the hard
drive, select the installation location, and configure basic settings such as username,
password, and network configuration.
6. Once the installation is complete, the machine will restart and you will be able to log in to
your new Linux system.

Result :

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Illustrate UNIX commands and Shell Programming

Exp.no: 2

Date:

Aim:

To Illustrate UNIX commands and Shell Programming.

Study :

UNIX commands are a set of basic instructions that can be executed in a terminal window to perform
various tasks in a UNIX-based operating system, such as Linux and macOS. Here are some common
UNIX commands:

1. ls: Lists the files and directories in the current directory.


2. cd: Changes the current directory.
3. mkdir: Creates a new directory.
4. rmdir: Deletes an empty directory.
5. rm: Deletes a file.
6. touch: Creates a new empty file.
7. cp: Copies a file or directory.
8. mv: Moves or renames a file or directory.
9. cat: Displays the contents of a file.
10. echo: Writes text to the terminal or a file.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

This script starts with a shebang line that specifies the path to the bash interpreter,
followed by a comment that explains what the script does. The echo command is used
to print a message to the console.

Shell programming is a way to automate tasks and perform operations on a computer


using a shell, which is a command-line interface that allows you to interact with the
operating system. The shell reads commands from the user, executes them, and returns
the results. Some common shell programs include the Bourne shell (sh), the C shell (csh),
and the Bourne-Again shell (bash).

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Process Management using System Calls: Fork, Exec, Getpid, Exit, Wait, Close

Exp.no: 3

Date:

Aim:

To Process Management using System Calls : Fork, Exec, Getpid, Exit, Wait, Close.

Algorithm:

Step 1: Declare a pid_t variable to store the process ID

Step 2: Call fork() to create a child process

Step 3: If fork() returns a negative value, print an error message and exit with an error code

Step 4: If fork() returns 0, the process is the child:

Step 4.1: Get the process ID of the child using getpid()

Step 4.2: Execute a command using execlp()

Step 5: If fork() returns a positive value, the process is the parent:

Step 5.1: Get the process ID of the parent using getpid()

Step 5.2: Call wait() to wait for the child process to complete

Step 5.3: Print a message to the console indicating that the child process has completed

Step 6: Call exit() to exit the program

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Program :

#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 handling


fprintf(stderr, "Fork failed\n");
exit(1);
}
else if (pid == 0) { // Child process
printf("I am the child process, pid=%d\n", getpid());

// Execute a command using exec


execlp("/bin/ls", "ls", NULL);
}
else { // Parent process
printf("I am the parent process, pid=%d\n", getpid());

// Wait for the child process to complete


wait(NULL);

printf("Child process has completed\n");


}

// Close the program


printf("Exiting program\n");
exit(0);
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

I am the parent process, pid=12345


I am the child process, pid=12346
file1.txt file2.txt program.c
Child process has completed
Exiting program

Result :

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the various CPU Scheduling Algorithms

Exp.no: 4 a

Date:

Aim:

To write C programs to implement the various CPU Scheduling Algorithms using First Come
First Serve algorithm.

Algorithm:

Step 1: Initialize the total waiting time and total turnaround time to 0.

Step 2: Read the number of processes to be scheduled.

Step 3: For each process, read in its arrival time and burst time.

Step 4: Sort the processes in increasing order of arrival time, so that the first process to arrive is
first in the queue.

Step 5: For each process, calculate its waiting time as the sum of the burst times of all
processes that arrived before it. For the first process, its waiting time is 0.

Step 6: For each process, calculate its turnaround time as the sum of its waiting time and its
burst time.

Step 7: Calculate the average waiting time and the average turnaround time by dividing the
total waiting time and total turnaround time by the number of processes.

Step 8: Print out the results.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Program:

#include <stdio.h>

int main() {
int n, i;
float avg_wt, avg_tat;
int burst_time[20], waiting_time[20], turnaround_time[20];

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


scanf("%d", &n);

printf("Enter the burst times for each process:\n");


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

// Calculate waiting time for the first process


waiting_time[0] = 0;

// Calculate waiting time for each subsequent process


for (i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i - 1] + burst_time[i - 1];
}

// Calculate turnaround time for each process


for (i = 0; i < n; i++) {
turnaround_time[i] = waiting_time[i] + burst_time[i];
}

// Calculate average waiting time and average turnaround time


float total_wt = 0, total_tat = 0;
for (i = 0; i < n; i++) {
total_wt += waiting_time[i];
total_tat += turnaround_time[i];
}
avg_wt = total_wt / n;
avg_tat = total_tat / n;

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

// Print the results


printf("Process\tBurst Time\tWaiting Time\tTurnaround Time\n");

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


printf("%d\t%d\t\t%d\t\t%d\n", i+1, burst_time[i], waiting_time[i], turnaround_time[i]);
}
printf("Average Waiting Time: %.2f\n", avg_wt);
printf("Average Turnaround Time: %.2f\n", avg_tat);

return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the various CPU Scheduling Algorithms

Exp.no: 4 b

Date:

Aim:

To write C programs to implement the various CPU Scheduling Algorithms using Shortest Job
First algorithm.

Algorithm:

Step 1: When a process arrives, its expected processing time is estimated, based on its past
behaviour or other factors.

Step 2: The process with the shortest expected processing time is assigned the CPU. If there are
multiple processes with the same expected processing time, any one of them may be selected.

Step 3: The process runs on the CPU until it completes, or until it is pre-empted by a higher-
priority process.

Step 4: When a new process arrives, its expected processing time is estimated, and it is added
to the ready queue.

Step 5: When the current process completes or is pre-empted, the process with the shortest
expected processing time in the ready queue is selected and assigned the CPU.

Program:

#include <stdio.h>

int main() {
int n, i, j, temp, time = 0, total_time = 0;
float avg_waiting_time, avg_turnaround_time;
int burst_time[20], process[20], waiting_time[20], turnaround_time[20];

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


scanf("%d", &n);

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

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


printf("Enter the burst time for process %d: ", i + 1);
scanf("%d", &burst_time[i]);
process[i] = i + 1;
}

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


for (j = i + 1; j < n; j++) {
if (burst_time[i] > burst_time[j]) {
temp = burst_time[i];
burst_time[i] = burst_time[j];
burst_time[j] = temp;
temp = process[i];
process[i] = process[j];
process[j] = temp;
}
}
}

waiting_time[0] = 0;

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


waiting_time[i] = 0;
for (j = 0; j < i; j++) {
waiting_time[i] += burst_time[j];
}
total_time += waiting_time[i];
}

avg_waiting_time = (float)total_time / n;
total_time = 0;

printf("\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time");

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


turnaround_time[i] = burst_time[i] + waiting_time[i];
total_time += turnaround_time[i];
printf("\n%d\t\t%d\t\t%d\t\t%d", process[i], burst_time[i], waiting_time[i],
turnaround_time[i]);

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

avg_turnaround_time = (float)total_time / n;
printf("\n\nAverage Waiting Time = %0.2f", avg_waiting_time);
printf("\nAverage Turnaround Time = %0.2f", avg_turnaround_time);

return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the various CPU Scheduling Algorithms

Exp.no: 4 c

Date:

Aim:

To write C programs to implement the various CPU Scheduling Algorithms using Priority
Scheduling algorithm.

Algorithm:

Step 1: Assign a priority to each process. This priority can be based on various criteria, such as
the amount of CPU time needed, the amount of memory required, or the importance of the
process.

Step 2: Initialize the ready queue with all the processes that are ready to run.

Step 3: Find the process with the highest priority in the ready queue.

Step 4: Assign the CPU to that process.

Step 5: If the scheduling is non-pre-emptive, the process will continue to run until it completes
or voluntarily gives up the CPU. If the scheduling is pre-emptive, the process will be
interrupted if a new process with a higher priority arrives in the ready queue.

Step 6: When a process completes or gives up the CPU, remove it from the system.

Step 7: If a new process arrives in the system, add it to the ready queue according to its priority.

Step 8: Repeat steps 3 to 7 until all processes have completed.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Program:

#include<stdio.h>

int main() {
int n, i, j, temp, total_wt = 0, total_tat = 0;
float avg_wt, avg_tat;
int burst_time[20], priority[20], process[20];

// Taking input from the user


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

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


printf("Enter burst time and priority for process %d: ", i + 1);
scanf("%d %d", &burst_time[i], &priority[i]);
process[i] = i + 1;
}

// Sorting processes based on priority


for(i = 0; i < n - 1; i++) {
for(j = i + 1; j < n; j++) {
if(priority[i] > priority[j]) {
temp = priority[i];
priority[i] = priority[j];
priority[j] = temp;

temp = burst_time[i];
burst_time[i] = burst_time[j];
burst_time[j] = temp;

temp = process[i];
process[i] = process[j];
process[j] = temp;
}
}
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

// Calculating waiting time and turnaround time


int wt[20], tat[20];
wt[0] = 0;
for(i = 1; i < n; i++) {
wt[i] = 0;
for(j = 0; j < i; j++) {
wt[i] += burst_time[j];
}
total_wt += wt[i];
}

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


tat[i] = burst_time[i] + wt[i];
total_tat += tat[i];
}

// Displaying results
avg_wt = (float)total_wt / n;
avg_tat = (float)total_tat / n;

printf("\nProcess\tBurst Time\tPriority\tWaiting Time\tTurnaround Time");


for(i = 0; i < n; i++) {
printf("\n%d\t%d\t\t%d\t\t%d\t\t%d", process[i], burst_time[i], priority[i], wt[i], tat[i]);
}

printf("\n\nAverage Waiting Time = %f", avg_wt);


printf("\nAverage Turnaround Time = %f", avg_tat);

return 0;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the various CPU Scheduling Algorithms

Exp.no: 4 d

Date:

Aim:

To write C programs to implement the various CPU Scheduling Algorithms using Round Robin
algorithm.

Algorithm:

Step 1: Initialize a queue Q to hold the processes that are ready to run.

Step 2: Set the time slice, or quantum, for each process.

Step 3: While there are processes in the queue:

Step 4: Dequeue the first process from the queue.

Step 5: If the process has not completed, and its remaining execution time is less than or equal
to the time slice:

Step 6: Run the process for its remaining execution time.

Step 7: Update the process's state to "completed".

Step 8: Record the process's turnaround time and wait time.

Step 9: Otherwise, if the process has not completed:

Step 10: Run the process for the time slice.

Step 11: Update the process's remaining execution time.

Step 12: Enqueue the process back onto the end of the queue.

Step 13: Calculate the average turnaround time and average wait time for all completed
processes.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Program:

#include<stdio.h>

int main() {
int i, n, t, j, count=0, quantum;
int waiting_time = 0, turnaround_time = 0;
int arrival_time[10], burst_time[10], temp_burst_time[10];
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the time quantum: ");
scanf("%d", &quantum);
for (i = 0; i < n; i++) {
printf("Enter the arrival time and burst time of process %d: ", i+1);
scanf("%d %d", &arrival_time[i], &burst_time[i]);
temp_burst_time[i] = burst_time[i];
}
t = 0;
while (1) {
int flag = 1;
for (i = 0; i < n; i++) {
if (temp_burst_time[i] > 0) {
flag = 0;
if (temp_burst_time[i] > quantum) {
t += quantum;
temp_burst_time[i] -= quantum;
}
else {
t = t + temp_burst_time[i];
waiting_time += t - arrival_time[i] - burst_time[i];
temp_burst_time[i] = 0;
turnaround_time += t - arrival_time[i];
}
}
}
if (flag == 1)
break;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

printf("\nProcess\tArrival Time\tBurst Time\tWaiting Time\tTurnaround Time");


for (i = 0; i < n; i++) {
printf("\nP%d\t\t%d\t\t%d\t\t%d\t\t%d", i+1, arrival_time[i], burst_time[i], waiting_time/n,
turnaround_time/n);
}
return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the various CPU Scheduling Algorithms

Exp.no: 4 e

Date:

Aim:

To write C programs to implement the various CPU Scheduling Algorithms using Multilevel
Queue Scheduling algorithm.

Algorithm:

Step 1: Divide the ready queue into multiple queues based on some criteria, such as process
priority or type of task.

Step 2: Assign a different scheduling algorithm to each queue, such as FCFS or SJF.

Step 3: When a new process arrives, it is assigned to the appropriate queue based on its
characteristics.

Step 4: The process in the highest priority queue is executed first, and if there are multiple
processes in the same queue, the scheduling algorithm for that queue is used to determine which
process is executed next.

Step 5: If a process in a lower-priority queue becomes ready to run, it will only be executed if
there are no processes in the higher-priority queues.

Step 6: When a process completes or is blocked, it is removed from the queue and the next
process in the queue is executed.

Step 7: The process in the highest-priority queue may pre-empty a process in a lower-priority
queue if it becomes ready to run.

Step 8: The processes in each queue are scheduled independently of each other.

Step 9: The system can be configured with a different number of queues and different
scheduling algorithms for each queue, depending on the requirements of the system.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Program:

#include <stdio.h>

#define MAX_QUEUE_SIZE 100

// Process structure
typedef struct {
int pid;
int burst_time;
int priority;
} Process;

// Queue structure
typedef struct {
int front;
int rear;
Process arr[MAX_QUEUE_SIZE];
} Queue;

// Initialize queue
void init_queue(Queue *q) {
q->front = -1;
q->rear = -1;
}

// Check if queue is empty


int is_empty(Queue *q) {
return q->front == -1;
}

// Check if queue is full


int is_full(Queue *q) {
return q->rear == MAX_QUEUE_SIZE - 1;
}

// Add process to queue


void enqueue(Queue *q, Process p) {
if (is_full(q)) {
printf("Queue is full\n");
return;

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

}
if (is_empty(q)) {
q->front = q->rear = 0;
} else {
q->rear++;
}
q->arr[q->rear] = p;
}

// Remove process from queue


Process dequeue(Queue *q) {
if (is_empty(q)) {
printf("Queue is empty\n");
Process p = { -1, -1, -1 };
return p;
}
Process p = q->arr[q->front];
if (q->front == q->rear) {
q->front = q->rear = -1;
} else {
q->front++;
}
return p;
}

// Main function
int main() {
// Initialize queues
Queue q1, q2, q3;
init_queue(&q1);
init_queue(&q2);
init_queue(&q3);

// Create processes
Process p1 = { 1, 6, 1 };
Process p2 = { 2, 4, 2 };
Process p3 = { 3, 8, 3 };
Process p4 = { 4, 3, 1 };
Process p5 = { 5, 5, 2 };
Process p6 = { 6, 2, 3 };

// Add processes to queues based on priority

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

enqueue(&q1, p1);
enqueue(&q2, p2);
enqueue(&q3, p3);
enqueue(&q1, p4);
enqueue(&q2, p5);
enqueue(&q3, p6);

// Run processes in each queue


printf("Queue 1:\n");
while (!is_empty(&q1)) {
Process p = dequeue(&q1);
printf("Running process %d with burst time %d\n", p.pid, p.burst_time);
}

printf("Queue 2:\n");
while (!is_empty(&q2)) {
Process p = dequeue(&q2);
printf("Running process %d with burst time %d\n", p.pid, p.burst_time);
}

printf("Queue 3:\n");
while (!is_empty(&q3)) {
Process p = dequeue(&q3);
printf("Running process %d with burst time %d\n", p.pid, p.burst_time);
}

return 0;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Illustrate the inter process communication strategy


Exp.no: 5

Date:

Aim:

To Illustrate the inter process communication strategy.

Algorithm:

Step 1: Start the program.

Step 2: Create a pipe using the pipe() system call and store the read and write ends of the pipe in fd[0] and
fd[1], respectively.

Step 3: Fork the current process using the fork() system call and store the return value in pid.

Step 4: If pid is negative, an error occurred during forking, so print an error message and exit the program.

Step 5: If pid is greater than zero, this is the parent process.

Step 6: Generate a random number using the rand() function and print it to the console.

Step 7: Write the number to the write end of the pipe using the write() system call.

Step 8: Close the write end of the pipe using the close() system call.

Step 9: If pid is zero, this is the child process.

Step 10: Read the number from the read end of the pipe using the read() system call.

Step 11: Multiply the number by 2.

Step 12: Write the result to the write end of the pipe using the write() system call.

Step 13: Close the read end of the pipe using the close() system call.

Step 14: Exit the child process using the exit() system call.

Step 15: Back in the parent process, wait for the child process to complete using the wait() system call.

Step 16: Read the result from the read end of the pipe using the read() system call.

Step 17: Print the result to the console.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Program:

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

int main() {
int fd[2];
pid_t pid;

if (pipe(fd) == -1) {
perror("pipe");
exit(1);
}

pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}

if (pid > 0) {
// Parent process
int number;
close(fd[0]); // Close read end of the pipe
number = rand() % 100; // Generate a random number
printf("Parent process generated number: %d\n", number);
write(fd[1], &number, sizeof(number)); // Write number to the pipe
close(fd[1]); // Close write end of the pipe
}
else {
// Child process
int number, result;
close(fd[1]); // Close write end of the pipe
read(fd[0], &number, sizeof(number)); // Read number from the pipe
printf("Child process received number: %d\n", number);
result = number * 2; // Multiply the number by 2
write(fd[1], &result, sizeof(result)); // Write the result to the pipe
close(fd[0]); // Close read end of the pipe
}
return 0;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Implement mutual exclusion by Semaphores


Exp.no: 6

Date:

Aim:

To Implement mutual exclusion by Semaphores

Algorithm:

Step 1: Declare a semaphore variable mutex and a shared resource variable shared_resource.

Step 2: Initialize the semaphore using the sem_init() function with a value of 1, indicating that
only one thread can access the critical section at a time.

Step 3: Create several threads that will access the critical section of the code.

Step 4: In each thread, loop through several iterations.

Step 5: Call sem_wait() on the semaphore to wait for access to the critical section.

Step 6: Read the value of the shared resource.

Step 7: Modify the value of the shared resource.

Step 8: Call sem_post() on the semaphore to release access to the critical section.

Step 8: End the loop and the thread using pthread_exit().

Step 10: Wait for all threads to finish using pthread_join().

Step 11: Destroy the semaphore using sem_destroy().

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Program:

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

sem_t mutex;
int shared_resource = 0;

void *thread_function(void *arg)


{
int i, val;

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


sem_wait(&mutex);
val = shared_resource;
printf("Thread %ld: Read %d from shared resource\n", (long)arg, val);
val++;
printf("Thread %ld: Writing %d to shared resource\n", (long)arg, val);
shared_resource = val;
sem_post(&mutex);
}
pthread_exit(NULL);
}

int main()
{
pthread_t threads[3];
int i, ret;
sem_init(&mutex, 0, 1);

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


ret = pthread_create(&threads[i], NULL, thread_function, (void *)i);
if (ret != 0) {
printf("Error: pthread_create() failed\n");
return -1;
}
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

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


ret = pthread_join(threads[i], NULL);
if (ret != 0) {
printf("Error: pthread_join() failed\n");
return -1;
}
}

sem_destroy(&mutex);
return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write a C program to avoid Deadlock using Banker's Algorithm


Exp.no: 7

Date:

Aim:

To Write a C program to avoid Deadlock using Banker's Algorithm.

Algorithm:

Step 1: We consider n= number of processes and m=number of resource types.

Step 2: Allocation:

• Specifies the number of resources currently allocated to a process.


• 2-D array of size n*m.
• Allocation[i,j]=k, ie, 'k' instances of a resource Rj is allocated to process Pi.

Step 3: Max need:

• Specifies the number of resources needed by a process.


• 2-D array of size n*m.
• Maxneed[i,j]=Max[i,j]-Allocation[i,j].

Step 4: Available:

• Specifies the number of available resources for a process.


• 1-D array of size m.
• Available[j]=k, ie, resource type Rj has k instances.

Step 5: Remaining need(Max):

• Specifies the maximum demand of each process in a system.


• 2-D array of size n*m.
• Max[i,j]=k, Resource type Rj requests at most k instances of process Pi.

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Program:

#include <stdio.h>
#include <conio.h>
void main() {
int
k=0,a=0,b=0,instance[5],availability[5],allocated[10][5],need[10][5],MAX[10][5],process,P[10]
,no_of_resources, cnt=0,i, j;
printf("\n Enter the number of resources : ");
scanf("%d", &no_of_resources);
printf("\n enter the max instances of each resources\n");
for (i=0;i<no_of_resources;i++) {
availability[i]=0;
printf("%c= ",(i+97));
scanf("%d",&instance[i]);
}
printf("\n Enter the number of processes : ");
scanf("%d", &process);
printf("\n Enter the allocation matrix \n ");
for (i=0;i<no_of_resources;i++)
printf(" %c",(i+97));
printf("\n");
for (i=0;i <process;i++) {
P[i]=i;
printf("P[%d] ",P[i]);
for (j=0;j<no_of_resources;j++) {
scanf("%d",&allocated[i][j]);
availability[j]+=allocated[i][j];
}
}
printf("\nEnter the MAX matrix \n ");
for (i=0;i<no_of_resources;i++) {
printf(" %c",(i+97));
availability[i]=instance[i]-availability[i];
}
printf("\n");
for (i=0;i <process;i++) {
printf("P[%d] ",i);
for (j=0;j<no_of_resources;j++)
scanf("%d", &MAX[i][j]);
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

printf("\n");
A: a=-1;
for (i=0;i <process;i++) {
cnt=0;
b=P[i];
for (j=0;j<no_of_resources;j++) {
need[b][j] = MAX[b][j]-allocated[b][j];
if(need[b][j]<=availability[j])
cnt++;
}
if(cnt==no_of_resources) {
op[k++]=P[i];
for (j=0;j<no_of_resources;j++)
availability[j]+=allocated[b][j];
} else
P[++a]=P[i];
}
if(a!=-1) {
process=a+1;
goto A;
}
printf("\t <");
for (i=0;i<k;i++)
printf(" P[%d] ",op[i]);
printf(">");
getch();
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write a C program to Implement Deadlock Detection Algorithm


Exp.no: 8

Date:

Aim:

To Write a C program to Implement Deadlock Detection Algorithm

Algorithm:

Step 1
1. Let Work(vector) length = m
2. Finish(vector) length = n
3. Initialise Work= Available.
1. if Allocationi = 0 ∀ i ∈[0,N-1], then Finish[i] = true;
otherwise, Finish[i]= false.
Step 2
1. Find an index i such that both
1. Finish[i] == false
2. Work >= Requesti
If there exists no i, go to step 4.
Step 3
1. Work += Allocationi
2. Finish[i] = true
Go to Step 2.
Step 4
1. For some i in [0,N), if Finish[i]==false, then the system is considered in a deadlock
state. Moreover, if Finish[i]==false the process Pi is deadlocked.

Program:

#include
using namespace std;
int arrmax[100][100];

int alloc[100][100];
int need[100][100];
int avail[100];
int n, r;

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

void input()
{
int i, j;
cout << "Enter the no of Processes\t";
cin >> n;
cout << "Enter the no of resource instances\t";
cin >> r;
cout << "Enter the Max Matrix\n";
for (i = 0; i < n; i++)
{
for (j = 0; j < r; j++)
{
cin >> arrmax[i][j];
}
}
cout << "Enter the Allocation Matrix\n";
for (i = 0; i < n; i++)
{
for (j = 0; j < r; j++)
{
cin >> alloc[i][j];
}
}
cout << "Enter the available Resources\n";
for (j = 0; j < r; j++)
{
cin >> avail[j];
}
}
void show()
{
int i, j;
cout << "Process\t Allocation\t Max\t Available\t";
for (i = 0; i < n; i++)
{
cout << "\nP" << i + 1 << "\t ";
for (j = 0; j < r; j++)
{
cout << alloc[i][j] << " ";
}
cout << "\t\t";

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

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


{
cout << arrmax[i][j] << " ";
}
cout << "\t ";
if (i == 0)
{
for (j = 0; j < r; j++)
cout << avail[j] << " ";
}
}
}
void cal()
{
int finish[100], temp, need[100][100], flag = 1, k, c1 = 0;
int dead[100];
int safe[100];
int i, j;
for (i = 0; i < n; i++)
{
finish[i] = 0;
}
//find need matrix
for (i = 0; i < n; i++)
{
for (j = 0; j < r; j++)
{
need[i][j] = arrmax[i][j] - alloc[i][j];
}
}
while (flag)
{
flag = 0;
for (i = 0; i < n; i++)
{
int c = 0;
for (j = 0; j < r; j++)
{
if ((finish[i] == 0) && (need[i][j] <= avail[j]))
{
c++;
if (c == r)

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

{
for (k = 0; k < r; k++)
{
avail[k] += alloc[i][j];
finish[i] = 1;
flag = 1;
}
//cout<<"\nP%d",i;
if (finish[i] == 1)
{
i = n;
}
}
}
}
}
}
j = 0;
flag = 0;
for (i = 0; i < n; i++)
{
if (finish[i] == 0)
{
dead[j] = i;
j++;
flag = 1;
}
}
if (flag == 1)
{
cout << "\n\nSystem is in Deadlock and the Deadlock process are\n";
for (i = 0; i < n; i++)
{
cout << "P" << dead[i] << "\t";
}
}
else
{
cout << "\nNo Deadlock Occur";
}
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

int main()
{
int i, j;
cout << "********** Deadlock Detection Algorithm ************\n";
input();
show();
cal();
return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C program to implement Threading


Exp.no: 9

Date:

Aim:

To Write C program to implement Threading

Algorithm:

Step 1: Define a function func that takes a void* argument and returns a void* pointer.
Step 2: Inside the func function, detach the current thread using pthread_detach(pthread_self())
so that it can continue running independently of the parent thread.
Step 3: Print a message indicating that the function is running.
Step 4: Exit the thread using pthread_exit(NULL) so that it terminates.
Step 5: Define a function fun.
Step 6: Declare a pthread_t variable named ptid to store the ID of the new thread that will be
created.
Step 7: Inside the fun function, create a new thread using pthread_create(&ptid, NULL, &func,
NULL) with the func function as the thread function.
Step 8: Print a message indicating that the current line may be printed before the thread
terminates.
Step 9: Compare the ID of the current thread with the ID of the newly created thread using
pthread_equal(ptid, pthread_self()).
Step 10: If the IDs are equal, print a message indicating that the threads are equal.
Step 11: If the IDs are not equal, print a message indicating that the threads are not equal.
Step 12: Wait for the newly created thread to terminate using pthread_join(ptid, NULL).
Step 13: Print a message indicating that the current line will be printed after the thread ends.
Step 14: Exit the thread using pthread_exit(NULL).

Program:

// C program to show thread functions

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

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

void* func(void* arg)


{
// detach the current thread
// from the calling thread
pthread_detach(pthread_self());

printf("Inside the thread\n");

// exit the current thread


pthread_exit(NULL);
}

void fun()
{
pthread_t ptid;

// Creating a new thread


pthread_create(&ptid, NULL, &func, NULL);
printf("This line may be printed"
" before thread terminates\n");

// The following line terminates


// the thread manually
// pthread_cancel(ptid);

// Compare the two threads created


if(pthread_equal(ptid, pthread_self())
printf("Threads are equal\n");
else
printf("Threads are not equal\n");

// Waiting for the created thread to terminate


pthread_join(ptid, NULL);

printf("This line will be printed"


" after thread ends\n");

pthread_exit(NULL);
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

// Driver code
int main()
{
fun();
return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Implement the paging Technique using C program

Exp.no: 10

Date:

Aim:

To Implement the paging Technique using C program

Algorithm:

Step 1: Declare variables to store the memory size, page size, number of pages, frame numbers
for each page, frame number, offset, logical address, physical address, loop counter, and choice.
Step 2: Prompt the user to enter the memory size and print the value.
Step 3: Prompt the user to enter the page size and store the value.
Step 4: Calculate the number of pages by dividing the memory size by the page size and store
the value.
Step 5: Use a loop to prompt the user to enter the frame number for each page and store the
values in an array.
Step 6: Use a do-while loop to allow the user to enter a logical address and map it to a physical
address until the user chooses to stop.
Step 7: Inside the do-while loop, prompt the user to enter a logical address and store the value.
Step 8: Calculate the frame number by dividing the logical address by the page size and store
the value.
Step 9: Calculate the offset by finding the remainder of the logical address divided by the page
size and store the value.
Step 10: Calculate the physical address by multiplying the frame number with the page size and
adding the offset, and store the value.
Step 11: Print the physical address.
Step 12: Prompt the user to continue or stop and store the choice.
Step 13: Continue the loop if the choice is 1.
Step 14: Exit the loop if the choice is 0.
Step 15: Exit the program

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Program:

#include<stdio.h>
void main()

{
int memsize=15;
int pagesize,nofpage;
int p[100];
int frameno,offset;
int logadd,phyadd;
int i;
int choice=0;
printf("\nYour memsize is %d ",memsize);
printf("\nEnter page size:");
scanf("%d",&pagesize);

nofpage=memsize/pagesize;

for(i=0;i<nofpage;i++)
{
printf("\nEnter the frame of page%d:",i+1);
scanf("%d",&p[i]);
}

do
{
printf("\nEnter a logical address:");
scanf("%d",&logadd);
frameno=logadd/pagesize;
offset=logadd%pagesize;
phyadd=(p[frameno]*pagesize)+offset;
printf("\nPhysical address is:%d",phyadd);
printf("\nDo you want to continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1);
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the following Memory Allocation Methods

Exp.no: 11 a

Date:

Aim:

To Write C programs to implement the following Memory Allocation Methods


a. First Fit b. Worst Fit c. Best Fit

Algorithm:

Step 1: Initialize the memory and memory status arrays to indicate that all memory blocks are
free.
Step 2: Search for the first contiguous block of free memory that is large enough to hold the
requested size.
Step 3: If a block of sufficient size is found, allocate the block by setting the status of each
memory location in the block to "allocated" and return a pointer to the beginning of the block.
Step 4: If a block of sufficient size is not found, return NULL to indicate that the allocation
failed.

Program:

#include <stdio.h>

#define MAX_MEMORY 10000


#define FREE 0
#define ALLOCATED 1

int memory[MAX_MEMORY];
int memoryStatus[MAX_MEMORY];

void initMemory() {
for(int i = 0; i < MAX_MEMORY; i++) {
memory[i] = 0;
memoryStatus[i] = FREE;
}
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

void displayMemory() {
printf("Memory:\n");
for(int i = 0; i < MAX_MEMORY; i++) {
if(memoryStatus[i] == ALLOCATED) {
printf("%d ", memory[i]);
}
else {
printf("- ");
}
}
printf("\n");
}

void *firstFit(int size) {


int startIndex = -1;
int count = 0;
for(int i = 0; i < MAX_MEMORY; i++) {
if(memoryStatus[i] == FREE) {
if(count == 0) {
startIndex = i;
}
count++;
}
else {
if(count >= size) {
for(int j = startIndex; j < startIndex + size; j++) {
memoryStatus[j] = ALLOCATED;
}
return &memory[startIndex];
}
count = 0;
}
}
if(count >= size) {
for(int j = startIndex; j < startIndex + size; j++) {
memoryStatus[j] = ALLOCATED;
}
return &memory[startIndex];
}
return NULL;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

int main() {
initMemory();
displayMemory();
int *p1 = (int*)firstFit(10);
if(p1 != NULL) {
*p1 = 10;
}
int *p2 = (int*)firstFit(20);
if(p2 != NULL) {
*p2 = 20;
}
displayMemory();
return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the following Memory Allocation Methods

Exp.no: 11 b

Date:

Aim:

To Write C programs to implement the following Memory Allocation Methods


a. First Fit b. Worst Fit c. Best Fit

Algorithm:

Step 1: Initialize the memory and memory status arrays to indicate that all memory blocks are
free.
Step 2: Search for the largest contiguous block of free memory that is large enough to hold the
requested size.
Step 3: If a block of sufficient size is found, allocate the block by setting the status of each
memory location in the block to "allocated" and return a pointer to the beginning of the block.
Step 4: If a block of sufficient size is not found, return NULL to indicate that the allocation
failed.

Program:

#include <stdio.h>

#define MAX_MEMORY 10000


#define FREE 0
#define ALLOCATED 1

int memory[MAX_MEMORY];
int memoryStatus[MAX_MEMORY];

void initMemory() {
for(int i = 0; i < MAX_MEMORY; i++) {
memory[i] = 0;
memoryStatus[i] = FREE;
}
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

void displayMemory() {
printf("Memory:\n");
for(int i = 0; i < MAX_MEMORY; i++) {
if(memoryStatus[i] == ALLOCATED) {
printf("%d ", memory[i]);
}
else {
printf("- ");
}
}
printf("\n");
}

void *worstFit(int size) {


int startIndex = -1;
int count = 0;
int maxCount = 0;
for(int i = 0; i < MAX_MEMORY; i++) {
if(memoryStatus[i] == FREE) {
if(count == 0) {
startIndex = i;
}
count++;
}
else {
if(count >= size && count > maxCount) {
startIndex = i - count;
maxCount = count;
}
count = 0;
}
}
if(count >= size && count > maxCount) {
startIndex = MAX_MEMORY - count;
maxCount = count;
}
if(maxCount >= size) {
for(int j = startIndex; j < startIndex + size; j++) {
memoryStatus[j] = ALLOCATED;
return &memory[startIndex];
}
return NULL;

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

int main() {
initMemory();
displayMemory();
int *p1 = (int*)worstFit(10);
if(p1 != NULL) {
*p1 = 10;
}
int *p2 = (int*)worstFit(20);
if(p2 != NULL) {
*p2 = 20;
}
displayMemory();
return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the following Memory Allocation Methods

Exp.no: 11 c

Date:

Aim:

To Write C programs to implement the following Memory Allocation Methods


a. First Fit b. Worst Fit c. Best Fit

Algorithm:

Step 1: Initialize the memory and memory status arrays to indicate that all memory blocks are
free.
Step 2: Search for the smallest contiguous block of free memory that is large enough to hold
the requested size.
Step 3: If a block of sufficient size is found, allocate the block by setting the status of each
memory location in the block to "allocated" and return a pointer to the beginning of the block.
Step 4: If a block of sufficient size is not found, return NULL to indicate that the allocation
failed.

Program:

#include <stdio.h>

#define MAX_MEMORY 10000


#define FREE 0
#define ALLOCATED 1

int memory[MAX_MEMORY];
int memoryStatus[MAX_MEMORY];

void initMemory() {
for(int i = 0; i < MAX_MEMORY; i++) {
memory[i] = 0;
memoryStatus[i] = FREE;
}
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

void displayMemory() {
printf("Memory:\n");
for(int i = 0; i < MAX_MEMORY; i++) {
if(memoryStatus[i] == ALLOCATED) {
printf("%d ", memory[i]);
}
else {
printf("- ");
}
}
printf("\n");
}

void *bestFit(int size) {


int startIndex = -1;
int count = 0;
int minCount = MAX_MEMORY + 1;
for(int i = 0; i < MAX_MEMORY; i++) {
if(memoryStatus[i] == FREE) {
if(count == 0) {
startIndex = i;
}
count++;
}
else {
if(count >= size && count < minCount) {
startIndex = i - count;
minCount = count;
}
count = 0;
}
}
if(count >= size && count < minCount) {
startIndex = MAX_MEMORY - count;
minCount = count;
}
if(minCount >= size) {
for(int j = startIndex; j < startIndex + size; j++) {
memoryStatus[j] = ALLOCATED;
}
return &memory[startIndex];
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

return NULL;
}

int main() {
initMemory();
displayMemory();
int *p1 = (int*)bestFit(10);
if(p1 != NULL) {
*p1 = 10;
}
int *p2 = (int*)bestFit(20);
if(p2 != NULL) {
*p2 = 20;
}
displayMemory();
return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the various Page Replacement Algorithms

Exp.no: 12 a

Date:

Aim:

To Write C programs to implement the various Page Replacement Algorithms using First-In,
First-Out (FIFO) Page Replacement Algorithm.

Algorithm:

Step 1: Initialize a queue to store the pages currently in memory.

Step 2: For each page request:


a. If the page is already in memory, continue to the next page request.
b. If the memory is not full, add the page to the end of the queue and mark it as "in memory".
c. If the memory is full, remove the first page from the queue, add the new page to the end of
the queue, and mark it as "in memory".

Step 3: Repeat step 2 for each page request.

Program:

#include <stdio.h>
#define MAX_FRAMES 3
#define MAX_REFERENCES 20

int frames[MAX_FRAMES];
int head = 0;
int faultCount = 0;

void initFrames() {
for (int i = 0; i < MAX_FRAMES; i++) {
frames[i] = -1;
}
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

int findPage(int page) {


for (int i = 0; i < MAX_FRAMES; i++) {
if (frames[i] == page) {
return i;
}
}
return -1;
}

void displayFrames() {
for (int i = 0; i < MAX_FRAMES; i++) {
printf("%d ", frames[i]);
}
printf("\n");
}

void fifo(int references[], int n) {


initFrames();
for (int i = 0; i < n; i++) {
int page = references[i];
int index = findPage(page);
if (index == -1) {
frames[head] = page;
head = (head + 1) % MAX_FRAMES;
faultCount++;
}
displayFrames();
}
printf("FIFO Fault Count: %d\n", faultCount);
}
int main() {
int references[MAX_REFERENCES] = {0, 1, 2, 3, 0, 1, 4, 0, 1, 2, 3, 4, 2, 3, 0, 3, 2, 1, 2, 0};
int n = 20;
fifo(references, n);
return 0;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the various Page Replacement Algorithms

Exp.no: 12 b

Date:

Aim:

To Write C programs to implement the various Page Replacement Algorithms using Least
Recently Used algorithm.

Algorithm:

Step 1: Initialize a list to store the pages currently in memory.

Step 2: For each page request:


a. If the page is already in memory, move it to the end of the list (to indicate it was most
recently used).
b. If the memory is not full, add the page to the end of the list and mark it as "in memory".
c. If the memory is full, remove the first page from the list, add the new page to the end of the
list, and mark it as "in memory".

Step 3: Repeat step 2 for each page request.

Program:

#include<stdio.h>
main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf("Enter no of pages:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

k++;
for(i=1;i<n;i++)
{
c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

b[r]=b[j];
b[j]=t;
}
}
}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf("\t%d",q[r]);
}
printf("\n");
}
}
}
printf("\nThe no of page faults is %d",c);

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the various Page Replacement Algorithms

Exp.no: 12 c

Date:

Aim:

To Write C programs to implement the various Page Replacement Algorithms using Optimal
Page Replacement algorithm.
.

Algorithm:

Step 1: Initialize a table to store the future references for each page.

Step 2: For each page request:


a. If the page is already in memory, continue to the next page request.
b. If the memory is not full, add the page to memory and update the future references table
for the page.
c. If the memory is full, determine which page in memory has the latest future reference.
d. Replace the page with the latest future reference and add the new page to memory.

Step 3: Repeat step 2 for each page request.

Program:

#include<stdio.h>
int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j, k,
pos, max, faults = 0;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);

printf("Enter number of pages: ");


scanf("%d", &no_of_pages);

printf("Enter page reference string: ");

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

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


scanf("%d", &pages[i]);
}

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


frames[i] = -1;
}

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


flag1 = flag2 = 0;

for(j = 0; j < no_of_frames; ++j){


if(frames[j] == pages[i]){
flag1 = flag2 = 1;
break;
}
}

if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == -1){
faults++;
frames[j] = pages[i];
flag2 = 1;
break;
}
}
}

if(flag2 == 0){
flag3 =0;

for(j = 0; j < no_of_frames; ++j){


temp[j] = -1;

for(k = i + 1; k < no_of_pages; ++k){


if(frames[j] == pages[k]){
temp[j] = k;
break;
}
}
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

for(j = 0; j < no_of_frames; ++j){


if(temp[j] == -1){
pos = j;
flag3 = 1;
break;
}
}

if(flag3 ==0){
max = temp[0];
pos = 0;

for(j = 1; j < no_of_frames; ++j){


if(temp[j] > max){
max = temp[j];
pos = j;
}
}
}
frames[pos] = pages[i];
faults++;
}

printf("\n");

for(j = 0; j < no_of_frames; ++j){


printf("%d\t", frames[j]);
}
}

printf("\n\nTotal Page Faults = %d", faults);

return 0;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the various Page Replacement Algorithms

Exp.no: 12 d

Date:

Aim:

To Write C programs to implement the various Page Replacement Algorithms using Clock Page
Replacement algorithm.

Algorithm:

Step 1: Initialize a circular list to store the pages currently in memory.

Step 2: For each page request:


a. If the page is already in memory, set its reference bit to 1 and continue to the next page
request.
b. If the memory is not full, add the page to memory with its reference bit set to 1.
c. If the memory is full, traverse the list of pages in memory:
i. If the reference bit of the current page is 0, replace the page with the new page and set its
reference bit to 1.
ii. If the reference bit of the current page is 1, set the reference bit to 0 and move to the
next page.
iii. If all pages in memory have a reference bit of 1, start over from the beginning of the
list.

Step 3: Repeat step 2 for each page request.

Program:

#include<stdio.h>
int main()
{
int n,p[100],f[10],ava,hit=0,usebit[10],i,j;
printf("enter the length of the Reference string: ");
scanf("%d",&n);
printf("enter the reference string: \n");
for(i=0;i<n;i++)
scanf("%d",&p[i]);

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

for(i=0;i<n;i++)
{
ava=0;
// found
for(j=0;j<3;j++)
{
if(p[i]==f[j])
{
ava=1;
hit++;
usebit[j]=1;
break;
}
}
//search for usebit 0
if(ava==0)
{
for(j=0;j<3;j++)
{
if(usebit[j]==0)
{
f[j]=p[i];
usebit[j]=1;
ava=1;
break;
}
}
}
// fifo
if(ava==0)
{
for(j=0;j<3;j++)
usebit[j]=0;
}
f[0]=p[i];
usebit[0]=1;
}
printf("The number of Hits: %d",hit);
return 0;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to implement the various Page Replacement Algorithms

Exp.no: 12 e

Date:

Aim:

To Write C programs to implement the various Page Replacement Algorithms using Least-
Frequently Used algorithm.

Algorithm:

Step 1: Initialize a table to store the frequency count for each page in memory.

Step 2: For each page request:


a. If the page is already in memory, increment its frequency count and continue to the next
page request.
b. If the memory is not full, add the page to memory with a frequency count of 1.
c. If the memory is full, determine which page in memory has the lowest frequency count.
d. Replace the page with the lowest frequency count and add the new page to memory with a
frequency count of 1.

Step 3: Repeat step 2 for each page request.

Program:

#include<stdio.h>
void print(int frameno,int frame[])
{
int j;
for(j=0;j<frameno;j++)
printf("%d\t",frame[j]);
printf("\n");
}
int main()
{
int i,j,k,n,page[50],frameno,frame[10],move=0,flag,count=0,count1[10]={0},
repindex,leastcount;
float rate;
printf("Enter the number of pages\n");

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

scanf("%d",&n);
printf("Enter the page reference numbers\n");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter the number of frames\n");
scanf("%d",&frameno);
for(i=0;i<frameno;i++)
frame[i]=-1;
printf("Page reference string\tFrames\n");
for(i=0;i<n;i++)
{
printf("%d\t\t\t",page[i]);
flag=0;
for(j=0;j<frameno;j++)
{
if(page[i]==frame[j])
{
flag=1;
count1[j]++;
printf("No replacement\n");
break;
}
}
if(flag==0&&count<frameno)
{
frame[move]=page[i];
count1[move]=1;
move=(move+1)%frameno;
count++;
print(frameno,frame);
}
else if(flag==0)
{
repindex=0;
leastcount=count1[0];
for(j=1;j<frameno;j++)
{
if(count1[j]<leastcount)
{
repindex=j;
leastcount=count1[j];
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

frame[repindex]=page[i];
count1[repindex]=1;
count++;
print(frameno,frame);
}
}
rate=(float)count/(float)n;
printf("Number of page faults is %d\n",count);
printf("Fault rate is %f\n",rate);
return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to Implement the various File Organization Techniques

Exp.no: 13 a

Date:

Aim:

To Write C programs to Implement the various File Organization Techniques.

Algorithm:
Step 1:Sort the records in the file based on a specific key
Step 2: Open the file in read mode
Step 3: Read the first record
Step 4: Process the record
Step 5:Read the next record until end of file
Step 6: Close the file

Program:

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

typedef struct student {


int rollNo;
char name[30];
int marks;
} Student;

int main() {
FILE *fp;
Student s;
int i, n;
char filename[20];

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


scanf("%d", &n);

// create a new file for writing


printf("Enter the file name: ");

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

scanf("%s", filename);
fp = fopen(filename, "wb");

// write data to the file


for (i = 0; i < n; i++) {
printf("\nEnter roll number: ");
scanf("%d", &s.rollNo);
printf("Enter name: ");
scanf("%s", s.name);
printf("Enter marks: ");
scanf("%d", &s.marks);

fwrite(&s, sizeof(Student), 1, fp);


}

fclose(fp);

// open the file for reading


fp = fopen(filename, "rb");

// read data from the file


printf("\nRoll No.\tName\t\tMarks\n");
while (fread(&s, sizeof(Student), 1, fp)) {
printf("%d\t\t%s\t\t%d\n", s.rollNo, s.name, s.marks);
}

fclose(fp);
return 0;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to Implement the various File Organization Techniques

Exp.no: 13 b

Date:

Aim:

To Write C programs to Implement the various File Organization Techniques.

Algorithm:

Step 1:Determine the number of records that can be stored in a block


Step 2:Divide the file into blocks and allocate each block to a specific record using a hashing
function
Step 3:Open the file in read or write mode
Step 4:Compute the block number for the record
Step 5:Read or write the record to the block
Step 6:Close the file
Program:

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

typedef struct student {


int rollNo;
char name[30];
int marks;
} Student;

typedef struct index {


int rollNo;
int offset;
} Index;

int main() {
FILE *fp, *ip;
Student s;
Index idx;
int i, n;
char filename[20], indexFilename[20];

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

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


scanf("%d", &n);

// create a new file for writing


printf("Enter the file name: ");
scanf("%s", filename);
fp = fopen(filename, "wb");

// create a new index file for writing


printf("Enter the index file name: ");
scanf("%s", indexFilename);
ip = fopen(indexFilename, "wb");

// write data to the file and index file


for (i = 0; i < n; i++) {
printf("\nEnter roll number: ");
scanf("%d", &s.rollNo);
printf("Enter name: ");
scanf("%s", s.name);
printf("Enter marks: ");
scanf("%d", &s.marks);

// write data to the file


fwrite(&s, sizeof(Student), 1, fp);

// write data to the index file


idx.rollNo = s.rollNo;
idx.offset = i * sizeof(Student);
fwrite(&idx, sizeof(Index), 1, ip);
}

fclose(fp);
fclose(ip);

// open the index file for reading


ip = fopen(indexFilename, "rb");

// search for a student record


int rollNo, found = 0;
printf("\nEnter the roll number to search: ");
scanf("%d", &rollNo);

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

while (fread(&idx, sizeof(Index), 1, ip)) {


if (idx.rollNo == rollNo) {
// open the data file and seek to the record
fp = fopen(filename, "rb");
fseek(fp, idx.offset, SEEK_SET);
fread(&s, sizeof(Student), 1, fp);
printf("\nRoll No.: %d\nName: %s\nMarks: %d\n", s.rollNo, s.name, s.marks);
found = 1;
break;
}
}

if (!found) {
printf("\nStudent record not found.\n");
}

fclose(fp);
fclose(ip);

return 0;
}

Output:

Result

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs to Implement the various File Organization Techniques

Exp.no: 13 b

Date:

Aim:

To Write C programs to Implement the various File Organization Techniques.

Algorithm:

Step 1:Create an index file with keys and pointers to the corresponding records in the data file
Step 2:Open the index file in read or write mode
Step 3:Read or write the index entries
Step 4:Open the data file in read or write mode
Step 5:Read or write the record using the pointer from the index file
Step 6:Close both files
Program:

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

typedef struct student {


int rollNo;
char name[30];
int marks;
} Student;

int main() {
FILE *fp;
Student s;
int i, n;
char filename[20];

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


scanf("%d", &n);

// create a new file for writing


printf("Enter the file name: ");

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

scanf("%s", filename);
fp = fopen(filename, "wb");
// write data to the file
for (i = 0; i < n; i++) {
printf("\nEnter roll number: ");
scanf("%d", &s.rollNo);
printf("Enter name: ");
scanf("%s", s.name);
printf("Enter marks: ");
scanf("%d", &s.marks);
fwrite(&s, sizeof(Student), 1, fp);
}

fclose(fp);

// open the file for reading


fp = fopen(filename, "rb");

// search for a student record


int rollNo, found = 0;
printf("\nEnter the roll number to search: ");
scanf("%d", &rollNo);

while (fread(&s, sizeof(Student), 1, fp)) {


if (s.rollNo == rollNo) {
found = 1;
printf("\nStudent details:\n");
printf("Roll number: %d\n", s.rollNo);
printf("Name: %s\n", s.name);
printf("Marks: %d\n", s.marks);
break;
}
}

if (!found) {
printf("\nStudent not found.\n");
}

fclose(fp);

return 0;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Implement the following File Allocation Strategies using C programs

Exp.no: 14 a

Date:

Aim:

To Implement the following File Allocation Strategies using C programs


a. Sequential b. Indexed c. Linked

Algorithm:

Step 1: Calculate the number of blocks needed for the file


Step 2: Allocate the blocks sequentially
Step 3: Write the records to the blocks
Step 4: Read the records from the blocks

Program:

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

#define BLOCK_SIZE 512

int main()
{
int num_blocks, num_files, i, j, file_size;
char buffer[BLOCK_SIZE];
FILE *fp;

printf("Enter the number of blocks in the disk: ");


scanf("%d", &num_blocks);

// initialize the disk with all zeroes


fp = fopen("disk.bin", "wb");
for (i = 0; i < num_blocks; i++) {
fwrite(buffer, BLOCK_SIZE, 1, fp);
}
fclose(fp);

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

// prompt user for number of files


printf("Enter the number of files: ");
scanf("%d", &num_files);

// create files on disk


for (i = 1; i <= num_files; i++) {
printf("Enter the size of file %d: ", i);
scanf("%d", &file_size);

// check if there is enough space on disk to write file


fp = fopen("disk.bin", "rb+");
int block_num = 0;
while (fread(buffer, BLOCK_SIZE, 1, fp)) {
int free_space = 0;
for (j = 0; j < BLOCK_SIZE; j++) {
if (buffer[j] == 0) {
free_space++;
if (free_space == file_size) {
break;
}
} else {
free_space = 0;
}
}
if (free_space == file_size) {
// write file to disk
fseek(fp, block_num * BLOCK_SIZE + j - free_space + 1, SEEK_SET);
for (j = 0; j < file_size; j++) {
buffer[block_num * BLOCK_SIZE + j] = 1;
}
fwrite(buffer, BLOCK_SIZE, 1, fp);
printf("File %d written to disk at block %d\n", i, block_num);
break;
}
block_num++;
}
fclose(fp);
}

return 0;
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Implement the following File Allocation Strategies using C programs

Exp.no: 14 b

Date:

Aim:

To Implement the following File Allocation Strategies using C programs


a. Sequential b. Indexed c. Linked

Algorithm:
Step 1:Calculate the number of blocks needed for the file
Step 2: Allocate the blocks using indexed allocation
Step 3: Write the records to the blocks
Step 4: Read the records from the blocks

Program:

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

#define BLOCK_SIZE 512


#define MAX_BLOCKS 100

typedef struct {
int blockNumber;
int fileSize;
} Index;

void createFile(char *filename, int *file, int fileSize) {


FILE *fp = fopen(filename, "wb");
int numBlocks = (fileSize + BLOCK_SIZE - 1) / BLOCK_SIZE;
fwrite(file, sizeof(int), fileSize, fp);
for (int i = fileSize; i < numBlocks * BLOCK_SIZE; i++) {
fputc(0, fp);
}
fclose(fp);
}

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

void indexFile(char *filename, char *indexFilename, int fileSize) {


FILE *fp = fopen(filename, "rb");
FILE *ip = fopen(indexFilename, "wb");
int numBlocks = (fileSize + BLOCK_SIZE - 1) / BLOCK_SIZE;
Index index[numBlocks];
for (int i = 0; i < numBlocks; i++) {
index[i].blockNumber = i + 1;
if (i == numBlocks - 1) {
index[i].fileSize = fileSize - i * BLOCK_SIZE;
} else {
index[i].fileSize = BLOCK_SIZE;
}
fwrite(&index[i], sizeof(Index), 1, ip);
}
fclose(fp);
fclose(ip);
}

void readFile(char *filename, char *indexFilename) {


FILE *fp = fopen(filename, "rb");
FILE *ip = fopen(indexFilename, "rb");
Index index[MAX_BLOCKS];
int i = 0;
while (fread(&index[i], sizeof(Index), 1, ip)) {
if (index[i].blockNumber != -1) {
fseek(fp, (index[i].blockNumber - 1) * BLOCK_SIZE, SEEK_SET);
for (int j = 0; j < index[i].fileSize; j++) {
printf("%c", fgetc(fp));
}
}
i++;
}
fclose(fp);
fclose(ip);
}

int main() {
char filename[20], indexFilename[20];
int fileSize, file[MAX_BLOCKS];
printf("Enter file name: ");
scanf("%s", filename);

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

printf("Enter file size: ");


scanf("%d", &fileSize);
printf("Enter file contents: ");
for (int i = 0; i < fileSize; i++) {
scanf("%d", &file[i]);
}
createFile(filename, file, fileSize);
indexFile(filename, indexFilename, fileSize);
readFile(filename, indexFilename);
return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Implement the following File Allocation Strategies using C programs

Exp.no: 14 c

Date:

Aim:

To Implement the following File Allocation Strategies using C programs


a. Sequential b. Indexed c. Linked

Algorithm:

Step 1: Define a structure to represent each block in the file


Step 2: Initialize a linked list of blocks to represent the file
Step 3: Open the file in write mode
Step 4: Open the file in read mode
Step 5: To append a block to the file
Step 6: To delete a block from the file

Program:

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

#define BLOCK_SIZE 512

typedef struct block {


char data[BLOCK_SIZE];
int next;
} Block;

int main() {
FILE *fp;
Block b;
int i, n, head, tail, newBlock;
char filename[20];

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

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


scanf("%d", &n);

// create a new file for writing


printf("Enter the file name: ");
scanf("%s", filename);
fp = fopen(filename, "wb");

// initialize the first block


head = 0;
tail = 0;
b.next = -1;
fwrite(&b, sizeof(Block), 1, fp);

// allocate and write data to the file blocks


for (i = 1; i <= n; i++) {
printf("\nEnter data for block %d: ", i);
scanf("%s", b.data);

// write data to the current block


fwrite(&b, sizeof(Block), 1, fp);

// remember the current block position


tail = ftell(fp) - sizeof(Block);

// allocate a new block


b.next = -1;
fwrite(&b, sizeof(Block), 1, fp);

// remember the new block position


newBlock = ftell(fp) - sizeof(Block);

// update the previous block's next pointer to point to the new block
fseek(fp, tail, SEEK_SET);
fread(&b, sizeof(Block), 1, fp);
b.next = newBlock;
fseek(fp, tail, SEEK_SET);
fwrite(&b, sizeof(Block), 1, fp);
}

fclose(fp);

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

// read and print data from the file blocks


printf("\nData in the file:\n");
fp = fopen(filename, "rb");
fseek(fp, head, SEEK_SET);

while (head != -1) {


fread(&b, sizeof(Block), 1, fp);
printf("%s", b.data);
head = b.next;
fseek(fp, head, SEEK_SET);
}

fclose(fp);

return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Write C programs for the implementation of various disk scheduling algorithms

Exp.no: 15

Date:

Aim:

Write C programs for the implementation of various disk scheduling algorithms

Algorithm:

Step 1: Determine the current head position on the disk.


Step 2: Select a disk scheduling algorithm to use: FCFS, SSTF, SCAN, C-SCAN, LOOK, or C-
LOOK.
Step 3: FCFS (First-Come-First-Serve): Traverse the list of requests in the order they were
received
Step 4: SSTF (Shortest-Seek-Time-First): Sort the list of requests by their distance from the
current head position
Step 5: SCAN: Sort the list of requests by their location on the disk and process the requests in
the sorted order in one direction
Step 6: Output the order in which the requests were processed

Program:

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

int main() {
int queue[20], n, head, i;
float avg_seek_time;

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


scanf("%d", &n);

printf("Enter the queue of disk positions to be read: ");


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

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

scanf("%d", &queue[i]);
}

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


scanf("%d", &head);

int distance = abs(head - queue[0]);


for (i = 1; i < n; i++) {
distance += abs(queue[i] - queue[i-1]);
}

avg_seek_time = (float)distance / n;

printf("Average seek time = %f\n", avg_seek_time);

return 0;
}

Output:

Result:

Downloaded by Deepa S (dpa148106@gmail.com)


lOMoARcPSD|38975850

Downloaded by Deepa S (dpa148106@gmail.com)

You might also like