0% found this document useful (0 votes)
4 views35 pages

Cs3461 Lab Manual

The document outlines various laboratory exercises conducted at Dr. G.U. Pope College of Engineering, focusing on programming in C for different operating system concepts. It includes system calls in UNIX, CPU scheduling algorithms, inter-process communication, mutual exclusion using semaphores, deadlock avoidance and detection algorithms, threading, and memory management techniques. Each exercise provides an aim, algorithm, program code, and results indicating successful execution.

Uploaded by

zann7400
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)
4 views35 pages

Cs3461 Lab Manual

The document outlines various laboratory exercises conducted at Dr. G.U. Pope College of Engineering, focusing on programming in C for different operating system concepts. It includes system calls in UNIX, CPU scheduling algorithms, inter-process communication, mutual exclusion using semaphores, deadlock avoidance and detection algorithms, threading, and memory management techniques. Each exercise provides an aim, algorithm, program code, and results indicating successful execution.

Uploaded by

zann7400
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/ 35

CSI THOOTHUKUDI-NAZARETH DIOCESE

DR.G.U.POPE COLLEGE OF ENGINEERING


POPE NAGAR SAWYERPURAM-628 251

Register No :

Certified that this is the bonafide record of work done by


Selvan/Selvi ……………………………………………………………………… of ……….
Semester ……….. branch for the lab ……………………………………………………
During the year…………………

Staff In-charge H. O.D

Submitted for the university practical Examination held on …………..

Internal Examiner External Examiner

1
S.NO DATE TITLE PAGE MARK SIGN
1

10

11

12

2
13

14

15

3
PROGRAM FOR SYSTEM CALLS OF UNIX
Ex.No:1
OPERATING SYSTEM(fork, getpid, exit)

Aim:
To program for system calls of unix operating system(fork, getpid, exit)

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the variables pid,pid1,pid2.
STEP 3: Call fork() system call to create process.
STEP 4: If pid==-1, exit.
STEP 5: Ifpid!=-1 , get the process id using getpid().
STEP 6: Print the process id.
STEP 7:Stop the program

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 occurred


perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) { // Child process
printf("Child process: PID = %d\n", getpid());
// Child process exits
exit(EXIT_SUCCESS);
} else { // Parent process
printf("Parent process: PID = %d\n", getpid());
// Wait for the child to terminate
wait(NULL);
printf("Child process has terminated\n");
}

return 0;
}

4
Output:

Result:Thus program for system calls of unix operating system(fork, getpid, exit) executed
successfully.

5
CPU SCHEDULING ALGORITHMS
Ex.No:2
PRIORITY

AIM:
To write a C program for implementation of Priority scheduling algorithms.

ALGORITHM:
Step 1: Inside the structure declare the variables.
Step 2: Declare the variable i,j as integer, totwtime and totttime is equal to zero.
Step 3: Get the value of „n‟ assign p and allocate the memory.
Step 4: Inside the for loop get the value of burst time and priority.
Step 5: Assign wtime as zero .
Step 6: Check p[i].pri is greater than p[j].pri .
Step 7: Calculate the total of burst time and waiting time and assign as turnaround time.
Step 8: Stop the program.

PROGRAM:
#include <stdio.h>

struct Process {
int id, arrival, burst;
};

void turnaround(struct Process p[], int n, int t[]) {


for (int i = 0, ct = 0; i < n; i++) {
ct += p[i].burst;
t[i] = ct - p[i].arrival;
}
}

float avg_turnaround(int t[], int n) {


float avg = 0;
for (int i = 0; i < n; i++) {
avg += t[i];
}
return avg / n;
}

int main() {
struct Process p[] = {{1, 0, 5}, {2, 2, 3}, {3, 5, 8}, {4, 9, 2}};
int t[sizeof(p)/sizeof(p[0])]; // Array to store turnaround times

turnaround(p, sizeof(p)/sizeof(p[0]), t);


printf("Average Turnaround Time: %.2f\n", avg_turnaround(t, sizeof(p)/sizeof(p[0])));

return 0;
}

