0% found this document useful (0 votes)
2 views

OS_Programs

Uploaded by

mohitsurwade149
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

OS_Programs

Uploaded by

mohitsurwade149
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

KJEI’s

Trinity Academy Of Engineering, Pune

Operating System
LAB MANUAL

Department of IT
(A.Y. 2024-25)

Subject: Operating System Lab (314442)


Subject In charge: Ms. Snehal R. Shinde

Savitribai Phule Pune University, Pune


Third Year Information Technology (2019 Course)
314446: Operating System Lab

Credit
Teaching Scheme Examination Scheme
Scheme
Practical : 02 Credits Term work : 25 Marks
4 Hrs. / Week Practical: 25 Marks

Prerequisites:

1. C Programming
2. Fundamentals of Data Structure

Course Objectives:

● To introduce and learn Linux commands required for administration.


● To learn shell programming concepts and applications.
● To demonstrate the functioning of OS basic building blocks like processes, threads
under the LINUX.
● To demonstrate the functioning of OS concepts in user space like concurrency control
(process synchronization, mutual exclusion), CPU Scheduling, Memory Management
and Disk Scheduling in LINUX.
● To demonstrate the functioning of Inter Process Communication under LINUX.
● To study the functioning of OS concepts in kernel space like embedding the system
call in any LINUX kernel.

Course Outcomes:

On completion of the course, students will be able to–

CO1: Apply the basics of Linux commands.

CO2: Build shell scripts for various applications.

CO3: Implement basic building blocks like processes, threads under the Linux.

CO4: Develop various system programs for the functioning of OS concepts in user space like
concurrency control, CPU Scheduling, Memory Management and Disk Scheduling in Linux.
CO5: Develop system programs for Inter Process Communication in Linux.

INDEX

OPERATING SYSTEM LABORATORY


Sr. No Group-A

1 A. Study of Basic Linux Commands: echo, ls, read, cat, touch, test, loops,
arithmetic comparison, conditional loops, grep, sed etc.

B. Write a program to implement an address book with options given below: a)


Create address book. b) View address book. c) Insert a record. d) Delete a record.
e) Modify a record. f) Exit.

2 Process control system calls: The demonstration of FORK, EXECVE and WAIT
system calls along with zombie and orphan states.

A. Implement the C program in which main program accepts the integers to be


sorted. Main program uses the FORK system call to create a new process called a
child process. Parent process sorts the integers using sorting algorithm and waits
for child process using WAIT system call to sort the integers using any sorting
algorithm. Also demonstrate zombie and orphan states.

B. Implement the C program in which main program accepts an array. Main


program uses the FORK system call to create a new process called a child process.
Parent process sorts an array and passes the sorted array to child process through
the command line arguments of EXECVE system call. The child process uses
EXECVE system call to load new program which display array in reverse order.

3 Implement the C program for CPU Scheduling Algorithms: Shortest Job First
(Pre-emptive) and Round Robin with different arrival time.

4 A.Thread synchronization using counting semaphores. Application to


demonstrate: producer- consumer problem with counting semaphores and mutex.

B.Thread synchronization and mutual exclusion using mutex. Application to


demonstrate: Reader- Writer problem with reader priority.

5 Implement the C program for Deadlock Avoidance Algorithm: Bankers


Algorithm.

6 Implement the C program for Page Replacement Algorithms: FCFS, LRU, and
Optimal for frame size as minimum three.

7 Inter process communication in Linux using following.

A. FIFOS: Full duplex communication between two independent processes. First


process accepts sentences and writes on one pipe to be read by second process and
second process counts number of characters, number of words and number of lines
in accepted sentences, writes this output in a text file and writes the contents of the
file on second pipe to be read by first process and displays on standard output.

B. Inter-process Communication using Shared Memory using System V.


Application to demonstrate: Client and Server Programs in which server process
creates a shared memory segment and writes the message to the shared memory
segment. Client process reads the message from the shared memory segment and
displays it to the screen.

8 Implement the C program for Disk Scheduling Algorithms: SSTF, SCAN, C-Look
considering the initial head position moving away from the spindle.

Study Assignment: Implement a new system call in the kernel space, add this new system
call in the Linux kernel by the compilation of this kernel (any kernel source, any architecture
and any Linux kernel distribution) and demonstrate the use of this embedded system call
using C program in user space.

Roll No.: Name:

Assignment 1A
Problem Statement: Study of Basic Linux Commands: echo, ls, read, cat, touch, test, loops,
arithmetic comparison, conditional loops, grep, sed etc.

Program:

# 1) Print
echo "Students"

# 2) Remove spaces
echo -e "PES \bModern \bCollege \bOf \bEngineering"

# 3) Remove word behind \c


echo -e "Operating \cSystem"

# 4) Add new line


echo -e "Final \nSubmission"

# 5) Add tabs
echo -e "Operating \tSystem \tLab"

## ls

# 1) Long listing of files


ls -l

## read

# 1) Read value to variable and print


read name
echo "Hello $name!"

## cat

# 1) Show content of file


cat ./myaddressbook.txt

# 2) Copy the content of file source > destination


cat ./myaddressbook.txt > ../temp.txt

## touch

# 1) Creat file
touch tempfile.txt

## test

# 1) Return 0 if name == Ramesh else return 1 (used to check the


previous command is succcessfully executed or not)
read name
test $name = Ramesh
echo $?

## Loops

# 1) For loop
for i in 1 2 3 4 5
do
echo "Value of i $i"
done

# 2) While loop
num=0
while [ "$num" -lt 5 ]
do
echo "Value of num $num"
num=`expr $num + 1`
done

## Conditionals

