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

unix

The document contains multiple shell scripts and C programs for various tasks, including arithmetic operations, temperature conversion, file existence checks, and process scheduling. It explains the logic and commands used in each script, such as reading user input, performing calculations, and managing processes with pipes. Additionally, it covers file manipulation and sorting based on size, providing a comprehensive overview of scripting and programming techniques.

Uploaded by

kmk39199
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

unix

The document contains multiple shell scripts and C programs for various tasks, including arithmetic operations, temperature conversion, file existence checks, and process scheduling. It explains the logic and commands used in each script, such as reading user input, performing calculations, and managing processes with pipes. Additionally, it covers file manipulation and sorting based on size, providing a comprehensive overview of scripting and programming techniques.

Uploaded by

kmk39199
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

1,

a)Write a shell script to perform arithmetic operations (+, -, *, /) based on user input (choose
operation).

#!/bin/bash

# User input
echo "Enter rst number: "
read num1
echo "Enter an operation (+, -, *, /): "
read op
echo "Enter second number: "
read num2

# Perform calculation
case $op in
+)
result=$(( num1 + num2 ))
;;
-)
result=$(( num1 - num2 ))
;;
\*)
result=$(( num1 * num2 ))
;;
/)
if (( num2 == 0 )); then
echo "Error: Division by zero is not allowed"
exit 1

# Use bc for oating-point division


result=$(echo "scale=2; $num1 / $num2" | bc)
;;
*)
echo "Invalid operation"
exit 1
;;
esac

# Output the result


echo "Result: $result"

echo : This command prints a message to the terminal asking the user for input.
read : This command captures the user's input and stores it in the speci ed variable (num1, op, or
num2).
num1: Stores the rst number entered by the user.
op: Stores the arithmetic operation (+, -, *, /) entered by the user.
num2: Stores the second number entered by the user.

b)Write a shell script that nds the largest and smallest element in an array.

• The -a option in the read command is used to read input into an array in Bash
• Ex: read -a arr.
This command reads a line of space-separated numbers from the user and stores them in an
array named arr.
• Each element in the input gets assigned to an index in the array (e.g., arr[0], arr[1], etc.).

#!/bin/bash
fi
fi
fi
fl
fi
fi
# Read array from user
echo "Enter numbers separated by space: "
read -a arr

# Check if array is empty


if [ ${#arr[@]} -eq 0 ]; then
echo "No numbers entered."
exit 1

# Initialize min and max with rst element


min=${arr[0]}
max=${arr[0]}

# Loop through array to nd min and max


for num in "${arr[@]}"
do
# Check if the number is less than current min
if [[ $num -lt $min ]]; then
min=$num

# Check if the number is greater than current max


if [[ $num -gt $max ]]; then
max=$num

done

# Output the smallest and largest elements


echo "Smallest element: $min"
echo "Largest element: $max"

# Output the result


echo "Result: $result"

2
a)Write a shell script to convert temperature from Celsius to Fahrenheit and vice versa.

#!/bin/bash

# Function to convert Celsius to Fahrenheit


celsius_to_fahrenheit() {
celsius=$1
# Multiply by 9 and divide by 5, then add 32
fahrenheit=$(echo "scale=2; ($celsius * 9 / 5) + 32" | bc)
echo "$celsius°C = $fahrenheit°F"
}

# Function to convert Fahrenheit to Celsius


fahrenheit_to_celsius() {
fahrenheit=$1
# Subtract 32, multiply by 5 and divide by 9
celsius=$(echo "scale=2; ($fahrenheit - 32) * 5 / 9" | bc)
echo "$fahrenheit°F = $celsius°C"
}

# Display options to the user


echo "Temperature Converter"
echo "1. Celsius to Fahrenheit"
echo "2. Fahrenheit to Celsius"
fi
fi
fi
fi
fi
echo "3. Exit"
echo -n "Please choose an option (1/2/3): "
read choice

# Perform conversion based on user's choice


case $choice in
1)
echo -n "Enter temperature in Celsius: "
read celsius
# Check if input is numeric
if [[ $celsius =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then
celsius_to_fahrenheit $celsius
else
echo "Invalid input. Please enter a numeric value."

;;
2)
echo -n "Enter temperature in Fahrenheit: "
read fahrenheit
# Check if input is numeric
if [[ $fahrenheit =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then
fahrenheit_to_celsius $fahrenheit
else
echo "Invalid input. Please enter a numeric value."

;;
3)
echo "Exiting the program."
exit 0
;;
*)
echo "Invalid choice, please select 1, 2, or 3."
;;
esac

b)Write a C program that uses a pipe to pass a string from a parent process to a child
process.

