Skip to content

Instantly share code, notes, and snippets.

@mukeshgurpude
Last active December 27, 2021 11:24
Show Gist options
  • Save mukeshgurpude/fee646bc4e741625c9d3ad52c3ae6db8 to your computer and use it in GitHub Desktop.
Save mukeshgurpude/fee646bc4e741625c9d3ad52c3ae6db8 to your computer and use it in GitHub Desktop.
OS-Lab Exercises
# iterate through jpg files in current directory
# and rename them to start with today's date
for file in $( ls *.jpg )
do
mv $file $(date +%F)-$file
done
# Delete the zero sized files in the current directory
find . -type f -size 0 -exec rm {} \;
# Remove duplicate lines from a file
#- Line numbers file
# Sort the file
# Remove duplicates
# sort according to line numbers
# Remove line numbers
file=$1;
cat -n $file > .a.tmp
sort -k 2 .a.tmp > .b.tmp
uniq -f 1 .b.tmp > .a.tmp
sort -n .a.tmp > .b.tmp
cut -f 2 .b.tmp > .a.tmp
echo "The file $file has been cleaned"
cat .a.tmp > $file
rm .a.tmp .b.tmp
echo "Cleaned file is: "
cat $file
# Script to perform common file system commands
# Run this script with the command: " . ./2.sh "
# Reference: https://stackoverflow.com/a/255416/15733823
echo "1. Present Working directory"
echo "2. List files"
echo "3. Create a directory"
echo "4. Change directory"
echo "5. Remove a file"
echo "6. Remove a directory"
echo "7. Rename a file"
echo "8. Create a new file"
echo "9. Display file contents"
read -p "Please enter a command: " command
if [[ $command -eq 1 ]]
then
echo -e "Current Directory: $(pwd)"
elif [[ $command -eq 2 ]]
then
ls
elif [[ $command -eq 3 ]]
then
read -p "Enter a directory name: " folder
mkdir $folder
elif [[ $command -eq 4 ]]
then
read -p "Enter a directory to change: " folder
cd $folder
elif [[ $command -eq 5 ]]
then
read -p "Enter a file to remove: " file1
rm $file1
elif [[ $command -eq 6 ]]
then
read -p "Enter a directory to remove: " folder
rmdir $folder
elif [[ $command -eq 7 ]]
then
read -p "Enter old file name: " file1
read -p "Enter a new name for $file1: " file2
mv $file1 $file2
elif [[ $command -eq 8 ]]
then
read -p "Name of new file: " file
touch $file
elif [[ $command -eq 9 ]]
then
read -p "Enter the name of file: " file
cat $file
fi
// Reverse string using pipes
// Compile: gcc 3.c
// Run: ./a.out
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
void processA(int writefd){
int len;
char buff[80];
printf("Enter a string: ");
fgets (buff,80,stdin);
len=strlen(buff);
if(buff[len-1]=='\n') len--;
write(writefd,buff,len);
}
void processB(int readfd){
int n,i,j;
char str[80],temp;
n=read(readfd,str,80);
str[n]='\0';
i=0;
j=strlen(str)-1;
while(i<j) {
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("Reversed string: %s\n",str);
}
int main(void) {
int pipe1[2];
pid_t childpid;
pipe(pipe1);
childpid = fork();
if (childpid==0) {
close (pipe1[1]);
processB (pipe1[0]);
} else {
close (pipe1[0]);
processA (pipe1[1]);
}
return EXIT_SUCCESS;
}
#include<stdio.h>
#include<stdlib.h>
typedef struct process {
char name[5];
int bt;
int at;
int prt;
int wt, ta;
int flag;
}
processes;
void bubble_sort(processes proc[], int n) {
processes t;
int i, j;
for (i = 1; i < n; i++)
for (j = 0; j < n - i; j++) {
if (proc[j].at > proc[j + 1].at) {
t = proc[j];
proc[j] = proc[j + 1];
proc[j + 1] = t;
}
}
}
int get_Processes(processes P[]) {
int i, n;
printf("\n Enter total no. of processes : ");
scanf("%d", & n);
for (i = 0; i < n; i++) {
printf("\n PROCESS [%d]", i + 1);
printf(" Enter process name : ");
scanf("%s", & P[i].name);
printf(" Enter burst time : ");
scanf("%d", & P[i].bt);
printf(" Enter arrival time : ");
scanf("%d", & P[i].at);
printf(" Enter priority : ");
scanf("%d", & P[i].prt);
}
printf("\n PROC.\tB.T.\tA.T.\tPRIORITY");
for (i = 0; i < n; i++)
printf("\n %s\t%d\t%d\t%d", P[i].name, P[i].bt, P[i].at, P[i].prt);
return n;
}
// FCFS Algorithm
void FCFS(processes P[], int n) {
processes proc[10];
int sumw = 0, sumt = 0;
int x = 0;
float avgwt = 0.0, avgta = 0.0;
int i, j;
for (i = 0; i < n; i++)
proc[i] = P[i];
bubble_sort(proc, n);
printf("\n\n PROC.\tB.T.\tA.T.");
for (i = 0; i < n; i++)
printf("\n %s\t%d\t%d", proc[i].name, proc[i].bt, proc[i].at);
sumw = proc[0].wt = 0;
sumt = proc[0].ta = proc[0].bt - proc[0].at;
for (i = 1; i < n; i++) {
proc[i].wt = (proc[i - 1].bt + proc[i - 1].at + proc[i - 1].wt) - proc[i].at;;
proc[i].ta = (proc[i].wt + proc[i].bt);
sumw += proc[i].wt;
sumt += proc[i].ta;
}
avgwt = (float) sumw / n;
avgta = (float) sumt / n;
printf("\n\n PROC.\tB.T.\tA.T.\tW.T\tT.A.T");
for (i = 0; i < n; i++)
printf("\n %s\t%d\t%d\t%d\t%d", proc[i].name, proc[i].bt, proc[i].at, proc[i].wt, proc[i].ta);
printf("0\t");
for (i = 1; i <= n; i++) {
x += proc[i - 1].bt;
printf("%d ", x);
}
printf("\n\n Average waiting time = %0.2f\n Average turn-around = %0.2f.", avgwt, avgta);
}
//Shortest Job First - Pre-emptive
void SJF_P(processes P[], int n) {
int i, t_total = 0, tcurr, b[10], min_at, j, x, min_bt;
int sumw = 0, sumt = 0;
float avgwt = 0.0, avgta = 0.0;
processes proc[10], t;
for (i = 0; i < n; i++) {
proc[i] = P[i];
t_total += P[i].bt;
}
bubble_sort(proc, n);
for (i = 0; i < n; i++)
b[i] = proc[i].bt;
i = j = 0;
avgwt = (float) sumw / n;
avgta = (float) sumt / n;
printf("\n\n Average waiting time = %0.2f\n Average turn-around = %0.2f.", avgwt, avgta);
}
//SJF Non Pre-emptive
void SJF_NP(processes P[], int n) {
processes proc[10];
processes t;
int sumw = 0, sumt = 0;
int x = 0;
float avgwt = 0.0, avgta = 0.0;
int i, j;
for (i = 0; i < n; i++)
proc[i] = P[i];
bubble_sort(proc, n);
for (i = 2; i < n; i++)
for (j = 1; j < n - i + 1; j++) {
if (proc[j].bt > proc[j + 1].bt) {
t = proc[j];
proc[j] = proc[j + 1];
proc[j + 1] = t;
}
}
printf("\n\n PROC.\tB.T.\tA.T.");
for (i = 0; i < n; i++)
printf("\n %s\t%d\t%d", proc[i].name, proc[i].bt, proc[i].at);
sumw = proc[0].wt = 0;
sumt = proc[0].ta = proc[0].bt - proc[0].at;
for (i = 1; i < n; i++) {
proc[i].wt = (proc[i - 1].bt + proc[i - 1].at + proc[i - 1].wt) - proc[i].at;;
proc[i].ta = (proc[i].wt + proc[i].bt);
sumw += proc[i].wt;
sumt += proc[i].ta;
}
avgwt = (float) sumw / n;
avgta = (float) sumt / n;
printf("\n\n PROC.\tB.T.\tA.T.\tW.T\tT.A.T");
for (i = 0; i < n; i++)
printf("\n %s\t%d\t%d\t%d\t%d", proc[i].name, proc[i].bt, proc[i].at, proc[i].wt, proc[i].ta);
printf("0\t");
for (i = 1; i <= n; i++) {
x += proc[i - 1].bt;
printf("%d ", x);
}
printf("\n\n Average waiting time = %0.2f\n Average turn-around = %0.2f.", avgwt, avgta);
}
// Priority - Preemptive
void Priority_P(processes P[], int n) {
int i, t_total = 0, tcurr, b[10], j, x, min_pr;
int sumw = 0, sumt = 0;
float avgwt = 0.0, avgta = 0.0;
processes proc[10], t;
for (i = 0; i < n; i++) {
proc[i] = P[i];
t_total += P[i].bt;
}
bubble_sort(proc, n);
for (i = 0; i < n; i++)
b[i] = proc[i].bt;
i = j = 0;
printf(" %d", tcurr);
avgwt = (float) sumw / n;
avgta = (float) sumt / n;
printf("\n\n Average waiting time = %0.2f\n Average turn-around = %0.2f.", avgwt, avgta);
}
//Priority Non Pre-emptive
void Priority_NP(processes P[], int n) {
processes proc[10];
processes t;
int sumw = 0, sumt = 0;
float avgwt = 0.0, avgta = 0.0;
int i, j;
int x = 0;
for (i = 0; i < n; i++)
proc[i] = P[i];
bubble_sort(proc, n);
for (i = 2; i < n; i++)
for (j = 1; j < n - i + 1; j++) {
if (proc[j].prt > proc[j + 1].prt) {
t = proc[j];
proc[j] = proc[j + 1];
proc[j + 1] = t;
}
}
printf("\n\n PROC.\tB.T.\tA.T.");
for (i = 0; i < n; i++)
printf("\n %s\t%d\t%d", proc[i].name, proc[i].bt, proc[i].at);
sumw = proc[0].wt = 0;
sumt = proc[0].ta = proc[0].bt - proc[0].at;
for (i = 1; i < n; i++) {
proc[i].wt = (proc[i - 1].bt + proc[i - 1].at + proc[i - 1].wt) - proc[i].at;;
proc[i].ta = (proc[i].wt + proc[i].bt);
sumw += proc[i].wt;
sumt += proc[i].ta;
}
avgwt = (float) sumw / n;
avgta = (float) sumt / n;
printf("\n\n PROC.\tB.T.\tA.T.\tW.T\tT.A.T");
for (i = 0; i < n; i++)
printf("\n %s\t%d\t%d\t%d\t%d", proc[i].name, proc[i].bt, proc[i].at, proc[i].wt, proc[i].ta);
printf("0\t");
for (i = 1; i <= n; i++) {
x += proc[i - 1].bt;
printf("%d ", x);
}
printf("\n\n Average waiting time = %0.2f\n Average turn-around = %0.2f.", avgwt, avgta);
}
//Round Robin Scheduling
void RR(processes P[], int n) {
int pflag = 0, t, tcurr = 0, k, i, Q = 0;
int sumw = 0, sumt = 0;
float avgwt = 0.0, avgta = 0.0;
processes proc1[10], proc2[10];
for (i = 0; i < n; i++)
proc1[i] = P[i];
bubble_sort(proc1, n);
for (i = 0; i < n; i++)
proc2[i] = proc1[i];
printf("\n Enter quantum time : ");
scanf("%d", & Q);
for (k = 0;; k++) {
if (k > n - 1)
k = 0;
if (proc1[k].bt > 0)
printf(" %d %s", tcurr, proc1[k].name);
t = 0;
while (t < Q && proc1[k].bt > 0) {
t++;
tcurr++;
proc1[k].bt--;
}
if (proc1[k].bt <= 0 && proc1[k].flag != 1) {
proc1[k].wt = tcurr - proc2[k].bt - proc1[k].at;
proc1[k].ta = tcurr - proc1[k].at;
pflag++;
proc1[k].flag = 1;
sumw += proc1[k].wt;
sumt += proc1[k].ta;
}
if (pflag == n)
break;
}
printf(" %d", tcurr);
avgwt = (float) sumw / n;
avgta = (float) sumt / n;
printf("\n\n Average waiting time = %0.2f\n Average turn-around = %0.2f.", avgwt, avgta);
}
int main() {
processes P[10];
int ch, n;
do {
printf("\n\n SIMULATION OF CPU SCHEDULING ALGORITHMS\n");
printf("\n Options:");
printf("\n 0. Enter process data.");
printf("\n 1. FCFS");
printf("\n 2. SJF (Pre-emptive)");
printf("\n 3. SJF (Non Pre-emptive)");
printf("\n 4. Priority Scheduling (Pre-emptive)");
printf("\n 5. Priority Scheduling (Non Pre-emptive)");
printf("\n 6. Round Robin");
printf("\n 7. Exit\n Select : ");
scanf("%d", & ch);
switch (ch) {
case 0:
n = get_Processes(P);
break;
case 1:
FCFS(P, n);
break;
case 2:
SJF_P(P, n);
break;
case 3:
SJF_NP(P, n);
break;
case 4:
Priority_P(P, n);
break;
case 5:
Priority_NP(P, n);
break;
case 6:
RR(P, n);
break;
case 7:
exit(0);
}
} while (ch != 7);
return 0;
}
#!/bin/python3
from typing import List
def calculate_need(max_resources: List[List[int]], allocation: List[List[int]]):
need = []
for max_resource, alloc in zip(max_resources, allocation):
# Maximum resources - allocated resources for each process
need.append([i-j for i, j in zip(max_resource, alloc)])
return need
def calculate_available(total_resources: List[int], allocation: List[List[int]]):
for alloc in allocation:
# Subtract allocated resources from total resources
total_resources = [i-j for i, j in zip(total_resources, alloc)]
return total_resources
def algorithm(num_processes: int, num_resources: int, max_resources: List[List[int]], allocation: List[List[int]], total_resources: List[int]):
need = calculate_need(max_resources, allocation)
running = [True] * num_processes # Opposite of finished
available = calculate_available(total_resources, allocation)
safe_sequence = []
# While there are still processes that haven't finished
while any(running):
safe = False
for i in range(num_processes):
if not running[i]:
# Skip if process is already finished
continue
# Check if all resources are available
if all(available[j] >= need[i][j] for j in range(num_resources)):
safe = True
running[i] = False # Mark process as finished
safe_sequence.append(i+1)
available = [i+j for i, j in zip(available, allocation[i])]
break # Break out of for loop, so that earlier processes are checked
if not safe: return False, safe_sequence
return True, safe_sequence
if __name__ == '__main__':
num_processes = int(input('Number of processes: '))
num_resources = int(input('Number of resources: '))
total_resources = list(map(int, input('Total resources: ').split()))
print('Allocated resources: ')
allocation = [
list(map(int, input(f'\tProcess {i+1}: ').split())) for i in range(num_processes)
]
print('Maximum resources: ')
max_resources = [
list(map(int, input(f'\tProcess {i+1}: ').split())) for i in range(num_processes)
]
safe, safe_sequence = algorithm(num_processes, num_resources, max_resources, allocation, total_resources)
if safe:
print('\nDeadlock cleared, system is in safe state')
print('Safe sequence: ', safe_sequence)
else:
print('Deadlock detected, system is in unsafe state')
import sys
def fifo_policy(pages, num_frames):
page_faults = 0
page_hits = 0
memory = []
for page in pages:
if page in memory:
page_hits += 1
else:
page_faults += 1
if len(memory) < num_frames:
memory.append(page)
else:
# First page will be oldest one
memory.pop(0)
memory.append(page)
return page_faults, page_hits
def lru_policy(pages, num_frames):
page_faults = 0
page_hits = 0
memory = []
for page in pages:
if page in memory:
# Change the position of already present page, so that it is treated as used recently
memory.remove(page)
memory.append(page)
page_hits += 1
else:
page_faults += 1
if len(memory) < num_frames:
memory.append(page)
else:
# First page will be least recently used
memory.pop(0)
memory.append(page)
return page_faults, page_hits
def find_last(pages, memory):
to_be_replaced = 0
access = 0
for i, page in enumerate(memory):
if page not in pages:
return i
time = pages.index(page)
if(time > access):
to_be_replaced = i
access = time
return to_be_replaced
def optimal_policy(pages, num_frames):
page_faults = 0
page_hits = 0
memory = []
for i, page in enumerate(pages):
if page in memory:
page_hits += 1
elif len(memory) < num_frames:
memory.append(page)
page_faults += 1
else:
# Find page which will not be used for longest time
last_page = find_last(pages[i+1:], memory)
memory[last_page] = page
page_faults += 1
return page_faults, page_hits
if __name__ == '__main__':
# while running `python3 main.py run`, pages and number of frames will be automatically filled
if len(sys.argv) > 1 and sys.argv[1] == 'run':
pages = ['7', '0', '1', '2', '0', '3', '0', '4',
'2', '3', '0', '3', '2', '1', '2', '0',
'1', '7', '0', '1']
num_frames = 3
else:
pages = list(input('Enter pages separated by space: ').split())
num_frames = int(input('Enter number of frames: '))
print('''
Please choose the page replacement policy from below
1. Fifo
2. Optimal
3. LRU
4. Exit
''')
policy = int(input('Enter your choice: '))
if policy == 1:
f, h = fifo_policy(pages, num_frames)
print(f'''
FIFO page replacement policy
Reference string: {' '.join(pages)}
Frames: {num_frames}
Number of Page faults: {f}
Number of Page hits: {h}
''')
elif policy == 2:
f, h = optimal_policy(pages, num_frames)
print(f'''
Optimal page replacement policy
Reference string: {' '.join(pages)}
Frames: {num_frames}
Number of Page faults: {f}
Number of Page hits: {h}
''')
elif policy == 3:
f, h = lru_policy(pages, num_frames)
print(f'''
LRU page replacement policy
Reference string: {' '.join(pages)}
Frames: {num_frames}
Number of Page faults: {f}
Number of Page hits: {h}
''')
elif policy == 4:
print('Exiting...')
else:
print('Invalid input...')
from typing import List
class Task:
waiting_time: int = None
turnaround_time: int = None
def __init__(self, name: str, arrival_time: int, burst_time: int, priority: int = 1):
self.name = name
self.arrival_time = arrival_time
self.priority = priority
self.burst_time = burst_time
def pretty_print(tasks):
print("{:^5} {:>5} {:^8} {:>5} {:>5}".format("Task", "BT", "Priority", "WT", "TAT"))
for task in tasks:
print("{:^5} {:>5} {:^8} {:>5} {:>5}".format(task.name, task.burst_time, task.priority, task.waiting_time, task.turnaround_time))
def schedule(tasks: List[Task]):
tasks.sort(key=lambda task: task.arrival_time)
current_time = 0
total_tat = 0
total_wt = 0
for task in tasks:
task.waiting_time = current_time
task.turnaround_time = current_time + task.burst_time
current_time += task.burst_time
total_tat += task.turnaround_time
total_wt += task.waiting_time
pretty_print(tasks)
print(f'Average waiting time {total_wt/len(tasks):.2f}')
print(f'Average Turnaround time {total_tat/len(tasks):.2f}')
if __name__ == '__main__':
# data = [
# Task("A", 0, 5, 5),
# Task("B", 2, 4, 2),
# Task("C", 3, 6, 1),
# Task("D", 1, 2, 3),
# Task("E", 4, 7, 4),
# ]
n = int(input('Enter number of tasks: '))
data = []
for i in range(n):
a, b = input('Enter Arrival time, Burst time: ').split()
name = chr(ord('A') + i)
data.append(Task(name, int(a), int(b)))
schedule(data)
duplicate
lines
here
lines
duplicate
line
here
with
duplicate
lines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment