[go: up one dir, main page]

0% found this document useful (0 votes)
11 views24 pages

Abc C

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 24

//1..

Dinning philospher

#include <stdio.h>

#include <pthread.h>

#include <semaphore.h>

#include <unistd.h>

#define N 5 // Number of philosophers

#define THINKING 0

#define HUNGRY 1

#define EATING 2

#define LEFT (ph_num + 4) % N // Left neighbor

#define RIGHT (ph_num + 1) % N // Right neighbor

sem_t mutex; // Semaphore for mutual exclusion

sem_t S[N]; // Semaphore array for each philosopher (for waiting on forks)

int state[N]; // Array to track the state of each philosopher

int phil[N] = {0, 1, 2, 3, 4}; // Philosopher numbers

void test(int ph_num) {

if (state[ph_num] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) {

// Philosopher can start eating if neighbors are not eating

state[ph_num] = EATING;

printf("Philosopher %d takes fork %d and %d\n", ph_num + 1, LEFT + 1, ph_num + 1);

printf("Philosopher %d is Eating\n", ph_num + 1);

sleep(2); // Simulating eating

// Signal the philosopher that they can eat

sem_post(&S[ph_num]);

}
void take_fork(int ph_num) {

sem_wait(&mutex); // Lock the mutex

state[ph_num] = HUNGRY;

printf("Philosopher %d is Hungry\n", ph_num + 1);

// Test if this philosopher can eat

test(ph_num);

sem_post(&mutex); // Release the mutex

// Wait if unable to eat

sem_wait(&S[ph_num]);

sleep(1);

void put_fork(int ph_num) {

sem_wait(&mutex); // Lock the mutex

state[ph_num] = THINKING; // Philosopher is thinking

printf("Philosopher %d puts down fork %d and %d\n", ph_num + 1, LEFT + 1, ph_num + 1);

printf("Philosopher %d is Thinking\n", ph_num + 1);

// Test if the left and right neighbors can now eat

test(LEFT);

test(RIGHT);

sem_post(&mutex); // Release the mutex

void* philosopher(void* num) {

while (1) {

int* ph_num = num;

sleep(1); // Thinking
take_fork(*ph_num); // Trying to eat

sleep(0); // Eating

put_fork(*ph_num); // Done eating, putting down the forks

int main() {

pthread_t thread_id[N];

// Initialize the semaphores

sem_init(&mutex, 0, 1); // Semaphore for mutual exclusion

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

sem_init(&S[i], 0, 0); // Semaphore for each philosopher (initial value 0)

// Create philosopher threads

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

pthread_create(&thread_id[i], NULL, philosopher, &phil[i]);

printf("Philosopher %d is Thinking\n", i + 1);

// Join philosopher threads

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

pthread_join(thread_id[i], NULL);

return 0;

}
//2…FCFS

#include<stdio.h>

void findwaitingtime(int n, int bt[],int at[],int wt[],int tat[]){

int ct[n];

int st[n];

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

if(i == 0){

st[i] = at[i];

else{

if(ct[i-1]>at[i]){

st[i]=ct[i-1];

else{

st[i]=at[i];

ct[i]=st[i]+bt[i];

tat[i]=ct[i]-at[i];

wt[i]=tat[i]-bt[i];

void ganttchartAndAvg(int n,int bt[],int at[]){

int wt[n];

int tat[n];

double twt=0,ttat=0;

findwaitingtime(n,bt,at,wt,tat);

printf("Gantt chart:");

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

printf("P%d", i);

}
printf("\n");

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

ttat += tat[i];

twt += wt[i];

printf("Average waiting time =%.2f\n",twt/n);

printf("Average turn around time =%.2f\n",ttat/n);

int main(){

int n;

printf("Enter the number of process");

scanf("%d",&n);

int at[n],bt[n];

printf("Enter the arrival times");

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

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

printf("Enter the burst times");

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

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

ganttchartAndAvg(n, bt,at);

return 0;

}
//3…sjf---NP

#include <stdio.h>

#include <stdbool.h>

void findWaitingTime(int n, int bt[], int at[], int wt[],int tat[]){

int completed[n], finish_time[n];

int current_time = 0;

int total_completed = 0;

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

completed[i] = 0;

while (total_completed < n){

int shortest = -1;

int min_bt = 10000;

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

if (at[i] <= current_time && !completed[i] && bt[i] < min_bt){

min_bt = bt[i];

shortest = i;

if (shortest != -1){

current_time += bt[shortest];

finish_time[shortest] = current_time;

wt[shortest] = finish_time[shortest] - at[shortest] - bt[shortest];

if (wt[shortest] < 0){

wt[shortest] = 0;

completed[shortest] = 1;

total_completed++;

else{

current_time++;
}

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

tat[i] = bt[i] + wt[i];

void findAverageTimes(int n, int bt[], int at[])

int wt[n], tat[n];

int twt = 0, ttat = 0;

findWaitingTime(n, bt, at, wt,tat);

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

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

twt += wt[i];

ttat += tat[i];

printf("P%d\t\t%d\t\t%d\t\t%d\t\t%d\n", i + 1, bt[i],at[i], wt[i], tat[i]);

float avg_waiting_time = (float)twt / n;

float avg_turnaround_time = (float)ttat / n;

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

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

int main() {

int n;

printf("Enter number of processes: ");

scanf("%d", &n);

int bt[n], at[n];

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


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

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

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

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

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

findAverageTimes(n, bt, at);

return 0;

//4….producer_consumer

#include <pthread.h>

#include <semaphore.h>

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#define BUFFER_SIZE 5

int buffer[BUFFER_SIZE];

int in = 0, out = 0;

sem_t empty;

sem_t full;

pthread_mutex_t mutex;

void *producer(void *arg) {

int item;

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

item = rand() % 100; // Produce a random item

sem_wait(&empty); // Decrement empty semaphore

pthread_mutex_lock(&mutex); // Lock the buffer

buffer[in] = item; // Produce an item

printf("Producer produced: %d\n", item);

in = (in + 1) % BUFFER_SIZE; // Move to the next index


pthread_mutex_unlock(&mutex); // Unlock the buffer

sem_post(&full); // Increment full semaphore

sleep(1); // Simulate time taken to produce

return NULL;

void *consumer(void *arg) {

int item;

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

sem_wait(&full); // Decrement full semaphore

pthread_mutex_lock(&mutex); // Lock the buffer

item = buffer[out]; // Consume an item

printf("Consumer consumed: %d\n", item);

out = (out + 1) % BUFFER_SIZE; // Move to the next index

pthread_mutex_unlock(&mutex); // Unlock the buffer

sem_post(&empty); // Increment empty semaphore

sleep(2); // Simulate time taken to consume

return NULL;

int main() {

pthread_t prod_thread, cons_thread;

// Initialize semaphores and mutex

sem_init(&empty, 0, BUFFER_SIZE);

sem_init(&full, 0, 0);

pthread_mutex_init(&mutex, NULL);

// Create producer and consumer threads

pthread_create(&prod_thread, NULL, producer, NULL);

pthread_create(&cons_thread, NULL, consumer, NULL);

// Wait for both threads to finish

pthread_join(prod_thread, NULL);
pthread_join(cons_thread, NULL);

// Destroy semaphores and mutex

sem_destroy(&empty);

sem_destroy(&full);

pthread_mutex_destroy(&mutex);

return 0;

//5…priority

#include <stdio.h>

int main(){

int n, i, j;

printf("Number of processes: ");

scanf("%d", &n);

int burst_time[n], arrival_time[n], priority[n], process[n];

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

process[i] = i;

printf("Enter burst time, arrival time and priority of P%d: ", i);

scanf("%d %d %d", &burst_time[i], &arrival_time[i], &priority[i]);

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

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

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

int temp = priority[i];

priority[i] = priority[j];

priority[j] = temp;

temp = burst_time[i];

burst_time[i] = burst_time[j];

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

arrival_time[i] = arrival_time[j];

arrival_time[j] = temp;

temp = process[i];

process[i] = process[j];

process[j] = temp;

int waiting_time[n], turnaround_time[n];

waiting_time[0] = 0;

turnaround_time[0] = burst_time[0];

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

waiting_time[i] = waiting_time[i - 1] + burst_time[i - 1];

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

printf("Gantt Chart: ");

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

printf("P%d ", process[i]);

printf("\n");

float avg_waiting_time = 0, avg_turnaround_time = 0;

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

avg_waiting_time += waiting_time[i];

avg_turnaround_time += turnaround_time[i];

printf("Average waiting time: %.2f\n", avg_waiting_time/n);

printf("Average turnaround time: %.2f\n", avg_turnaround_time/n);

return 0;

}
//6….bankers algo

#include <stdio.h>

#define MAX 10

void calculateNeed(int need[MAX][MAX], int max[MAX][MAX], int alloc[MAX][MAX], int n, int m) {

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

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

need[i][j] = max[i][j] - alloc[i][j];

int isSafe(int alloc[MAX][MAX], int max[MAX][MAX], int avail[MAX], int n, int m) {

int need[MAX][MAX];

calculateNeed(need, max, alloc, n, m);

int f[MAX] = {0};

int ans[MAX];

int ind = 0;

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

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

if (f[i] == 0) {

int flag = 0;

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

if (need[i][j] > avail[j]) {

flag = 1;

break;

if (flag == 0) {

ans[ind++] = i;

for (int y = 0; y < m; y++) {

avail[y] += alloc[i][y];

}
f[i] = 1;

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

if (f[i] == 0) {

printf("The following system is not safe\n");

return 0;

printf("Following is the SAFE Sequence\n");

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

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

printf(" P%d\n", ans[n - 1]);

return 1;

int main() {

int n, m;

printf("Enter number of processes: ");

scanf("%d", &n);

printf("Enter number of resources: ");

scanf("%d", &m);

int alloc[MAX][MAX], max[MAX][MAX], avail[MAX];

printf("Enter Allocation Matrix:\n");

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

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

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

}
printf("Enter MAX Matrix:\n");

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

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

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

printf("Enter Available Resources:\n");

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

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

isSafe(alloc, max, avail, n, m);

return 0;

// 7….. round robin

#include<stdio.h>

#include<conio.h>

#define max 30

int main(){

int n,i,j,temp,sq=0,tq,count=0;

int at[max],bt[max],ct[max],tat[max],wt[max],rem_bt[max] ;

float awt = 0 , atat =0;

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

scanf("%d",&n);

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

printf("Enter the Arrival and Burst time of process %d : ",i+1);

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

rem_bt[i] = bt[i];
}

printf("Enter Time Quantum : ");

scanf("%d",&tq);

while(count < n){

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

if(rem_bt[i] == 0){

continue;

if(rem_bt[i] > tq){

rem_bt[i] -= tq;

sq += tq;

else{

sq += rem_bt[i];

rem_bt[i] = 0;

ct[i] = sq;

count++;

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

tat[i] = ct[i] - at[i];

wt[i] = tat[i] - bt[i];

awt += wt[i];

atat += tat[i];

printf("Process\tArrival Time\tBurst Time\tCompletion Time\tTurn Around Time\tWaiting


Time\n");
for(i=0 ; i<n ; i++){

printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n",i+1,at[i],bt[i],ct[i],tat[i],wt[i]);

awt = awt/n;

atat = atat/n;

printf("Average Waiting Time = %f\n",awt);

printf("Average Turn Around Time = %f",atat);

return 0;

// 8 inter process through pipe

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>

int main() {

int pipefds[2];

pid_t pid;

char write_msg[] = "Hello from Parent!";

char read_msg[50];

// Create the pipe

if (pipe(pipefds) == -1) {

perror("pipe");

exit(EXIT_FAILURE);

// Fork a child process

pid = fork();
if (pid == -1) {

perror("fork");

exit(EXIT_FAILURE);

if (pid == 0) { // Child process

// Close the write end of the pipe

close(pipefds[1]);

// Read the message from the parent

read(pipefds[0], read_msg, sizeof(read_msg));

printf("Child received: %s\n", read_msg);

// Close the read end of the pipe

close(pipefds[0]);

} else { // Parent process

// Close the read end of the pipe

close(pipefds[0]);

// Write the message to the child

write(pipefds[1], write_msg, strlen(write_msg) + 1);

printf("Parent sent: %s\n", write_msg);

// Close the write end of the pipe

close(pipefds[1]);

// Wait for the child process to finish

wait(NULL);

return 0;}
//…sjf preemtive…9

#include <stdio.h>

#define MAX 100

struct Process {

int id; // Process ID

int at; // Arrival Time

int bt; // Burst Time

int rt; // Remaining Time

int ct; // Completion Time

int wt; // Waiting Time

int tat; // Turnaround Time

};

int main() {

int n, total = 0, completed = 0, current_time = 0, min_rt, shortest;

float avg_wt = 0, avg_tat = 0;

struct Process p[MAX];

// Input: number of processes

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

scanf("%d", &n);

// Input: arrival time and burst time of each process

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

printf("Enter Arrival Time and Burst Time for Process %d: ", i + 1);

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

p[i].id = i + 1; // Process ID

p[i].rt = p[i].bt; // Initialize remaining time with burst time

}
// Start processing with SJF Preemptive

while (completed != n) {

// Find the process with the shortest remaining time that has arrived

shortest = -1;

min_rt = MAX;

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

if (p[i].at <= current_time && p[i].rt > 0 && p[i].rt < min_rt) {

min_rt = p[i].rt;

shortest = i;

if (shortest == -1) {

current_time++; // No process is ready to execute, so just increment time

continue;

// Execute the selected process

p[shortest].rt--;

current_time++;

// If the process finishes executing

if (p[shortest].rt == 0) {

completed++;

p[shortest].ct = current_time; // Completion time

p[shortest].tat = p[shortest].ct - p[shortest].at; // Turnaround time

p[shortest].wt = p[shortest].tat - p[shortest].bt; // Waiting time

avg_wt += p[shortest].wt;
avg_tat += p[shortest].tat;

// Print the results

printf("\nProcess\tArrival Time\tBurst Time\tCompletion Time\tTurnaround Time\tWaiting Time\


n");

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

printf("P%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", p[i].id, p[i].at, p[i].bt, p[i].ct, p[i].tat, p[i].wt);

avg_wt /= n;

avg_tat /= n;

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

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

return 0;

// 10 …Write a C program to simulate multi-level queue scheduling algorithm considering the


following scenario: all the processes in the system are divided into two categories – system processes
and user processes. System processes are to be given higher priority than user processes. Use FCFS
scheduling for the processes in each queue.

#include <stdio.h>

#define MAX 100

// Structure to represent a process

struct Process {

int id; // Process ID

int at; // Arrival Time

int bt; // Burst Time

int ct; // Completion Time


int wt; // Waiting Time

int tat; // Turnaround Time

int isSystemProcess; // Flag to indicate if the process is a system process (1 for system, 0 for user)

};

// Function to sort processes by arrival time (FCFS)

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

struct Process temp;

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

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

if (p[i].at > p[j].at) {

temp = p[i];

p[i] = p[j];

p[j] = temp;

// Function to calculate completion, turnaround, and waiting time

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

int currentTime = 0;

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

if (currentTime < p[i].at) {

currentTime = p[i].at;

p[i].ct = currentTime + p[i].bt; // Completion time

p[i].tat = p[i].ct - p[i].at; // Turnaround time

p[i].wt = p[i].tat - p[i].bt; // Waiting time

currentTime = p[i].ct; // Update current time

}
}

// Function to simulate multi-level queue scheduling

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

// Separate system and user processes into two queues

struct Process systemQueue[MAX], userQueue[MAX];

int systemCount = 0, userCount = 0;

// Classify the processes

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

if (p[i].isSystemProcess == 1) {

systemQueue[systemCount++] = p[i];

} else {

userQueue[userCount++] = p[i];

// Sort both queues by arrival time (FCFS scheduling)

sortByArrival(systemQueue, systemCount);

sortByArrival(userQueue, userCount);

// Process the system queue first (higher priority)

printf("\nScheduling system processes (higher priority):\n");

calculateTimes(systemQueue, systemCount);

printf("ID\tAT\tBT\tCT\tTAT\tWT\n");

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

printf("P%d\t%d\t%d\t%d\t%d\t%d\n", systemQueue[i].id, systemQueue[i].at,


systemQueue[i].bt, systemQueue[i].ct, systemQueue[i].tat, systemQueue[i].wt);

// Process the user queue next (lower priority)


printf("\nScheduling user processes (lower priority):\n");

calculateTimes(userQueue, userCount);

printf("ID\tAT\tBT\tCT\tTAT\tWT\n");

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

printf("P%d\t%d\t%d\t%d\t%d\t%d\n", userQueue[i].id, userQueue[i].at, userQueue[i].bt,


userQueue[i].ct, userQueue[i].tat, userQueue[i].wt);

int main() {

int n;

struct Process p[MAX];

// Input: number of processes

printf("Enter number of processes: ");

scanf("%d", &n);

// Input: arrival time, burst time, and process type for each process

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

printf("Enter Arrival Time and Burst Time for Process %d: ", i + 1);

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

printf("Enter 1 if Process %d is a System Process, otherwise enter 0: ", i + 1);

scanf("%d", &p[i].isSystemProcess);

p[i].id = i + 1; // Assign process ID

// Simulate the multi-level queue scheduling

multiLevelQueueScheduling(p, n);

return 0;

You might also like