6
OUTPUT:

RESULT: Thus write a C program for implementation of Priority scheduling algorithms executed
successfully..

7
Ex.No:3 Program to use IPC strategy

AIM:
To write a c program to implement IPC strategy
ALGORITHM:

Step 1: Start the process


Step 2: Declare the segment size
Step 3: Create the shared memory
Step 4: Read the data from the shared memory
Step 5: Write the data to the shared memory
Step 6: Edit the data
Step 7: Stop the process

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 1024

struct SharedData { int value; };

int main() {
key_t key = ftok("shared_memory_key", 65);
int shmid = shmget(key, SHM_SIZE, 0666 | IPC_CREAT);

struct SharedData *s = (struct SharedData*)shmat(shmid, NULL, 0);


s->value = 42;
shmdt(s);

s = (struct SharedData*)shmat(shmid, NULL, 0);


printf("Value: %d\n", s->value);
shmdt(s);

shmctl(shmid, IPC_RMID, NULL);

return 0;
}

8
OUTPUT:

RESULT: Thus write a c program to implement ipc strategy executed successfully.

9
IMPLEMENT MUTUAL EXCLUSION BY SEMAPHORE
Ex.No:4 USING C

AIM:
To implement mutual exclusion by semaphore using c

ALGORITHIM:
Step 1 :Initialize Variables
Step 2 :Include Thread Function (critical_section)
Step 3 :The threads compete for access to the critical section
Step 4 :Inside the critical section, the shared resource is updated in a mutually exclusive manner
Step 5 :The program exits gracefully after completing the execution of all threads

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

#define NUM_THREADS 2

int shared_resource = 0;
sem_t mutex;

void *critical_section(void *tid) {


sem_wait(&mutex);
printf("Thread %d in critical section. Shared Resource: %d\n", *(int *)tid, ++shared_resource);
sem_post(&mutex);
pthread_exit(NULL);
}

int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS] = {0, 1};
sem_init(&mutex, 0, 1);

for (int i = 0; i < NUM_THREADS; i++)


if (pthread_create(&threads[i], NULL, critical_section, (void *)&thread_ids[i]))
exit(EXIT_FAILURE);

for (int i = 0; i < NUM_THREADS; i++) pthread_join(threads[i], NULL);

sem_destroy(&mutex);
return 0;
}

10
OUTPUT:

RESULT:Thus implement mutual exclusion by semaphore using c executed successfully.

11
Ex.No:5 BANKERS ALGORITHM FOR DEADLOCK AVOIDANCE

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

ALGORITHM:

Step-1: Start the program.


Step-2: Declare the memory for the process.
Step-3: Read the number of process, resources, allocation matrix and available
matrix.Step-4: Compare each and every process using the banker‟s algorithm.
Step-5: If the process is in safe state then it is a not a deadlock process otherwise it is a
deadlock process
Step-6: produce the result of state of process
Step-7: Stop the program

PROGRAM:
#include <stdio.h>

#define P 5
#define R 5

int issafe(int p[], int a[][R], int m[][R], int al[][R]) {


int n[P][R], f[P] = {0}, w[R], c = 0;
for (int i = 0; i < P; i++)
for (int j = 0; j < R; j++)
n[i][j] = m[i][j] - a[i][j];
for (int i = 0; i < R; i++)
w[i] = a[0][i];
while (c < P) {
int d = 0;
for (int i = 0; i < P; i++) {
if (!f[i]) {
int j;
for (j = 0; j < R && n[i][j] <= w[j]; j++);
if (j == R) {
for (int k = 0; k < R; k++)
w[k] += a[i][k];
f[i] = 1;
d = 1;
c++;
}
}
}
if (!d)
return 0;
}
return 1;
}

