0% found this document useful (0 votes)
18 views62 pages

OS Lab Manual

The document discusses the code of conduct, vision, mission and objectives of Vidya Vikas Institute of Engineering and Technology. It outlines the standards of conduct expected from faculty towards the institute, students, colleagues and their discipline. It also provides the vision, mission and objectives of the institute and computer science department.

Uploaded by

sudarshannk38
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)
18 views62 pages

OS Lab Manual

The document discusses the code of conduct, vision, mission and objectives of Vidya Vikas Institute of Engineering and Technology. It outlines the standards of conduct expected from faculty towards the institute, students, colleagues and their discipline. It also provides the vision, mission and objectives of the institute and computer science department.

Uploaded by

sudarshannk38
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/ 62

VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

OPERATING SYSTEM
LAB MANUAL
BCS303

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

1. Code of Conduct

2. Vision and Mission of the Institute

3. Vision and Mission of the Department

4. Program Outcomes

5. Program Specific Outcomes

6. Syllabus

7. Laboratory Manual

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Code of Conduct

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

VidyaVikas Educational Trust®

1. Code of Conduct
Standards of Conduct

To,
Syeda Arbeena Kausar,
Department of Computer Science
VVIET, Mysore

Towards the College, the Faculty shall:

a. Read and abide by the policies established by the college


b. Contribute to the college by participating in the committees and clubs at various levels. They may
include Program committees, student clubs, faculty projects etc.,
c. Be asked to serve in any of the Institutions run by The VVET®.
d. Avoid potential conflicts of interest
e. Not engage in outside professional activity that conflicts with their responsibilities and duties in
College.
f. Avoid misrepresentation of personal views as a statement of position of the College.
g. Strictly adhere to the dress code prescribed by the Institution. Women - Sari; Men – formal trousers,
shirt and shoes.
h. Not be found to indulge in smoking, drinking,or other unacceptable behavior within the campus or
in its immediate proximity
i. English should be the language of teaching and communication in class and at all times with the
students.
j. Each faculty member is responsible for the material provided in class during his/her presence in
class.
k. Subsequently, after the class, the room shall be locked and key returned to the department. Keys
will only be handled by the Faculty and must not be given to students.
l. Faculty must use the infrastructure at their disposal, like video projectors, lap tops etc, as an aid in
their class room teaching.
m. Use of mobile phones is strictly prohibited in the class room and in the corridors of the college. They
must be switched off/ placed in silent mode during class.
n. Arrive at class on time and stay for the duration of time stipulated for the lecture in the time table

ll. Towards Students, The Faculty Shall:

a. Treat all students with fairness and respect.


b. Encourage the free exchange of ideas between themselves and students.
c. Any extra time after the lecture may be used for feedback and subject discussion with the students.
Students will not be allowed to leave before the completion of the time allotted.
d. Conscientiously strive to be fair and balanced in the evaluation of student work.
e. Should not exploit students for personal gain.
f. Should be fair and objective when providing references for students.
g. Should not disclose information about students to outside agencies.
h. Faculties are obliged to attend classes as scheduled and to maintain office hours
i. Faculty should help students and provide access to study material and information
j. Ragging in any form among students is strictly prohibited and such incidents must be brought to
the notice of the Management for suitable action.

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

III. Towards Colleagues, Faculty Shall:

a. Treat each other with fairness and respect, and conduct themselves with dignity and restraint in all
exchanges with colleagues.
b. Be fair and objective when presenting a professional judgment on their colleagues’ work
c. Not use threatening or abusive behavior or language, verbal harassment or intimidation of another
member of the faculty, under any circumstance while on the college campus.
d. Not knowingly misrepresent the views/positions of colleagues to further their own position or
point of view.

IV. Towards their Disciplines, Faculty Shall:

a. Exhibit intellectual honesty and integrity in all scholarly endeavors.


b. Work toward improving the quality of instruction.
c. Participate in all training programs provided to them.
d. Update themselves regularly in the advancements in their academic fields

v. Course Plan and Delivery: Faculty Shall

a. Faculty shall discuss with their Principal/HOD and submit a semester wise Lesson Plan. This will
be followed-up and monitored on a regular basis by the respective Principal/HOD.
b. The HODs/Principals shall make periodic surprise visits to classes to provide feedback on the
teaching methods and materials used. They will also check the diaries the faculty are expected to
maintain.

“I have read all the terms and conditions outlined in this document and agree to abide by them”

Name of the Faculty Signature of the Faculty

Syeda Arbeena Kausar

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Institute Vision and Mission

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

2. Institute Vision and Mission

Institute Vision

Our vision is to provide learning opportunities, ensuring excellence in education,


research and facilitate an inspiring world class environment to encourage
creativity. The Institute is committed to disseminating knowledge, and through its
ingenuity, bring this knowledge to bear on the world's great challenges. VVIET is
dedicated to providing its students with an education that combines academic
study and the excitement of discovery kindled by a diverse campus community.

Institute Mission

 Offer highest professional and academic standards in terms of personal


growth and satisfaction, and promote growth and value to our research
sponsors.
 Provide students a platform where independent learning and scientific
study are encouraged with emphasis on latest engineering techniques.
 Encourage students to implement applications of engineering with a focus
on societal needs for the betterment of communities.
 Empower students with vast technical and life skills to raise their stakes of
getting placements in top reputed companies.
 Create a benchmark in the areas of research, education and public outreach.

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Department Vision and


Mission

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

3. Department Vision and Mission

Department Vision

“To produce proficient computer professionals, having essential technical


knowledge and skills, with good work ethics”