Explanation:
1. Pipe Creation:
o The pipe() system call creates a pipe. It returns two le descriptors:
▪ pipe_fd[0]: For reading.
▪ pipe_fd[1]: For writing.
2. Fork:
o fork() creates a new child process. The child process inherits the parent's le
descriptors.
3. Parent Process:
o Closes the read end of the pipe (pipe_fd[0]).
o Writes a string to the pipe using write().
4. Child Process:
o Closes the write end of the pipe (pipe_fd[1]).
o Reads the string from the pipe using read() and prints it.

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
fi
fi
fi
fi
#de ne BUFFER_SIZE 100

int main() {
int pipe_fd[2]; // File descriptors for the pipe
pid_t pid; // Process ID returned by fork()
char write_msg[] = "Hello from parent process!"; // Message to be written
char read_msg[BUFFER_SIZE]; // Bu er to store the read message

// Create the pipe


if (pipe(pipe_fd) == -1) {
perror("Pipe failed");
return 1;
}

// Fork a child process


pid = fork();
if (pid < 0) {
perror("Fork failed");
return 1;
}

if (pid > 0) {
// Parent process
close(pipe_fd[0]); // Close the read end of the pipe (not needed by parent)

// Write the message to the pipe


printf("Parent process writing: %s\n", write_msg);
write(pipe_fd[1], write_msg, strlen(write_msg) + 1); // Include null terminator

close(pipe_fd[1]); // Close the write end after writing


} else {
// Child process
close(pipe_fd[1]); // Close the write end of the pipe (not needed by child)

// Read the message from the pipe


read(pipe_fd[0], read_msg, BUFFER_SIZE);

// Print the received message


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

close(pipe_fd[0]); // Close the read end after reading


}

return 0;
}

3
a)Write a shell script that takes a lename as input and checks if the le exists. If the le
exists,
print the content of the le

[ -f "$ lename" ]:
The -f ag checks if the given lename corresponds to a regular le.
If the le exists, the condition evaluates to true, and the script proceeds to the next block.

#!/bin/bash

# Prompt user for lename


echo "Enter the lename: "
fi
fi
fi
fl
fi
fi
fi
fi
fi
ff
fi
fi
fi
read lename

# Check if le exists
if [ -f "$ lename" ]; then
echo "File exists. Contents of the le:"
cat "$ lename"
else
echo "Error: File does not exist."

b)Write a C program to calculate and display the area of the circle in the child’s process and
the nd
the area of a square in the parent process.

void calculateCircleArea( oat radius);: Declares a function to calculate the area of a circle.
void calculateSquareArea( oat side);: Declares a function to calculate the area of a square.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

#de ne PI 3.14159

// Function prototypes
void calculateCircleArea( oat radius);
void calculateSquareArea( oat side);

int main() {
pid_t pid;
oat radius, side;

// Input for square


printf("Enter the side length of the square: ");
scanf("%f", &side);

// Input for circle


printf("Enter the radius of the circle: ");
scanf("%f", &radius);

// Create a child process


pid = fork();

if (pid < 0) {
// Fork failed
perror("Fork failed");
exit(1);
} else if (pid == 0) {
// Child process
calculateCircleArea(radius);
exit(0); // Exit child process
} else {
// Parent process
wait(NULL); // Wait for child process to nish
calculateSquareArea(side);
}

return 0;
fi
fl
fi
fi
fi
fi
fi
fi
fl
fl
fl
fl
fi
fi
}

// Function to calculate and display area of a circle


void calculateCircleArea( oat radius) {
oat area = PI * radius * radius;
printf("Child Process: The area of the circle with radius %.2f is %.2f\n", radius, area);
}

// Function to calculate and display area of a square


void calculateSquareArea( oat side) {
oat area = side * side;
printf("Parent Process: The area of the square with side %.2f is %.2f\n", side, area);
}