int main() {
int a[P][R] = {{0, 1, 0}, {2, 0, 0}, {3, 0, 2}, {2, 1, 1}, {0, 0, 2}};
int m[P][R] = {{7, 5, 3}, {3, 2, 2}, {9, 0, 2}, {2, 2, 2}, {4, 3, 3}};

12
printf("%s state, %s deadlock detected.\n", issafe(NULL, a, m, a) ? "safe" : "Unsafe", issafe(NULL, a, m, a) ? "no" :
"deadlock");
return 0;
}

OUTPUT:

RESULT: Thus write a C program to implement banker‟s algorithm for deadlock avoidance executed
successfully.

13
Ex.No:6 ALGORITHM FOR DEADLOCK DETECTION

AIM:
To write a C program to implement algorithm for deadlock detection.
ALGORITHM:

Step-1: Start the program.


Step-2: Declare the memory for the process.
Step-3: Read the number of process, resources, allocation matrix and available
matrix.Step-4: Compare each and every process using the banker‟s algorithm.
Step-5: If the process is in safe state then it is a not a deadlock process otherwise it is a
deadlock process
Step-6: produce the result of state of process
Step-7: Stop the program

PROGRAM:
#include <stdio.h>

#define P 5 // Number of processes


#define R 3 // Number of resources

int isSafe(int av[], int max[][R], int alloc[][R], int need[][R]) {


int work[R], finish[P] = {0}, safeSeq[P], count = 0;
for (int i = 0; i < R; i++) work[i] = av[i];
while (count < P) {
int found = 0;
for (int p = 0; p < P; p++) {
if (!finish[p]) {
int j = 0;
for (; j < R && need[p][j] <= work[j]; j++);
if (j == R) {
for (int k = 0; k < R; k++) work[k] += alloc[p][k];
finish[p] = 1, safeSeq[count++] = p, found = 1;
}
}
}
if (!found) break;
}
if (count == P) {
printf("System is in safe state.\nSafe sequence: ");
for (int i = 0; i < P; i++) printf("%d ", safeSeq[i]);
printf("\n");
return 1;
} else {
printf("System is in unsafe state. Deadlock detected.\n");
return 0;
}
}

int main() {
int av[R] = {3, 3, 2}, max[P][R] = {{7, 5, 3}, {3, 2, 2}, {9, 0, 2}, {2, 2, 2}, {4, 3, 3}},
alloc[P][R] = {{0, 1, 0}, {2, 0, 0}, {3, 0, 2}, {2, 1, 1}, {0, 0, 2}}, need[P][R];
for (int i = 0; i < P; i++) for (int j = 0; j < R; j++) need[i][j] = max[i][j] - alloc[i][j];

14
isSafe(av, max, alloc, need);
return 0;
}

OUTPUT:

RESULT:Thus write a C program to implement algorithm for deadlock detection executed successfully.

15
Ex.No:7 WRITE A C PROGRAM TO IMPLEMENT THREADING

AIM:
To write a c program to implement Threading.
ALGORITHM:

Step 1: Start the process


Step 2: Declare process thread, thread-id.
Step 3: Read the process thread and thread state.
Step 4: Check the process thread equals to thread-id by using if condition.
Step 5: Check the error state of the thread.
Step 6: Display the completed thread process.
Step 7: Stop the process

PROGRAM:

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

void *threadFunc(void *arg) {


printf("%s\n", (char *)arg);
pthread_exit(NULL);
}

int main() {
pthread_t tid[2];
char *messages[] = {"Thread 1 says: Hello from thread 1!", "Thread 2 says: Hello from thread 2!"};

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


if (pthread_create(&tid[i], NULL, threadFunc, (void *)messages[i]) != 0) {
perror("pthread_create");
return 1;
}
}

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


if (pthread_join(tid[i], NULL) != 0) {
perror("pthread_join");
return 1;
}
}

puts("Main thread exiting.");


return 0;
}

16
OUTPUT:

RESULT:Thus write a c program to implement Threading executed successfully.

17
Ex.No:8 PAGING TECHNIQUE OF MEMORY MANAGEMENT

AIM:
To write a c program to implement Paging technique for memory management.

ALGORITHM:

Step 1: Start the process


Step 2: Declare page number, page table, frame number and process size.
Step 3: Read the process size, total number of pages
Step 4: Read the relative address
Step 5: Calculate the physical address
Step 6: Display the address
Step 7: Stop the process

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>

#define P printf
#define N 10
#define F 4

void init(int T[N]) {


for (int i = 0; i < N; i++) T[i] = -1;
}

void ref(int T[N], int p, int *q, int *r) {


bool f = (T[p] == -1);
P("Page ref: %d\n", p);
if (f) {
if (*q == F) {
P("Evicting page %d\n", T[*q]);
T[T[*q]--] = -1;
}
P("Bringing page %d into frame %d\n", p, *r);
T[(*r)++] = p;
} else P("Page %d is already in memory (Frame %d)\n", p, T[p]);
}

int main() {
int T[N], Q[F], R = 0;
init(T);
srand(time(NULL));
for (int i = 0; i < 15; i++) ref(T, rand() % N, Q, &R);
return 0;
}

18
OUTPUT:

RESULT:Thus write a c program to implement Paging technique for memory management executed successfully.

19
MEMORY ALLOCATION METHODS FOR FIXED PARTITION
Ex.No:9
FIRST FIT

AIM:
To write a C program for implementation memory allocation methods for fixed partition
using first fit.

ALGORITHM:

Step 1:Define the max as 25.


Step 2: Declare the variable frag[max],b[max],f[max],i,j,nb,nf,temp, highest=0, bf[max],ff[max].
Step 3: Get the number of blocks,files,size of the blocks using for loop.
Step 4: In for loop check bf[j]!=1, if so temp=b[j]-f[i]
Step 5: Check highest<temp,if so assign ff[i]=j,highest=temp
Step 6: Assign frag[i]=highest, bf[ff[i]]=1,highest=0
Step 7: Repeat step 4 to step 6.
Step 8: Print file no,size,block no,size and fragment.
Step 9: Stop the program.

PROGRAM:

#include <stdio.h>
#include <stdbool.h>

#define MEM_SIZE 100


#define PROCESSES 5

void initMemory(bool mem[], int size) {


for (int i = 0; i < size; i++) mem[i] = false;
}

void displayMemory(bool mem[], int size) {


printf("Memory Status: ");
for (int i = 0; i < size; printf(mem[i++] ? "X " : ". "));
printf("\n");
}

void firstFit(bool mem[], int size, int procSize[], int numProc) {


for (int i = 0; i < numProc; i++) {
printf("Allocating memory for Process %d (Size: %d)\n", i + 1, procSize[i]);
bool allocated = false;
for (int j = 0; j < size; j++) {
if (!mem[j]) {
int count = 0;
while (j + count < size && !mem[j + count] && count < procSize[i]) count++;
if (count >= procSize[i]) {
for (int k = j; k < j + procSize[i]; mem[k++] = true);
printf("Memory allocated for Process %d from block %d to %d\n", i + 1, j, j + count - 1);
allocated = true;
break;
}
j += count;
}
}
if (!allocated) printf("Memory allocation failed for Process %d\n", i + 1), displayMemory(mem, size);
20
}
}

int main() {
bool mem[MEM_SIZE];
int procSize[PROCESSES] = {10, 20, 30, 40, 50};
initMemory(mem, MEM_SIZE), firstFit(mem, MEM_SIZE, procSize, PROCESSES);
return 0;
}

OUTPUT:

RESULT:Thus write a C program for implementation memory allocation methods for fixed partitionusing
first fit executed successfully.

21
MEMORY ALLOCATION METHODS FOR FIXED PARTITION
Ex.No:10
BEST FIT