Department Mission

M1: To promote growth of an individual by imparting comprehensive knowledge using latest


tools and technologies.

M2: To inculcate professionalism, social awareness and to promote creativity, research


aptitude by mentoring the students.

M3: To establish industry institute interaction, to enable students to cater the ever changing
industry demands and to nurture entrepreneurial qualities.

M4: To provide state-of-the-art environment and opportunities to enhance professional skills.

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Programme Educational
Objectives

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

4. Programme Educational Objectives

PEO 1: To provide Graduates of computer science & engineering course with a


solid foundation in the principles and practices of computer science and
engineering enabling them to have successful professional career.

PEO 2: To encourage Graduates of computer science & engineering course to


pursue higher education.

PEO 3: To prepare Graduates of computer science & engineering course to adapt


to technological advancements by engaging in lifelong learning.

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Programme Outcome

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

5. Program Outcomes (POs)


1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex
engineeringproblems.
2. Problem analysis: Identify, formulate, research literature, and Analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineeringsciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and
environmentalconsiderations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide validconclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities
with an understanding of thelimitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and theconsequent responsibilities relevant to
the professional engineeringpractice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineeringpractice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinarysettings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering 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.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinaryenvironments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technologicalchange.

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Programme Specific
Outcomes

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

6. Programme Specific Outcomes

PSO 1: Apply the appropriate programming constructs for solving


engineering problems.
PSO 2: Adapt to software development methodologies
PSO 3: Demonstrate the knowledge towards the domain specific
initiatives of Information Technology.

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Specification of the Laboratory

SI.NO MAJOR EQUPIMENT/SYSTEM SPECIFICATION

1 Computer CORE I5 8GB RAM 160GB HDD 17inch


MONITOR

2 SOFTWARE

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Syllabus

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Syllabus

OPERATING SYSTEM(BCS303)
1. Develop a c program to implement the Process system calls (fork (), exec(), wait(), create
process,
terminate process)
2. Simulate the following CPU scheduling algorithms to find turnaround time and waiting time
a) FCFS
3. b) SJF c) Round Robin d) Priority.
4. Develop a C program to simulate producer-consumer problem using semaphores.
5. Develop a C program which demonstrates interprocess communication between a reader
6. process and a writer process. Use mkfifo, open, read, write and close APIs in your program.
7. Develop a C program to simulate Bankers Algorithm for DeadLock Avoidance.
8. Develop a C program to simulate the following contiguous memory allocation Techniques:
a) Worst fit b) Best fit c) First fit.
9. Develop a C program to simulate page replacement algorithms:
a) FIFO b) LRU
10. Simulate following File Organization Techniques
a) Single level directory b) Two level directory
11. Develop a C program to simulate the Linked file allocation strategies.
12. Develop a C program to simulate SCAN disk scheduling algorithm.

Signature of the Lab Incharge Signature of the HOD

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

1. Develop a c program to implement the Process system calls (fork (), exec(),
wait(), create process, terminate process)

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

int main()
{
pid_t child_pid;
int status;

printf("Parent process (PID: %d)\n", getpid());

// Fork a child process


child_pid = fork();

if (child_pid < 0)
{
perror("Fork failed");
exit(1);
}

if (child_pid == 0)
{
// This code will be executed by the child process
printf("Child process (PID: %d) is running\n", getpid());

// Replace the child process image with a new program using exec
char *args[] = {"./child_program", NULL};

// Replace "./child_program" with the path to your child program


execv(args[0], args);

// The code after exec will only execute if exec fails


perror("Exec failed");
exit(1);
}
else {
// This code will be executed by the parent process

printf("Parent process is waiting for the child to terminate...\n");

// Wait for the child process to terminate


wait(&status);

if (WIFEXITED(status)) {
printf("Child process terminated with status: %d\n", WEXITSTATUS(status));
} else {
printf("Child process did not terminate normally\n");
VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

printf("Parent process is done\n");


}

return 0;
}

output
Parent process (PID: 1574)
Parent process is waiting for the child to terminate...
Child process (PID: 1578) is running
Exec failed: No such file or directory
Child process terminated with status: 1
Parent process is done

...Program finished with exit code 0

Press ENTER to exit console.

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

2. Write a c program to Simulate CPU scheduling algorithms to find turnaround


time and waiting time using FCFS.
a) FCFS
#include <stdio.h>

// Function to calculate turnaround time and waiting time for FCFS


void calculateFCFS(int processes[], int n, int burst_time[]) {
int waiting_time[n], turnaround_time[n];

// First process has a waiting time of 0


waiting_time[0] = 0;

// Calculate waiting time for each process


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

// Calculate turnaround time for each process


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

// Calculate and print the average waiting time and turnaround time
float total_waiting_time = 0, total_turnaround_time = 0;
for (int i = 0; i < n; i++) {
total_waiting_time += waiting_time[i];
total_turnaround_time += turnaround_time[i];
}

float avg_waiting_time = total_waiting_time / n;


float avg_turnaround_time = total_turnaround_time / n;

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


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

printf("\nAverage Waiting Time: %.2f\n", avg_waiting_time);


VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

printf("Average Turnaround Time: %.2f\n", avg_turnaround_time);


}

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

int processes[n];
int burst_time[n];

// Input burst times for each process


for (int i = 0; i < n; i++) {
processes[i] = i + 1;
printf("Enter burst time for P%d: ", i + 1);
scanf("%d", &burst_time[i]);
}

calculateFCFS(processes, n, burst_time);

return 0;
}