# 1) If else block
read num
if [ `expr $num % 2` -eq 0 ]
then
echo "$num is even"
else
echo "$num is odd"
fi

## grep

# 1) Return the line containing matching string (case insensitive)


grep -i 'ranjeet' ./myaddressbook.txt

# 2) Return the count/ occurance of given string


grep -c '20' ./myaddressbook.txt

# 3) Return the lines contains given string also adds line number at
begining
grep -n '20' ./myaddressbook.txt

## sed

# 1) Replace 20 with 30
sed 's/20/30/' ./myaddressbook.txt
Output:
Roll No.: Name:

Assignment 1B

Problem Statement: Write a program to implement an address book with options given
below: a) Create address book. b) View address book. c) Insert a record. d) Delete a record.
e) Modify a record. f) Exit.

Program 1:
#!/bin/bash

clear

choice=0

address_book='addressbook'

while test $choice != 7


do
echo -e "\n------------------------------"
echo "1 --> Create"
echo "2 --> View"
echo "3 --> Insert"
echo "4 --> Delete"
echo "5 --> Modify"
echo "6 --> Search"
echo -e "7 --> Exit\n"
read -p "Enter your choice: " choice

case "$choice" in
"1")
echo ""
read -p "Enter address book name: " address_book

touch D:/Ubuntu18/osl/practical1/$address_book.txt

if [ $? -eq 0 ]
then
echo -e "\n$address_book.txt created."
else
echo "Could not create $address_book.txt"
fi
;;

"2")
echo -e "\n---- Record of address book ---- \n"
cat D:/Ubuntu18/osl/practical1/$address_book.txt
echo ""

if [ $? -ne 0 ]
then
echo "Could not read $address_book.txt"
fi
;;
"3")
# Name validation
read -p "Enter name: " name
name_pattern="^[A-Za-z]"
while [[ ! "$name" =~ $name_pattern ]]
do
read -p "Please enter valid name: " name
done

# Email validation
read -p "Enter email : " email
email_pattern="^[a-z0-9._%-+]+@[a-z]+\.[a-z]{2,4}$"
while [[ ! $email =~ $email_pattern ]]
do
read -p "Please enter valid email: " email
done

# Phone number validation


read -p "Enter phone number : " phno
phno_pattern="^[0-9]{10,12}$"
while [[ ! $phno =~ $phno_pattern ]]
do
read -p "Please enter valid phone number: " phno
done

# Age validation
read -p "Enter age : " age
age_pattern="[0-9]"
while [[ ! $age =~ $age_pattern ]]
do
read -p "Please enter valid age: " age
done

# Address validation
read -p "Enter address : " address
address_pattern="^[A-Za-z0-9]"
while [[ ! $address =~ $address_pattern ]]
do
read -p "Please enter valid address: " address
done

echo $name $email $phno $age $address >>


D:/Ubuntu18/osl/practical1/$address_book.txt

if [ $? -eq 0 ]
then
echo -e "\nData inserted to $address_book.txt."
else
echo "Could not insert data to $address_book.txt"
fi
;;

"4")
echo -e "\n---- Record of address book ---- \n"
cat D:/Ubuntu18/osl/practical1/$address_book.txt

echo ""
read -p "Enter user name to delete record: " delete_name

sed -i "/$delete_name/d"
D:/Ubuntu18/osl/practical1/$address_book.txt

if [ $? -ne 0 ]
then
echo "Could not delete data in $address_book.txt"
else
echo -e "\n---- Record of address book ---- \n"
cat D:/Ubuntu18/osl/practical1/$address_book.txt
fi

;;

"5")
echo -e "\n---- Record of address book ---- \n"
cat D:/Ubuntu18/osl/practical1/$address_book.txt

echo -e "\nEnter number to modify: "


read search_string

echo "Enter new number to modify: "


read modify_string

sed -i "s/$search_string/$modify_string/"
D:/Ubuntu18/osl/practical1/$address_book.txt

if [ $? -ne 0 ]
then
echo "Could not modify $address_book.txt"
else
echo -e "\n---- Record of address book ---- \n"
cat D:/Ubuntu18/osl/practical1/$address_book.txt
fi
;;

"6")
echo ""
read -p "Enter name to search: " search_string

echo -e "\n---- Search result ---- \n"


grep -i $search_string
D:/Ubuntu18/osl/practical1/$address_book.txt

if [ $? -ne 0 ]
then
echo "Could not search data in $address_book.txt"
fi
;;

"7")
echo "Exit."
exit
;;
esac
done
exit

Output:
Roll No.: Name:

Assignment 2A

Problem Statement: Process control system calls: The demonstration of FORK, EXECVE
and WAIT system calls along with zombie and orphan states.

A. Implement the C program in which main program accepts the integers to be sorted. Main
program uses the FORK system call to create a new process called a child process. Parent
process sorts the integers using sorting algorithm and waits for child process using WAIT
system call to sort the integers using any sorting algorithm. Also demonstrate zombie and
orphan states.

Program:
#include<stdio.h>

#include<unistd.h>

#include<sys/types.h>

#define MAX 20

void bubble_asc(int arr[],int n)

int i,j,temp;

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

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

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

temp=arr[j];

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

arr[j+1]=temp;

}
void bubble_dsc(int arr[],int n)

int i,j,temp;

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

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

if(arr[j]<arr[j+1])

temp=arr[j];

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

arr[j+1]=temp;

void print(int arr[],int n)

int i;

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

printf("\t%d",arr[i]);

printf("\n\n");

int main()

int i,n,arr[MAX],f,pid;

printf("\nHOW MANY NOS DO YOU WANT IN ARRAY : ");