AIM:
To write a C program for implementation of FCFS and SJF scheduling algorithms.

ALGORITHM:

Step 1:Define the max as 25.


Step 2: Declare the variable frag[max],b[max],f[max],i,j,nb,nf,temp, highest=0, bf[max],ff[max].
Step 3: Get the number of blocks,files,size of the blocks using for loop.
Step 4: In for loop check bf[j]!=1, if so temp=b[j]-f[i]
Step 5: Check lowest>temp,if so assign
ff[i]=j,highest=tempStep 6: Assign frag[i]=lowest,
bf[ff[i]]=1,lowest=10000 Step 7: Repeat step 4 to step 6.
Step 8: Print file no,size,block no,size and fragment.
Step 9: Stop the program.

PROGRAM:
#include <stdio.h>
#include <stdbool.h>

#define MEM_SIZE 100


#define PROCESSES 5

void initMemory(bool mem[], int size) {


for (int i = 0; i < size; i++) mem[i] = false;
}

void displayMemory(bool mem[], int size) {


printf("Memory Status: ");
for (int i = 0; i < size; i++) printf(mem[i] ? "X " : ". ");
printf("\n");
}

void bestFit(bool mem[], int size, int procSize[], int numProc) {


for (int i = 0; i < numProc; i++) {
printf("Allocating memory for Process %d (Size: %d)\n", i + 1, procSize[i]);
int bestFitIndex = -1, bestFitSize = size + 1;
for (int j = 0; j < size; j++) {
if (!mem[j]) {
int count = 0;
while (j + count < size && !mem[j + count] && count < procSize[i]) count++;
if (count >= procSize[i] && count < bestFitSize) bestFitIndex = j, bestFitSize = count;
j += count;
}
}
if (bestFitIndex != -1) {
for (int k = bestFitIndex; k < bestFitIndex + procSize[i]; mem[k++] = true);
printf("Memory allocated for Process %d from block %d to %d\n", i + 1, bestFitIndex, bestFitIndex +
bestFitSize - 1);
displayMemory(mem, size);
} else printf("Memory allocation failed for Process %d\n", i + 1), displayMemory(mem, size);
}
}

int main() {
22
bool mem[MEM_SIZE];
int procSize[PROCESSES] = {10, 20, 30, 40, 50};
initMemory(mem, MEM_SIZE), displayMemory(mem, MEM_SIZE), bestFit(mem, MEM_SIZE, procSize,
PROCESSES);
return 0;
}

OUTPUT:

RESULT:Thus write a C program for implementation of FCFS and SJF scheduling algorithms executed
successfully.
.

23
FILE ORGANIZATION TECHNIQUE
Ex.No:11
SINGLE LEVEL DIRECTORY

AIM:
To write C program to organize the file .

ALGORITHM:

Step-1: Start the program.


Step-2: Declare the count, file name, graphical
interface.Step-3: Read the number of files
Step-4: Read the file name
Step-5: Declare the root directory
Step-6: Using the file eclipse function define the files in a single
levelStep-7: Display the files
Step-8: Stop the program

PROGRAM:
#include <stdio.h>
#include <string.h>

#define MAX_FILES 10
#define MAX_FILENAME_LEN 20

struct File {
char filename[MAX_FILENAME_LEN];
int size;
};

struct Directory {
struct File files[MAX_FILES];
int file_count;
};

void initDirectory(struct Directory *dir) {


dir->file_count = 0;
}

void addFile(struct Directory *dir, const char *filename, int size) {


if (dir->file_count >= MAX_FILES) {
printf("Directory is full. Cannot add file '%s'.\n", filename);
return;
}

struct File *file = &dir->files[dir->file_count++];


strncpy(file->filename, filename, MAX_FILENAME_LEN - 1);
file->filename[MAX_FILENAME_LEN - 1] = '\0'; // Ensure null-termination
file->size = size;
printf("File '%s' added successfully.\n", filename);
}