Output
Enter the number of processes: 5
Enter burst time for P1: 4
Enter burst time for P2: 5
Enter burst time for P3: 2
Enter burst time for P4: 6
Enter burst time for P5: 2
Process Burst Time Waiting Time Turnaround Time
P1 4 0 4
P2 5 4 9
P3 2 9 11
P4 6 11 17
P5 2 17 19

Average Waiting Time: 8.20


Average Turnaround Time: 12.00

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

...Program finished with exit code 0


Press ENTER to exit console.

B) SJF
#include <stdio.h>

void findWaitingTime(int processes[], int n, int burst_time[], int waiting_time[]) {


waiting_time[0] = 0;

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


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

void findTurnaroundTime(int processes[], int n, int burst_time[], int


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

void findAverageTimes(int processes[], int n, int burst_time[]) {


int waiting_time[n], turnaround_time[n];

findWaitingTime(processes, n, burst_time, waiting_time);


findTurnaroundTime(processes, n, burst_time, waiting_time,
turnaround_time);

float total_waiting_time = 0, total_turnaround_time = 0;


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

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

float avg_waiting_time = total_waiting_time / n;


float avg_turnaround_time = total_turnaround_time / n;

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


for (int i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", processes[i], burst_time[i],
waiting_time[i], turnaround_time[i]);
}

printf("\nAverage Waiting Time: %.2f\n", avg_waiting_time);


printf("Average Turnaround Time: %.2f\n", avg_turnaround_time);
}

int main() {
int n;

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


scanf("%d", &n);

int processes[n], burst_time[n];

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


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

findAverageTimes(processes, n, burst_time);

return 0;
}

Output
Enter the number of processes: 5
Enter burst time for P1: 4
Enter burst time for P2: 5
Enter burst time for P3: 2
Enter burst time for P4: 6
Enter burst time for P5: 2

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Process Burst Time Waiting Time Turnaround Time


P1 4 0 4
P2 5 4 9
P3 2 9 11
P4 6 11 17
P5 2 17 19

Average Waiting Time: 8.20


Average Turnaround Time: 12.00

C Write a c program to Simulate CPU scheduling algorithms to find turnaround time and
waiting time using ROUNDROBIN
#include <stdio.h>

#define MAX_PROCESS 10

// Function to calculate the minimum of two integers


int min(int a, int b) {
return (a < b) ? a : b;
}

void calculateTurnaroundTimeWaitingTime(int processes[], int n, int


burst_time[], int time_quantum) {
int remaining_time[MAX_PROCESS];
int waiting_time[MAX_PROCESS] = {0};
int turnaround_time[MAX_PROCESS] = {0};

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


remaining_time[i] = burst_time[i];
}

int t = 0; // Current time


int done = 0; // Flag to check if all processes are done

while (!done) {
done = 1; // Assume all processes are done

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


if (remaining_time[i] > 0) {
VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

done = 0; // At least one process is not done

// Reduce the remaining time by the time quantum


int time_slice = min(time_quantum, remaining_time[i]);
t += time_slice;
remaining_time[i] -= time_slice;

// Calculate waiting time for the process


waiting_time[i] = t - burst_time[i];

// If the process has finished, update turnaround time


if (remaining_time[i] == 0) {
turnaround_time[i] = t;
}
}
}
}

// Print the results


float total_waiting_time = 0, total_turnaround_time = 0;
for (int i = 0; i < n; i++) {
total_waiting_time += waiting_time[i];
total_turnaround_time += turnaround_time[i];
}

float avg_waiting_time = total_waiting_time / n;


float avg_turnaround_time = total_turnaround_time / n;

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


for (int i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", processes[i], burst_time[i],
waiting_time[i], turnaround_time[i]);
}

printf("\nAverage Waiting Time: %.2f\n", avg_waiting_time);


printf("Average Turnaround Time: %.2f\n", avg_turnaround_time);
}

int main() {

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

int n, time_quantum;

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


scanf("%d", &n);

int processes[MAX_PROCESS], burst_time[MAX_PROCESS];

printf("Enter the time quantum: ");


scanf("%d", &time_quantum);

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


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

calculateTurnaroundTimeWaitingTime(processes, n, burst_time,
time_quantum);

return 0;
}

OUTPUT
Enter the number of processes: 5
Enter the time quantum: 5
Enter burst time for P1: 4
Enter burst time for P2: 5
Enter burst time for P3: 2
Enter burst time for P4: 6
Enter burst time for P5: 2
Process Burst Time Waiting Time Turnaround Time
P1 4 0 4
P2 5 4 9
P3 2 9 11
P4 6 13 19
P5 2 16 18

Average Waiting Time: 8.40

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Average Turnaround Time: 12.20

...Program finished with exit code 0


Press ENTER to exit console.

D. Write a c program to Simulate CPU scheduling algorithms to find turnaround time and
waiting time using PRIORITY.
#include <stdio.h>

#define MAX_PROCESS 10

void findWaitingTimeTurnaroundTime(int processes[], int n, int burst_time[], int


priority[], int waiting_time[], int turnaround_time[]) {
waiting_time[0] = 0;

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


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

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


turnaround_time[i] = burst_time[i] + waiting_time[i];
}
}

void findAverageTimes(int processes[], int n, int burst_time[], int priority[]) {


int waiting_time[MAX_PROCESS], turnaround_time[MAX_PROCESS];

findWaitingTimeTurnaroundTime(processes, n, burst_time, priority,


waiting_time, turnaround_time);

float total_waiting_time = 0, total_turnaround_time = 0;


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

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

float avg_waiting_time = total_waiting_time / n;


float avg_turnaround_time = total_turnaround_time / n;

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


for (int i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\t\t%d\n", processes[i], burst_time[i],
priority[i], waiting_time[i], turnaround_time[i]);
}