4
a)Create a shell script that reads the content of a le and counts the number of lines, words
and
number of characters in the le.

Purpose of < (Input Redirection)


< "$ lename" redirects the content of the le as input to the wc (word count) command in this
program.

#!/bin/bash

# Prompt user for lename


echo "Enter the lename: "
read lename

# Check if the le exists


if [ ! -f "$ lename" ]; then
echo "File does not exist. Please provide a valid le."
exit 1

# Count the number of lines, words, and characters in the le


line_count=$(wc -l < "$ lename")
word_count=$(wc -w < "$ lename")
char_count=$(wc -m < "$ lename")

# Display the results


echo "File: $ lename"
echo "Number of lines: $line_count"
echo "Number of words: $word_count"
echo "Number of characters: $char_count"

b)Write a C program to simulate a basic scheduler that executes tasks in First come rst
Serve.

#include <stdio.h>

int main() {
int n, i, j;
int bt[20], at[20], wt[20], tat[20], ct[20];
oat avwt = 0, avtat = 0;

// Input: Total number of processes


printf("Enter total number of processes (maximum 20): ");
scanf("%d", &n);
fi
fl
fl
fl
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fi
fl
fi
fi
fi
fi
fi
fi
// Input: Burst time and Arrival time for each process
printf("Enter Process Burst Time and Arrival Time:\n");
for (i = 0; i < n; i++) {
printf("Process %d - Burst Time: ", i + 1);
scanf("%d", &bt[i]);
printf("Process %d - Arrival Time: ", i + 1);
scanf("%d", &at[i]);
}

// Calculate completion time


ct[0] = at[0] + bt[0]; // First process completes after its burst time
for (i = 1; i < n; i++) {
if (ct[i - 1] < at[i]) {
ct[i] = at[i] + bt[i]; // If CPU is idle until the next process arrives
} else {
ct[i] = ct[i - 1] + bt[i]; // Otherwise, continue from last completion time
}
}

// Calculate turnaround time and waiting time


printf("\nProcess\tBurst Time\tArrival Time\tCompletion Time\tTurnaround Time\tWaiting
Time\n");
for (i = 0; i < n; i++) {
tat[i] = ct[i] - at[i]; // Turnaround time = Completion time - Arrival time
wt[i] = tat[i] - bt[i]; // Waiting time = Turnaround time - Burst time
avwt += wt[i];
avtat += tat[i];
printf("P[%d]\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", i + 1, bt[i], at[i], ct[i], tat[i], wt[i]);
}

// Calculate and display average waiting time and average turnaround time
avwt /= n; // Average waiting time
avtat /= n; // Average turnaround time

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


printf("\nAverage Turnaround Time: %.2f\n", avtat);

return 0;
}

5
a)Write a script that searches for all les in a present working directory and sorts them by
size, displaying
the largest le rst.

#!/bin/bash

# Get the current directory (present working directory)


directory=$(pwd)

# Find all les in the directory and its subdirectories, calculate their sizes,
# sort them by size in descending order, and display the top 10 largest les.
nd "$directory" -type f -exec du -h {} + | sort -rh | head -n 10
fi
fi
fi
fi
fi
fi
Explanation:
• nd "$directory" -type f:
nd: This command is used to search for les and directories.
"$directory": The search starts in the speci ed directory (stored in the $directory variable). -
type f: This option tells nd to search for les only (not directories). It will match only regular
les.
• -exec du -h {} +:
-exec: This option tells nd to execute a command on each le found.
du -h: The du command (disk usage) is used to show the disk space used by les and
directories.
-h: This makes the output human-readable (e.g., 1K, 2M, 3G), so the le sizes are displayed
in a more understandable format (KB, MB, GB).
{}: This is a placeholder that gets replaced by the current le found by nd. For each le, nd
runs the command du -h and passes the le as an argument to du.
+: The + after {} is used to group multiple les together into a single du command. It improves
performance by running du on multiple les at once, instead of running it separately for each
le.
Without +, the -exec command would execute du -h for every individual le, which is less
e cient.
With +, all the les are passed to du in a single call.
• | sort -rh:
|: This is the pipe operator, which takes the output of the command on the left ( nd ... -exec
du -h {}) and passes it as input to the command on the right (sort -rh).
sort -rh:
sort: The sort command arranges the lines of input in a speci ed order.
-r: This option sorts the les in reverse order, meaning the largest les will appear rst.
-h: This option ensures the sorting works on human-readable sizes (like 1K, 2M, 3G) correctly.
Without this, sort would treat the le sizes as plain text and not in a meaningful way.
• | head -n 10:
head: The head command limits the output to the rst N lines.
-n 10: This option limits the output to the top 10 lines. In this case, it will show the top 10
largest les by size.

