OS Practical


  1. Create a child process in Linux using the fork system call. From the child process obtain

the process ID of both child and parent by using getpid and getppid system call.


#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <sys/wait.h>


int main() {

    int pid;

    int status;


    pid = fork();


    if (pid < 0) {

        perror("Fork failed");

        exit(EXIT_FAILURE);

    } else if (pid == 0) {

        printf("Executing Child Process\n");

        printf("Pid of current process: %d\n", getpid());

        printf("Pid of child's parent is %d\n", getppid());

        printf("Exiting Child....\n");

        exit(EXIT_SUCCESS); // Child process should exit after its work is done

    } else {

        printf("Executing parent process\n");

        printf("Pid of current process: %d\n", getpid());

        printf("Pid of parent's parent is %d\n", getppid());

        waitpid(pid, &status, 0); // Waiting for the child process to finish

        printf("Exiting Parent...\n");

    }


    return 0;

}





  1. Program to copy contents of one file (source) to another file (destination). Finally

displaying contents of destination file.



#include <stdio.h>

#include <fcntl.h>

#include <unistd.h>


#define BUFFER_SIZE 1024


int main() {

    char source_file[100];

    char destination_file[100];

    char buffer[BUFFER_SIZE];

    ssize_t bytes_read;


    printf("Enter source file name: ");

    scanf("%s", source_file);

    printf("Enter destination file name: ");

    scanf("%s", destination_file);


    int source_fd = open(source_file, O_RDONLY);

    if (source_fd == -1) {

        printf("Error opening source file\n");

        return 1;

    }


    int destination_fd = open(destination_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);

    if (destination_fd == -1) {

        printf("Error opening destination file\n");

        close(source_fd);

        return 1;

    }


    while ((bytes_read = read(source_fd, buffer, BUFFER_SIZE)) > 0) {

        if (write(destination_fd, buffer, bytes_read) != bytes_read) {

            printf("Error writing to destination file\n");

            close(source_fd);

            close(destination_fd);

            return 1;

        }

    }


    printf("File copied successfully.\n");


    close(source_fd);

    close(destination_fd);


    // Display contents of destination file

    destination_fd = open(destination_file, O_RDONLY);

    if (destination_fd == -1) {

        printf("Error opening destination file for reading\n");

        return 1;

    }


    printf("Contents of destination file:\n");

    while ((bytes_read = read(destination_fd, buffer, BUFFER_SIZE)) > 0) {

        printf("%.*s", (int)bytes_read, buffer);

    }

    printf("\n");


    close(destination_fd);


    return 0;

}




  1. FCFS cpu scheduling


#include <stdio.h>


// Process structure to store process information

struct Process {

    int arrival_time;

    int burst_time;

};


// Function to input processes

void input_processes(struct Process processes[], int num_processes) {

    printf("Enter process details:\n");

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

        printf("Process %d:\n", i + 1);

        printf("Enter arrival time: ");

        scanf("%d", &processes[i].arrival_time);

        printf("Enter burst time: ");

        scanf("%d", &processes[i].burst_time);

    }

}


int main() {

    struct Process processes[10]; // Maximum 10 processes

    int num_processes; // Number of processes


    // Input the number of processes

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

    scanf("%d", &num_processes);


    // Input process details

    input_processes(processes, num_processes);


    int current_time = 0;

    int total_waiting_time = 0;

    int total_turnaround_time = 0;


    printf("\nArrival Time \t Burst Time \t Waiting Time \t Turnaround Time\n");

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

        int waiting_time = (current_time > processes[i].arrival_time) ? (current_time - processes[i].arrival_time) : 0;

        int turnaround_time = waiting_time + processes[i].burst_time;


        total_waiting_time += waiting_time;

        total_turnaround_time += turnaround_time;


        printf("%d\t\t%d\t\t%d\t\t%d\n", processes[i].arrival_time, processes[i].burst_time, waiting_time, turnaround_time);

       

        current_time = (current_time > processes[i].arrival_time) ? (current_time + processes[i].burst_time) : (processes[i].arrival_time + processes[i].burst_time);

    }


    float avg_waiting_time = (float)total_waiting_time / num_processes;

    float avg_turnaround_time = (float)total_turnaround_time / num_processes;


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

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


    return 0;

}



  1. SJF cpu scheduling


#include <stdio.h>


// Process structure to store process information

struct Process {

    int arrival_time;

    int burst_time;

};


// Function to input processes