printf("\nAverage Waiting Time: %.2f\n", avg_waiting_time);


printf("Average Turnaround Time: %.2f\n", avg_turnaround_time);
}

int main() {
int n;

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


scanf("%d", &n);

int processes[MAX_PROCESS], burst_time[MAX_PROCESS],


priority[MAX_PROCESS];

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


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

findAverageTimes(processes, n, burst_time, priority);

return 0;
}
OUTPUT
Enter the number of processes: 5
Enter burst time for P1: 4
Enter priority for P1: 1

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Enter burst time for P2: 5


Enter priority for P2: 3
Enter burst time for P3: 2
Enter priority for P3: 4
Enter burst time for P4: 6
Enter priority for P4: 2
Enter burst time for P5: 2
Enter priority for P5: 5
Process Burst Time Priority Waiting Time Turnaround Time
P1 4 1 0 4
P2 5 3 4 9
P3 2 4 9 11
P4 6 2 11 17
P5 2 5 17 19

Average Waiting Time: 8.20


Average Turnaround Time: 12.00

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

3. Develop a C program to simulate producer-consumer problem using semaphores.


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

#define BUFFER_SIZE 5

int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;

sem_t mutex, full, empty;

void *producer(void *arg) {


int item;
for (int i = 0; i < 10; i++) {
item = rand() % 100; // Produce a random item
sem_wait(&empty); // Wait for an empty slot in the buffer
sem_wait(&mutex); // Wait for exclusive access to the buffer

// Critical section: Add item to buffer


buffer[in] = item;
printf("Produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;

sem_post(&mutex); // Release access to the buffer


sem_post(&full); // Signal that the buffer is now full
}
pthread_exit(NULL);
}

void *consumer(void *arg) {


int item;
for (int i = 0; i < 10; i++) {
sem_wait(&full); // Wait for a full slot in the buffer
sem_wait(&mutex); // Wait for exclusive access to the buffer

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

// Critical section: Remove item from buffer


item = buffer[out];
printf("Consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;

sem_post(&mutex); // Release access to the buffer


sem_post(&empty); // Signal that the buffer is now empty
}
pthread_exit(NULL);
}

int main() {
pthread_t producer_thread, consumer_thread;

// Initialize semaphores
sem_init(&mutex, 0, 1);
sem_init(&full, 0, 0);
sem_init(&empty, 0, BUFFER_SIZE);

// Create producer and consumer threads


pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);

// Wait for threads to finish


pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);

// Destroy semaphores
sem_destroy(&mutex);
sem_destroy(&full);
sem_destroy(&empty);

return 0;
}

OUTPUT
Produced: 83
Produced: 86
Produced: 77

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Produced: 15
Produced: 93
Consumed: 83
Consumed: 86
Consumed: 77
Consumed: 15
Consumed: 93
Produced: 35
Produced: 86
Produced: 92
Produced: 49
Produced: 21
Consumed: 35
Consumed: 86
Consumed: 92
Consumed: 49
Consumed: 21

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

4. Develop a C program which demonstrates interprocess communication between a reader process and
a writer process. Use mkfifo, open, read, write and close APIs in your program

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define FIFO_NAME "myfifo"


#define BUFFER_SIZE 256

void writer_process() {
int fd;
char message[BUFFER_SIZE];

// Create the FIFO (named pipe)


mkfifo(FIFO_NAME, 0666);

printf("Writer process opening FIFO...\n");

// Open the FIFO for writing


fd = open(FIFO_NAME, O_WRONLY);

printf("Enter a message to send to the reader process (type 'exit' to


end):\n");

while (1) {
// Read input from the user
fgets(message, BUFFER_SIZE, stdin);

// Remove the newline character


message[strlen(message) - 1] = '\0';

// Write the message to the FIFO


write(fd, message, strlen(message) + 1);

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

// Check if the user wants to exit


if (strcmp(message, "exit") == 0)
break;
}

// Close the FIFO


close(fd);

// Remove the FIFO


unlink(FIFO_NAME);

printf("Writer process finished.\n");


}

void reader_process() {
int fd;
char message[BUFFER_SIZE];

printf("Reader process opening FIFO...\n");

// Open the FIFO for reading


fd = open(FIFO_NAME, O_RDONLY);

printf("Reader process waiting for messages...\n");

while (1) {
// Read from the FIFO
read(fd, message, BUFFER_SIZE);

// Check for exit condition


if (strcmp(message, "exit") == 0)
break;

printf("Received message: %s\n", message);


}

// Close the FIFO


close(fd);

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

printf("Reader process finished.\n");


}

int main() {
pid_t pid;

// Create a child process


if ((pid = fork()) < 0) {
perror("Fork error");
exit(EXIT_FAILURE);
}

if (pid == 0) {
// Child process (reader)
reader_process();
} else {
// Parent process (writer)
writer_process();
}

return 0;
}
OUTPUT
Writer process opening FIFO...
Reader process opening FIFO...
Reader process waiting for messages...
Enter a message to send to the reader process (type 'exit' to end):
HI
Received message: HI

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

5. Develop a C program to simulate Bankers Algorithm for DeadLock Avoidance


#include <stdio.h>

#define MAX_PROCESSES 5
#define MAX_RESOURCES 3

int available[MAX_RESOURCES];
int max[MAX_PROCESSES][MAX_RESOURCES];
int allocation[MAX_PROCESSES][MAX_RESOURCES];
int need[MAX_PROCESSES][MAX_RESOURCES];

void initialize() {
// Initialize available resources
printf("Enter the number of available resources:\n");
for (int i = 0; i < MAX_RESOURCES; i++) {
scanf("%d", &available[i]);
}

// Initialize maximum resources for each process


printf("Enter the maximum demand of each process:\n");
for (int i = 0; i < MAX_PROCESSES; i++) {
printf("For process %d: ", i);
for (int j = 0; j < MAX_RESOURCES; j++) {
scanf("%d", &max[i][j]);
}
}

// Initialize allocation and need matrices


for (int i = 0; i < MAX_PROCESSES; i++) {
for (int j = 0; j < MAX_RESOURCES; j++) {
allocation[i][j] = 0;
need[i][j] = max[i][j];
}
}
}

int requestResources(int process, int request[]) {


// Check if the request is valid

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

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


if (request[i] > need[process][i] || request[i] > available[i]) {
return 0; // Request is invalid
}
}

// Try to allocate the resources temporarily


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

// Check if the system is in a safe state after the temporary allocation


if (isSafe()) {
return 1; // Request is granted
} else {
// Undo the temporary allocation if it leads to an unsafe state
for (int i = 0; i < MAX_RESOURCES; i++) {
available[i] += request[i];
allocation[process][i] -= request[i];
need[process][i] += request[i];
}
return 0; // Request is denied
}
}

int releaseResources(int process, int release[]) {


// Release the resources
for (int i = 0; i < MAX_RESOURCES; i++) {
available[i] += release[i];
allocation[process][i] -= release[i];
need[process][i] += release[i];
}

return 1; // Resources released successfully


}

int isSafe() {

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

int work[MAX_RESOURCES];
int finish[MAX_PROCESSES] = {0};

// Initialize work array with available resources


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

// Try to find an execution sequence


for (int i = 0; i < MAX_PROCESSES; i++) {
if (finish[i] == 0) {
int j;
for (j = 0; j < MAX_RESOURCES; j++) {
if (need[i][j] > work[j])
break;
}

if (j == MAX_RESOURCES) {
// Process i can finish, release its resources
finish[i] = 1;
for (int k = 0; k < MAX_RESOURCES; k++) {
work[k] += allocation[i][k];
}
i = -1; // Restart the loop
}
}
}

// Check if all processes finished


for (int i = 0; i < MAX_PROCESSES; i++) {
if (finish[i] == 0) {
return 0; // System is in an unsafe state
}
}

return 1; // System is in a safe state


}

int main() {

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

initialize();

int process;
int request[MAX_RESOURCES];

printf("Enter the process number requesting resources: ");


scanf("%d", &process);

printf("Enter the resource request for process %d:\n", process);


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

if (requestResources(process, request)) {
printf("Request granted. System is in a safe state.\n");
} else {
printf("Request denied. System would be in an unsafe state.\n");
}

return 0;
}
OUTPUT
main.c: In function ‘requestResources’:
main.c:60:9: warning: implicit declaration of function ‘isSafe’ [-Wimplicit-
function-declaration]
60 | if (isSafe()) {
| ^~~~~~
Enter the number of available resources:
5
4
6
Enter the maximum demand of each process:
For process 0: 7

1
2
For process 1: 3
4
2

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

For process 2: 2
3
4
For process 3: 4
5
3
For process 4: 2
3
4
Enter the process number requesting resources: 2
Enter the resource request for process 2:
1
2
2
Request denied. System would be in an unsafe state.

...Program finished with exit code 0


Press ENTER to exit console.

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

6 Develop a C program to simulate the following contiguous memory allocation Techniques: a) Worst fit b)
Best fit c) First fit
#include <stdio.h>

#define MAX_BLOCKS 50

void worstFit(int blockSize[], int m, int processSize[], int n) {


int allocation[MAX_BLOCKS];

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


int worstFitIdx = -1;
for (int j = 0; j < m; j++) {
if (blockSize[j] >= processSize[i]) {
if (worstFitIdx == -1 || blockSize[j] > blockSize[worstFitIdx]) {
worstFitIdx = j;
}
}
}

if (worstFitIdx != -1) {
allocation[i] = worstFitIdx;
blockSize[worstFitIdx] -= processSize[i];
printf("Worst Fit: Process %d allocated to block %d\n", i + 1, worstFitIdx + 1);
} else {
printf("Worst Fit: Process %d cannot be allocated\n", i + 1);
}
}
}

void bestFit(int blockSize[], int m, int processSize[], int n) {


int allocation[MAX_BLOCKS];

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


int bestFitIdx = -1;
for (int j = 0; j < m; j++) {
if (blockSize[j] >= processSize[i]) {
if (bestFitIdx == -1 || blockSize[j] < blockSize[bestFitIdx]) {
bestFitIdx = j;
}
VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

}
}

if (bestFitIdx != -1) {
allocation[i] = bestFitIdx;
blockSize[bestFitIdx] -= processSize[i];
printf("Best Fit: Process %d allocated to block %d\n", i + 1, bestFitIdx + 1);
} else {
printf("Best Fit: Process %d cannot be allocated\n", i + 1);
}
}
}

void firstFit(int blockSize[], int m, int processSize[], int n) {


int allocation[MAX_BLOCKS];

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


int firstFitIdx = -1;
for (int j = 0; j < m; j++) {
if (blockSize[j] >= processSize[i]) {
firstFitIdx = j;
break;
}
}

if (firstFitIdx != -1) {
allocation[i] = firstFitIdx;
blockSize[firstFitIdx] -= processSize[i];
printf("First Fit: Process %d allocated to block %d\n", i + 1, firstFitIdx + 1);
} else {
printf("First Fit: Process %d cannot be allocated\n", i + 1);
}
}
}