b)Write a shell script that computes the gross salary of an employee according to the
following
rules

i) If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the basic.
ii) If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic
The basic salary is entered interactively through the key board.

#!/bin/bash

# Prompt user for basic salary


read -p "Enter the basic salary of the employee: Rs " basic_salary

# Validate input to ensure it's numeric


if [[ ! $basic_salary =~ ^[0-9]+$ ]]; then
echo "Invalid input. Please enter a valid numeric salary."
exit 1

# Calculate HRA and DA based on the basic salary


if [ $basic_salary -lt 15000 ]; then
# For basic salary < 15000
hra=$((basic_salary / 10)) # HRA is 10% of basic salary
da=$((basic_salary * 9 / 10)) # DA is 90% of basic salary
else
# For basic salary >= 15000
fi
fi
fi
fi
ffi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
hra=500 # Fixed HRA of Rs 500
da=$((basic_salary * 98 / 100)) # DA is 98% of basic salary

# Calculate gross salary


gross=$((basic_salary + hra + da))

# Display the results


echo "Basic Salary: Rs $basic_salary"
echo "HRA: Rs $hra"
echo "DA: Rs $da"
echo "Gross Salary: Rs $gross"

6
a)Write a C program that appends a string to an existing le. Read the le name and text as
command
line arguments

#!/bin/bash

# Check if exactly two arguments are provided


if [ "$#" -ne 2 ]; then
echo "Usage: $0 < lename> <text to append>"
exit 1

# Extract arguments
lename="$1"
text="$2"

# Check if the le exists


if [ ! -f "$ lename" ]; then
echo "Error: File '$ lename' does not exist."
exit 1

# Append the text to the le


echo "$text" >> "$ lename"

# Con rm the operation


echo "Text appended successfully to '$ lename'."

b)Write a C program to simulate a basic scheduler that executes tasks in round-robin


fashion

#include <stdio.h>

int main() {
// Initialize variables
int i, NOP, sum = 0, count = 0, y, quant;
int wt = 0, tat = 0, at[10], bt[10], temp[10];
oat avg_wt, avg_tat;

// Input: Total number of processes


printf("Total number of processes in the system: ");
scanf("%d", &NOP);
y = NOP; // Assign the number of processes to variable y
fi
fi
fi
fi
fl
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
// Input: Arrival time and Burst time for each process
for (i = 0; i < NOP; i++) {
printf("\nEnter the Arrival and Burst time of Process[%d]\n", i + 1);
printf("Arrival time: "); // Accept arrival time
scanf("%d", &at[i]);
printf("Burst time: "); // Accept burst time
scanf("%d", &bt[i]);
temp[i] = bt[i]; // Store the burst time in a temporary array
}

// Input: Time Quantum


printf("Enter the Time Quantum for the process: ");
scanf("%d", &quant);

// Display headers for the output


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

// Round Robin Scheduling Logic


for (sum = 0, i = 0; y != 0;) {
if (temp[i] <= quant && temp[i] > 0) {
// If the remaining burst time is less than or equal to the time quantum
sum += temp[i];
temp[i] = 0; // Mark the process as completed
count = 1;
} else if (temp[i] > 0) {
// If the remaining burst time is greater than the time quantum
temp[i] -= quant;
sum += quant;
}

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


// Process completed
y--; // Decrement the number of remaining processes
printf("Process No[%d]\t%d\t\t%d\t\t%d\n", i + 1, bt[i], sum - at[i], sum - at[i] - bt[i]);
wt += sum - at[i] - bt[i]; // Accumulate waiting time
tat += sum - at[i]; // Accumulate turnaround time
count = 0; // Reset count
}

// Move to the next process


if (i == NOP - 1) {
i = 0; // Reset to the rst process
} else if (at[i + 1] <= sum) {
i++; // Move to the next process if its arrival time is within the current time
} else {
i = 0; // Reset to the rst process if no other process is ready
}
}

