OPERATING SYSTEM
SEMISTER –III
GROUP:[Link](AI) PRACTICAL PROGRAMMS
1. write the program to implement CPU scheduling algorithm for first come first serve
scheduling using c programming.
A. Simple C program that implements the First Come First Serve (FCFS) CPU
Scheduling Algorithm. It calculates the waiting time and turnaround time for each
process.
#include <stdio.h>
int main() {
int n, i;
float avg_waiting_time = 0, avg_turnaround_time = 0;
printf("Enter the number of processes: ");
scanf("%d", &n);
int burst_time[n], waiting_time[n], turnaround_time[n];
// Input burst times
printf("Enter Burst Time for each process:\n");
for (i = 0; i < n; i++) {
printf("P%d: ", i + 1);
scanf("%d", &burst_time[i]);
}
// Waiting time for first process is always 0
waiting_time[0] = 0;
// Calculate waiting time
for (i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i - 1] + burst_time[i - 1];
}
// Calculate turnaround time
for (i = 0; i < n; i++) {
turnaround_time[i] = waiting_time[i] + burst_time[i];
}
// Calculate average waiting time and turnaround time
for (i = 0; i < n; i++) {
avg_waiting_time += waiting_time[i];
avg_turnaround_time += turnaround_time[i];
}
avg_waiting_time /= n;
avg_turnaround_time /= n;
// Display results
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", i + 1, burst_time[i], waiting_time[i],
turnaround_time[i]);
}
printf("\nAverage Waiting Time: %.2f", avg_waiting_time);
printf("\nAverage Turnaround Time: %.2f\n", avg_turnaround_time);
return 0;
}
OUTPUT:
Enter the number of processes: Enter Burst Time for each process:
P1: P2: P3: P4: P5:
Process Burst Time Waiting Time Turnaround Time
P1 12 0 12
P2 15 12 27
P3 14 27 41
P4 13 41 54
P5 19 54 73
Average Waiting Time: 26.80
Average Turnaround Time: 41.40
Explanation:
Takes the number of processes and their burst times as input.
Computes waiting time and turnaround time using FCFS logic.
Prints each process’s burst time, waiting time, and turnaround time.
Displays the average waiting and turnaround times.
[Link] the program to implement CPU scheduling algorithm for shortest job first
scheduling using c programming language
A. Simple C program that implements the Shortest job First (SJFS) Scheduling
Algorithm (Non- Preemptive). This version assumes all processes arrive at time 0
and only burst time is considered for scheduling. The algorithm sorts the jobs by
their burst time and schedules the shortest job first.
#include <stdio.h>
int main() {
int n, i, j;
int process[20], bt[20], wt[20], tat[20];
int temp;
float avg_wt = 0, avg_tat = 0;
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter Burst Time for each process:\n");
for (i = 0; i < n; i++) {
printf("P[%d]: ", i + 1);
scanf("%d", &bt[i]);
process[i] = i + 1;
}
// Sort burst times (selection sort)
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (bt[ j] < bt[i]) {
temp = bt[i];
bt[i] = bt[ j];
bt[ j] = temp;
temp = process[i];
process[i] = process[ j];
process[ j] = temp;
}
}
}
// First process has 0 waiting time
wt[0] = 0;
// Calculate waiting time
for (i = 1; i < n; i++) {
wt[i] = 0;
for (j = 0; j < i; j++) {
wt[i] += bt[ j];
}
}
// Calculate turnaround time
for (i = 0; i < n; i++) {
tat[i] = bt[i] + wt[i];
avg_wt += wt[i];
avg_tat += tat[i];
}
avg_wt /= n;
avg_tat /= n;
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P[%d]\t%d\t\t%d\t\t%d\n", process[i], bt[i], wt[i], tat[i]);
}
printf("\nAverage Waiting Time: %.2f", avg_wt);
printf("\nAverage Turnaround Time: %.2f\n", avg_tat);
return 0;
}
OUTPUT:
Enter number of processes: Enter Burst Time for each process:
P[1]: P[2]: P[3]: P[4]: P[5]:
Process Burst Time Waiting Time Turnaround Time
P[4] 14 0 14
P[3] 25 14 39
P[1] 32 39 71
P[5] 63 71 134
P[2] 65 134 199
Average Waiting Time: 51.60
Average Turnaround Time: 91.40
Explanation:
This program takes the number of processes and their burst times, sorts them, and
schedules the shortest job first.
It calculates and displays the waiting and turnaround times for each process, together
with the average waiting and turnaround times.
Provide a C program for preemptive SJF (SRTF) with arrival times
Show a test case and output for a non-preemptive SJF C program
How to calculate waiting and turnaround times step-by-step
Modify SJF C code to handle ties by arrival time
Convert the SJF program to use dynamic input from a file
3. Write a C program to perform priority scheduling.
A. Simple C program that performs priority scheduling (non-preemptive):
#include <stdio.h>
struct Process {
int id;
int burst;
int priority;
int waiting;
int turnaround;
};
void sortByPriority(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].priority > p[ j].priority) { // lower number = higher priority
temp = p[i];
p[i] = p[ j];
p[ j] = temp;
}
}
}
}
int main() {
int n;
printf("Enter number of processes: ");
scanf("%d", &n);
struct Process p[n];
for (int i = 0; i < n; i++) {
p[i].id = i + 1;
printf("Enter burst time for process %d: ", i+1);
scanf("%d", &p[i].burst);
printf("Enter priority for process %d (lower number = higher priority): ", i+1);
scanf("%d", &p[i].priority);
}
sortByPriority(p, n);
p[0].waiting = 0;
for (int i = 1; i < n; i++) {
p[i].waiting = 0;
for (int j = 0; j < i; j++) {
p[i].waiting += p[ j].burst;
}
}
float avg_wt = 0, avg_tat = 0;
printf("\nProcess\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++) {
p[i].turnaround = p[i].waiting + p[i].burst;
avg_wt += p[i].waiting;
avg_tat += p[i].turnaround;
printf("P%d\t%d\t\t%d\t\t%d\t\t%d\n",
p[i].id, p[i].burst, p[i].priority, p[i].waiting, p[i].turnaround);
}
avg_wt /= n;
avg_tat /= n;
printf("\nAverage Waiting Time: %.2f", avg_wt);
printf("\nAverage Turnaround Time: %.2f\n", avg_tat);
return 0;
}
OUTPUT:
Enter number of processes: Enter burst time for process 1: Enter priority for process
1 (lower number = higher priority): Enter burst time for process 2: Enter priority for
process 2 (lower number = higher priority):
Process Burst Time Priority Waiting Time Turnaround Time
P1 3 2 0 3
P2 4 5 3 7
Average Waiting Time: 1.50
Average Turnaround Time: 5.00
EXPLANATION:
Takes input for processes with burst time and priority.
Sorts processes by ascending priority ( lower priority value runs first).
Calculates waiting time of each process as the sum of burst times of
preceding processes.
Calculates turnaround time as waiting plus burst time.
Outputs each process’s details and average waiting and turnaround time.
This program assumes all processes arrive at the same time
(arrival time = 0) and uses non- preemptive priority scheduling.
4. Write a program to implement CPU scheduling for Round Robin Scheduling.
A. #include <stdio.h>
int main() {
int n, i, time_quantum;
int bt[20], rem_bt[20], wt[20], tat[20];
int t = 0, done;
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter burst time for each process:\n");
for(i = 0; i < n; i++) {
printf("P[%d]: ", i + 1);
scanf("%d", &bt[i]);
rem_bt[i] = bt[i]; // initialize remaining burst times
wt[i] = 0;
}
printf("Enter time quantum: ");
scanf("%d", &time_quantum);
int completed = 0;
while (completed < n) {
done = 1;
for(i = 0; i < n; i++) {
if(rem_bt[i] > 0) {
done = 0;
if(rem_bt[i] > time_quantum) {
t += time_quantum;
rem_bt[i] -= time_quantum;
} else {
t += rem_bt[i];
wt[i] = t - bt[i];
rem_bt[i] = 0;
completed++;
}
}
}
if(done)
break;
}
// Calculate turnaround time
for(i = 0; i < n; i++) {
tat[i] = bt[i] + wt[i];
}
// Print results
float avg_wt = 0, avg_tat = 0;
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for(i = 0; i < n; i++) {
printf("P[%d]\t%d\t\t%d\t\t%d\n", i+1, bt[i], wt[i], tat[i]);
avg_wt += wt[i];
avg_tat += tat[i];
}
avg_wt /= n;
avg_tat /= n;
printf("\nAverage Waiting Time: %.2f", avg_wt);
printf("\nAverage Turnaround Time: %.2f\n", avg_tat);
return 0;
}
OUTPUT:
Enter number of processes: Enter burst time for each process:
P[1]: P[2]: P[3]: P[4]: P[5]: Enter time quantum:
Process Burst Time Waiting Time Turnaround Time
P[1] 2 0 2
P[2] 3 2 5
P[3] 4 5 9
P[4] 5 9 14
P[5] 6 14 20
Average Waiting Time: 6.00
Average Turnaround Time: 10.00
EXPLANATION:
Takes number of processes and their burst times. Takes a time quantum input.
Cyclically allocates CPU times slices (time quantum) to each process until all
processes finish.
Calculates waiting time and turnaround time for each process.
Print average waiting time and turnaround time.
This implementation assumes all processes arrive at time 0 and uses simple Round
Robin Scheduling logic.
5. Execute various file/directory handing commands in unix
A. Here is a practical execution of various file and directory handling commands in Unix
with explanation:
bash
# Show the current working directory
pwd
# List all files and directories in the current directory
ls
# List all files including hidden ones in long detailed format
ls -la
# Change directory to /usr/local
cd /usr/local
# Go back to the home directory
cd ~
# Create a new directory named 'projects'
mkdir projects
# Create nested directories
mkdir -p projects/test/code
# Remove an empty directory named 'temp'
rmdir temp
# Create an empty file named '[Link]'
touch [Link]
# Copy '[Link]' to 'file_backup.txt'
cp [Link] file_backup.txt
# Move (or rename) '[Link]' to 'file_old.txt'
mv [Link] file_old.txt
# Remove the file 'file_old.txt'
rm file_old.txt
# Show first 10 lines of 'file_backup.txt'
head file_backup.txt
# Show last 10 lines of 'file_backup.txt'
tail file_backup.txt
# Display contents of 'file_backup.txt' page by page
less file_backup.txt
# Display detailed file permissions and sizes of files in the
directory
ls -l
# Find all files named '*.conf' under /etc directory
find /etc -name "*.conf"
# Change ownership of 'file_backup.txt' to user 'john' and group 'staff'
chown john:staff file_backup.txt
EXPLANATION:
These commands cover the basics of file and directory navigation, creation, copying,
moving, deleting, viewing, permission changing, and finding files in Unix/Linux systems.
They can be executed directly in a Unix shell or terminal.
[Link] a shell script for basic arithmetic and logical calculations.
A. echo "Enter two numbers:"
read a b
a=10
b=5
Arithmetic Operations:
echo "Arithmetic Operations:"
echo "Addition: $((a + b))"
echo "Subtraction: $((a - b))"
echo "Multiplication: $((a * b))"
echo "Division: $((a / b))"
echo "Modulus: $((a % b))"
Logical Operations:
x=1
y=0
echo "x = $x, y = $y"
if (( x && y )); then
echo "Logical AND: true"
else
echo "Logical AND: false"
fi
if (( x || y )); then
echo "Logical OR: true"
else
echo "Logical OR: false"
fi
if (( !y )); then
echo "Logical NOT: true"
else
echo "Logical NOT: false"
fi
How to run:
Save this code to a file, e.g., [Link]
Make it executable: chmod +x [Link]
Execute: ./[Link]
This script covers arithmetic operations like addition, subtraction, multiplication,
division, modulo, exponentiation, increment, and decrement. It also demonstrates
logical AND, OR, and NOT conditions using shell arithmetic evaluation.
[Link] a shell script to display list of users currently logged in.
A. Here is a simple shell script to display the list of users currently logged in:
bash
#!/bin/bash
echo "Currently logged in users:"
who | awk '{print $1}' | sort | uniq
Explanation:
who command lists currently logged-in users along with their terminal and login
time.
awk '{print $1}' extracts just the usernames from the who output.
sort | uniq removes duplicates and sorts the list of usernames.
Alternatively, other commands useful for showing logged-in users:
users — prints all users currently logged in in a single line.
w — shows logged-in users plus their current activity.
who — detailed user login info.
Example to run in shell:
bash
$ ./logged_in_users.sh
Currently logged in users:
user1
user2
If needed, I can provide a script with menu options using these commands.
[Link] a shell script to delete all the temporary files.
A. A shell script to delete temporary files can be created using the rm command, typically targeting
common temporary directories like /tmp and /var/tmp. It is crucial to exercise caution when using rm -
rf as it permanently deletes files and directories without prompting.
Here is a basic script to remove all files and subdirectories within /tmp and /var/tmp:
#!/bin/bash
# Script name [Link]
# Script for removing all temporary files from temporary directory
TMP_DIR="/tmp"
echo "Removing all temporary files from $TMP_DIR"
# Counting the number of temporary files
files=`ls -l $TMP_DIR | wc -l`
echo "There are total $files temporary files/directory in $TMP_DIR"
rm -rf $TMP_DIR/*
if [[ "$?" == "0" ]];then
echo "All temporary files successfully deleted"
else
echo "Failed to delete temporary files"
fi
# Counting the number of temporary files
files=`ls -l $TMP_DIR | wc -l`
echo "There are total $files temporary files/directory in $TMP_DIR directory"
9. Write a shell script to search an element from an array using binary searching.
A. Here is a shell script to perform binary search on a sorted array:
bash
#!/bin/bash
# Binary Search in Bash
sorted_array=(2 5 8 12 16 23 38 56 72 91)
n=${#sorted_array[@]}
read -p "Enter element to search: " target
low=0
high=$((n - 1))
found=-1
while [ $low -le $high ]; do
mid=$(((low + high) / 2))
if [ "${sorted_array[$mid]}" -eq "$target" ]; then
found=$mid
break
elif [ "${sorted_array[$mid]}" -lt "$target" ]; then
low=$((mid + 1))
else
high=$((mid - 1))
fi
done
if [ $found -ne -1 ]; then
echo "Element $target found at index $found"
else
echo "Element $target not found in the array"
fi
Explanation:
The array sorted_array must be sorted for binary search to work.
low and high represent the current search bounds.
The middle element is compared to the target.
Search bounds update based on comparison.
If found, it prints index; otherwise, indicates not found.
Save this as binary_search.sh, make it executable (chmod +x), and run it.
This approach implements the classic binary search algorithm within a Bash script.
[Link] a shell script to determine whether a given number is a prime number or not.
bash
#!/bin/bash
read -p "Enter a number: " number
if [ $number -lt 2 ]; then
echo "$number is not a prime number."
exit 1
fi
i=2
while [ $i -le $(expr $number / 2) ]
do
if [ $(expr $number % $i) -eq 0 ]; then
echo "$number is not a prime number."
exit 1
fi
i=$(expr $i + 1)
done
echo "$number is a prime number."
OUTPUT:
ENTER THE NUMBER :1
1 is not a prime number
ENTER THE NUMBER :2
2 is a prime number
ENTER THE NUMBER :3
3 is a prime number
ENTER THE NUMBER :4
4 is not a prime number
ENTER THE NUMBER: 5
5 is a prime number
ENTER THE NUMBER :6
6 is not a prime number.
ENTER THE NUMBER 10
10 is not a prime number
Explanation:
Validates that the number is at least 2.
Loops from 2 up to half of the number.
Checks if the number is divisible by any number in that range.
If divisible, it’s not prime.
If no divisors found, it’s prime.
Save this script as check_prime.sh, make it executable using chmod +x
check_prime.sh, and run it.
[Link] a shell script to print the first n Fibonacci number
#!/bin/bash
echo "Hello, World!"
#!/bin/bash
# Prompt user for number of terms
read -p "Enter the number of Fibonacci terms: " n
# Validate input
if ! [[ "$n" =~ ^[0-9]+$ ]] || [ "$n" -le 0 ]; then
echo "Error: Enter a positive integer."
exit 1
fi
# Initialize first two Fibonacci numbers
a=0
b=1
echo "First $n Fibonacci numbers:"
for (( i=1; i<=n; i++ ))
do
echo -n "$a "
fn=$((a + b))
a=$b
b=$fn
done
OUTPUT: 10
Hello, World!
First 10 Fibonacci numbers:
0 1 1 2 3 5 8 13 21 34
12. Execute various system administrative commands in unix ?
A. Here is a list of various common system administration commands in Unix along
with a brief explanation for each:
System Information:
uname - Displays system information.
Example: uname -a shows kernel details and OS information.
uptime - Shows how long the system has been running.
who - Shows which users are currently logged in.
w - Displays who is logged in and what they are doing.
whoami - Shows the current user.
Process Management:
ps aux - Lists all running processes.
top - Dynamic real-time view of running processes and resource usage.
kill <pid> - Sends a signal to terminate a process.
pkill <name> - Kills processes by name.
renice - Changes priority of running processes.
jobs, bg, fg - Manage background and foreground jobs.
Disk and Filesystem:
df -h - Shows disk space usage in human-readable format.
du -sh <dir> - Shows disk usage of directory.
mount - Lists mounted filesystems.
umount - Unmounts a mounted filesystem.
User and Group Management:
id - Displays user ID and group information.
who and users - List logged-in users.
passwd - Change user password.
adduser/useradd - Add a new user.
groupadd - Add a new group.
usermod - Modify existing user.
File and Directory Commands:
ls, cd, pwd - Navigate and list files/directories.
mkdir, rmdir - Create or remove directories.
cp, mv, rm - Copy, move/rename, and remove files.
chmod, chown - Change file permissions and ownership.
Networking:
ifconfig or ip addr - Show network interfaces.
ping - Check connectivity to a host.
netstat - Display network connections.
ssh - Secure shell login to remote machines.
System Monitoring and Logs:
dmesg - Displays system boot and kernel messages.
journalctl - Accesses systemd logs.
tail -f /var/log/syslog - Follow system logs in real time.
Scheduling Jobs:
crontab -e - Edit scheduled cron jobs.
at - Schedule one-time jobs.
Explanation:
These are essential commands frequently used to administer and monitor Unix/Linux
systems safely and efficiently. Each command has many options providing powerful
control and detailed information.