void input_processes(struct Process processes[], int num_processes) {

    printf("Enter process details:\n");

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

        printf("Process %d:\n", i + 1);

        printf("Enter arrival time: ");

        scanf("%d", &processes[i].arrival_time);

        printf("Enter burst time: ");

        scanf("%d", &processes[i].burst_time);

    }

}


// Function to perform Shortest Job First (SJF) scheduling

void SJF(struct Process processes[], int num_processes) {

    // Sort processes based on burst time (selection sort)

    for (int i = 0; i < num_processes - 1; i++) {

        int min_index = i;

        for (int j = i + 1; j < num_processes; j++) {

            if (processes[j].burst_time < processes[min_index].burst_time) {

                min_index = j;

            }

        }

        // Swap processes

        struct Process temp = processes[min_index];

        processes[min_index] = processes[i];

        processes[i] = temp;

    }


    // Variables to calculate waiting time and turnaround time

    int current_time = 0;

    int total_waiting_time = 0;

    int total_turnaround_time = 0;


    // Display process details and calculate waiting/turnaround time

    printf("\nArrival Time \t Burst Time \t Waiting Time \t Turnaround Time\n");

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

        int waiting_time = (current_time > processes[i].arrival_time) ? (current_time - processes[i].arrival_time) : 0;

        int turnaround_time = waiting_time + processes[i].burst_time;


        total_waiting_time += waiting_time;

        total_turnaround_time += turnaround_time;


        printf("%d\t\t%d\t\t%d\t\t%d\n", processes[i].arrival_time, processes[i].burst_time, waiting_time, turnaround_time);


        current_time = (current_time > processes[i].arrival_time) ? (current_time + processes[i].burst_time) : (processes[i].arrival_time + processes[i].burst_time);

    }


    // Calculate and display average waiting time and average turnaround time

    float avg_waiting_time = (float)total_waiting_time / num_processes;

    float avg_turnaround_time = (float)total_turnaround_time / num_processes;


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

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

}


int main() {

    struct Process processes[10]; // Maximum 10 processes

    int num_processes; // Number of processes


    // Input the number of processes

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

    scanf("%d", &num_processes);


    // Input process details

    input_processes(processes, num_processes);


    // Perform SJF scheduling

    SJF(processes, num_processes);


    return 0;

}


  1. SRTF cpu scheduling


#include <stdio.h>

#include <conio.h>

int main()

{

int arrival[10], burst[10], remaining[10], smallest,i, count = 0, time,

processes, endTime;

float avgWait = 0, avgTurnaround = 0;

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

scanf("%d", &processes);

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

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

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

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

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

{

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

remaining[i] = burst[i];

}

remaining[9] = 9999;

printf("\nProcess Turnaround Time Waiting Time\n");

for (time = 0; count != processes; time++)

{

smallest = 9;

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

{

if (arrival[i] <= time && burst[i] < burst[smallest] && burst[i] > 0)

{

smallest = i;

}

}

burst[smallest]--;

if (burst[smallest] == 0)

{

count++;

endTime = time + 1;

printf("P[%d]\t\t%d\t\t%d\n", smallest + 1, endTime - arrival[smallest],

endTime - arrival[smallest] - remaining[smallest]);

avgWait += endTime - arrival[smallest] - remaining[smallest];

avgTurnaround += endTime - arrival[smallest];

}

}

printf("\nAverage waiting time = %f\n", avgWait / processes);

printf("Average Turnaround time = %f\n", avgTurnaround / processes);

getch();

return 0;

}


  1. RR cpu scheduling


#include<stdio.h>  

#include<conio.h>  

 

void main()  