int main() {
int m, n;

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

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

scanf("%d", &m);

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


scanf("%d", &n);

int blockSize[MAX_BLOCKS];
int processSize[MAX_BLOCKS];

printf("Enter the sizes of memory blocks:\n");


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

printf("Enter the sizes of processes:\n");


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

worstFit(blockSize, m, processSize, n);


bestFit(blockSize, m, processSize, n);
firstFit(blockSize, m, processSize, n);

return 0;
}
OUTPUT
Enter the number of memory blocks: 5
Enter the number of processes: 5
Enter the sizes of memory blocks:
4
5\
Enter the sizes of processes:
Worst Fit: Process 1 allocated to block 2
Worst Fit: Process 2 allocated to block 2
Worst Fit: Process 3 allocated to block 2
Worst Fit: Process 4 allocated to block 2
Worst Fit: Process 5 allocated to block 2
Best Fit: Process 1 allocated to block 3
Best Fit: Process 2 allocated to block 3
Best Fit: Process 3 allocated to block 3

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Best Fit: Process 4 allocated to block 3


Best Fit: Process 5 allocated to block 3
First Fit: Process 1 allocated to block 1
First Fit: Process 2 allocated to block 1
First Fit: Process 3 allocated to block 1
First Fit: Process 4 allocated to block 1
First Fit: Process 5 allocated to block 1

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

7. Develop a C program to simulate page replacement algorithms: a) FIFO b) LRU


#include <stdio.h>

#define MAX_PAGES 50

void fifo(int pages[], int n, int capacity) {


int frame[capacity];
int frameIndex = 0;

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


int page = pages[i];
int pageFound = 0;

// Check if page is already in the frame


for (int j = 0; j < capacity; j++) {
if (frame[j] == page) {
pageFound = 1;
break;
}
}

if (!pageFound) {
frame[frameIndex] = page;
frameIndex = (frameIndex + 1) % capacity;
}

printf("FIFO: Page %d -> ", page);


for (int j = 0; j < capacity; j++) {
if (frame[j] != -1) {
printf("%d ", frame[j]);
}
}
printf("\n");
}
}

void lru(int pages[], int n, int capacity) {


int frame[capacity];
VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

int counter[MAX_PAGES] = {0};

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


int page = pages[i];
int pageFound = 0;

// Check if page is already in the frame


for (int j = 0; j < capacity; j++) {
if (frame[j] == page) {
pageFound = 1;
counter[page]++;
break;
}
}

if (!pageFound) {
int replaceIdx = 0;
int minCounter = counter[frame[0]];

// Find the page with the least recently used counter


for (int j = 1; j < capacity; j++) {
if (counter[frame[j]] < minCounter) {
minCounter = counter[frame[j]];
replaceIdx = j;
}
}

frame[replaceIdx] = page;
counter[page]++;

// Reset the counter for the replaced page


counter[frame[replaceIdx]] = 0;
}

printf("LRU: Page %d -> ", page);


for (int j = 0; j < capacity; j++) {
if (frame[j] != -1) {
printf("%d ", frame[j]);
}

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

}
printf("\n");
}
}

int main() {
int n, capacity;

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


scanf("%d", &n);

int pages[MAX_PAGES];

printf("Enter the page sequence:\n");


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

printf("Enter the capacity of the page frame: ");


scanf("%d", &capacity);

// Initialize frames to -1 indicating empty


int initialFrame[MAX_PAGES];
for (int i = 0; i < capacity; i++) {
initialFrame[i] = -1;
}

printf("\nInitial Page Frame: ");


for (int i = 0; i < capacity; i++) {
printf("%d ", initialFrame[i]);
}
printf("\n\n");

fifo(pages, n, capacity);

// Reset frames for LRU


for (int i = 0; i < capacity; i++) {
initialFrame[i] = -1;
}

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

printf("\nInitial Page Frame: ");


for (int i = 0; i < capacity; i++) {
printf("%d ", initialFrame[i]);
}
printf("\n\n");

lru(pages, n, capacity);

return 0;
}
OUTPUT

Enter the number of pages: 3


Enter the page sequence:
2
3
4
Enter the capacity of the page frame: 3

Initial Page Frame: -1 -1 -1

FIFO: Page 2 -> 2 32582 301514563


FIFO: Page 3 -> 2 3 301514563
FIFO: Page 4 -> 2 3 4

Initial Page Frame: -1 -1 -1

8. Simulate following File Organization Techniques a) Single level directory b) Two level directory
#include <stdio.h>
#include <string.h>

#define MAX_FILES 50
#define MAX_NAME_LENGTH 20

struct File {
char name[MAX_NAME_LENGTH];
int size;

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

};

struct SingleLevelDirectory {
struct File files[MAX_FILES];
int fileCount;
};

struct TwoLevelDirectory {
struct SingleLevelDirectory directories[MAX_FILES];
int directoryCount;
};