void displayDirectory(struct Directory *dir) {


printf("Files in the directory:\n");
24
for (int i = 0; i < dir->file_count; i++) {
printf("File Name: %s, Size: %d\n", dir->files[i].filename, dir->files[i].size);
}
}

int main() {
struct Directory dir;
initDirectory(&dir);

// Adding files to the directory


addFile(&dir, "file1.txt", 100);
addFile(&dir, "file2.txt", 200);
addFile(&dir, "file3.txt", 150);
addFile(&dir, "file4.txt", 300);

// Displaying files in the directory


displayDirectory(&dir);

return 0;
}

OUTPUT:

RESULT:Thus write C program to organize the file executed successfully.

25
FILE ALLOCATION STRATEGIES
Ex.No:12
SEQUENTIAL

AIM:
To write a C program for sequential file for processing the student information.

ALGORITHM:

Step-1: Start the program.


Step-2: Get the number of records user want to store in the system.
Step-3: Using Standard Library function open the file to write the data into the file.
Step-4: Store the entered information in the system.
Step-5: Using do..While statement and switch case to create the options such
as1-DISPLAY, 2.SEARCH, 3.EXIT.
Step-6: Close the file using fclose() function.
Step-7: Process it and display the result.
Step-8: Stop the program.

PROGRAM:
#include <stdio.h>

#define MAX_FILES 10

int main() {
int file_sizes[MAX_FILES] = {100, 200, 150, 300}; // File sizes
int disk_space = 0; // Current allocated disk space
for (int i = 0; i < MAX_FILES; i++) {
if (disk_space + file_sizes[i] <= 1000) { // Assuming total disk space is 1000
printf("File %d allocated at position %d\n", i + 1, disk_space);
disk_space += file_sizes[i]; // Increment disk space
} else {
printf("Disk space full. Cannot allocate File %d\n", i + 1);
break;
}
}
return 0;
}

OUTPUT:

26
RESULT:Thus write a C program for sequential file for processing the student information executed successfully.

27
PAGE REPLACE ALGORITHIM
Ex.No:13
FIFO

AIM:

To write a C program for implementation of FIFO page replacement algorithm.

ALGORITHM:

Step 1: Start the program.


Step 2: Declare the necessary variables.
Step 3: Enter the number of frames.
Step 4: Enter the reference string end with zero.
Step 5: FIFO page replacement selects the page that has been in memory the longest time and
when the page must be replaced the oldest page is chosen.
Step 6: When a page is brought into memory, it is inserted at the tail of the queue.
Step 7: Initially all the three frames are empty.
Step 8: The page fault range increases as the no of allocated frames also increases.
Step 9: Print the total number of page faults.
Step 10: Stop the program.

PROGRAM:

#include <stdio.h>

int main() {
int i, j, n, a, frame, no, k, avail, count = 0;

printf("\n ENTER THE NUMBER OF PAGES:\n");


scanf("%d", &n);

printf("\n ENTER THE PAGE NUMBER :\n");


for (i = 1; i <= n; i++)
scanf("%d", &a[i]);

printf("\n ENTER THE NUMBER OF FRAMES :");


scanf("%d", &no);

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


frame[i] = -1;

j = 0;

printf("\tref string\t page frames\n");

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


printf("%d\t\t", a[i]);
28
avail = 0;
for (k = 0; k < no; k++)
if (frame[k] == a[i])
avail = 1;

if (avail == 0) {
frame[j] = a[i];
j = (j + 1) % no;
count++;
}

for (k = 0; k < no; k++)


printf("%d\t", frame[k]);
printf("\n");
}

printf("Page Fault Is %d", count);

return 0;
}

OUTPUT:

29
RESULT:Thus write a C program for page replace algorithim executed successfully.

30
MEMORY ALLOCATION METHODS FOR FIXED PARTITION
Ex.No:14
WORST FIT

AIM:
To write a C program for implementation of FCFS and SJF scheduling algorithms.