{  

    // initlialize the variable name  

    int i, NOP, sum=0,count=0, y, quant, wt=0, tat=0, at[10], bt[10], temp[10];  

    float avg_wt, avg_tat;  

    printf(" Total number of process in the system: ");  

    scanf("%d", &NOP);  

    y = NOP; // Assign the number of process to variable y  

 

// Use for loop to enter the details of the process like Arrival time and the Burst Time  

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

{  

printf("\n Enter the Arrival and Burst time of the Process[%d]\n", i+1);  

printf(" Arrival time is: \t");  // Accept arrival time  

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

printf(" \nBurst time is: \t"); // Accept the Burst time  

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

temp[i] = bt[i]; // store the burst time in temp array  

}  

// Accept the Time qunat  

printf("Enter the Time Quantum for the process: \t");  

scanf("%d", &quant);  

// Display the process No, burst time, Turn Around Time and the waiting time  

printf("\n Process No \t\t Burst Time \t\t TAT \t\t Waiting Time ");  

for(sum=0, i = 0; y!=0; )  

{  

if(temp[i] <= quant && temp[i] > 0) // define the conditions  

{  

    sum = sum + temp[i];  

    temp[i] = 0;  

    count=1;  

    }    

    else if(temp[i] > 0)  

    {  

        temp[i] = temp[i] - quant;  

        sum = sum + quant;    

    }  

    if(temp[i]==0 && count==1)  

    {  

        y--; //decrement the process no.  

        printf("\nProcess No[%d] \t\t %d\t\t\t\t %d\t\t\t %d", i+1, bt[i], sum-at[i], sum-at[i]-bt[i]);  

        wt = wt+sum-at[i]-bt[i];  

        tat = tat+sum-at[i];  

        count =0;    

    }  

    if(i==NOP-1)  

    {  

        i=0;  

    }  

    else if(at[i+1]<=sum)  

    {  

        i++;  

    }  

    else  

    {  

        i=0;  

    }  

}  

// represents the average waiting time and Turn Around time  

avg_wt = wt * 1.0/NOP;  

avg_tat = tat * 1.0/NOP;  

printf("\n Average Turn Around Time: \t%f", avg_wt);  

printf("\n Average Waiting Time: \t%f", avg_tat);  

getch();  

}




  1. FCFS Paging page


#include<stdio.h>

#include<stdlib.h>


int findPage(int frame[], int size, int page) {

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

if (frame[i] == page) {

return 1; // Page found

}

}

return 0; // Page not found

}


int main() {

int n_frames, n_pages, pageHit = 0, pageMiss = 0;

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

scanf("%d", &n_frames);




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

scanf("%d", &n_pages);


int frames[n_frames], pages[n_pages];

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

frames[i] = -1; // Initialize frames

}


printf("Enter the page reference string: ");

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

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

}


int index = 0;

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

if(!findPage(frames, n_frames, pages[i])) {

// Page miss

pageMiss++;

frames[index] = pages[i];

index = (index + 1) % n_frames;

} else {

// Page hit

pageHit++;

}

}


printf("\nPage Hits: %d\n", pageHit);

printf("Page Miss: %d\n", pageMiss);

float hitRatio = (float)pageHit / (float)n_pages;

float missRatio = (float)pageMiss / (float)n_pages;

printf("Page Hit Ratio: %.2f\n", hitRatio);

printf("Page Miss Ratio: %.2f\n", missRatio);



return 0;

}




  1. LRU paging page


#include<stdio.h>

#include<stdlib.h>


int findLRU(int time[], int n) {

int i, minimum = time[0], pos = 0;

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

if(time[i] < minimum) {

minimum = time[i];

pos = i;

}

}

return pos;

}


int main() {

int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0,

time[10], flag1, flag2, i, j, pos, faults = 0;

printf("Enter number of frames: ");

scanf("%d", &no_of_frames);


printf("Enter number of pages: ");

scanf("%d", &no_of_pages);



printf("Enter page reference string: ");

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

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

}


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

frames[i] = -1;

}


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

flag1 = flag2 = 0;


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

if(frames[j] == pages[i]) {

counter++;

time[j] = counter;

flag1 = flag2 = 1;

break;

}

}


if(flag1 == 0) {

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

if(frames[j] == -1) {

counter++;

faults++;

frames[j] = pages[i];

time[j] = counter;

flag2 = 1;

break;

}

}

}


if(flag2 == 0) {



pos = findLRU(time, no_of_frames);

counter++;

faults++;

frames[pos] = pages[i];

time[pos] = counter;

}

}


printf("\nPage Miss: %d", faults);

printf("\nPage Hits: %d", no_of_pages - faults);

float hitRatio = (float)(no_of_pages - faults) / no_of_pages;

float missRatio = (float)faults / no_of_pages;

printf("\nPage Hit Ratio: %.2f", hitRatio);

printf("\nPage Miss Ratio: %.2f\n", missRatio);


return 0;

}





  1. FCFS Disk Management


#include <stdio.h>

#include <stdlib.h>


#define MAX_REQUESTS 100


// Function to sort an array in ascending order

void sort(int arr[], int n) {

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

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

            if (arr[j] > arr[j + 1]) {

                int temp = arr[j];

                arr[j] = arr[j + 1];

                arr[j + 1] = temp;

            }

        }

    }

}