void singleLevelDirectory(struct SingleLevelDirectory *rootDir) {


int choice;
do {
printf("\nSingle Level Directory Menu:\n");
printf("1. Create File\n");
printf("2. Display Files\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1: {
if (rootDir->fileCount < MAX_FILES) {
printf("Enter file name: ");
scanf("%s", rootDir->files[rootDir->fileCount].name);
printf("Enter file size: ");
scanf("%d", &rootDir->files[rootDir->fileCount].size);
rootDir->fileCount++;
printf("File created successfully!\n");
} else {
printf("Maximum file limit reached!\n");
}
break;
}
case 2: {
printf("\nFiles in the Single Level Directory:\n");
for (int i = 0; i < rootDir->fileCount; i++) {

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

printf("File Name: %s, Size: %d\n", rootDir->files[i].name, rootDir-


>files[i].size);
}
break;
}
case 3: {
printf("Exiting Single Level Directory Menu...\n");
break;
}
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 3);
}

void twoLevelDirectory(struct TwoLevelDirectory *rootDir) {


int choice;
do {
printf("\nTwo Level Directory Menu:\n");
printf("1. Create Directory\n");
printf("2. Create File\n");
printf("3. Display Files\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1: {
if (rootDir->directoryCount < MAX_FILES) {
printf("Enter directory name: ");
scanf("%s", rootDir->directories[rootDir-
>directoryCount].files[0].name);
rootDir->directories[rootDir->directoryCount].fileCount = 1;
rootDir->directoryCount++;
printf("Directory created successfully!\n");
} else {
printf("Maximum directory limit reached!\n");
}
break;

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

}
case 2: {
char directoryName[MAX_NAME_LENGTH];
printf("Enter directory name: ");
scanf("%s", directoryName);

int dirIndex = -1;


for (int i = 0; i < rootDir->directoryCount; i++) {
if (strcmp(rootDir->directories[i].files[0].name, directoryName) == 0)
{
dirIndex = i;
break;
}
}

if (dirIndex != -1) {
if (rootDir->directories[dirIndex].fileCount < MAX_FILES) {
printf("Enter file name: ");
scanf("%s", rootDir->directories[dirIndex].files[rootDir-
>directories[dirIndex].fileCount].name);
printf("Enter file size: ");
scanf("%d", &rootDir->directories[dirIndex].files[rootDir-
>directories[dirIndex].fileCount].size);
rootDir->directories[dirIndex].fileCount++;
printf("File created successfully!\n");
} else {
printf("Maximum file limit reached in the directory!\n");
}
} else {
printf("Directory not found!\n");
}
break;
}
case 3: {
printf("\nFiles in the Two Level Directory:\n");
for (int i = 0; i < rootDir->directoryCount; i++) {
printf("Directory Name: %s\n", rootDir->directories[i].files[0].name);
for (int j = 0; j < rootDir->directories[i].fileCount; j++) {
printf("File Name: %s, Size: %d\n", rootDir-

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

>directories[i].files[j].name, rootDir->directories[i].files[j].size);
}
printf("\n");
}
break;
}
case 4: {
printf("Exiting Two Level Directory Menu...\n");
break;
}
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 4);
}

int main() {
int choice;
struct SingleLevelDirectory singleDir;
singleDir.fileCount = 0;

struct TwoLevelDirectory twoDir;


twoDir.directoryCount = 0;

do {
printf("\nFile Organization Techniques Menu:\n");
printf("1. Single Level Directory\n");
printf("2. Two Level Directory\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1: {
singleLevelDirectory(&singleDir);
break;
}
case 2: {
twoLevelDirectory(&twoDir);

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

break;
}
case 3: {
printf("Exiting File Organization Techniques Menu...\n");
break;
}
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 3);

return 0;
}

OUTPUT
File Organization Techniques Menu:
1. Single Level Directory
2. Two Level Directory
3. Exit
Enter your choice: 1

Single Level Directory Menu:


1. Create File
2. Display Files
3. Exit
Enter your choice: 1
Enter file name: DEE
Enter file size: 4
File created successfully!

Single Level Directory Menu:


1. Create File
2. Display Files
3. Exit
Enter your choice: 2

Files in the Single Level Directory:


File Name: DEE, Size: 4

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

Single Level Directory Menu:


1. Create File
2. Display Files
3. Exit
Enter your choice:

9. Develop a C program to simulate the Linked file allocation strategies.


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

#define MAX_FILES 50
#define MAX_BLOCKS 100

struct Block {
int blockNumber;
struct Block* nextBlock;
};

struct File {
char name[20];
struct Block* firstBlock;
};

void createFile(struct File* files, int* fileCount, char name[20], int* blockCount) {
if (*fileCount < MAX_FILES) {
struct File* file = &files[*fileCount];
strcpy(file->name, name);

printf("Enter the number of blocks for file %s: ", name);


int numBlocks;
scanf("%d", &numBlocks);

file->firstBlock = NULL;

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


if (*blockCount < MAX_BLOCKS) {
struct Block* block = (struct Block*)malloc(sizeof(struct Block));
block->blockNumber = *blockCount;
block->nextBlock = NULL;

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

if (file->firstBlock == NULL) {
file->firstBlock = block;
} else {
struct Block* currentBlock = file->firstBlock;
while (currentBlock->nextBlock != NULL) {
currentBlock = currentBlock->nextBlock;
}
currentBlock->nextBlock = block;
}

(*blockCount)++;
} else {
printf("Maximum block limit reached!\n");
break;
}
}

printf("File %s created successfully!\n", name);


(*fileCount)++;
} else {
printf("Maximum file limit reached!\n");
}
}

void displayFiles(struct File* files, int fileCount) {


if (fileCount == 0) {
printf("No files created yet!\n");
} else {
printf("\nFiles and Blocks:\n");
for (int i = 0; i < fileCount; i++) {
struct File* file = &files[i];
printf("File %s: ", file->name);

struct Block* currentBlock = file->firstBlock;


while (currentBlock != NULL) {
printf("%d ", currentBlock->blockNumber);
currentBlock = currentBlock->nextBlock;
}

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

printf("\n");
}
}
}

