KEMBAR78
OS Lab Exercise Final | PDF | Concurrent Computing | Computer Engineering
0% found this document useful (0 votes)
44 views18 pages

OS Lab Exercise Final

The document contains code snippets for various programming concepts including mutual exclusion using semaphores, deadlock avoidance using the Banker's algorithm, and threading in C. It also includes a paging technique for managing memory addresses. Each section provides a structured approach to handling concurrency and resource management in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views18 pages

OS Lab Exercise Final

The document contains code snippets for various programming concepts including mutual exclusion using semaphores, deadlock avoidance using the Banker's algorithm, and threading in C. It also includes a paging technique for managing memory addresses. Each section provides a structured approach to handling concurrency and resource management in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

EXNO-6 MUTUAL EXCLUSION BY mutex = signal(mutex);

SEMAPHORE
}
PROGRAM:
void consumer() {
#include <stdio.h>
mutex = wait(mutex);
#include <stdlib.h>
full = wait(full);
#define SIZE 3 // Buffer size
int item = buffer[out];
int buffer[SIZE];
printf("Consumer consumed item %d
int in = 0, out = 0; from index %d\n", item, out);
int mutex = 1, full = 0, empty = SIZE; out = (out + 1) % SIZE;
// Semaphore-like operations empty = signal(empty);
int wait(int s) { mutex = signal(mutex);
return (--s); }
} int main() {
int signal(int s) { int choice;
return (++s); while (1) {
} printf("\n--- MENU ---\n");
void producer() { printf("1. PRODUCE\n");
int item; printf("2. CONSUME\n");
printf("Enter the item to produce: "); printf("3. EXIT\n");
scanf("%d", &item); printf("Enter your choice: ");
mutex = wait(mutex); scanf("%d", &choice);
empty = wait(empty); switch (choice) {
buffer[in] = item; case 1:
printf("Producer produced item %d at if ((mutex == 1) && (empty != 0))
index %d\n", item, in);
producer();
in = (in + 1) % SIZE;
else
printf("Buffer is FULL. Cannot
full = signal(full); produce.\n");
break; ENTER YOUR CHOICE: 1
case 2: Enter the item produced by the producer:
20
if ((mutex == 1) && (full != 0))
Producer produces the item 20 at index 1
consumer();
else
ENTER YOUR CHOICE: 1
printf("Buffer is EMPTY.
Cannot consume.\n"); Enter the item produced by the producer:
30
break;
Producer produces the item 30 at index 2
case 3:
printf("Exiting...\n");
ENTER YOUR CHOICE: 1
exit(0);
BUFFER IS FULL
default:
printf("Invalid choice. Try again.\
n"); ENTER YOUR CHOICE: 2
} Consumer consumes item 10 from index 0
}
ENTER YOUR CHOICE: 2
return 0; Consumer consumes item 20 from index 1
}
OUTPUT ENTER YOUR CHOICE: 2
1. PRODUCER Consumer consumes item 30 from index 2
2. CONSUMER
3. EXIT ENTER YOUR CHOICE: 2
ENTER YOUR CHOICE: 1 BUFFER IS EMPTY
Enter the item produced by the producer:
10
ENTER YOUR CHOICE: 1
Producer produces the item 10 at index 0
Enter the item produced by the producer:
40
Producer produces the item 40 at index 0
ENTER YOUR CHOICE: 1
Enter the item produced by the producer:
50
Producer produces the item 50 at index 1
ENTER YOUR CHOICE: 2
Consumer consumes item 40 from index 0
EXNO-7 DEADLOCK AVOIDANCE
USING BANKERS ALGORITHM
for (i = 0; i < n; i++) {
#include <stdio.h>
printf("P%d: ", i);
#include <stdlib.h>
for (j = 0; j < m; j++) {
int available[20];
scanf("%d", &max[i][j]);
int max[20][20];
}
int allocation[20][20];
}
int need[20][20];
// Input Available resources
int flag[20];
printf("\nEnter Available Resources:\n");
int main() {
for (i = 0; i < m; i++) {
int n, m, i, j, k, processCount = 0;
printf("Resource %d: ", i);
int safe, request[20], processNo, choice;
scanf("%d", &available[i]);
printf("Enter the number of processes: ");
}
scanf("%d", &n);
// Calculate Need Matrix
printf("Enter the number of resources: ");
printf("\nNeed Matrix:\n");
scanf("%d", &m);
for (i = 0; i < n; i++) {
// Input Allocation Matrix
for (j = 0; j < m; j++) {
printf("\nEnter the Allocation Matrix:\n");
need[i][j] = max[i][j] - allocation[i][j];
for (i = 0; i < n; i++) {
printf("%d ", need[i][j]);
printf("P%d: ", i);
}
for (j = 0; j < m; j++) {
printf("\n");
scanf("%d", &allocation[i][j]);
}
}
// Safety Check
}
printf("\nChecking system for safe state...\n");
// Input Max Matrix
int finish[20] = {0}, work[20];
printf("\nEnter the Max Matrix:\n");
for (i = 0; i < m; i++) {
work[i] = available[i]; }

} // Request Logic

int count = 0; while (1) {

while (count < n) { printf("\nDo you want to make a resource


request? (1=Yes / 0=No): ");
safe = 0;
scanf("%d", &choice);
for (i = 0; i < n; i++) {
if (choice == 0) break;
if (finish[i] == 0) {
printf("Enter process number making the
for (j = 0; j < m; j++) { request (0 to %d): ", n - 1);
if (need[i][j] > work[j]) { scanf("%d", &processNo);
break; printf("Enter the request vector:\n");
} for (i = 0; i < m; i++) {
} printf("Resource %d: ", i);
if (j == m) { scanf("%d", &request[i]);
for (k = 0; k < m; k++) { }
work[k] += allocation[i][k]; int valid = 1;
} for (i = 0; i < m; i++) {
printf("Process P%d is executed if (request[i] > need[processNo][i]) {
safely.\n", i);
valid = 0;
finish[i] = 1;
break;
safe = 1;
}
count++;
}
}
if (!valid) {
}
printf("Error: Request exceeds the process's
} maximum need.\n");
if (safe == 0) { continue;
printf("System is in unsafe state.\n"); }
break; for (i = 0; i < m; i++) {
}
if (request[i] > available[i]) { if (finish[i] == 0) {

valid = -1; for (j = 0; j < m; j++) {

break; if (need[i][j] > work[j])

} break;

} }

if (valid == -1) { if (j == m) {

printf("Resources not available. Process P for (k = 0; k < m; k++) {


%d must wait.\n", processNo);
work[k] += allocation[i][k];
continue;
}
}
finish[i] = 1;
// Pretend to allocate resources
safe = 1;
for (i = 0; i < m; i++) {
count++;
available[i] -= request[i];
}
allocation[processNo][i] += request[i];
}
need[processNo][i] -= request[i];
}
}
if (safe == 0)
// Check if system remains in safe state
break;
for (i = 0; i < m; i++) {
}
work[i] = available[i];

}
if (count == n) {

printf("Request can be granted. System


for (i = 0; i < n; i++) { remains in a safe state.\n");

finish[i] = 0; } else {

} printf("Request cannot be granted. System


would be unsafe.\n");
count = 0;
// Rollback
while (count < n) {
for (i = 0; i < m; i++) {
safe = 0;
available[i] += request[i];
for (i = 0; i < n; i++) {
allocation[processNo][i] -= request[i];

need[processNo][i] += request[i]; Resource 2: 2

} Need Matrix

} P0: 7 4 3

P1: 1 2 2

return 0; P2: 6 0 0

} Checking system for safe state...

OUTPUT: Process P1 is executed safely.

Number of processes: 3 Process P2 is executed safely.

Number of resources: 3 Process P0 is executed safely.

Allocation Matrix:

P0: 0 1 0

P1: 2 0 0

P2: 3 0 2

Max Matrix:

P0: 7 5 3

P1: 3 2 2

P2: 9 0 2

Available Resources:

Resource 0: 3

Resource 1: 3
EXNO-8 DEADLOCK AVOIDANCE // Input request matrix
ALGORITHM
printf("Enter the Request matrix (%d x %d):\n",
np, nr);
PROGRAM:
for (i = 0; i < np; i++) {
#include <stdio.h> for (j = 0; j < nr; j++) {
int main() { scanf("%d", &request[i][j]);
int alloc[10][10], request[10][10], avail[10], }
total[10], work[10];
}
int mark[20] = {0}; // initialized to 0
// Calculate Available = Total - Allocated
int i, j, np, nr;
for (j = 0; j < nr; j++) {
printf("Enter the number of processes: ");
avail[j] = total[j];
scanf("%d", &np);
for (i = 0; i < np; i++) {
printf("Enter the number of resources: ");
avail[j] -= alloc[i][j];
scanf("%d", &nr);
}
// Input total resources
}
for (i = 0; i < nr; i++) {

printf("Enter total instances of resource R%d:


", i + 1); // Initialize work vector = available

scanf("%d", &total[i]); for (j = 0; j < nr; j++) {

} work[j] = avail[j];

// Input allocation matrix }

printf("Enter the Allocation matrix (%d x %d):\ // Mark processes with 0 allocation as completed
n", np, nr);
for (i = 0; i < np; i++) {
for (i = 0; i < np; i++) {
int zeroAlloc = 1;
for (j = 0; j < nr; j++) {
for (j = 0; j < nr; j++) {
scanf("%d", &alloc[i][j]);
if (alloc[i][j] != 0) {
}
zeroAlloc = 0;
}
break;
} } while (done);

if (zeroAlloc) // Check for deadlock

mark[i] = 1; int deadlock = 0;

} for (i = 0; i < np; i++) {

// Try to find a process whose request can be if (mark[i] == 0) {


satisfied
deadlock = 1;
int done;
break;
do {
}
done = 0;
}
for (i = 0; i < np; i++) {
if (deadlock) {
if (mark[i] == 0) {
printf("\n❌ Deadlock detected.\n");
int canProceed = 1;
printf("Processes involved in deadlock:\n");
for (j = 0; j < nr; j++) {
for (i = 0; i < np; i++) {
if (request[i][j] > work[j]) {
if (mark[i] == 0) {
canProceed = 0;
printf("P%d ", i);
break;
}
}
}
}
printf("\n");
if (canProceed) {
} else {
for (j = 0; j < nr; j++) {
printf("\n✅ No Deadlock detected. System is
work[j] += alloc[i][j]; in a safe state.\n");

} }

mark[i] = 1;

done = 1; return 0;

} }

} OUTPUT

} Number of processes: 3
Number of resources: 2

Total instances of resource R1: 6

Total instances of resource R2: 3

Allocation matrix:

10

21

31

Request matrix:

10

11

11

❌ Deadlock detected.

Processes involved in deadlock:

P1 P2
err = pthread_create(&tid[i], NULL,
&createthread, NULL);
EXNO-9
THREADING if (err != 0)

PROGRAM: printf("\nCan't create thread [%d]: %s", i +


1, strerror(err));

else
#include <stdio.h>
printf("\nThread %d created successfully\
#include <string.h> n", i + 1);
#include <pthread.h> }
#include <stdlib.h> // Join the threads to wait for them to finish
#include <unistd.h> for (int i = 0; i < 2; i++) {
pthread_t tid[2]; // Only 2 threads needed pthread_join(tid[i], NULL);
void* createthread(void* arg) { }
pthread_t id = pthread_self(); printf("\nAll threads completed.\n");
if (pthread_equal(id, tid[0])) { return 0;
printf("\nFirst thread processing...\n"); }
} else if (pthread_equal(id, tid[1])) { OUTPUT
printf("\nSecond thread processing...\n"); Thread 1 created successfully
} Thread 2 created successfully
// Simulate work

for (unsigned long i = 0; i < 10000000; i++); First thread processing...


printf("Thread [%lu] finished processing.\n", Second thread processing...
id);
Thread [140284569679616] finished processing.
return NULL;
Thread [140284561286912] finished processing.
}

int main(void) {
All threads completed.
int err;

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


EXNO-10 PAGING TECHNIQUE printf("\nPage Table:\n");

PROGRAM: printf("Page No\tFrame No\n");

#include <stdio.h> for (i = 0; i < n; i++) {

int main() { printf("%d\t%d\n", pno[i], fno[i]);

int n, size, la, i, pno[10], fno[10]; }

int offset, pa, limit, p; // Calculate page number and offset from logical
address
printf("Enter the number of pages: ");
p = la / size;
scanf("%d", &n);
offset = la % size;
printf("Enter the size of each page (in bytes): ");
// Find frame number corresponding to page p
scanf("%d", &size);
int frame = -1;
limit = n * size - 1;
for (i = 0; i < n; i++) {
printf("Enter the logical address (0 to %d): ",
limit); if (pno[i] == p) {

scanf("%d", &la); frame = fno[i];

if (la > limit || la < 0) { break;

printf("❌ Error: Logical address exceeds }


limit!\n");
}
return 1;
if (frame == -1) {
}
printf("\n❌ Error: Page number %d not found
printf("\nEnter the page table info (page no and in page table.\n", p);
corresponding frame no):\n");
return 1;
for (i = 0; i < n; i++) {
}
printf("Page %d: ", i);
pa = frame * size + offset;
scanf("%d", &pno[i]);
printf("\n✅ Logical Address Translation:\n");
printf("Frame for Page %d: ", pno[i]);
printf("Page Number: %d\n", p);
scanf("%d", &fno[i]);
printf("Offset: %d\n", offset);
}
printf("Physical Address: %d\n", pa);
return 0;

OUTPUT

Enter the number of pages: 3

Enter the size of each page (in bytes): 100

Enter the logical address (0 to 299): 170

Enter the page table info (page no and


corresponding frame no):

Page 0: 0

Frame for Page 0: 5

Page 1: 1

Frame for Page 1: 8

Page 2: 2

Frame for Page 2: 2

Page Table:

Page No Frame No

0 5

1 8

2 2

✅ Logical Address Translation:

Page Number: 1

Offset: 70

Physical Address: 870


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

EXNO-11 MEMORY ALLOCATION if(bsize[j] >= psize[i]) {


METHODS
allocation[i] = j;
EXNO-11(A) FIRST FIT
bsize[j] -= psize[i]; // reduce the block
PROGRAM: size
#include <stdio.h>
break;
int main() {
}
int bsize[10], psize[10], bno, pno;
}
int allocation[10]; // process-to-block mapping
}
int i, j;
// Display allocation
printf("Enter number of blocks: ");
printf("\nProcess No.\tProcess Size\tBlock No.\
scanf("%d", &bno); n");

printf("Enter size of each block:\n"); for(i = 0; i < pno; i++) {

for(i = 0; i < bno; i++) { printf("%d\t\t%d\t\t", i + 1, psize[i]);

printf("Block %d: ", i + 1); if(allocation[i] != -1)

scanf("%d", &bsize[i]); printf("%d\n", allocation[i] + 1);

} else

printf("\nEnter number of processes: "); printf("Not Allocated\n");

scanf("%d", &pno); }

printf("Enter size of each process:\n"); }

for(i = 0; i < pno; i++) { OUTPUT

printf("Process %d: ", i + 1); Enter number of blocks: 5

scanf("%d", &psize[i]); Block 1: 100

allocation[i] = -1; // initialize allocation as not Block 2: 500


done
Block 3: 200
}
Block 4: 300
// First Fit allocation
Block 5: 600
for(i = 0; i < pno; i++) {
Enter number of processes: 4 scanf("%d", &b[i]);

Process 1: 212 }

Process 2: 417 printf("\nEnter the size of each process:\n");

Process 3: 112 for(i = 1; i <= np; i++) {

Process 4: 426 printf("Process %d: ", i);

Process No. Process Size Block No. scanf("%d", &p[i]);

1 212 2 }

2 417 5 // Best Fit Allocation Logic

3 112 3 for(i = 1; i <= np; i++) {

4 426 Not Allocated lowest = 10000;

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

if(barray[j] != 1) { // block is not allocated

EXNO-11(B) BEST FIT temp = b[j] - p[i];

PROGRAM: if(temp >= 0 && temp < lowest) {


#include <stdio.h>
parray[i] = j;
int main() {
lowest = temp;
int fragment[20], b[20], p[20], i, j, nb, np, temp,
}
lowest;
}
static int barray[20], parray[20];
}
printf("\n\t\t MEMORY MANAGEMENT
SCHEME - BEST FIT\n");

printf("\nEnter the number of blocks: "); if(parray[i] != 0) {

scanf("%d", &nb); fragment[i] = lowest;

printf("Enter the number of processes: "); barray[parray[i]] = 1; // mark block as


allocated
scanf("%d", &np);
}
printf("Enter the size of each block:\n");
}
for(i = 1; i <= nb; i++) {

printf("Block %d: ", i);


printf("\nProcess No.\tProcess Size\tBlock No.\ Process No. Process Size Block No. Block
tBlock Size\tFragment"); Size Fragment

for(i = 1; i <= np; i++) { 1 212 4 300 88

if(parray[i] != 0) { 2 417 2 500 83

printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", 3 112 3 200 88

i, p[i], parray[i], b[parray[i]], 4 426 5 600 174


fragment[i]);

} else {

printf("\n%d\t\t%d\t\tNot Allocated", i,
p[i]);

return 0;

OUTPUT

Enter the number of blocks: 5

Block 1: 100

Block 2: 500

Block 3: 200

Block 4: 300

Block 5: 600

Enter the number of processes: 4

Process 1: 212

Process 2: 417

Process 3: 112

Process 4: 426
if(temp >= 0 && temp > greatest) {
EXNO-11(C) WORST FIT parray[i] = j;
greatest = temp;
PROGRAM: }
#include <stdio.h> }
}
int main() {
int fragment[20], b[20], p[20], i, j, nb, if(parray[i] != 0) {
np, temp, greatest; fragment[i] = greatest;
static int barray[20], parray[20]; barray[parray[i]] = 1; // mark block
as used
printf("\n\t\t MEMORY }
MANAGEMENT SCHEME - WORST }
FIT\n");
printf("\nProcess No.\tProcess Size\
printf("\nEnter the number of blocks: "); tBlock No.\tBlock Size\tFragment");
scanf("%d", &nb); for(i = 1; i <= np; i++) {
if(parray[i] != 0) {
printf("Enter the number of processes: "); printf("\n%d\t\t%d\t\t%d\t\t%d\t\t
scanf("%d", &np); %d",
i, p[i], parray[i], b[parray[i]],
printf("\nEnter the size of each block:\ fragment[i]);
n"); } else {
for(i = 1; i <= nb; i++) { printf("\n%d\t\t%d\t\tNot
printf("Block no %d: ", i); Allocated", i, p[i]);
scanf("%d", &b[i]); }
} }

printf("\nEnter the size of each process:\ return 0;


n"); }
for(i = 1; i <= np; i++) {
printf("Process no %d: ", i);
scanf("%d", &p[i]);
}

// Worst Fit Allocation Logic


for(i = 1; i <= np; i++) {
greatest = -1;
for(j = 1; j <= nb; j++) {
if(barray[j] != 1) {
temp = b[j] - p[i];
OUTPUT

Process No. Process Size Block No. Block


Size Fragment

1 212 5 600 388

2 417 2 500 83

3 112 4 300 188

4 426 Not Allocated

You might also like