// Function to calculate the total seek time

int calculateSeekTime(int requests[], int n, int head) {

    int seek_time = 0;

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

        seek_time += abs(requests[i] - head);

        head = requests[i];

    }

    return seek_time;

}


int main() {

    int requests[MAX_REQUESTS];

    int n, head;


    // Input the number of requests

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

    scanf("%d", &n);


    // Input the requests

    printf("Enter the requests:\n");

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

        printf("Request %d: ", i + 1);

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

    }


    // Input the initial position of the disk head

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

    scanf("%d", &head);


    // Sort the requests in ascending order

    sort(requests, n);


    // Calculate and display the total seek time

    int seek_time = calculateSeekTime(requests, n, head);

    printf("Total seek time: %d\n", seek_time);


    return 0;

}





  1.  SSTF Disk Management


#include<math.h>

#include<stdio.h>

#include<stdlib.h>

int main()

{

    int i,n,k,req[50],mov=0,cp,index[50],min,a[50],j=0,mini,cp1;

    printf("enter the current position\n");

    scanf("%d",&cp);

    printf("enter the number of requests\n");

    scanf("%d",&n);

    cp1=cp;

    printf("enter the request order\n");

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

    {

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

    }

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

    {

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

    {

        index[i]=abs(cp-req[i]); // calculate distance of each request from current position

    }

    // to find the nearest request

    min=index[0];

    mini=0;

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

    {

        if(min>index[i])

        {

            min=index[i];

            mini=i;

        }

    }

    a[j]=req[mini];

    j++;

    cp=req[mini]; // change the current position value to next request

    req[mini]=999;

    } // the request that is processed its value is changed so that it is not processed again

    printf("Sequence is : ");

    printf("%d",cp1);

    mov=mov+abs(cp1-a[0]);    // head movement

    printf(" -> %d",a[0]);

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

    {

        mov=mov+abs(a[i]-a[i-1]); ///head movement

        printf(" -> %d",a[i]);

    }

    printf("\n");

    printf("total head movement = %d\n",mov);

}



  1. SCAN Disk Management



#include <stdio.h>

#include <stdlib.h>

#include <limits.h>


// Function to find the request with the minimum seek time from the current head position

int findMinSeekTime(int arr[], int head, int n) {

    int minSeekTime = INT_MAX;

    int minIndex = -1;

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

        if (arr[i] >= head && arr[i] - head < minSeekTime) {

            minSeekTime = arr[i] - head;

            minIndex = i;

        }

    }

    return minIndex;

}


// Function to implement SCAN disk scheduling algorithm

void SCAN(int arr[], int head, int n) {

    int seekCount = 0;

    int distance;

    int curHead = head;

    int direction = 1; // 1 for moving towards higher positions, -1 for moving towards lower positions


    // Sort the array to find the order of requests

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

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

            if (arr[i] > arr[j]) {

                int temp = arr[i];

                arr[i] = arr[j];

                arr[j] = temp;

            }

        }

    }


    // Move towards the end of the disk

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

        if (arr[i] >= curHead) {

            distance = abs(arr[i] - curHead);

            seekCount += distance;

            printf("Move to %d\n", arr[i]);

            curHead = arr[i];

        }

    }


    // Reverse direction and move towards the start of the disk

    direction = -1;

    for (int i = n - 1; i >= 0; i--) {

        if (arr[i] <= curHead) {

            distance = abs(arr[i] - curHead);

            seekCount += distance;

            printf("Move to %d\n", arr[i]);

            curHead = arr[i];

        }

    }


    printf("Total seek count = %d\n", seekCount);

}


int main() {

    int arr[] = {90, 29, 28, 60, 92, 11, 41, 80};

    int head = 50;

    int n = sizeof(arr) / sizeof(arr[0]);


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

    SCAN(arr, head, n);


    return 0;

}



  1. FIRST FIT 


#include <stdio.h>

#include <stdlib.h>


void firstFit(int blocks[], int holes[], int num_blocks, int num_holes) {

    int allocation[num_blocks];

    int fragmentation = 0;


    // Initialize allocation array with -1

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

        allocation[i] = -1;

    }


    // First-fit allocation

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

        for (int j = 0; j < num_holes; j++) {

            if (holes[j] >= blocks[i]) {

                allocation[i] = j;

                holes[j] -= blocks[i];

                break;

            }

        }

    }


    // Calculate fragmentation

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

        if (allocation[i] == -1) {

            fragmentation += blocks[i];

        }

    }


    // Print allocation and fragmentation

    printf("\nBlock Allocation using First-fit:\n");

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

        if (allocation[i] != -1) {

            printf("Block %d of size %d is allocated to Hole %d\n", i + 1, blocks[i], allocation[i] + 1);

        } else {

            printf("Block %d of size %d could not be allocated\n", i + 1, blocks[i]);

        }

    }

    printf("\nTotal Fragmentation: %d units\n", fragmentation);

}