int main() {
struct File files[MAX_FILES];
int fileCount = 0;
int blockCount = 0;

int choice;
do {
printf("\nLinked File Allocation Menu:\n");
printf("1. Create File\n");
printf("2. Display Files\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1: {
char fileName[20];
printf("Enter the name of the file: ");
scanf("%s", fileName);
createFile(files, &fileCount, fileName, &blockCount);
break;
}
case 2: {
displayFiles(files, fileCount);
break;
}
case 3: {
printf("Exiting Linked File Allocation Menu...\n");
break;
}
default:
printf("Invalid choice! Please try again.\n");
}

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

} while (choice != 3);

// Free allocated memory for blocks


for (int i = 0; i < fileCount; i++) {
struct Block* currentBlock = files[i].firstBlock;
while (currentBlock != NULL) {
struct Block* nextBlock = currentBlock->nextBlock;
free(currentBlock);
currentBlock = nextBlock;
}
}

return 0;
}

OUTPUT

main.c: In function ‘createFile’:


main.c:28:9: warning: implicit declaration of function ‘strcpy’ [-Wimplicit-
function-declaration]
28 | strcpy(file->name, name);
| ^~~~~~
main.c:11:1: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
10 | #include <stdlib.h>
+++ |+#include <string.h>
11 |
main.c:28:9: warning: incompatible implicit declaration of built-in function
‘strcpy’ [-Wbuiltin-declaration-mismatch]
28 | strcpy(file->name, name);
| ^~~~~~
main.c:28:9: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’

Linked File Allocation Menu:


1. Create File
2. Display Files
3. Exit
Enter your choice: 1
Enter the name of the file: JATHIN
Enter the number of blocks for file JATHIN: 5

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

File JATHIN created successfully!

Linked File Allocation Menu:


1. Create File
2. Display Files
3. Exit
Enter your choice: 2

Files and Blocks:


File JATHIN: 0 1 2 3 4

Linked File Allocation Menu:


1. Create File
2. Display Files
3. Exit
Enter your choice:

10. Develop a C program to simulate SCAN disk scheduling algorithm.

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

#define MAX_REQUESTS 100

void scan(int requests[], int n, int head, char direction) {


int totalCylinders = 200; // Assuming total cylinders on the disk is 200
int distance = 0;

printf("SCAN Disk Scheduling Algorithm\n");


printf("Head Movement Order: ");

if (direction == 'left') {
// Sort the requests in ascending order
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (requests[j] > requests[j + 1]) {
int temp = requests[j];
requests[j] = requests[j + 1];
requests[j + 1] = temp;
}
VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

}
}

// Move head to the leftmost cylinder


distance += abs(head - 0);
printf("%d -> 0 ", 0);

// Move head to the rightmost requested cylinder


distance += abs(0 - requests[n - 1]);
printf("%d -> %d ", requests[n - 1], 0);

// Move head to the leftmost requested cylinder


distance += abs(requests[n - 1] - requests[0]);
printf("%d -> ", requests[0]);

// Visit the remaining requested cylinders


for (int i = 1; i < n; i++) {
distance += abs(requests[i - 1] - requests[i]);
printf("%d -> ", requests[i]);
}
} else if (direction == 'right') {
// Sort the requests in descending order
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (requests[j] < requests[j + 1]) {
int temp = requests[j];
requests[j] = requests[j + 1];
requests[j + 1] = temp;
}
}
}

// Move head to the rightmost cylinder


distance += abs(head - totalCylinders);
printf("%d -> %d ", totalCylinders, head);

// Move head to the leftmost requested cylinder


distance += abs(totalCylinders - requests[n - 1]);
printf("%d -> %d ", requests[n - 1], totalCylinders);

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

// Move head to the rightmost requested cylinder


distance += abs(requests[n - 1] - requests[0]);
printf("%d -> ", requests[0]);

// Visit the remaining requested cylinders


for (int i = 1; i < n; i++) {
distance += abs(requests[i - 1] - requests[i]);
printf("%d -> ", requests[i]);
}
}

printf("\nTotal Head Movement: %d cylinders\n", distance);


}

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

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


scanf("%d", &n);

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


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

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


scanf("%d", &head);

printf("Enter the direction (left or right): ");


scanf("%s", &direction);

if (direction != 'left' && direction != 'right') {


printf("Invalid direction. Exiting program.\n");
return 1;
}

printf("Enter the disk request queue:\n");

VVIET, Mysuru
VIDYA VIKAS INSTITUTE OF ENGINEERING & TECHNOLOGY

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


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

scan(requests, n, head, direction);

return 0;
}

Output

main.c: In function ‘scan’:


main.c:21:22: warning: multi-character character constant [-Wmultichar]
21 | if (direction == 'left') {
| ^~~~~~
main.c:50:29: warning: character constant too long for its type
50 | } else if (direction == 'right') {
| ^~~~~~~
main.c: In function ‘main’:
main.c:102:22: warning: multi-character character constant [-Wmultichar]
102 | if (direction != 'left' && direction != 'right') {
| ^~~~~~
main.c:102:45: warning: character constant too long for its type
102 | if (direction != 'left' && direction != 'right') {
| ^~~~~~~
Enter the number of requests: 5
Enter the current head position: 3
Enter the direction (left or right): right
Invalid direction. Exiting program.

...Program finished with exit code 1


Press ENTER to exit console.

VVIET, Mysuru

You might also like