ALGORITHM:

Step 1:Define the max as 25.


Step 2: Declare the variable frag[max],b[max],f[max],i,j,nb,nf,temp, highest=0, bf[max],ff[max].
Step 3: Get the number of blocks,files,size of the blocks using for loop.
Step 4: In for loop check bf[j]!=1, if so temp=b[j]-f[i]
Step 5: Check temp>=0,if so assign ff[i]=j break the for loop.
Step 6: Assign frag[i]=temp,bf[ff[i]]=1;
Step 7: Repeat step 4 to step 6.
Step 8: Print file no,size,block no,size and fragment.
Step 9: Stop the program.

PROGRAM:

#include <stdio.h>

void worstFit(int blockSize[], int blocks, int


processSize[], int processes) {
int allocation[processes];
int occupied[blocks];

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


allocation[i] = -1;
}

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


occupied[i] = 0;
}

block
for (int i = 0; i < processes; i++) {
int indexPlaced = -1;
for (int j = 0; j < blocks; j++) {
if (blockSize[j] >= processSize[i] &&
!occupied[j]) {
if (indexPlaced == -1) {
indexPlaced = j;
}

else if (blockSize[indexPlaced] <


blockSize[j]) {
indexPlaced = j;

31
}
}
}
if (indexPlaced != -1) {

allocation[i] = indexPlaced;
occupied[indexPlaced] = 1;

blockSize[indexPlaced] -= processSize[i];
}
}

printf("\nProcess No.\tProcess Size\tBlock


no.\n");
for (int i = 0; i < processes; i++) {
printf("%d \t\t\t %d \t\t\t", i + 1,
processSize[i]);
if (allocation[i] != -1) {
printf("%d\n", allocation[i] + 1);
} else {
printf("Not Allocated\n");
}
}
}

int main() {
int blockSize[] = {5, 4, 3, 6, 7};
int processSize[] = {3, 2, 4, 1, 5};
int processes = sizeof(processSize) /
sizeof(processSize[0]);
int blocks = sizeof(blockSize) /
sizeof(blockSize[0]);

worstFit(blockSize, blocks, processSize,


processes);

return 0;
}

OUTPUT:

32
RESULT:Thus write a C program for worst fit has been executed successfully.

33
CPU SCHEDULING ALGORITHMS
Ex.No:15
FCFS

AIM:
To write a C program for implementation of FCFS and SJF scheduling algorithms.

ALGORITHM:

Step 1: Inside the structure declare the variables.


Step 2: Declare the variable i,j as integer,totwtime and totttime is equal to zero.
Step 3: Get the value of „n‟ assign pid as I and get the value of p[i].btime.
Step 4: Assign p[0] wtime as zero and tot time as btime and inside the loop calculate wait time
and turnaround time.
Step 5: Calculate total wait time and total turnaround time by dividing by total number of
process.
Step 6: Print total wait time and total turnaround time.
Step 7: Stop the program.

PROGRAM:

#include <stdio.h>

int main() {
int n, i, j, temp;
float avgWait, avgTurnaround;

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


scanf("%d", &n);

int burst[n], wait[n], turnaround[n];

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


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

wait[0] = 0;
for (i = 1; i < n; i++) {
wait[i] = wait[i - 1] + burst[i - 1];
}

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


turnaround[i] = wait[i] + burst[i];
}

avgWait = 0;
avgTurnaround = 0;

34
for (i = 0; i < n; i++) {
avgWait += wait[i];
avgTurnaround += turnaround[i];
}
avgWait /= n;
avgTurnaround /= n;

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


for (i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", i + 1, burst[i], wait[i], turnaround[i]);
}
printf("\nAverage Waiting Time: %.2f", avgWait);
printf("\nAverage Turnaround Time: %.2f", avgTurnaround);

return 0;
}

OUTPUT:

RESULT:Thus write a C program for CPU scheduling on FCFS has been executed successfully.

35

You might also like