int main() {

    int holes_sizes[] = {100, 200, 150};

    int blocks_sizes[] = {50, 80, 120, 150};

    int num_holes = sizeof(holes_sizes) / sizeof(holes_sizes[0]);

    int num_blocks = sizeof(blocks_sizes) / sizeof(blocks_sizes[0]);


    firstFit(blocks_sizes, holes_sizes, num_blocks, num_holes);


    return 0;

}






  1. BEST FIT


#include <stdio.h>

#include <stdlib.h>


void bestFit(int blocks[], int holes[], int num_blocks, int num_holes) {

    int allocation[num_blocks];

    int fragmentation = 0;


    // Initialize allocation array with -1

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

        allocation[i] = -1;

    }


    // Best-fit allocation

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

        int best_idx = -1;

        for (int j = 0; j < num_holes; j++) {

            if (holes[j] >= blocks[i]) {

                if (best_idx == -1 || holes[j] < holes[best_idx]) {

                    best_idx = j;

                }

            }

        }


        if (best_idx != -1) {

            allocation[i] = best_idx;

            holes[best_idx] -= blocks[i];

        } else {

            fragmentation += blocks[i];

        }

    }


    // Print allocation and fragmentation

    printf("\nBlock Allocation using Best-fit:\n");

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

        if (allocation[i] != -1) {

            printf("Block %d of size %d is allocated to Hole %d\n", i + 1, blocks[i], allocation[i] + 1);

        } else {

            printf("Block %d of size %d could not be allocated\n", i + 1, blocks[i]);

        }

    }

    printf("\nTotal Fragmentation: %d units\n", fragmentation);

}


int main() {

    int holes_sizes[] = {100, 200, 150};

    int blocks_sizes[] = {50, 80, 120, 70};

    int num_holes = sizeof(holes_sizes) / sizeof(holes_sizes[0]);

    int num_blocks = sizeof(blocks_sizes) / sizeof(blocks_sizes[0]);


    bestFit(blocks_sizes, holes_sizes, num_blocks, num_holes);


    return 0;

}

  1. WORST FIT


#include <stdio.h>

#include <stdlib.h>


void worstFit(int blocks[], int holes[], int num_blocks, int num_holes) {

    int allocation[num_blocks];

    int fragmentation = 0;


    // Initialize allocation array with -1

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

        allocation[i] = -1;

    }


    // Worst-fit allocation

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

        int worst_idx = -1;

        for (int j = 0; j < num_holes; j++) {

            if (holes[j] >= blocks[i]) {

                if (worst_idx == -1 || holes[j] > holes[worst_idx]) {

                    worst_idx = j;

                }

            }

        }


        if (worst_idx != -1) {

            allocation[i] = worst_idx;

            holes[worst_idx] -= blocks[i];

        } else {

            fragmentation += blocks[i];

        }

    }


    // Print allocation and fragmentation

    printf("\nBlock Allocation using Worst-fit:\n");

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

        if (allocation[i] != -1) {

            printf("Block %d of size %d is allocated to Hole %d\n", i + 1, blocks[i], allocation[i] + 1);

        } else {

            printf("Block %d of size %d could not be allocated\n", i + 1, blocks[i]);

        }

    }

    printf("\nTotal Fragmentation: %d units\n", fragmentation);

}


int main() {

    int holes_sizes[] = {100, 200, 150};

    int blocks_sizes[] = {50, 80, 120, 220};

    int num_holes = sizeof(holes_sizes) / sizeof(holes_sizes[0]);

    int num_blocks = sizeof(blocks_sizes) / sizeof(blocks_sizes[0]);


    worstFit(blocks_sizes, holes_sizes, num_blocks, num_holes);


    return 0;

}






  1. DEADLOCK DETECT , BANKERS ALGO



#include <stdio.h>


#define MAX_PROCESSES 10

#define MAX_RESOURCES 10


int processes, resources;

int available[MAX_RESOURCES];