scanf("%d",&n);
printf("ENTER ARRAY ELEMENT : ");

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

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

pid=fork();

if(pid==0)

/*ORPHAN STATE */

printf("\n\t\t**********ORPHAN STATE**************\n");

sleep(5);

printf("\n\t CHILD PROCESS PID : %d ", getpid());

printf("\n\t PARENT PROCESS PPID : %d",getppid());

system("ps -el | grep init");

printf("\n\nARRAY IN ASSCENDING ORDER : ");

bubble_asc(arr,n);

print(arr,n);

else if(pid >0)

/*ZOMBIE STATE */

printf("\n\t\t\t**********ZOMBIE STATE**************\n");

system("ps -el | grep Z");


f=wait(0);

printf("\n\tTERMINATED CHILD PID : %d",f);

printf("\n\tPARENT PID (MAIN) : %d",getpid());

printf("\n\tPARENTS PARENT PPID (BASH) : %d ",getppid());

printf("\n\nARRAY IN DESCENDING ORDER : ");

bubble_dsc(arr,n);

print(arr,n);

else

printf("\nERROR IN FORK!!");

return 0;

Output:
Roll No.: Name:

Assignment 2B

Problem Statement: Process control system calls: The demonstration of FORK, EXECVE
and WAIT system calls along with zombie and orphan states.

B. Implement the C program in which main program accepts an array. Main program uses the
FORK system call to create a new process called a child process. Parent process sorts an
array and passes the sorted array to child process through the command line arguments of
EXECVE system call. The child process uses EXECVE system call to load new program
which display array in reverse order.

Program B.1:
#include<stdio.h>

#include <sys/types.h>

#include <unistd.h>

#include <sys/wait.h>

#include<stdlib.h>

void bubble_asc(int arr[],int n)

int i,j,temp;

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

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

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

temp=arr[j];

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

arr[j+1]=temp;

}
}

printf("\nArray in ascending order: ");

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

printf("\t%d",arr[i]);

int main(int argc,char *argv[]) //5 2 7 9 4

int i,j=2,l,k;

int n=argc-2;

int a[n];

char *args[n+1];

args[0]=argv[1];

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

args[i]=argv[j];

args[i]=(char*)0;//0 1 2 3 4 5 6

//second 5 2 7 9 4 '0'

for(l=0,i=1;i<=n;i++,l++)

a[l]=atoi(args[i]);

bubble_asc(a,n);

for(l=0,i=1;i<=n;i++,l++)

sprintf(args[i],"%d",a[l]);

pid_t pid;
pid=fork();

if(pid==0)

printf("\nI am Child Process,my pid is %d \n",getpid());

printf("I am Parent Process,my pid is %d \n",getppid());

execve(argv[1],args,NULL);

else

k=wait(0);

printf("\nI am Parent Process,my pid is %d \n",getpid());

printf("I am Parent's Parent Process,my pid is %d\n\


n",getppid());

return 0;

Output:

Program B.2:
#include<stdio.h>

#include <sys/types.h>

#include <unistd.h>

#include <sys/wait.h>

#include<stdlib.h>

void bubble_dsc(int arr[],int n)

int i,j,temp;

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

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

if(arr[j]<arr[j+1])

temp=arr[j];

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

arr[j+1]=temp;

printf("\nArray in dscending order: ");

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

printf("\t%d",arr[i]);

printf("\n");

int main(int argc,char *argv[])

int i,j=1,l;

int n=argc-1;

int a[n];

char *args[n+1];

printf("\nPid of the 2nd program is:%d\n",getpid());

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

args[i]=argv[j];

args[i]=(char*)0;

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

a[l]=atoi(args[i]);

bubble_dsc(a,n);

return 0;

Output:
Roll No.: Name:

Assignment 3

Problem Statement: Implement the C program for CPU Scheduling Algorithms: Shortest
Job First (Pre-emptive) and Round Robin with different arrival time.

Program 1:
//sjf_preemptive
#include <stdio.h>
#include <stdbool.h>

struct Process
{
int pid;
int at;
int bt;
int ct, tt, wt, rt, st;
};

int main()
{
int size = 0;
printf("Enter number of processes: ");
scanf("%d", &size);
struct Process ps[size];

printf("\nEnter process Details: \n");


for (int i = 0; i < size; ++i)
{
printf("Enter %dth process details: \n", i + 1);
ps[i].pid = i + 1;

printf("\tEnter Arrival Time: ");


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

printf("\tEnter Burst Time: ");


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

printf("\
n======================================================================
==============\n\n");
printf("PID\tAT \t BT\n");
for (int i = 0; i < size; i++)
{
printf("%d \t %d \t %d \n", ps[i].pid, ps[i].at, ps[i].bt);
}
printf("\n\
n======================================================================
==============\n\n");

// Input Done
int n = size;
int completed = 0;
int currentTime = 0;
int burstTimeR[4];
bool iscompleted[4] = {false};

float avgWT = 0, avgTT = 0, avgRT = 0;

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


{
burstTimeR[i] = ps[i].bt;
}

while (completed != n)
{

int minimum = 99999;


int miniI = -1;
for (int i = 0; i < n; i++)
{
if ((ps[i].at <= currentTime) && (iscompleted[i] ==
false))
{
if (burstTimeR[i] < minimum)
{
minimum = burstTimeR[i];
miniI = i;
}
if (burstTimeR[i] == minimum)
{
if (ps[i].at < ps[miniI].at)
{
minimum = burstTimeR[i];
miniI = i;
}
}
}
}

if (miniI == -1)
{
currentTime++;
}
else
{

if (burstTimeR[miniI] == ps[miniI].bt)
{
ps[miniI].st = currentTime;
}

burstTimeR[miniI] -= 1;
currentTime++;

if (burstTimeR[miniI] == 0)
{

ps[miniI].ct = currentTime;
ps[miniI].tt = ps[miniI].ct - ps[miniI].at;
ps[miniI].wt = ps[miniI].tt - ps[miniI].bt;
ps[miniI].rt = ps[miniI].st - ps[miniI].at;

avgWT += ps[miniI].wt;
avgTT += ps[miniI].tt;
avgRT += ps[miniI].rt;

completed++;
iscompleted[miniI] = true;
}
}
}

printf("PID \t AT \t BT \t CT \t TT \t WT \t RT \t\n");
for (int i = 0; i < n; i++)
{

printf("%d \t %d \t %d \t %d \t %d \t %d \t %d \t\n",
ps[i].pid, ps[i].at, ps[i].bt, ps[i].ct, ps[i].tt, ps[i].wt, ps[i].rt);
}
printf("\n\
n======================================================================
==============\n");

printf("\n\n AVG WT: %f", avgWT / n);


printf("\n\n AVG TT: %f", avgTT / n);
printf("\n\n AVG RT: %f", avgRT / n);
printf("\n\
n======================================================================
==============\n");
}

Output:
Program 2:
//round_robin
#include <stdio.h>
// #include <limits.h>
#include <stdbool.h> //for bool datatype
// #include <stdlib.h> //for qsort

struct process_struct
{
int pid;
int at;
int bt;
int ct, wt, tat, rt, start_time;
int bt_remaining;
} ps[100];

int findmax(int a, int b)


{
return a > b ? a : b;
}

int comparatorAT(const void *a, const void *b)


{
int x = ((struct process_struct *)a)->at;
int y = ((struct process_struct *)b)->at;
if (x < y)
return -1; // No sorting
else if (x >= y) // = is for stable sort
return 1; // Sort
}

int comparatorPID(const void *a, const void *b)


{
int x = ((struct process_struct *)a)->pid;
int y = ((struct process_struct *)b)->pid;
if (x < y)
return -1; // No sorting
else if (x >= y)
return 1; // Sort
}

int main()
{

int n, index;
int cpu_utilization;
// queue<int> q;

bool visited[100] = {false}, is_first_process = true;


int current_time = 0, max_completion_time;
int completed = 0, tq, total_idle_time = 0, length_cycle;
printf("Enter total number of processes: ");
scanf("%d", &n);
int queue[100], front = -1, rear = -1;
float sum_tat = 0, sum_wt = 0, sum_rt = 0;

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


{
printf("\nEnter Process %d Arrival Time: ", i);
scanf("%d", &ps[i].at);
ps[i].pid = i;
}

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


{
printf("\nEnter Process %d Burst Time: ", i);
scanf("%d", &ps[i].bt);
ps[i].bt_remaining = ps[i].bt;
}

printf("\nEnter time quanta: ");


scanf("%d", &tq);

// sort structure on the basis of Arrival time in increasing order


qsort((void *)ps, n, sizeof(struct process_struct), comparatorAT);
// q.push(0);
front = rear = 0;
queue[rear] = 0;
visited[0] = true;

while (completed != n)
{
index = queue[front];
// q.pop();
front++;

if (ps[index].bt_remaining == ps[index].bt)
{
ps[index].start_time = findmax(current_time, ps[index].at);
total_idle_time += (is_first_process == true) ? 0 :
ps[index].start_time - current_time;
current_time = ps[index].start_time;
is_first_process = false;
}

if (ps[index].bt_remaining - tq > 0)
{
ps[index].bt_remaining -= tq;
current_time += tq;
}
else
{
current_time += ps[index].bt_remaining;
ps[index].bt_remaining = 0;
completed++;

ps[index].ct = current_time;
ps[index].tat = ps[index].ct - ps[index].at;
ps[index].wt = ps[index].tat - ps[index].bt;
ps[index].rt = ps[index].start_time - ps[index].at;

sum_tat += ps[index].tat;
sum_wt += ps[index].wt;
sum_rt += ps[index].rt;
}
// check which new Processes needs to be pushed to Ready Queue from
Input list
for (int i = 1; i < n; i++)
{
if (ps[i].bt_remaining > 0 && ps[i].at <= current_time &&
visited[i] == false)
{
// q.push(i);
queue[++rear] = i;
visited[i] = true;
}
}
// check if Process on CPU needs to be pushed to Ready Queue
if (ps[index].bt_remaining > 0)
// q.push(index);
queue[++rear] = index;

// if queue is empty, just add one process from list, whose


remaining burst time > 0
if (front > rear)
{
for (int i = 1; i < n; i++)
{
if (ps[i].bt_remaining > 0)
{
queue[rear++] = i;
visited[i] = true;
break;
}
}
}
} // end of while

// Calculate Length of Process completion cycle


max_completion_time = 1e-9;

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


max_completion_time = findmax(max_completion_time, ps[i].ct);

length_cycle = max_completion_time - ps[0].at; // ps[0].start_time;

cpu_utilization = (float)(length_cycle - total_idle_time) /


length_cycle;

// sort so that process ID in output comes in Original order (just


for interactivity- Not needed otherwise)
qsort((void *)ps, n, sizeof(struct process_struct), comparatorPID);

// Output
printf("\nProcess No.\tAT\tCPU Burst Time\tStart Time\tCT\tTAT\tWT\
tRT\n");
for (int i = 0; i < n; i++)
printf("%d\t\t%d\t%d\t\t%d\t\t%d\t%d\t%d\t%d\n", i, ps[i].at,
ps[i].bt, ps[i].start_time, ps[i].ct, ps[i].tat, ps[i].wt, ps[i].rt);
printf("\n");

printf("\nAverage Turn Around time= %.2f", (float)sum_tat / n);


printf("\nAverage Waiting Time= %.2f", (float)sum_wt / n);
printf("\nAverage Response Time= %.2f", (float)sum_rt / n);
printf("\nThroughput= %.2f", n / (float)length_cycle);
printf("\nCPU Utilization(Percentage)= %.2f", cpu_utilization * 100);
return 0;
}

Output:
Roll No.: Name:

Assignment 4A

Problem Statement: Thread synchronization using counting semaphores. Application to


demonstrate: producer- consumer problem with counting semaphores and mutex.

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

/*
This program provides a possible solution for producer-consumer problem
using mutex and semaphore.
I have used 5 producers and 5 consumers to demonstrate the solution.
You can always play with these values.
*/

#define MaxItems 5 // Maximum items a producer can produce or a


consumer can consume
#define BufferSize 5 // Size of the buffer

sem_t empty;
sem_t full;
int in = 0;
int out = 0;
int buffer[BufferSize];
pthread_mutex_t mutex;

void *producer(void *pno)


{
int item;
for(int i = 0; i < MaxItems; i++) {
item = rand(); // Produce an random item
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[in] = item;
printf("Producer %d: Insert Item %d at %d\n", *((int
*)pno),buffer[in],in);
in = (in+1)%BufferSize;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer(void *cno)
{
for(int i = 0; i < MaxItems; i++) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
int item = buffer[out];
printf("Consumer %d: Remove Item %d from %d\n",*((int
*)cno),item, out);
out = (out+1)%BufferSize;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}

int main()
{

pthread_t pro[5],con[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&empty,0,BufferSize);
sem_init(&full,0,0);

int a[5] = {1,2,3,4,5}; //Just used for numbering the producer


and consumer

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


pthread_create(&pro[i], NULL, (void *)producer, (void *)&a[i]);
}
for(int i = 0; i < 5; i++) {
pthread_create(&con[i], NULL, (void *)consumer, (void *)&a[i]);
}

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


pthread_join(pro[i], NULL);
}
for(int i = 0; i < 5; i++) {
pthread_join(con[i], NULL);
}

pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);

return 0;

Output:
Roll No.: Name:

Assignment 4B

Problem Statement: Thread synchronization and mutual exclusion using mutex. Application
to demonstrate: Reader- Writer problem with reader priority.

Program:
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>

/*
This program provides a possible solution for first readers writers
problem using mutex and semaphore.
I have used 10 readers and 5 producers to demonstrate the solution. You
can always play with these values.
*/

sem_t wrt;
pthread_mutex_t mutex;
int cnt = 1;
int numreader = 0;

void *writer(void *wno)


{
sem_wait(&wrt);
cnt = cnt*2;
printf("Writer %d modified count to %d\n",(*((int *)wno)),cnt);
sem_post(&wrt);

}
void *reader(void *rno)
{
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
numreader++;
if(numreader == 1) {
sem_wait(&wrt); // If this id the first reader, then it will
block the writer
}
pthread_mutex_unlock(&mutex);
// Reading Section
printf("Reader %d: read count as %d\n",*((int *)rno),cnt);

// Reader acquire the lock before modifying numreader


pthread_mutex_lock(&mutex);
numreader--;
if(numreader == 0) {
sem_post(&wrt); // If this is the last reader, it will wake up
the writer.
}
pthread_mutex_unlock(&mutex);
}
int main()
{

pthread_t read[10],write[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt,0,1);

int a[10] = {1,2,3,4,5,6,7,8,9,10}; //Just used for numbering the


producer and consumer

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


pthread_create(&read[i], NULL, (void *)reader, (void *)&a[i]);
}
for(int i = 0; i < 5; i++) {
pthread_create(&write[i], NULL, (void *)writer, (void *)&a[i]);
}

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


pthread_join(read[i], NULL);
}
for(int i = 0; i < 5; i++) {
pthread_join(write[i], NULL);
}

pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);

return 0;

Output:
Roll No.: Name:

Assignment 5

Problem Statement: Implement the C program for Deadlock Avoidance Algorithm: Bankers
Algorithm.

Program:
// Banker's Algorithm
#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here
int n, m, i, j, k;
printf("\nEnter Number of processes: ");
scanf("%d", &n);

printf("\nEnter Number of resources : ");


scanf("%d", &m);

int alloc[n][m];
int max[n][m];

printf("\n\nEnter Details for Allocation matrix:(%dX%d) \n", n, m);


for (int i = 0; i < n; i++)
{
printf("\n\tEnter %dth row: ", i + 1);
for (int j = 0; j < m; j++)
{
scanf("%d", &alloc[i][j]);
}
}
printf("\n\nEnter Details for Max matrix:(%dX%d) \n", n, m);
for (int i = 0; i < n; i++)
{
printf("\n\tEnter %dth row: ", i + 1);
for (int j = 0; j < m; j++)
{
scanf("%d", &max[i][j]);
}
}

int avail[m]; // Available Resources


printf("\n\nEnter Details for Available Resources:\n");
for (int j = 0; j < m; j++)
{
scanf("%d", &avail[j]);
}

int f[n], ans[n], ind = 0;


for (k = 0; k < n; k++)
{
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < m; k++)
{
for (i = 0; i < n; i++)
{
if (f[i] == 0)
{
int flag = 0;
for (j = 0; j < m; j++)
{
if (need[i][j] > avail[j])
{
flag = 1;
break;
}
}

if (flag == 0)
{
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}

int flag = 1;

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


{
if (f[i] == 0)
{
flag = 0;
printf("The following system is not safe");
break;
}
}

if (flag == 1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}

return (0);
}
Output:
Roll No.: Name:

Assignment 6

Problem Statement: Implement the C program for Page Replacement Algorithms: FCFS,
LRU, and Optimal for frame size as minimum three.

Program 1:

//Time Complexity = O(n)


//Space Complexity= O(no of frames + size of Page Table)

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

struct PageTable
{
int frame_no;
bool valid;
};

//Function to check if referenced/asked page is already present in


frame[] or not
//Returns true if page is already present else returns false
bool isPagePresent(struct PageTable PT[],int page,int n)
{
if(PT[page].valid == 1)
return true;
return false;
}

//Function to update the page table


//Return Nothing
void updatePageTable(struct PageTable PT[],int page,int fr_no,int
status)
{
PT[page].valid=status;
//if(status == 1 )
PT[page].frame_no=fr_no;
}

//Function to print the frame contents


//Return nothing
void printFrameContents(int frame[],int no_of_frames)
{
for(int i=0;i<no_of_frames;i++)
printf("%d ",frame[i]);
printf("\n");
}

int main()
{
int i,n,no_of_frames,page_fault=0,current=0;
bool flag=false;
printf("\n Enter the no. of pages:\n");
scanf("%d",&n);
//create reference string array
int reference_string[n];
printf("\n Enter the reference string(different page numbers) :\
n");
for(int i=0;i<n;i++)
scanf("%d",&reference_string[i]);
printf("\n Enter the no. of frames you want to give to the
process :");
scanf("%d",&no_of_frames);
//create frame array to store the pages at different point of times
int frame[no_of_frames];
memset(frame,-1,no_of_frames*sizeof(int));
struct PageTable PT[50] ; //asume page table can have entries for
page 0 to 49
for(int i=0;i<50;i++)
PT[i].valid=0;

printf("\n****The Contents inside the Frame array at different


time:****\n");
for(int i=0;i<n;i++)
{
//search the ith page in all allocated frames
if( ! (isPagePresent(PT,reference_string[i],n)))
{
page_fault++; // Increase the count of page fault
if(flag==false && current < no_of_frames)
{
frame[current]=reference_string[i];
printFrameContents(frame,no_of_frames);
updatePageTable(PT,reference_string[i],current,1);
current = current + 1;
if(current == no_of_frames)
{
current=0;
flag=true; // so that we do not come to this if
block again
}

else //frame are full , APPLY FIFO


{
//find the FIFO page (victim page) to replace;
//The page pointed by current_head is FIFO page (victim
page), so need to find it :)
//mark that page as INVALID as in Page Table
//set invalid frame no as -1 or anything ( as function
needs this parameter),
updatePageTable(PT,frame[current], -1 ,0);
frame[current]=reference_string[i];
printFrameContents(frame,no_of_frames);
updatePageTable(PT,reference_string[i],current,1);
current = ( current + 1)% no_of_frames;
}
} //end of outer if
} //end of for loop

printf("\nTotal No. of Page Faults = %d\n",page_fault);


printf("\nPage Fault ratio = %.2f\n",(float)page_fault/n);
printf("\nPage Hit Ratio = %.2f\n",(float)(n- page_fault)/n);
return 0;
}

Output:
Program 2:
#include<stdio.h>
#include<stdbool.h>
#include<string.h>
#include<limits.h>

struct PageTable
{
int frame_no;
int last_time_of_access;
bool valid;
};
//Function to check if referenced/asked page is already present in
frame[] or not
//Returns true if page is already present else returns false
bool isPagePresent(struct PageTable PT[],int page)
{
if(PT[page].valid == 1)
return true;
return false;
}

//Function to update the page table


//Return Nothing
void updatePageTable(struct PageTable PT[],int page,int fr_no,int
status,int access_time)
{
PT[page].valid=status;
if(status == 1 )
{
PT[page].last_time_of_access = access_time;
PT[page].frame_no=fr_no;
}
}

//Function to print the frame contents


//Return nothing
void printFrameContents(int frame[],int no_of_frames)
{
for(int i=0;i<no_of_frames;i++)
printf("%d ",frame[i]);
printf("\n");
}

//Function to find the victim page index in frame[]


//Return that LRU page index using call by address
void searchLRUPage(struct PageTable PT[], int frame[], int
no_of_frames, int *LRU_page_index)
{
int min = INT_MAX;
for(int i=0; i<no_of_frames;i++)
{
if(PT[frame[i]].last_time_of_access < min)
{
min = PT[frame[i]].last_time_of_access;
*LRU_page_index = i;
}
}

int main()
{
int i,n,no_of_frames,page_fault=0,current=0;
bool flag=false;
printf("\n Enter the no. of pages:\n");
scanf("%d",&n);
//create reference string array
int reference_string[n];
printf("\n Enter the reference string(different page numbers) :\
n");
for(int i=0;i<n;i++)
scanf("%d",&reference_string[i]);
printf("\n Enter the no. of frames you want to give to the
process :");
scanf("%d",&no_of_frames);
//create frame array to store the pages at different point of times
int frame[no_of_frames];
memset(frame,-1,no_of_frames*sizeof(int));
struct PageTable PT[50] ; //asume page table can have entries for
page 0 to 49
for(int i=0;i<50;i++)
PT[i].valid=0;

printf("\n****The Contents inside the Frame array at different


time:****\n");
for(int i=0;i<n;i++)
{
//search the ith page in all allocated frames
if( ! (isPagePresent(PT,reference_string[i])))
{
page_fault++; // Increase the count of page fault
if(flag==false && current < no_of_frames)
{

frame[current]=reference_string[i];
printFrameContents(frame,no_of_frames);
updatePageTable(PT,reference_string[i],current,1,i);

current = current + 1;
if(current == no_of_frames)
{
//current=0;
flag=true;
}

else //frame are full , APPLY LRU Algo


{
//search the LRU page( victim page) with the help of PT
//mark that page as INVALID in Page Table
int LRU_page_index;
searchLRUPage(PT,frame,no_of_frames,&LRU_page_index);
updatePageTable(PT,frame[LRU_page_index], -1 ,0,i); //send
invalid frame_no =-1

frame[LRU_page_index]=reference_string[i];
printFrameContents(frame,no_of_frames);
//Update PT
updatePageTable(PT,reference_string[i],LRU_page_index,1,i);
}
}
//Update the Page Access time for reference_string[i]
PT[reference_string[i]].last_time_of_access = i;
} //end of for loop

printf("\nTotal No. of Page Faults = %d\n",page_fault);


printf("\nPage Fault ratio = %.2f\n",(float)page_fault/n);
printf("\nPage Hit Ratio = %.2f\n",(float)(n- page_fault)/n);
return 0;
}

Output:
Roll No.: Name:

Assignment 7A

Problem Statement: Inter process communication in Linux using following:

A. FIFOS: Full duplex communication between two independent processes. First process
accepts sentences and writes on one pipe to be read by second process and second process
counts number of characters, number of words and number of lines in accepted sentences,
writes this output in a text file and writes the contents of the file on second pipe to be read by
first process and displays on standard output.

Program 1:
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<unistd.h>

int main()
{
int fd,fd1;
char * myfifo = "myfifo";
char * myfifo1 = "myfifo1";
char buf[1024];

mkfifo(myfifo,0666);
mkfifo(myfifo1,0777);

fd=open(myfifo,O_WRONLY);
write(fd,"Hello Everyone! \nWelcome to Progressive Education
Society's Modern College of Engineering! \nPune, Maharashtra,
India.",sizeof("Hello Everyone! \nWelcome to Progressive Education
Society's Modern College of Engineering! \nPune, Maharashtra,
India."));

close(fd);

unlink(myfifo);

fd1=open(myfifo1,O_RDONLY);
read(fd1,buf,sizeof(buf));
printf("%s", buf);
unlink(myfifo1);
close(fd1);
return 0;
}
Output:
Program 2:
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>

int main()
{
int fd,fd1;
char * myfifo = "myfifo";
char * myfifo1 = "myfifo1";
char buf[1024], ch[400];

int words=1, character=0, line=1, i=0, j=0;


FILE *fp;

mkfifo(myfifo1, 0777);
fd=open(myfifo, O_RDONLY);
read(fd, buf, 1024);
printf("\nFirst message received: \n\n%s\n\n",buf);

while(buf[i]!='\0')
{
while(buf[i]==' ')
{
words++;
i++;
}
while(buf[i]=='\n')
{
line++;
i++;
}
i++;
character++;
}

printf("\nTotal Words := %d\n", words);


printf("\nTotal Lines := %d\n", line);
printf("\nTotal Charactes := %d\n", character);

fp=fopen("test.txt","w+");
fprintf(fp,"\nTotal Words := %d\n", words);
fprintf(fp,"\nTotal Lines := %d\n", line);
fprintf(fp,"\nTotal Charactes := %d\n", character);

fclose(fp);
fp=fopen("test.txt","r");

while(!feof(fp))
{
ch[j]=fgetc(fp);
j++;
}
fclose(fp);
close(fd);

unlink(myfifo);

fd1=open(myfifo1,O_WRONLY);

write(fd1,ch, strlen(ch));

close(fd1);
return 0;
}

Output:
Roll No.: Name:

Assignment 7B

Problem Statement: Inter process communication in Linux using following:

B. Inter-process Communication using Shared Memory using System V. Application to


demonstrate: Client and Server Programs in which server process creates a shared memory
segment and writes the message to the shared memory segment. Client process reads the
message from the shared memory segment and displays it to the screen.

Program:

Client:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 27

void die(char *s)


{
perror(s);
exit(1);
}

int main()
{
int shmid;
key_t key;
char *shm, *s;

key = 1;//5679

if ((shmid = shmget(key, MAXSIZE, 2)) < 0)


die("shmget");

if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)


die("shmat");

printf("\n\nClient started reading\n\n");

for (s = shm; *s != '\0'; s++)


{
putchar(*s);
printf("\t");
}
putchar('\n');

*shm = '*';
printf("\n\nClient Terminated!!!\n\n");

exit(0);
}
Server:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 27

void die(char *s)


{
perror(s);
exit(1);
}

int main()
{
char c;
int shmid;
key_t key;
char *shm, *s;

key = 1; // 5679

if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 2)) < 0) // 666


die("shmget");

if ((shm = shmat(shmid, NULL, 0)) == (char *)-1)


die("shmat");

s = shm;

for (c = 'a'; c <= 'z'; c++)


*s++ = c;

printf("\n\nServer is Ready!!\n\nNow data is available on shared


memory!!\n");

/*
* Waiting for other process
*/

while (*shm != '*')


sleep(1);

printf("\n\nServer Terminated!!!\n\n");

exit(0);
}
Output:
Roll No.: Name:

Assignment 8

Problem Statement: Implement the C program for Disk Scheduling Algorithms: SSTF,
SCAN, C-Look considering the initial head position moving away from the spindle.

Program 1: SCAN
#include <stdio.h>
//#inlude<Maths.h>
#include <limits.h>
int no_Track, N, Initial_Head_Pos, No_head_move, direction;

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


{
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
if (type == 1)
{
if (arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
else
{
if (arr[i] < arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
void SCAN(int req_que[])
{

int right[N - 1], left[N - 1], r = 0, l = 0;

right[r++] = no_Track - 1;
for (int i = 0; i < N; i++)
{
if (req_que[i] > Initial_Head_Pos)
{
right[r++] = req_que[i];
}
}

left[l++] = 0;
for (int i = 0; i < N; i++)
{
if (req_que[i] < Initial_Head_Pos)
{
left[l++] = req_que[i];
}
}

sort(right, 0, r);
sort(left, 1, l);

int completed = 2;
while (completed > 0)
{
if (direction == 0)
{
for (int i = 0; i < r; i++)
{
No_head_move += abs(Initial_Head_Pos - right[i]);
Initial_Head_Pos = right[i];
printf("\t%d", right[i]);
}
direction = 1;
}
else
{
for (int i = 0; i < l; i++)
{
No_head_move += abs(Initial_Head_Pos - left[i]);
Initial_Head_Pos = left[i];
printf("\t%d", left[i]);
}
direction = 0;
}
completed--;
}

/* printf("\nright");
for(int i=0;i<r;i++)
printf("\t%d",right[i]);
printf("\nleft");
for(int i=0;i<l;i++)
printf("\t%d",left[i]);*/
}

void main()
{
printf("Enter the Number of track on Disk:");
scanf("%d", &no_Track);
printf("Enter the Number of process requesting to access Disk:");
scanf("%d", &N);
int Request_que[N];
printf("Enter the Request Queue:");

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


{
scanf("%d", &Request_que[i]);
}
printf("Enter the initial Head position:");

scanf("%d", &Initial_Head_Pos);

printf("enter the Direction of Move (0 for higher otherwise 1):");


scanf("%d", &direction);
printf("\n=========================================");
printf("\n O U T P U T ");
printf("\n SEEK Sequesnce:");
SCAN(Request_que);
printf("\n Number of Head Move:%d", No_head_move);
}

Output:
Program 2: SSTF
#include <stdio.h>
//#inlude<Maths.h>
#include <limits.h>
int no_Track, N, Initial_Head_Pos, No_head_move;

int min_index(int req_que[], int visited[])


{
int min = INT_MAX, index = -1;
for (int i = 0; i < N; i++)
{
if (!visited[i] && abs(Initial_Head_Pos - req_que[i]) < min)
{
min = abs(Initial_Head_Pos - req_que[i]);
index = i;
}
}
return index;
}

void SSTF(int request_que[], int visited[])


{
int min_Index;
for (int i = 0; i < N; i++)
{
min_Index = min_index(request_que, visited);
visited[min_Index] = 1;
Initial_Head_Pos = request_que[min_Index];
printf("\t%d", request_que[min_Index]);
No_head_move += request_que[min_Index];
}
}
void main()
{
printf("Enter the Number of track on Disk:");
scanf("%d", &no_Track);
printf("Enter the Number of process requesting to access Disk:");
scanf("%d", &N);
int Request_que[N];
printf("Enter the Request Queue:");

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


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

printf("Enter the initial Head position:");


scanf("%d", &Initial_Head_Pos);
int Visited[N];
for (int i = 0; i < N; i++)
Visited[i] = 0;
printf("\n");

printf("\n=========================================");
printf("\n O U T P U T ");
printf("\n SEEK Sequesnce:");
SSTF(Request_que, Visited);
printf("\n Number of Head Move:%d", No_head_move);
}

Output:
Program 3: LOOK
#include <stdio.h>
//#inlude<Maths.h>
#include <limits.h>
int no_Track, N, Initial_Head_Pos, No_head_move, direction;

void sort(int arr[], int n)


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

if (arr[i] < arr[j])


{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
void SCAN(int req_que[])
{

int right[N - 1], left[N - 1], r = 0, l = 0;

// adding the request in right which are higher than initial head
possition

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


{
if (req_que[i] > Initial_Head_Pos)
{
right[r++] = req_que[i];
}
}

// adding the request in left which are lower than initial head
possition

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


{
if (req_que[i] < Initial_Head_Pos)
{
left[l++] = req_que[i];
}
}

sort(right, r);

sort(left, l);

int completed = 2;
while (completed > 0)
{
if (direction == 0)
{
for (int i = 0; i < r; i++)
{
No_head_move += abs(Initial_Head_Pos - right[i]);
Initial_Head_Pos = right[i];
printf("\t%d", right[i]);
}
direction = 1;
}
else
{
for (int i = 0; i < l; i++)
{
No_head_move += abs(Initial_Head_Pos - left[i]);
Initial_Head_Pos = left[i];
printf("\t%d", left[i]);
}
direction = 0;
}
completed--;
}

/* printf("\nright");
for(int i=0;i<r;i++)
printf("\t%d",right[i]);
printf("\nleft");
for(int i=0;i<l;i++)
printf("\t%d",left[i]);*/
}

void main()
{
printf("Enter the Number of track on Disk:");
scanf("%d", &no_Track);
printf("Enter the Number of process requesting to access Disk:");
scanf("%d", &N);
int Request_que[N];
printf("Enter the Request Queue:");

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


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

printf("Enter the initial Head position:");

scanf("%d", &Initial_Head_Pos);

printf("enter the Direction of Move (0 for higher otherwise 1):");


scanf("%d", &direction);
printf("\n=========================================");
printf("\n O U T P U T ");
printf("\n SEEK Sequesnce:");
SCAN(Request_que);
printf("\n Number of Head Move:%d", No_head_move);
}
Output:

You might also like