// Calculate and display average waiting time and turnaround time


avg_wt = ( oat)wt / NOP;
avg_tat = ( oat)tat / NOP;

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


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

return 0;
}
fl
fl
fi
fi
7
a)Create a shell script that implements a basic calculator (addition, subtraction,
multiplication, division)
using a case statement.

#!/bin/bash

# Check if exactly three arguments are provided


if [ "$#" -ne 3 ]; then
echo "Usage: $0 <num1> <operator> <num2>"
echo "Operators: +, -, *, /"
exit 1

# Extract arguments
num1=$1
operator=$2
num2=$3

# Validate numeric inputs (integers or oating-point numbers)


if ! [[ "$num1" =~ ^-?[0-9]+([.][0-9]+)?$ ]] || ! [[ "$num2" =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then
echo "Error: Both arguments must be numbers."
exit 1

# Perform calculation using bc for oating-point support


case "$operator" in
+)
result=$(echo "$num1 + $num2" | bc)
;;
-)
result=$(echo "$num1 - $num2" | bc)
;;
'*'|x)
result=$(echo "$num1 * $num2" | bc)
;;
/)
if [[ "$num2" == "0" ]]; then
echo "Error: Division by zero is not allowed."
exit 1

result=$(echo "scale=2; $num1 / $num2" | bc)


;;
*)
echo "Invalid operator. Use +, -, *, or /."
exit 1
;;
esac

# Display the result


echo "Result: $result"

b)Write a script to change le permissions using `chmod`.

#!/bin/bash

# Prompt user for le name and permissions


echo -n "Enter lename: "
read lename
fi
fi
fi
fi
fi
fi
fi
fl
fl
echo -n "Enter permissions (e.g., 755): "
read permissions

# Check if the le exists


if [ ! -e "$ lename" ]; then
echo "Error: File '$ lename' does not exist."
exit 1

# Display le details before permission change


echo "File details before permission change:"
ls -l "$ lename"

# Change le permissions
chmod "$permissions" "$ lename" 2>/dev/null
if [ $? -ne 0 ]; then
echo "Error: Invalid permissions '$permissions'. Please enter valid permissions."
exit 1

# Display le details after permission change


echo "File details after permission change:"
ls -l "$ lename"

# Con rm the operation


echo "Permissions of '$ lename' changed to '$permissions' successfully."

The command to change le or directory permissions in Linux and Unix systems is chmod
chmod [OPTIONS] MODE FILE
MODE can be numeric (e.g., 755) or symbolic (e.g., u+rwx).
FILE is the target le or directory.
Example: chmod 755 lename
Owner: read, write, execute (7)

8a)Write a shell script to print Fibonacci numbers up to n (user input) using a while loop.

#!/bin/bash

# Prompt user for input


read -p "Enter the number of Fibonacci terms: " n

# Validate input
if ! [[ "$n" =~ ^[0-9]+$ ]]; then
echo "Error: Please enter a positive integer."
exit 1

if [ "$n" -le 0 ]; then


echo "Error: Number of terms must be greater than 0."
exit 1

# Initialize rst two Fibonacci numbers


a=0
b=1

echo "Fibonacci sequence up to $n terms:"

count=0
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
while [ $count -lt $n ]
do
echo -n "$a " # Print current Fibonacci number
fn=$((a + b)) # Compute next number
a=$b # Shift values
b=$fn
count=$((count + 1))
done

echo # Add a newline at the end

b)Write a C program to simulate a basic scheduler that executes tasks in round-robin


fashion.

#include <stdio.h>