int max_allocation[MAX_PROCESSES][MAX_RESOURCES];

int current_allocation[MAX_PROCESSES][MAX_RESOURCES];

int need[MAX_PROCESSES][MAX_RESOURCES];

int safe_sequence[MAX_PROCESSES];

int finish[MAX_PROCESSES];


void input() {

    printf("Enter number of processes: ");

    scanf("%d", &processes);


    printf("Enter number of resources: ");

    scanf("%d", &resources);


    printf("Enter available instances of each resource:\n");

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

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

    }


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

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

        printf("For process %d: ", i);

        for (int j = 0; j < resources; ++j) {

            scanf("%d", &max_allocation[i][j]);

        }

    }


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

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

        printf("For process %d: ", i);

        for (int j = 0; j < resources; ++j) {

            scanf("%d", &current_allocation[i][j]);

            need[i][j] = max_allocation[i][j] - current_allocation[i][j];

        }

    }

}


int is_safe() {

    int work[MAX_RESOURCES];

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

        work[i] = available[i];

    }


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

        finish[i] = 0;

    }


    int count = 0;

    while (count < processes) {

        int found = 0;

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

            if (!finish[i]) {

                int j;

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

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

                        break;

                }


                if (j == resources) {

                    for (int k = 0; k < resources; ++k) {

                        work[k] += current_allocation[i][k];

                    }

                    safe_sequence[count++] = i;

                    finish[i] = 1;

                    found = 1;

                }

            }

        }

        if (!found) {

            return 0; // Deadlock detected

        }

    }

    return 1; // No deadlock

}


void display_safe_sequence() {

    printf("Safe Sequence: ");

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

        printf("%d ", safe_sequence[i]);

    }

    printf("\n");

}


int main() {

    input();

    if (is_safe()) {

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

        display_safe_sequence();

    } else {

        printf("Deadlock detected.\n");

    }

    return 0;

}





  1. WAP to demonstrate how to use lock mechanism to achieve process synchronization.


import threading

import time


shared_resource_no_sync = 0

shared_resource_with_sync = 0

lock = threading.Lock()


def increment_no_sync():

    global shared_resource_no_sync

    for _ in range(1000000):

        shared_resource_no_sync += 1


def decrement_no_sync():

    global shared_resource_no_sync

    for _ in range(1000000):

        shared_resource_no_sync -= 1


def increment_with_sync():

    global shared_resource_with_sync

    for _ in range(1000000):

        lock.acquire()

        shared_resource_with_sync += 1

        lock.release()


def decrement_with_sync():

    global shared_resource_with_sync

    for _ in range(1000000):

        lock.acquire()

        shared_resource_with_sync -= 1

        lock.release()


if __name__ == "__main__":

    t1_no_sync = threading.Thread(target=increment_no_sync)

    t2_no_sync = threading.Thread(target=decrement_no_sync)

    t1_with_sync = threading.Thread(target=increment_with_sync)

    t2_with_sync = threading.Thread(target=decrement_with_sync)

   

    t1_no_sync.start()

    t2_no_sync.start()

    t1_with_sync.start()

    t2_with_sync.start()

   

    t1_no_sync.join()

    t2_no_sync.join()

    t1_with_sync.join()

    t2_with_sync.join()

   

    print("Final shared resource value without synchronization:", shared_resource_no_sync)

    print("Final shared resource value with synchronization:", shared_resource_with_sync)




  1. WAP to demonstrate the use of Queue mechanism to achieve process synchronization

in Producer – Consumer Problem.



import threading

import queue

import time


# Define the size of the buffer

BUFFER_SIZE = 10


# Create a queue with a maximum size

buffer = queue.Queue(BUFFER_SIZE)


def producer(n):

    """Producer thread function."""

    for i in range(n):

        item = i

        buffer.put(item)

        print(f"Produced {item}")

        time.sleep(1) # Simulate time to produce an item


def consumer(n):

    """Consumer thread function."""

    for _ in range(n):

        item = buffer.get()

        print(f"Consumed {item}")

        time.sleep(1) # Simulate time to consume an item


if __name__ == "__main__":

    # Create producer and consumer threads

    producer_thread = threading.Thread(target=producer, args=(10,))

    consumer_thread = threading.Thread(target=consumer, args=(10,))


    # Start the threads

    producer_thread.start()

    consumer_thread.start()


    # Wait for both threads to complete

    producer_thread.join()

    consumer_thread.join()


    print("All items have been produced and consumed.")





Comments