int main() {
// Initialize variables
int i, NOP, sum = 0, count = 0, y, quant;
int wt = 0, tat = 0, at[10], bt[10], temp[10];
oat avg_wt, avg_tat;

// Input: Total number of processes


printf("Total number of processes in the system: ");
scanf("%d", &NOP);
y = NOP; // Assign the number of processes to variable y

// Input: Arrival time and Burst time for each process


for (i = 0; i < NOP; i++) {
printf("\nEnter the Arrival and Burst time of Process[%d]\n", i + 1);
printf("Arrival time: "); // Accept arrival time
scanf("%d", &at[i]);
printf("Burst time: "); // Accept burst time
scanf("%d", &bt[i]);
temp[i] = bt[i]; // Store the burst time in a temporary array
}

// Input: Time Quantum


printf("Enter the Time Quantum for the process: ");
scanf("%d", &quant);

// Display headers for the output


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

// Round Robin Scheduling Logic


for (sum = 0, i = 0; y != 0;) {
if (temp[i] <= quant && temp[i] > 0) {
// If the remaining burst time is less than or equal to the time quantum
sum += temp[i];
temp[i] = 0; // Mark the process as completed
count = 1;
} else if (temp[i] > 0) {
// If the remaining burst time is greater than the time quantum
temp[i] -= quant;
sum += quant;
}

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


// Process completed
fl
y--; // Decrement the number of remaining processes
printf("Process No[%d]\t%d\t\t%d\t\t%d\n", i + 1, bt[i], sum - at[i], sum - at[i] - bt[i]);
wt += sum - at[i] - bt[i]; // Accumulate waiting time
tat += sum - at[i]; // Accumulate turnaround time
count = 0; // Reset count
}

// Move to the next process


if (i == NOP - 1) {
i = 0; // Reset to the rst process
} else if (at[i + 1] <= sum) {
i++; // Move to the next process if its arrival time is within the current time
} else {
i = 0; // Reset to the rst process if no other process is ready
}
}

// Calculate and display average waiting time and turnaround time


avg_wt = ( oat)wt / NOP;
avg_tat = ( oat)tat / NOP;

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


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

return 0;
}

9
a)Write a shell script to display the current date, time, and the user's home directory.

#!/bin/bash

# Function to display usage instructions


usage() {
echo "Usage: $0 [-d <date_format>] [-t <time_format>]"
echo " -d: Specify custom date format (default: %Y-%m-%d)"
echo " -t: Specify custom time format (default: %H:%M:%S)"
exit 1
}

# Default date and time formats


date_format="%Y-%m-%d"
time_format="%H:%M:%S"

# Parse command-line arguments


while getopts ":d:t:" opt; do
case "$opt" in
d) date_format="$OPTARG" ;;
t) time_format="$OPTARG" ;;
*) usage ;;
esac
done

# Display the current date


echo "Current Date: $(date +"$date_format")"

# Display the current time


echo "Current Time: $(date +"$time_format")"
fl
fl
fi
fi
# Display the user's home directory
echo "User's Home Directory: $HOME"

# Completion message
echo "Script execution completed."

b)Write a C program to simulate a basic scheduler that executes tasks in First come rst
Serve.

#include <stdio.h>

int main() {
int n, i, j;
int bt[20], at[20], wt[20], tat[20], ct[20];
oat avwt = 0, avtat = 0;

// Input: Total number of processes


printf("Enter total number of processes (maximum 20): ");
scanf("%d", &n);

// Input: Burst time and Arrival time for each process


printf("Enter Process Burst Time and Arrival Time:\n");
for (i = 0; i < n; i++) {
printf("Process %d - Burst Time: ", i + 1);
scanf("%d", &bt[i]);
printf("Process %d - Arrival Time: ", i + 1);
scanf("%d", &at[i]);
}

// Calculate completion time


ct[0] = at[0] + bt[0]; // First process completes after its burst time
for (i = 1; i < n; i++) {
if (ct[i - 1] < at[i]) {
ct[i] = at[i] + bt[i]; // If CPU is idle until the next process arrives
} else {
ct[i] = ct[i - 1] + bt[i]; // Otherwise, continue from last completion time
}
}

// Calculate turnaround time and waiting time


printf("\nProcess\tBurst Time\tArrival Time\tCompletion Time\tTurnaround Time\tWaiting
Time\n");
for (i = 0; i < n; i++) {
tat[i] = ct[i] - at[i]; // Turnaround time = Completion time - Arrival time
wt[i] = tat[i] - bt[i]; // Waiting time = Turnaround time - Burst time
avwt += wt[i];
avtat += tat[i];
printf("P[%d]\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", i + 1, bt[i], at[i], ct[i], tat[i], wt[i]);
}

// Calculate and display average waiting time and average turnaround time
avwt /= n; // Average waiting time
avtat /= n; // Average turnaround time

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


printf("\nAverage Turnaround Time: %.2f\n", avtat);

return 0;
}
fl
fi
10
a)Write a shell script that calculates the factorial of a number entered by the user.

#!/bin/bash

# Prompt user for input


read -p "Enter a number: " num

# Validate input to ensure it's a non-negative integer


if ! [[ "$num" =~ ^[0-9]+$ ]]; then
echo "Error: Please enter a non-negative integer."
exit 1

# Initialize factorial to 1
fact=1

# Check if number is zero


if [ "$num" -eq 0 ]; then
echo "Factorial of 0 is: 1"
exit 0

# Calculate factorial using a while loop


i=$num
while [ "$i" -gt 1 ]; do
fact=$((fact * i)) # Multiply fact by i
i=$((i - 1)) # Decrement i
done

# Display the result


echo "Factorial of $num is: $fact"

b)Write a shell script that searches for a speci c word in a le and displays the matching
lines using

#!/bin/bash

# Prompt user for the lename


read -p "Enter the lename to search: " lename

# Check if le exists
if [ ! -f "$ lename" ]; then
echo "Error: File '$ lename' not found!"
exit 1

# Prompt user for the word to search


read -p "Enter the word to search for: " search_word

# Validate that the search word is not empty


if [ -z "$search_word" ]; then
echo "Error: Search word cannot be empty."
exit 1

# Use grep to search for the word in the le


fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
echo "Searching for '$search_word' in '$ lename':"
grep --color=auto "$search_word" "$ lename"

# Check if grep found any matches


if [ $? -eq 0 ]; then
echo "Search completed."
else
echo "No matches found."

11
a)Write a Shell Script to Check Whether a Given Number is Prime

#!/bin/bash

# Read a number from the user


read -p "Enter a number: " num

# Check if the number is less than 2 (not prime)


if [ "$num" -lt 2 ]; then
echo "$num is not a prime number."
exit 0

# Assume the number is prime


is_prime=1

# Check divisors from 2 to the square root of the number


for (( i=2; i*i<=num; i++ )); do
if [ $((num % i)) -eq 0 ]; then
is_prime=0 # Not prime
break

done

# Display result
if [ "$is_prime" -eq 1 ]; then
echo "$num is a prime number."
else
echo "$num is not a prime number."

b)Write a bash script that displays the top 15 processes based on CPU usage. The script
should
provide the following options to the user:
• Show processes for a speci c user (user input required).
• Sort and display processes by memory usage

#!/bin/bash

# Function to display process details


display_processes() {
echo "=============================="
echo " Current Running Processes "
echo "=============================="
ps -eo pid,user,%cpu,%mem,comm --sort=-%cpu | head -15
echo "------------------------------"
}
fi
fi
fi
fi
fi
fi
fi
# Loop until the user chooses to exit
while true; do
# Display initial process list
display_processes

# Display menu options


echo "Options:"
echo "1. Show processes for a speci c user"
echo "2. Sort processes by memory usage"
echo "3. Exit"
read -p "Enter your choice: " choice

# Handle user input


case $choice in
1)
read -p "Enter username: " username
if id "$username" >/dev/null 2>&1; then
echo "Processes for user: $username"
ps -u "$username" -o pid,%cpu,%mem,comm --sort=-%cpu
else
echo "Error: User '$username' does not exist."

;;
2)
echo "Top processes sorted by memory usage:"
ps -eo pid,user,%cpu,%mem,comm --sort=-%mem | head -15
;;
3)
echo "Exiting..."
break
;;
*)
echo "Invalid choice! Please try again."
;;
esac

# Pause before returning to the menu


echo "Press Enter to continue..."
read
done

Command to display 15 currently running processes:


ps -eo pid,user,%cpu,%mem,comm --sort=-%cpu | head -15
ps → Stands for "Process Status"; displays currently running processes.
-e → Lists all processes running on the system.
-o pid,user,%cpu,%mem,comm → Speci es the columns to display:
• pid → Process ID.
• user → The owner of the process.
• %cpu → Percentage of CPU usage by the process.
• %mem → Percentage of memory usage.
• comm → The command that started the process.
• --sort=-%cpu → Sorts the processes in descending order by CPU usage (- sign means
descending).
• | head -15 → Displays only the top 15 processes.
fi
fi
fi

You might also like