Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 108

PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:01 BASIC LINUX COMMANDS Date:14-03-2024

FILE RELATED COMMANDS:


A) COMMAND NAME: cat

DESCRIPTION:
 The cat command is used to create a file in a Linux operating system.
 The cat command is used to display the contents of the file,the cat command is also used
to merge multiple files into a single file.
SYNTAX:
 $ command name > File name.
 $ command name File name.
 $ command name File 1 File 2 > File 3.

B) COMMAND NAME: ls (list command)

DESCRIPTION:
 The list command is used to list the file & directories.
SYNTAX:
 $ ls –l
C) COMMAND NAME: clear

DESCRIPTION:
 The list command is used to clear the terminal screen in a LINUX.
SYNTAX:
 $ clear.

DIRECTORY RELATED COMMANDS:


D) COMMAND NAME: mkdir (make directory command)

DESCRIPTION:
 This command is used to create an empty directory in a disk.
SYNTAX:
 $ mkdir directory name.

E) COMMAND NAME: rmdir (Remove directory)

DESCRIPTION:
 This command is used to remove a directory from disk.

RULES TO BE FOLLOWED:
i. Directory must be empty.
ii. Directory cannot be current working directory.

SYNTAX:
 $rmdir directory name.

F) COMMAND NAME: cd (change directory)

DESCRIPTION:
 This command is used to move from one directory to another directory.
SYNTAX:
 $ cd directory name.
G) COMMAND NAME: pwd (Print working directory command)

DESCRIPTION:
 This command is used to current working directory.
SYNTAX:
 $ pwd.

GENERAL PURPOSE COMMANDS:

H) COMMAND NAME: date

DESCRIPTION:
 This command is used to display current date with day,time,month,year.
SYNTAX:
 $ date

I) COMMAND NAME: cal (Calendar command)

DESCRIPTION:
 This command is used to display current month and all months of a particular year.
SYNTAX:
 $ cal.
 $ cal particular year.
RESULT:
Thus the above basic linux commands are executed successfully.
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:02 SHELL SCRIPT BASICS Date: 14-03-2024

AIM:
To understand and implement the basic shell script commands.

A) PRINTING BASIC TEXT:


ALGORITHM:
1. Create a file with extension and type the program in it using gedit command.
2. Include #!/bin/bash in the first line of program to use bash for execution.
3. Type the program to print some text.
4. Using chmod +x scriptname.sh to provide execution permission.
5. Run the script using the command ./scriptname.sh.

SOURCE CODE:
#!/bin/bash
echo "Hello Second year IT students"

B) DISPLAY USER INPUT:

ALGORITHM:
1. Create a file with .sh extension method and type the program using gedit command.
2. Type the program using if – else statement then change the mode of the file as +x to provide
execution permisiion to it.
3. Execute the script using the following commands using <filename>.sh.

SOURCE CODE:
#!/bin/bash
Age=17
if [ "$Age" -ge 18 ]; then
echo "You can vote"
else
echo "You cannot vote"
fi
C) FUNCTIONS:
ALGORITHM:
1. Create a file with .sh extension and type the program in it using edit command.
2. Type the programs in modules to access the multiple times and then change the mode of the file
to +x to provide execution permission to it.
3. Execute the script using output command.

SOURCE CODE:
#!/bin/bash
#It is a function
myFunction ()
{
echo Hello World From IT
}
#function call
myFunction

D) STRING CONCATENATION:
ALGORITHM:
1. Create a file in gedit as “CONACT.sh”.
2. Initialize a string to variable “name” and a string to variable “age”.
3. Adding both strings lay & $ {name} $ {age} to variable “info”.
4. Display the result by echo command.

SOURCE CODE:
#!/bin/bash
Name="Satyajit"
if [ "$Name" = "Satyajit" ]; then
echo "His name is Satyajit. It is true."
fi

E) DECISION MAKING:
ALGORITHM:
1. Create a file in gedit as “if – sh”.
2. Create a variable “name” and initialize it to a string.
3. If the case matches,display the respective echo statement.
4. Display the program using “chmod” and “./if.sh” command.
SOURCE CODE:
name ='my name is Tom.'
age ='my age is 17.'
info ="${name} ${age}"
echo "Result: $info"

RESULT:
Thus the above basic shell script is executed successfully and output is verified.
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:03 SHELL SCRIPT EXAMPLES – I Date: 25-03-2024

A) ARMSTRONG NUMBER
AIM:
To write a shell script program to check whether a number is armstrong or not.

ALGORITHM:
1. Prompt the user to enter a number and store the input.
2. Set up variables to store the sum of the digits raised to the power of the number's length and a copy
of the original number.
3. Determine the number of digits in the input number.
4. Extract each digit from the number, raise it to the power of the number's length, and add the result
to the sum.
5. Compare the calculated sum with the original number.
6. Print whether the number is an Armstrong number or not based on the comparison.
SOURCE CODE:
#!/bin/bash
is_armstrong() {
local num=$1
local sum=0
local n=${#num}
local temp=$num
while [ $temp -gt 0 ]; do
digit=$((temp % 10))
sum=$((sum + digit**n))
temp=$((temp / 10))
done
if [ $sum -eq $num ]; then
echo "$num is an Armstrong number."
else
echo "$num is not an Armstrong number."
fi
}
read -p "Enter a number: " number
is_armstrong $number
OUTPUT:

RESULT:
Thus the shell script program to check whether a number is armstrong or not is executed
successfully.
B) FIBONACCI SERIES
AIM:
To write a shell script program to execute fibonacci series.

ALGORITHM:
1. Set the first two Fibonacci numbers with two variables.
2. Prompt the user to enter the number of terms.
3. Use a loop to calculate each Fibonacci number.
4. Display each fibonacci number.
5. Update the variables to get the next term.
6. Continue until the desired number of terms is reached.

SOURCE CODE:
#!/bin/bash
read -p "Enter the number of terms: " n
a=0
b=1
echo "Fibonacci series:"
for (( i=0; i<n; i++ )); do
echo -n "$a "
fn=$((a + b))
a=$b
b=$fn
done
echo

OUTPUT:

RESULT:
Thus the shell script program for fibonacci series is executed successfully.
C) PRIME NUMBER OR NOT
AIM:
To write a shell script program to check whether it is a prime number or not.

ALGORITHM:
1. Read the number.
2. If the number is less than 2, it is not a prime number.
3. For each integer from 2 to the square root of the number, check if it divides the number without
a remainder.
4. If a divisor is found, the number is not a prime number.
5. If no divisors are found in the loop, the number is a prime number.
6. Output the result indicating whether the number is prime or not.

SOURCE CODE:
#!/bin/bash
read -p "Enter a number: " num
if [ $num -lt 2 ]; then
echo "$num is not a prime number."
exit
fi
for ((i=2; i<=$((num/2)); i++))
do
if [ $((num % i)) -eq 0 ]; then
echo "$num is not a prime number."
exit
fi
done
echo "$num is a prime number."

OUTPUT:

RESULT:
Thus the shell script program to check whether it is prime number or not is executed successfully
and output is verified.

D) PALINDROME SERIES
AIM:
To write a shell script program to execute palindrome series.

ALGORITHM:
1. Read the string.
2. Reverse the string.
3. Compare the reversed string with the original string.
4. If they are identical, the string is a palindrome.
5. If they are not identical, the string is not a palindrome.
6. Output the result indicating whether the string is a palindrome or not.

SOURCE CODE:
#!/bin/bash
read -p "Enter a string: " str
reversed=$(echo "$str" | rev)
if [ "$str" == "$reversed" ]; then
echo "$str is a palindrome."
else
echo "$str is not a palindrome."
fi

OUTPUT:

RESULT:
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Thus the shell script


Expt.No:04 SHELLprogram to executeEXAMPLES
SCRIPT palindrome is executed
– II successfully
Date: and output is
01-04-2024
verified..

A) FACTORIAL OF A NUMBER
AIM:
To write a shell script program to execute factorial of a number.

ALGORITHM:
1. Read the number for which the factorial is to be calculated.
2. Initialize a variable to 1 to hold the result of the factorial.
3. For each integer from 1 up to the number, multiply the variable by the current integer.
4. Continue this multiplication until all integers up to the number have been processed.
5. The variable now contains the factorial of the number.
6. Output the calculated factorial.

SOURCE CODE :
#!/bin/bash
read -p "Enter a number: " num
factorial=1
for ((i=1; i<=num; i++))
do
factorial=$((factorial * i))
done
echo "Factorial of $num is $factorial."

OUTPUT:
RESULT:
Thus the shell script program to execute factorial of a number is compiled and verified the output.

B) SUM OF DIGITS
AIM:
To write a shell script program to execute sum of digits.

ALGORITHM:
1. Read the number.
2. Initialize a sum variable to 0.
3. While the number is greater than 0, perform the following steps:
4. Extract the last digit using modulo operation.
5. Add the digit to the sum.
6. Remove the last digit from the number by integer division.
7. Output the sum of the digits.
8. Ensure the number is non-negative; otherwise, indicate an error.

SOURCE CODE :
#!/bin/bash
read -p "Enter a number: " num
sum=0
while [ $num -gt 0 ]
do
digit=$((num % 10))
sum=$((sum + digit))
num=$((num / 10))
done
echo "Sum of digits is $sum."

OUTPUT:
RESULT:
Thus the shell script program to execute sum of digits is successfully executed.

C) REVERSE A NUMBER
AIM:
To write a shell script program to reverse a given number.

ALGORITHM:
1. Read the number.
2. Initialize a reversed number to 0.
3. While the number is greater than 0, perform the following steps:
4. Extract the last digit using modulo operation.
5. Add the digit to the reversed number, shifting it by one decimal place.
6. Remove the last digit from the original number by integer division.
7. Output the reversed number.
8. Ensure the number is non-negative; otherwise, indicate an error.

SOURCE CODE :
#!/bin/bash
read -p "Enter a number: " num
reversed=0
while [ $num -gt 0 ]
do
digit=$((num % 10))
reversed=$((reversed * 10 + digit))
num=$((num / 10))
done
echo "Reversed number is $reversed."

OUTPUT:

RESULT:
Thus the shell script program to reverse a given number is compiled and then verified the output.

D) SWAP TWO NUMBERS


AIM:
To write a shell script program to execute swapping of two numbers.

ALGORITHM:
1. Read two numbers.
2. Store the first number in a temporary variable.
3. Assign the second number to the first number.
4. Assign the value from the temporary variable to the second number.
5. Output the swapped numbers.
6. Ensure the numbers are valid; otherwise, indicate an error.

SOURCE CODE :
#!/bin/bash
read -p "Enter first number: " a
read -p "Enter second number: " b
temp=$a
a=$b
b=$temp
echo "After swapping: First number is $a and Second number is $b."

OUTPUT:
RESULT:
Thus the shell script program for swapping of two numbers is executed successfully.
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:05 SHELL SCRIPT EXAMPLES – III Date: 08-04-2024

A) LARGEST AND SMALLEST IN AN ARRAY


AIM:
To write a shell script program to find smallest and largest element in an array.

ALGORITHM:
1. Read the array elements.
2. Initialize the first element as both the smallest and largest.
3. Traverse each element of the array:
4. Update the smallest if the current element is smaller.
5. Update the largest if the current element is larger.
6. Output the smallest and largest elements.
7. Ensure the array is non-empty; otherwise, indicate an error.

SOURCE CODE :
read -p "Enter number of elements: " n
echo "Enter the elements: "
for ((i=0; i<n; i++))
do
read arr[i]
done
min=${arr[0]}
max=${arr[0]}
for ((i=1; i<n; i++))
do
if [ ${arr[i]} -lt $min ]; then
min=${arr[i]}
fi
if [ ${arr[i]} -gt $max ]; then
max=${arr[i]}
fi
done
echo "Smallest element is $min."
echo "Largest element is $max."
OUTPUT:

RESULT:
Thus the shell script program to find smallest and largest element is compiled and verified the
output.
B) AREA AND CIRCUMFERENCE OF A CIRCLE
AIM:
To write a shell script program to find area and circumference of a circle.

ALGORITHM:
1. Read the radius of the circle from the user.
2. Define the value of π (pi) as 3.14159.
3. Calculate the area of the circle using the formula area=π×radius2\text{area} = \pi \times \
text{radius}^2area=π×radius2.
4. Calculate the circumference of the circle using the formula circumference=2×π×radius\
text{circumference} = 2 \times \pi \times \text{radius}circumference=2×π×radius.
5. Output the calculated area of the circle.
6. Output the calculated circumference of the circle.

SOURCE CODE :
#!/bin/bash
read -p "Enter the radius of the circle: " r
pi=3.14159
area=$(echo "scale=2; $pi * $r * $r" | bc)
circumference=$(echo "scale=2; 2 * $pi * $r" | bc)
echo "Area of the circle is $area."
echo "Circumference of the circle is $circumference."

OUTPUT:

RESULT:
Thus the shell script program to find area and circumference is executed successfully and
output is verified.
C) RANK LIST OF STUDENTS
AIM:
To write a shell script program to print rank list of students.

ALGORITHM:
1. Read the number of students from the user.
2. For each student, read their name and score and store them in an array with the score first.
3. Use nested loops to sort the array in descending order based on scores.
4. In the outer loop, compare each score with the scores of subsequent students.
5. Swap elements if a higher score is found, ensuring the list is sorted properly.
6. After sorting, display the ranked list of students.

SOURCE CODE :
#!/bin/bash
read -p "Enter number of students: " n
echo "Enter student names followed by their scores:"
for ((i=0; i<n; i++))
do
read name score
students[i]="$score $name"
done
echo "Rank list of students:"
for ((i=0; i<n; i++))
do
for ((j=i+1; j<n; j++))
do
if [ ${students[i]%% *} -lt ${students[j]%% *} ]; then
temp=${students[i]}
students[i]=${students[j]}
students[j]=$temp
fi
done
done
for student in "${students[@]}"
do
echo "$student"
done
OUTPUT:

RESULT:
Thus the shell script program to print a rank list is executed successfully and output is verified.
D) VOWEL OR NOT
AIM:
To write a shell script program to check for vowel or not.

ALGORITHM:
1. Read a character from the user.
2. Compare the character against the list of vowels (both uppercase and lowercase).
3. If the character matches any vowel in the list, recognize it as a vowel.
4. If the character does not match any vowel, recognize it as not a vowel.
5. Display a message indicating whether the character is a vowel or not.
Ensure the input is a single character; otherwise, handle invalid input.

SOURCE CODE :
#!/bin/bash
read -p "Enter a character: " char
case $char in
[AEIOUaeiou])
echo "$char is a vowel."
;;
*)
echo "$char is not a vowel."
;;
esac

OUTPUT:

RESULT:
Thus the shell script program to check for vowel or not is successfully executed.
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:05
Expt.No:06 SHELL
SHELL
SCRIPT
SCRIPT
EXAMPLES
BASICS - IV Date:Date:
16-04-2024
14-3-24

A) SIMPLE INTEREST
AIM:
To execute shell script program for calculating simple interest in linux operating system.

ALGORITHM:
1. Ask the user to provide the principal amount (P).
2. Ask the user to input the annual interest rate (r), given as a percentage.
3. Ask the user to enter the time period (t) in years.
4. Convert the annual interest rate (r) from a percentage to a decimal (r_decimal = r / 100).
5. Calculate the simple interest (SI) using the formula: SI = P * r_decimal * t.
6. Display the computed simple interest (SI) to the user.

SOURCE CODE:
echo "Enter the principal amount (P):"
read P
echo "Enter the annual interest rate (r) in percentage:"
read r
echo "Enter the time period (t) in years:"
read t
r_decimal=$(echo "scale=4; $r / 100" | bc)
SI=$(echo "scale=2; $P * $r_decimal * $t" | bc)
echo "Simple Interest (SI) is: $SI"

OUTPUT:

RESULT:
Thus the shell script program to calculate simple interest is compiled and then verified the output.
B) COUNT ODD/EVEN NUMBERS IN AN ARRAY
AIM:
To execute shell script program for counting odd and even numbers in an array in linux operating
system.

ALGORITHM:
1. Start with two counters, odd_count and even_count, both initialized to zero.
2. Iterate through each number in the array.
3. Check if the current number is even (number % 2 == 0).
4. If true, increment the even_count.
5. If false, increment the odd_count.
6. After looping through all numbers, even_count will hold the count of even numbers, and odd_count
will hold the count of odd numbers in the array.

SOURCE CODE:
echo "Enter numbers separated by spaces:"
read -a array
odd_count=0
even_count=0
for num in "${array[@]}"
do
# Check if number is even or odd
if (( num % 2 == 0 )); then
(( even_count++ ))
else
(( odd_count++ ))
fi
done
echo "Odd numbers count: $odd_count"
echo "Even numbers count: $even_count"

OUTPUT:

RESULT:
Thus the shell script program to count odd/even numbers in an array is successfully executed.
C) REMOVE VOWELS FROM THE STRING
AIM:
To execute shell script program for removing vowels from the string in linux operating system.

ALGORITHM:

1. Initialize an empty string to store the result (result_string).


2. Iterate through each character in the original string.
3. Check if the character is a vowel (either 'a', 'e', 'i', 'o', 'u' or their uppercase variants).
4. If the character is not a vowel, append it to result_string.
5. Continue this process for every character in the original string.
6. After processing all characters, result_string will contain the original string with all vowels
removed.

SOURCE CODE:
remove_vowels() {
input="$1"
result=$(echo "$input" | tr -d 'aeiouAEIOU')
echo "$result"
}
echo "Enter a string:"
read input_string
output_string=$(remove_vowels "$input_string")
echo "String without vowels:"
echo "$output_string"

OUTPUT:

RESULT:
Thus the shell script program to remove vowels from the string is compiled and then verified the
output.
D) CONVERTING CELSIUS TO FAHRENHEIT
AIM:
To execute shell script program for converting celsius to fahrenheit in linux operating system.

ALGORITHM:

1. Multiply the celsius temperature (celsius_temp) by 9/5.


2. Add 32 to the result obtained from step 1.
3. Store the result in a variable (fahrenheit_temp).
4. Display or use fahrenheit_temp as needed.
5. Example: If celsius_temp is 20 degrees Celsius,
6. The conversion would be: 20×95+32=6820 \times \frac{9}{5} + 32 = 6820×59+32=68 degrees
Fahrenheit

SOURCE CODE:
celsius_to_fahrenheit() {
celsius=$1
fahrenheit=$(echo "scale=2; ($celsius * 9/5) + 32" | bc)
echo "$fahrenheit"
}
echo "Enter temperature in Celsius:"
read celsius_input
fahrenheit_output=$(celsius_to_fahrenheit $celsius_input)
echo "$celsius_input degrees Celsius is equal to $fahrenheit_output degrees Fahrenheit."

OUTPUT:

RESULT:
Thus the shell script program for converting celsius to fahrenheit is successfully executed.
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:07 SHELL SCRIPT- FILE OPERATIONS I Date: 23-04-2024

A) READ A FOLDER NAME AND COUNT THE NO.OF FILES AND SUB
DIRECTORIES IN IT
AIM:
To execute shell script program for reading a folder name and count the no of files and sub
directories in it using linux operating system.

ALGORITHM:
1. Initialize file_count and dir_count to zero.
2. Loop through each item (item) in folder_path.
3. If item is a file, increment file_count.
4. If item is a directory, increment dir_count.
5. Display file_count as the number of files.
6. Display dir_count as the number of subdirectories.

SOURCE CODE:
count_files_and_dirs() {
folder="$1"
# Initialize counters
file_count=0
dir_count=0
# Iterate over items in the directory
for item in "$folder"/*; do
if [ -f "$item" ]; then
# Increment file count if it's a file
file_count=$((file_count + 1))
elif [ -d "$item" ]; then
dir_count=$((dir_count + 1))
fi
done
echo "Number of files in '$folder': $file_count"
echo "Number of subdirectories in '$folder': $dir_count"
}
echo "Enter the folder path:"
read folder_name
count_files_and_dirs "$folder_name"
OUTPUT:

RESULT:
Thus the shell script program for reading a folder name and count the no of files and sub
directories is compiled and then verified the output.
B) COUNT THE OCCURRENCE OF THE KEYWORD IN THE SPECIFIED FILE
AIM:
To execute shell script program for counting the no of occurrence of the keyword in the specified
file using linux operating system.

ALGORITHM:
1. Open the text file in read mode.
2. Initialize a counter (count) to zero.
3. Read each line from the file until the end:
4. Split the line into words.
5. For each word in the line, check if it matches the keyword.
6. If a match is found, increment the count by 1.
7. Close the file after all lines have been processed.
8. Display the total count (count) of occurrences of the keyword in the text file.
9. Optionally, handle cases where the keyword may have different capitalizations or variations by
converting both the keyword and the words read to a consistent case (e.g., lowercase) before
comparison.

SOURCE CODE:
count_occurrences() {
file="$1"
keyword="$2"
# Use grep to find lines containing the keyword and count occurrences
count=$(grep -o "\b$keyword\b" "$file" | wc -l)
echo "Occurrences of '$keyword' in '$file': $count"
}
echo "Enter the filename (including path if necessary):"
read filename
echo "Enter the keyword to search:”
read keyword
count_occurrences "$filename" "$keyword"
OUTPUT:

RESULT:
Thus the shell script program for counting the no of occurrence of the keyword in the specified file
is successfully executed to verify the output.
C) CHANGE PERMISSIONS – DISPLAY NEW PERMISSION
AIM:
To execute shell script program for updating new permissions and displaying it in linux operating
system

ALGORITHM:
1. Prompt the user to enter the name of the file.
2. Check if the file exists:
3. If the file does not exist, inform the user and exit.
4. Display the current permissions of the file:
5. Use ls -l to list the file details and extract the permission string.
6. Ask the user to input new permissions:
7. Prompt the user to enter the new permissions in the format like rwxr-x---.
8. Change the permissions of the file:
9. Use the chmod command to set the new permissions on the file.
10. Confirm and display the updated permissions:
11. Use ls -l again to verify and display the updated permissions of the file.

SOURCE CODE:
echo -n "Enter the file name: "
read file_name
if [ ! -f "$file_name" ]; then
echo "File not found."
exit 1
fi
current_permissions=$(ls -l "$file_name" | cut -d ' ' -f 1)
echo "Current permissions for $file_name: $current_permissions"
echo -n "Enter new permissions (e.g., rwxr-x---): "
read new_permissions
chmod "$new_permissions" "$file_name"
echo "Permissions changed successfully."
new_permissions=$(ls -l "$file_name" | cut -d ' ' -f 1)
echo "New permissions for $file_name: $new_permissions"
OUTPUT:

RESULT:
Thus the shell script program for updating new permissions and displaying it is successfully
executed.
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:08 SHELL SCRIPT- FILE OPERATIONS II Date: 23-04-2024

A) COUNTING NO OF ARTICLES IN A FILE


AIM:
To execute file related shell script program for counting the number of articles in a file in linux
operating system.

ALGORITHM:
1. Ask the user for the name of the file.
2. Check if the file exists.
3. Set a counter to zero.
4. Read the file one line at a time.
5. For each line, count how many times the words "a", "an", and "the" appear.
6. Add these counts to the counter and, after finishing reading the file, print the total count.

SOURCE CODE:
if [ $# -ne 1 ]; then
echo "Usage: $0 <filename>"
exit 1
fi
filename=$1
if [ ! -f "$filename" ]; then
echo "Error: File '$filename' not found."
exit 1
fi
count_a=$(grep -o -i '\ba\b' "$filename" | wc -l)
count_an=$(grep -o -i '\ban\b' "$filename" | wc -l)
count_the=$(grep -o -i '\bthe\b' "$filename" | wc -l)
total_count=$((count_a + count_an + count_the))
echo "Number of articles (a, an, the) in '$filename': $total_count"

OUTPUT:

RESULT:
Thus the shell script program for counting the number of articles in a file is successfully compiled
to verify the output.
B) DELETE ALL LINES CONTAINING A SPECIFIED WORD IN A GIVEN FILE
AIM:
To execute file related shell script program for deleting all lines containing a specified word in a
given file in linux operating system.

ALGORITHM:

1. Ask the user for the name of the file.


2. Ask the user for the word to delete.
3. Check if the file exists.
4. Create a temporary file.
5. Copy all lines from the original file to the temporary file, except the lines containing the specified
word.
6. Replace the original file with the temporary file and confirm the deletion to the user.

SOURCE CODE:
echo -n "Enter the file name: "
read file_name
if [ ! -f "$file_name" ]; then
echo "File not found."
exit 1
fi
current_permissions=$(ls -l "$file_name" | cut -d ' ' -f 1)
echo "Current permissions for $file_name: $current_permissions"
echo -n "Enter new permissions (e.g., rwxr-x---): "
read new_permissions
chmod "$new_permissions" "$file_name"
echo "Permissions changed successfully."
new_permissions=$(ls -l "$file_name" | cut -d ' ' -f 1)
echo "New permissions for $file_name: $new_permissions"

OUTPUT:

RESULT:
Thus the shell script program for deleting all lines containing a specified word in a given file is
successfully executed and output is verified.
C) READ FILE NAME AND PRINT THE NO OF CHARACTERS, WORDS
AND LINES IN IT..
AIM:
To execute file related shell script program for printing no of character, words and lines in the file
using linux operating system.

ALGORITHM:
1. Prompt the user to enter the name of the file.
2. Read the file name input by the user and store it in a variable called filename.
3. Check if a file with the name filename exists.
4. If the file does not exist, display an error message saying the file was not found.
5. Exit the script to stop further execution.
6. If the file exists, count the number of characters in the file using the wc -m command and store the
result in char_count.
7. Count the number of words in the file using the wc -w command and store the result in
word_count.
8. Count the number of lines in the file using the wc -l command and store the result in line_count.
9. Display the number of characters in the file by printing the value of char_count.
10. Display the number of words in the file by printing the value of word_count.
11. Display the number of lines in the file by printing the value of line_count.

SOURCE CODE:
echo "Enter the name of the file:"
read filename
if [ ! -f "$filename" ]; then
echo "Error: File '$filename' not found."
exit 1
fi
char_count=$(wc -m < "$filename")
word_count=$(wc -w < "$filename")
line_count=$(wc -l < "$filename")
echo "Number of characters in '$filename': $char_count"
echo "Number of words in '$filename': $word_count"
echo "Number of lines in '$filename': $line_count"
OUTPUT:

RESULT:
Thus the shell script program for printing no of character, words and lines in the file is
successfully executed.
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:09 SHELL SCRIPT- FILE OPERATIONS III Date: 30-04-2024

A) TO STIMULATE MV COMMAND USING CP


AIM:
To execute fie related shell script program in linux operating system.

ALGORITHM:
1. Create a function definition to simulate_mv function is defined to take two arguments (source and
destination).
2. Argument check if exactly two arguments are provided. If not, it prints an error message and
returns.
3. Source existence check if it verifies if the source exists (-e "$source").
4. Copy operation if it performs the copy operation using cp -R (recursive copy).
5. Copy status check if the exit status of the cp command ($?). If successful ($copy_status -eq 0), it
6. proceeds to remove the source.
7. Remove operation the source using rm -rf.
8. Remove status check the exit status of the rm command. If removal fails, it prints a warning
message.
9. Success message if both copy and remove operations succeed, it prints a success message.
10. Error handling if any operation fails, it prints an appropriate error message.

SOURCE CODE:
simulate_mv()
{
if [ $# -ne 2 ]; then
echo "Usage: $0 <source> <destination>"
return 1
fi
source="$1"
destination="$2"
if [ ! -e "$source" ]; then
echo "Error: Source '$source' does not exist."
return 1
fi
cp -R "$source" "$destination"
copy_status=$?
if [ $copy_status -eq 0 ]; then
# Remove source if copy was successful
rm -rf "$source"
remove_status=$?
if [ $remove_status -ne 0 ]; then
echo "Warning: Failed to remove source '$source' after copy operation."
fi
echo "Moved '$source' to '$destination'."
return 0
else
echo "Error: Failed to copy '$source' to '$destination'."
return 1
fi
}

OUTPUT:

RESULT:
Thus the shell script program to stimulate mv command using cp is successfully executed to verify
the output.

B) OCCURRENCE OF A GIVEN WORD AND REPLACING WITH A NEW


WORD

AIM:
To execute shell script program to replace a new word in a given occurrence in linux operating
system.

ALGORITHM:
1. Create a function to find and replace word A with word B at odd occurrences.
2. Use sed to find and replace wordA with wordB at odd occurrences.
3. Here, we assume words are separated by whitespace boundaries (\b).
4. Checks if exactly three arguments are provided (filename, wordA, wordB).
5. Assigns these arguments to variables file, wordA, and wordB.
6. Verifies if the specified file exists (-f "$file").

SOURCE CODE:
#!/bin/bash
replace_odd_occurrences() {
if [ $# -ne 3 ]; then
echo "Usage: $0 <file> <wordA> <wordB>"
return 1
fi
file="$1"
wordA="$2"
wordB="$3"

# Check if file exists


if [ ! -f "$file" ]; then
echo "Error: File '$file' not found."
return 1
fi
sed -i '' -E ':loop /\<'"$wordA"'\>/!b; s//'"$wordB"'/; $b; N; b loop' "$file"
echo "Replacement of '$wordA' with '$wordB' at odd occurrences completed in '$file'."
OUTPUT:
RESULT:
Thus the shell script program to replace a new word in a given occurrence is compiled to verify
the
output.

C) SHELL SCRIPT THAT ACCEPTS TWO FILE NAMES AS ARGUMENTS


CHECKS IF THE PERMISSIONS FOR THESE FILES ARE IDENTICAL AND
IF THE PERMISSIONS ARE IDENTICAL OUTPUT COMMON
PERMISSIONS, OTHERWISE OUTPUT EACH FILE NAME FOLLOWED BY
ITS PERMISSIONS.

AIM:
To execute shell script that accepts two file names as arguments checks if the permissions for these
files are identical and if the permissions are identical output common permissions, otherwise output
each file name followed by its permissions in linux operating system.

ALGORITHM:
1. Create a function definition (compare_permissions) and Checks if exactly two arguments are
provided
2. (filename1 and filename2).
3. Assigns these arguments to variables file1 and file2 and verifies if both files exist (-f "$file1" and -f
"$file2").
4. Create astat Command as stat -c "%a" "$file1" retrieves the octal representation of permissions for
file1.
5. Similarly, stat -c "%a" "$file2" retrieves the octal representation of permissions for file2.
6. Compares the permissions (perm1 and perm2) using [ "$perm1" = "$perm2" ].
7. If permissions are identical, it outputs the common permissions.
8. If permissions differ, it outputs each filename followed by its respective permissions.

SOURCE CODE:
if [ "$#" -ne 2 ]; then
echo "Usage: $0 file1 file2"
exit 1
fi
file1=$1
file2=$2
if [ ! -e "$file1" ]; then
echo "File $file1 does not exist."
exit 1
fi
if [ ! -e "$file2" ]; then
echo "File $file2 does not exist."
exit 1
fi
perm1=$(stat -c "%A" "$file1")
perm2=$(stat -c "%A" "$file2")
if [ "$perm1" == "$perm2" ]; then
echo "The permissions are identical: $perm1"
else
echo "$file1: $perm1"
echo "$file2: $perm2"
fi

OUTPUT:
RESULT:
Thus the shell script to accepts two file names as arguments is successfully executed.

D) SHELL SCRIPT THAT ACCEPT A FILE NAME AND STARTING AND


ENDING LINE NUMBERS AS ARGUMENTS AND DISPLAY ALL THE LINES
BETWEEN GIVEN LINE NUMBERS.

AIM:
To execute shell script that accept a file name and starting and ending line numbers as arguments
and display all the lines between given line numbers.in linux operating system.

ALGORITHM:
1. Check argument count and verify that the script is called with exactly three arguments (filename,
start_line, end_line).
2. Assign arguments as the first argument ($1) to filename, the second argument ($2) to start_line,
and the third argument ($3) to end_line.
3. Check if the file specified by filename exists using -f "$filename".
4. If the file doesn't exist, print an error message and exit.
5. Verify that both start_line and end_line are valid integers.
6. If either start_line or end_line is not a valid integer, print an error message and exit.

SOURCE CODE:
#!/bin/bash
# Function to display lines between given line numbers in a file
display_lines_between() {
if [ $# -ne 3 ]; then
echo "Usage: $0 <filename> <start_line> <end_line>"
return 1
fi
filename="$1"
start_line="$2"
end_line="$3"
if [ ! -f "$filename" ]; then
echo "Error: File '$filename' not found."
return 1
fi
if ! [[ "$start_line" =~ ^[0-9]+$ ]]; then
echo "Error: Invalid start line number '$start_line'."
return 1
fi
if ! [[ "$end_line" =~ ^[0-9]+$ ]]; then
echo "Error: Invalid end line number '$end_line'."
retur
fi
sed -n "${start_line},${end_line}p" "$filename"

OUTPUT:
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:10 SHELL SCRIPT-DIRECTORIES Date: 09-05-2024

RESULT:
Thus the shell script that accept a file name and starting and ending line numbers as arguments
and display all the lines between given line numbers is successfully executed.

A) SHELL SCRIPT THAT TAKES A COMMAND LINE ARGUMENT AND


REPORTS ON WHETHER IT IS DIRECTORY, A FILE OR SOMETHING
ELSE.
AIM:
To execute shell script that takes a command line argument and reports on whether it is directory, a
file or something else in linux operating system.

ALGORITHM:
1. Create a file in gedit as “fo_4.sh”.
2. Inside the text editor, start the shell script program.
3. Check if the user provided an argument.
4. Check if the argument is the directory.
5. Check if the argument is a regular file.
6. Use if else condition if it’s neither a directory nor a regular file.
7. The program is displayed using “chmod” and “./fo_4.sh” command.

SOURCE CODE:
if [ $# -ne 1 ]; then
echo "Usage: $0 <file_or_directory_path>"
exit 1
fi
path=$1
if [ ! -e "$path" ]; then
echo "Error: $path does not exist."
exit 1
fi
if [ -d "$path" ]; then
echo "$path is a directory."
elif [ -f "$path" ]; then
echo "$path is a regular file."
else
echo "$path is something else (e.g., a symbolic link, socket, etc.)."
fi
OUTPUT:
RESULT:
Thus shell script that takes a command line argument and reports on whether it is directory, a file or
something else is successfully executed to verify the output.

B) SHELL SCRIPT TO DO ALPHABETICAL SORTING

AIM:
To execute shell script to do alphabetical sorting in linux operating system.

ALGORITHM:
1. Create a file in gedit as “fo_4.sh”.
2. Check if [ $# -ne 1 ]; then ... checks if exactly one argument (the file to sort) is provided
running the script. If not, it prints usage information and exits with status 1.
3. Store the filename=$1 stores the first argument (the filename) in the variable filename.
4. File existence check: if [ ! -f "$filename" ]; then ... checks if the file specified by
$filename exists and is a regular file (-f flag). If it doesn't exist or is not a regular file, it
prints an error message and exits with status 1.
5. Sorting: sort "$filename" is the command that sorts the contents of the file
alphabetically. It reads lines from the file specified by $filename, sorts them
alphabetically, and prints the sorted lines to the standard output.
6. The program is displayed using “chmod” and “./fo_4.sh” command.

SOURCE CODE:
if [ $# -ne 1 ]; then
echo "Usage: $0 <file_to_sort>"
exit 1
fi
filename=$1
if [ ! -f "$filename" ]; then
echo "Error: $filename does not exist or is not a regular file."
exit 1
fi
sort "$filename"
fi
OUTPUT:
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:11 LINUX COMMANDS IN C Date: 09-05-2024

RESULT:
Thus shell script to do alphabetical sorting is successfully executed to verify the output.

A) C PROGRAM TO SIMULATE GREP COMMAND


AIM:
To execute C program to simulate grep command in linux operating system.

ALGORITHM:
1. Include Headers of include <stdio.h> for standard input/output functions, <stdlib.h> for exit()
function,and <string.h> for string manipulation functions like strstr().
2. Create a Constants MAX_LINE_LENGTH defines the maximum length of a line we expect to
handle.
3. Create a grep Function as The grep() function takes a FILE* (file pointer) and a const char*
(pattern)
4. as arguments. It reads each line from the file using fgets() and checks if the pattern exists in the
line using strstr().
5. If the pattern is found (strstr() returns a non-null pointer), it prints the line using printf().
6. Create a main function and checks if exactly two arguments (pattern and filename) are provided.
If not,it prints the usage message and exits.
7. Retrieves the pattern and filename from command-line arguments (argv[1] and argv[2]).
8. Opens the file specified by filename in read mode ("r"). If the file cannot be opened, it prints an
error message using perror() and exits.
9. Calls the grep() function to search for the pattern in the opened file.
10. Closes the file with fclose() before exiting.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 1024
void grep(FILE *file, const char *pattern) {
char line[MAX_LINE_LENGTH];
while (fgets(line, sizeof(line), file)) {
if (strstr(line, pattern) != NULL) {
printf("%s", line);
}
}
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <pattern> <filename>\n", argv[0]);
return 1;
}

const char *pattern = argv[1];


const char *filename = argv[2];
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
grep(file, pattern);
fclose(file);
return 0;
}

OUTPUT:
RESULT:
Thus the C program to simulate grep command is successfully executed and output is verified.

B) C PROGRAM SIMULATE LS COMMAND USING SYSTEM CALLS

AIM:
To execute C program to simulate ls command using system calls in linux operating system.

ALGORITHM:
1. Include Headers as include <stdio.h> for standard input/output functions, <stdlib.h> for exit()
function, and <dirent.h> for directory manipulation functions.
2. Create a main function and Checks the number of command-line arguments (argc). If no
directory path is provided (argc == 1), it defaults to listing the current directory (dir_path =
"."). If a directory path is provided (argc == 2), it uses that as the directory to list.
3. Prints a usage message and exits if more than one argument is provided (argc > 2). Open
Directory and Uses opendir(dir_path) to open the directory specified by dir_path. If it
fails(returns NULL), it prints an error message using perror() and exits.
4. Read Directory Entries Uses a loop with readdir(dir) to read each entry from the directory
pointed to by dir. It prints the name of each entry (entry->d_name) using printf().
5. Close Directory and Uses closedir(dir) to close the directory once all entries have been read.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
void list_files(const char *path) {
struct dirent *entry;
DIR *dp = opendir(path);
if (dp == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dp))) {
printf("%s\n", entry->d_name);
}
closedir(dp);
}
int main(int argc, char *argv[]) {
const char *path = "."; // Default to current directory

if (argc > 1) {
path = argv[1];
}
list_files(path);
}

OUTPUT:
RESULT:
Thus the C program to simulate ls command using system calls is successfully executed .
C) C PROGRAM TO SIMULATE RMDIR COMMAND
AIM:
To write a C program to simulate rmdir command.

ALGORITHM:
1. Parse command-line arguments.
2. Check if exactly one argument (directory name) is provided.
3. If not, display usage information and exit.
4. Attempt to remove the directory using rmdir().
5. If rmdir() fails, print an error message and exit.
6. If successful, print confirmation message.
7. Check if the directory was indeed removed by attempting to access it.
8. If the directory still exists, print an error message and exit.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
if (rmdir(argv[1]) == -1) {
perror("rmdir failed");
return 1;
}
printf("Directory %s removed successfully.\n", argv[1]);
return 0;
}

OUTPUT:

RESULT:
Thus the C program to simulate rmdir command is successfully executed to verify the output.
\
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:12 PROCESS RELATED OPERATIONS Date: 16-05-2024

A) C PROGRAM TO MAKE THE PARENT PROCESS WAIT TILL THE


COMPLETION OF EXECUTION OF CHILD PROCESS
AIM:
To write a C program to make the parent process wait till the completion of execution of child
process.

ALGORITHM:
1. Declare a data type pid_t to access getpid(), pid.
2. Use fork() to create a new process.
3. Check if fork() returns a negative value, indicating failure.
4. If in the child process, print child-specific information including its PID and parent's PID.
5. If in the parent process, use wait() to wait for the child process to complete.
6. After the child process completes, print parent-specific information including its PID.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();

if (pid < 0) {
fprintf(stderr, "Fork Failed\n");
return 1;
} else if (pid == 0) {
printf("Child process\n");
printf("Child PID: %d\n", getpid());
printf("Parent PID: %d\n", getppid());
} else {
wait(NULL);
printf("Child process completed.\n");
printf("Parent PID: %d\n", getpid());
}
return 0;
}
OUTPUT:

RESULT:
Thus the C program to make the parent process wait till the completion of execution of child
process is successfully executed to verify the output.
B) PROGRAM TO SHOW THE PROCESS ID AND WHETHER IT IS PARENT OR
CHILD PROCESS
AIM:
To write a C program to make the parent process wait till the completion of execution of child
process.

ALGORITHM:
1. Declare a data type pid_t to access getpid().
2. Use fork() to create a new process.
3. Check if fork() returns a negative value, indicating failure.
4. If in the child process, print a message indicating it is the child process and display its PID.
5. If in the parent process, print a message indicating it is the parent process and display its PID.
6. Ensure the parent and child process print their respective messages.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid = fork();

if (pid < 0) {
fprintf(stderr, "Fork Failed\n");
return 1;
} else if (pid == 0) {
printf("Child Process\n");
printf("Child PID: %d\n", getpid());
} else {
printf("Parent Process\n");
printf("Parent PID: %d\n", getpid());
}
return 0;
}
OUTPUT:

RESULT:
Thus the C program to make the parent process wait till the completion of execution of child
process is successfully executed and output is verified.
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:13 SCHEDULING USING SYSTEM CALLS Date: 13-06-2024

A) C PROGRAM TO IMPLEMENT PRIORITY AND ROUND ROBIN


SCHEDULING USING SYSTEM CALLS
AIM:
To execute C program to implement priority and round robin scheduling using system calls in linux
operating system.

ALGORITHM:
1. Create and initialize a ProcessList to store processes and their priorities
2. Fork child processes using fork()and assign each process a random priority.
3. Sort the processes in the ProcessList based on their priorities in descending order.
4. Sequentially execute each process in the order of their priority and Use waitpid() to wait for each
process to finish execution.
5. After all processes have finished execution, clean up any remaining resources
6. Display the priority processes and round robin processes.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/types.h>
#define MAX_PROCESSES 10
#define TIME_SLICE 1 // Time slice for round robin scheduling in seconds
void priorityScheduling(pid_t pids[], int priorities[], int num_processes) {
// Sort processes by priority (in descending order)
for (int i = 0; i < num_processes - 1; i++) {
for (int j = 0; j < num_processes - i - 1; j++) {
if (priorities[j] < priorities[j + 1]) {
// Swap priorities
int temp_priority = priorities[j];
priorities[j] = priorities[j + 1];
priorities[j + 1] = temp_priority;

// Swap pids accordingly


pid_t temp_pid = pids[j];
pids[j] = pids[j + 1];
pids[j + 1] = temp_pid;
}
}
}
// Execute processes in priority order
for (int i = 0; i < num_processes; i++) {
printf("Executing process %d with priority %d\n", pids[i], priorities[i]);
waitpid(pids[i], NULL, 0);
printf("Process %d finished execution\n", pids[i]);
}
}
void roundRobinScheduling(pid_t pids[], int num_processes) {
int current_index = 0;
// Execute processes in round robin order
while (num_processes > 0) {
pid_t current_pid = pids[current_index];
printf("Executing process %d with time slice %d seconds\n", current_pid, TIME_SLICE);
kill(current_pid, SIGCONT); // Continue the process execution
sleep(TIME_SLICE); // Allow the process to run for the time slice
kill(current_pid, SIGSTOP); // Stop the process execution
if (waitpid(current_pid, NULL, WNOHANG) == current_pid) {
printf("Process %d finished execution\n", current_pid);
// Remove finished process from the array
for (int i = current_index; i < num_processes - 1; i++) {
pids[i] = pids[i + 1];
}
num_processes--;
} else {
current_index = (current_index + 1) % num_processes;
}
}
}
int main() {
pid_t pids[MAX_PROCESSES];
int priorities[MAX_PROCESSES];
// Create processes and assign random priorities
int num_processes = 5;
for (int i = 0; i < num_processes; i++) {
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
exit(1);
} else if (pid == 0) {
// Child process
printf("Child process %d created\n", getpid());
while (1) { // Simulate work
pause();
}
exit(0);
} else {
// Parent process
pids[i] = pid;
priorities[i] = rand() % 10; // Assign a random priority
}
}
// Priority Scheduling
printf("Priority Scheduling:\n");
priorityScheduling(pids, priorities, num_processes);
// Round Robin Scheduling
printf("Round Robin Scheduling:\n");
roundRobinScheduling(pids, num_processes);
return 0;
}
OUTPUT:

RESULT:
Thus the C program to implement priority and round robin scheduling using system calls is
successfully executed and output is verified.
B) C PROGRAM TO IMPLEMENT FIFO SCHEDULING USING SYSTEM CALLS

AIM:
To execute C program to implement FIFO Scheduling using system calls in linux operating system.

ALGORITHM:
1. Initialize a queue to hold processes and system call handler for process creation.
2. When a new process is created (using a system call like fork()), add it to the end of the queue.
3. Continuously check if the queue is not empty
4. Use a system call like exec() to load the process into memory and start its execution.
5. Ensure the process is properly cleaned up from the system resources
6. Repeat steps 3 to 5 until the queue is empty.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAX_PROCESSES 10
typedef struct {
int pid;
int burst_time;
} process;
void fifo_scheduling(process *proc, int n) {
for (int i = 0; i < n; i++) {
if (fork() == 0) {
// Child process
printf("Process %d is running for %d seconds\n", proc[i].pid, proc[i].burst_time);
sleep(proc[i].burst_time); // Simulate process execution
printf("Process %d has finished\n", proc[i].pid);
exit(0); // Child process exits
}
wait(NULL); // Parent process waits for the child to finish
}
}
int main() {
process proc[MAX_PROCESSES];
int n;
printf("Enter the number of processes (max %d): ", MAX_PROCESSES);
scanf("%d", &n);

if (n > MAX_PROCESSES) {
printf("Number of processes exceeds the maximum limit of %d.\n", MAX_PROCESSES);
return 1;
}

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


printf("Enter burst time for process %d: ", i + 1);
scanf("%d", &proc[i].burst_time);
proc[i].pid = i + 1;
}

fifo_scheduling(proc, n);
return 0;
}

OUTPUT:

RESULT:
Thus the C program to implement FIFO scheduling using system calls is successfully executed
and output is verified.
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:14 PROCESS SYNCHRONIZATION Date:13-06-2024

A) C PROGRAM TO IMPLEMENT READER / WRITER PROBLEM

AIM:
To execute C program to implement reader / writer problem in linux operating system.

ALGORITHM:
1. Initialize semaphores rw_mutex and mutex, and set read_count and shared_data to 0.
2. Read the number of readers and writers from the user.
3. Create reader and writer threads using pthread_create.
4. In the reader thread: wait on mutex semaphore, increment read_count. If it’s the first reader,
wait on rw_mutex to lock the shared resource, then post on mutex semaphore.
5. Print the shared data, simulate reading time, and then print a finished reading message.
6. Wait on mutex semaphore, decrement read_count. If it’s the last reader, post on rw_mutex to
unlock the shared resource, then post on mutex semaphore.
7. In the writer thread: wait on rw_mutex semaphore to lock the shared resource.
8. Write the writer’s ID to shared_data, simulate writing time, and then print a finished writing
message. Post on rw_mutex to unlock the shared resource.
9. Use pthread_join to wait for all reader and writer threads to finish.
10. Destroy the semaphores rw_mutex and mutex.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define MAX_READERS 10
#define MAX_WRITERS 10
sem_t rw_mutex; // Semaphore to control access to the shared resource
sem_t mutex; // Semaphore to control access to read_count
int read_count = 0; // Number of readers currently reading
int shared_data = 0; // Shared resource
void *reader(void *arg) {
int id = *(int *)arg;
free(arg);
sem_wait(&mutex);
read_count++;
if (read_count == 1) {
sem_wait(&rw_mutex);
}
sem_post(&mutex);
// Reading section
printf("Reader %d is reading the shared data: %d\n", id, shared_data);
sleep(rand() % 3 + 1); // Simulate reading time
printf("Reader %d has finished reading\n", id);
sem_wait(&mutex);
read_count--;
if (read_count == 0) {
sem_post(&rw_mutex); // Last reader unlocks the resource
}
sem_post(&mutex);
pthread_exit(NULL);
}
void *writer(void *arg) {
int id = *(int *)arg;
free(arg);
sem_wait(&rw_mutex); // Writer locks the resource
// Writing section
printf("Writer %d is writing to the shared data\n", id);
shared_data = id; // Write the writer's ID to shared data
sleep(rand() % 3 + 1); // Simulate writing time
printf("Writer %d has finished writing\n", id);
sem_post(&rw_mutex); // Writer unlocks the resource
pthread_exit(NULL);
}
int main() {
pthread_t readers[MAX_READERS], writers[MAX_WRITERS];
int num_readers, num_writers;
// Initialize semaphores
sem_init(&rw_mutex, 0, 1);
sem_init(&mutex, 0, 1);
printf("Enter the number of readers (max %d): ", MAX_READERS);
scanf("%d", &num_readers);
if (num_readers > MAX_READERS) {
printf("Number of readers exceeds the maximum limit of %d.\n", MAX_READERS);
return 1;
}
printf("Enter the number of writers (max %d): ", MAX_WRITERS);
scanf("%d", &num_writers);
if (num_writers > MAX_WRITERS) {
printf("Number of writers exceeds the maximum limit of %d.\n", MAX_WRITERS);
return 1;
}
for (int i = 0; i < num_readers; i++) {
int *id = malloc(sizeof(int));
*id = i + 1;
if (pthread_create(&readers[i], NULL, reader, id) != 0) {
perror("Failed to create reader thread");
return 1;
}
}
// Create writer threads
for (int i = 0; i < num_writers; i++) {
int *id = malloc(sizeof(int));
*id = i + 1;
if (pthread_create(&writers[i], NULL, writer, id) != 0) {
perror("Failed to create writer thread");
return 1;
}
}
// Wait for all reader threads to finish
for (int i = 0; i < num_readers; i++) {
pthread_join(readers[i], NULL);
}
// Wait for all writer threads to finish
for (int i = 0; i < num_writers; i++) {
pthread_join(writers[i], NULL);
}
// Destroy semaphores
sem_destroy(&rw_mutex);
sem_destroy(&mutex);
return 0;
}
OUTPUT:

RESULT:
Thus the C program to implement reader / writer problem is successfully executed and output is
verified.
B) C PROGRAM TO IMPLEMENT PRODUCER / CONSUMER PROBLEM

AIM:
To execute C program to implement producer / consumer problem in linux operating system.

ALGORITHM:
1) Start the program and declare necessary variables, including buffer, semaphores, and mutex.
2) Initialize semaphores empty (to track empty slots) and full (to track full slots) and the mutex.
3) Input the number of producers, consumers, and items to produce/consume.
4) Create producer threads:
a) Each producer waits for an empty slot using sem_wait(&empty).
b) Lock the buffer using pthread_mutex_lock(&mutex).
c) Produce an item, add it to the buffer, and update the buffer index.
d) Unlock the buffer using pthread_mutex_unlock(&mutex).
e) Signal that a new item is added using sem_post(&full).
5) Create consumer threads:
a) Each consumer waits for a full slot using sem_wait(&full).
b) Lock the buffer using pthread_mutex_lock(&mutex).
c) Consume an item from the buffer and update the buffer index.
d) Unlock the buffer using pthread_mutex_unlock(&mutex).
e) Signal that a slot is now empty using sem_post(&empty).
6) Wait for all producer threads to finish using pthread_join.
7) Wait for all consumer threads to finish using pthread_join.
8) Destroy semaphores and mutex, and end the program.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define MAX_PRODUCERS 10
#define MAX_CONSUMERS 10
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int in = 0; // Buffer index for the next produced item
int out = 0; // Buffer index for the next consumed item
int count = 0; // Number of items in the buffer
int items_to_produce; // Total items to produce
sem_t empty; // Semaphore to track empty slots in the buffer
sem_t full; // Semaphore to track full slots in the buffer
pthread_mutex_t mutex; // Mutex to protect buffer access
void *producer(void *arg) {
int id = *(int *)arg;
free(arg);
for (int i = 0; i < items_to_produce; i++) {
int item = rand() % 100; // Produce an item
sem_wait(&empty); // Wait for an empty slot
pthread_mutex_lock(&mutex); // Lock the buffer
buffer[in] = item;
printf("Producer %d produced item %d at index %d\n", id, item, in);
in = (in + 1) % BUFFER_SIZE;
count++;
pthread_mutex_unlock(&mutex); // Unlock the buffer
sem_post(&full); // Signal that a new item is added
sleep(rand() % 3 + 1); // Simulate production time
}
pthread_exit(NULL);
}
void *consumer(void *arg) {
int id = *(int *)arg;
free(arg);
for (int i = 0; i < items_to_produce; i++) {
sem_wait(&full); // Wait for a full slot
pthread_mutex_lock(&mutex); // Lock the buffer
int item = buffer[out];
printf("Consumer %d consumed item %d from index %d\n", id, item, out);
out = (out + 1) % BUFFER_SIZE;
count--;
pthread_mutex_unlock(&mutex); // Unlock the buffer
sem_post(&empty); // Signal that a slot is now empty
sleep(rand() % 3 + 1); // Simulate consumption time
}
pthread_exit(NULL);
}
int main() {
pthread_t producers[MAX_PRODUCERS], consumers[MAX_CONSUMERS];
int num_producers, num_consumers;
// Initialize semaphores and mutex
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
printf("Enter the number of producers (max %d): ", MAX_PRODUCERS);
scanf("%d", &num_producers);
if (num_producers > MAX_PRODUCERS) {
printf("Number of producers exceeds the maximum limit of %d.\n", MAX_PRODUCERS);
return 1;
}
printf("Enter the number of consumers (max %d): ", MAX_CONSUMERS);
scanf("%d", &num_consumers);
if (num_consumers > MAX_CONSUMERS) {
printf("Number of consumers exceeds the maximum limit of %d.\n", MAX_CONSUMERS);
return 1;
}
printf("Enter the number of items to produce and consume: ");
scanf("%d", &items_to_produce);
// Create producer threads
for (int i = 0; i < num_producers; i++) {
int *id = malloc(sizeof(int));
*id = i + 1;
if (pthread_create(&producers[i], NULL, producer, id) != 0) {
perror("Failed to create producer thread");
return 1;
}
}
// Create consumer threads
for (int i = 0; i < num_consumers; i++) {
int *id = malloc(sizeof(int));
*id = i + 1;
if (pthread_create(&consumers[i], NULL, consumer, id) != 0) {
perror("Failed to create consumer thread");
return 1;
}
}
// Wait for all producer threads to finish
for (int i = 0; i < num_producers; i++) {
pthread_join(producers[i], NULL);
}
// Wait for all consumer threads to finish
for (int i = 0; i < num_consumers; i++) {
pthread_join(consumers[i], NULL);
}
// Destroy semaphores and mutex
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
OUTPUT:

RESULT:
Thus the C program to implement producer / consumer is successfully compiled to verify the
output.
C) C PROGRAM TO IMPLEMENT DINING PHILOSOPHER PROBLEM

AIM:
To execute C program to implement dining philosopher problem in linux operating system.

ALGORITHM:
1. Initialize a semaphore waiter to control access to the table and mutexes for each chopstick.
2. Read the number of philosophers and iterations from the user.
3. Create philosopher threads using pthread_create.
4. In the philosopher thread: print a thinking message, then sleep to simulate thinking.
5. Wait on the waiter semaphore to get permission to sit at the table.
6. Lock the left and right chopstick mutexes to pick up chopsticks.
7. Print an eating message, then sleep to simulate eating.
8. Unlock the left and right chopstick mutexes to put down chopsticks and post on the waiter
semaphore.
9. Use pthread_join to wait for all philosopher threads to finish.
10. Destroy the semaphore waiter and mutexes for chopsticks.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define MAX_PHILOSOPHERS 10
pthread_mutex_t chopsticks[MAX_PHILOSOPHERS];
sem_t waiter; // Semaphore to control access to the table
int num_philosophers;
int num_iterations;
void *philosopher(void *arg) {
int id = *(int *)arg;
for (int i = 0; i < num_iterations; i++) {
printf("Philosopher %d is thinking\n", id);
sleep(rand() % 3); // Simulate thinking
sem_wait(&waiter); // Wait for permission to sit at the table
pthread_mutex_lock(&chopsticks[id]); // Pick up left chopstick
pthread_mutex_lock(&chopsticks[(id + 1) % num_philosophers]); // Pick up right chopstick
sem_post(&waiter); // Signal that the philosopher is seated
printf("Philosopher %d is eating\n", id);
sleep(rand() % 3); // Simulate eating
pthread_mutex_unlock(&chopsticks[id]); // Put down left chopstick
pthread_mutex_unlock(&chopsticks[(id + 1) % num_philosophers]); }
free(arg); // Free memory allocated for philosopher ID
pthread_exit(NULL);
}
int main() {
pthread_t philosophers[MAX_PHILOSOPHERS];
int *philosopher_ids[MAX_PHILOSOPHERS];
printf("Enter the number of philosophers (2 to %d): ", MAX_PHILOSOPHERS);
scanf("%d", &num_philosophers);
if (num_philosophers < 2 || num_philosophers > MAX_PHILOSOPHERS) {
printf("Number of philosophers must be between 2 and %d\n", MAX_PHILOSOPHERS);
return 1;
}
printf("Enter the number of iterations: ");
scanf("%d", &num_iterations);
if (num_iterations < 1) {
printf("Number of iterations must be positive\n");
return 1;
}
sem_init(&waiter, 0, num_philosophers - 1); // Initialize waiter semaphore
for (int i = 0; i < num_philosophers; i++) {
philosopher_ids[i] = malloc(sizeof(int));
if (philosopher_ids[i] == NULL) {
perror("Failed to allocate memory for philosopher ID");
return 1;
}
*philosopher_ids[i] = i;
pthread_mutex_init(&chopsticks[i], NULL); // Initialize mutexes for chopsticks
}
for (int i = 0; i < num_philosophers; i++) {
if (pthread_create(&philosophers[i], NULL, philosopher, philosopher_ids[i]) != 0) {
perror("Failed to create philosopher thread");
return 1;
}
}
for (int i = 0; i < num_philosophers; i++) {
pthread_join(philosophers[i], NULL);
}
sem_destroy(&waiter); // Destroy semaphore
for (int i = 0; i < num_philosophers; i++) {
pthread_mutex_destroy(&chopsticks[i]); // Destroy mutexes
free(philosopher_ids[i]); // Free memory allocated for philosopher IDs
}
return 0;
}
OUTPUT:

RESULT:
Thus the C program to implement dining philosopher problem is successfully executed.
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:15 DEALOCK HANDLING ALGORITHM Date: 24-06-2024

A) C PROGRAM TO IMPLEMENT BANKERS ALGORITHM

AIM:
To execute C program to implement bankers algorithm in linux operating system.

ALGORITHM:
1. Input the number of processes and resources.
2. Read available resources for each type.
3. Read maximum resources required by each process.
4. Read allocated resources for each process.
5. Calculate the need matrix by subtracting allocated resources from maximum resources.
6. Initialize the work vector to available resources and the finish vector to false for all processes.
7. Perform the safety check:
a. Loop through all processes to find an unprocessed one that can be allocated resources. for (int i
= 0; i < MAX_PROCESSES; i++) {
if (!finish[i] && !isDeadlocked(i, MAX_RESOURCES, request, work, allocation)) {
for (int j = 0; j < MAX_RESOURCES; j++) {
b. work[j] +=
c. If found, mark it as finished and add its allocated resources to the work vector.
d. If no such process is found in a pass, break the loop.
8. Check if all processes are finished to determine if the system is in a safe state.
9. Print the safe sequence if the system is safe, otherwise indicate that the system is not in a safe
state.

SOURCE CODE:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int MAX_PROCESSES, MAX_RESOURCES;
printf("Enter the number of processes: ");
scanf("%d", &MAX_PROCESSES);
printf("Enter the number of resources: ");
scanf("%d", &MAX_RESOURCES);
int available[MAX_RESOURCES];
int maximum[MAX_PROCESSES][MAX_RESOURCES];
int allocation[MAX_PROCESSES][MAX_RESOURCES];
int need[MAX_PROCESSES][MAX_RESOURCES];
int safetySequence[MAX_PROCESSES];
printf("Enter the Available resources: ");
for (int i = 0; i < MAX_RESOURCES; i++)
{
scanf("%d", &available[i]);
}
printf("Enter the Maximum resources for each process: \n");
for (int i = 0; i < MAX_PROCESSES; i++)
{
for (int j = 0; j < MAX_RESOURCES; j++)
{
scanf("%d", &maximum[i][j]);
}
}
printf("Enter the Allocation for each process: \n");
for (int i = 0; i < MAX_PROCESSES; i++)
{
for (int j = 0; j < MAX_RESOURCES; j++)
{
scanf("%d", &allocation[i][j]);
}
}
for (int i = 0; i < MAX_PROCESSES; i++)
{
for (int j = 0; j < MAX_RESOURCES; j++)
{
need[i][j] = maximum[i][j] - allocation[i][j];
}
}
bool finish[MAX_PROCESSES];
int work[MAX_RESOURCES];
for (int i = 0; i < MAX_RESOURCES; i++)
{
work[i] = available[i];
}
for (int i = 0; i < MAX_PROCESSES; i++)
{
finish[i] = false;
}
int count = 0;
while (count < MAX_PROCESSES) {
bool found = false;
for (int i = 0; i < MAX_PROCESSES; i++)
{
if (!finish[i])
{
bool canAllocate = true;
for (int j = 0; j < MAX_RESOURCES; j++)
{
if (need[i][j] > work[j])
{
canAllocate = false;
break;
}
}
if (canAllocate)
{
for (int k = 0; k < MAX_RESOURCES; k++)
{
work[k] += allocation[i][k];
}
finish[i] = true;
safetySequence[count++] = i;
found = true;
}
}
}
if (!found)
{
break;
}
}
bool safe = true;
for (int i = 0; i < MAX_PROCESSES; i++)
{
if (!finish[i])
{
safe = false;
break;
}
}
if (safe)
{
printf("The system is in a safe state.\n");
printf("Safe sequence is: ");
for (int i = 0; i < MAX_PROCESSES; i++)
{
printf("%d ", safetySequence[i]);
}
printf("\n");
}
else
{
printf("The system is not in a safe state.\n");
}

OUTPUT:

RESULT:
Thus the C program to implement bankers algorithm is successfully executed to verify the output.

B) C PROGRAM TO IMPLEMENT DEADLOCK AVOIDANCE ALGORITHM

AIM:
To execute C program to implement deadlock avoidance algorithm in linux operating system.

ALGORITHM:
1. Start the program and declare necessary variables.
2. Input the number of processes and resources.
3. Read available resources for each type.
4. Read the maximum need matrix for each process.
5. Read the allocation matrix for each process.
6. Calculate the need matrix by subtracting allocation from the maximum for each process.
7. Input the request vector and the process number making the request.
8. Check if the request can be granted by comparing it against the need and available resources.
9. If the request can be granted:
a. Temporarily allocate the requested resources.
b. Check if the system is in a safe state after allocation using the safety algorithm.
c. If safe, print that the request can be granted.
d. If not safe, revert the allocation and print that the request cannot be granted.
10. If the request cannot be granted initially, print that it cannot be granted.

SOURCE CODE:
#include <stdio.h>
#include <stdbool.h>
#define MAX_PROCESSES 10
#define MAX_RESOURCES 10
void printMatrix(int matrix[MAX_PROCESSES][MAX_RESOURCES], int processes, int
resources) {
for (int i = 0; i < processes; i++) {
for (int j = 0; j < resources; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
bool isSafeState(int processes, int resources, int available[], int max[MAX_PROCESSES]
[MAX_RESOURCES], int allocation[MAX_PROCESSES][MAX_RESOURCES], int
need[MAX_PROCESSES][MAX_RESOURCES]) {
int work[MAX_RESOURCES];
bool finish[MAX_PROCESSES] = { false };
for (int i = 0; i < resources; i++) {
work[i] = available[i];
}
while (true) {
bool found = false;
for (int i = 0; i < processes; i++) {
if (!finish[i]) {
bool canAllocate = true;
for (int j = 0; j < resources; j++) {
if (need[i][j] > work[j]) {
canAllocate = false;
break;
}
}
if (canAllocate) {
for (int j = 0; j < resources; j++) {
work[j] += allocation[i][j];
}
finish[i] = true;
found = true;
}
}
}
if (!found) {
break;
}
}
for (int i = 0; i < processes; i++) {
if (!finish[i]) {
return false;
}
}
return true;
}
int main() {
int processes, resources;
int available[MAX_RESOURCES];
int max[MAX_PROCESSES][MAX_RESOURCES];
int allocation[MAX_PROCESSES][MAX_RESOURCES];
int need[MAX_PROCESSES][MAX_RESOURCES];
int request[MAX_RESOURCES];
int requestProcess;
printf("Enter the number of processes: ");
scanf("%d", &processes);
printf("Enter the number of resources: ");
scanf("%d", &resources);
printf("Enter the Available resources:\n");
for (int i = 0; i < resources; i++) {
scanf("%d", &available[i]);
}
printf("Enter the maximum need matrix:\n");
for (int i = 0; i < processes; i++) {
for (int j = 0; j < resources; j++) {
scanf("%d", &max[i][j]);
}
}
printf("Enter the allocation matrix:\n");
for (int i = 0; i < processes; i++) {
for (int j = 0; j < resources; j++) {
scanf("%d", &allocation[i][j]);
}
}
for (int i = 0; i < processes; i++) {
for (int j = 0; j < resources; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
printf("Enter the process number making the request: ");
scanf("%d", &requestProcess);
printf("Enter the request vector:\n");
for (int i = 0; i < resources; i++) {
scanf("%d", &request[i]);
}
bool canGrant = true;
for (int i = 0; i < resources; i++) {
if (request[i] > need[requestProcess][i] || request[i] > available[i]) {
canGrant = false;
break;
}
}
if (canGrant) {
for (int i = 0; i < resources; i++) {
available[i] -= request[i];
allocation[requestProcess][i] += request[i];
need[requestProcess][i] -= request[i];
}
if (isSafeState(processes, resources, available, max, allocation, need)) {
printf("\nRequest can be granted. \nThe system remains in a safe state.\n");
} else {
printf("Request cannot be granted. \nThe system would enter an unsafe state.\n");

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


available[i] += request[i];
allocation[requestProcess][i] -= request[i];
need[requestProcess][i] += request[i];
}
}
} else {
printf("Request cannot be granted. \nEither it exceeds the process's maximum need or the
available resources.\n");
}
return 0;
}

OUTPUT:

RESULT:
Thus the C program to implement deadlock avoidance algorithm is successfully executed to verify
the output.

C) C PROGRAM TO IMPLEMENT DEADLOCK DETECTION AND RESOLVING


ALGORITHM

AIM:
To execute C program to implement deadlock detection and resolving algorithm in linux operating
system.

ALGORITHM:
1. Input the number of processes and resources.
2. Read available resources for each type.
3. Read allocated resources for each process.
4. Read requested resources for each process.
5. Initialize the work vector to available resources and the finish vector to false for all processes.
6. For each process, if it is not finished and it is not deadlocked, mark it as finished and add its
allocated resources to the work vector.
7. For each process that is still not finished, mark it as deadlocked, release its resources, and update
the vectors.
8. Check if the system is still in a deadlocked state after resolving.
9. Print the system's state (deadlocked or not) after resolving.

SOURCE CODE:
#include <stdio.h>
#include <stdbool.h>
bool isDeadlocked(int process, int MAX_RESOURCES, int request[][MAX_RESOURCES], int
work[], int allocation[][MAX_RESOURCES]);
int main() {
int MAX_PROCESSES, MAX_RESOURCES;
printf("Enter the number of processes: ");
scanf("%d", &MAX_PROCESSES);
printf("Enter the number of resources: ");
scanf("%d", &MAX_RESOURCES);
int available[MAX_RESOURCES];
int allocation[MAX_PROCESSES][MAX_RESOURCES];
int request[MAX_PROCESSES][MAX_RESOURCES];
printf("Enter the Available resources: ");
for (int i = 0; i < MAX_RESOURCES; i++) {
scanf("%d", &available[i]);
}
printf("Enter the Allocation for each process: \n");
for (int i = 0; i < MAX_PROCESSES; i++) {
for (int j = 0; j < MAX_RESOURCES; j++) {
scanf("%d", &allocation[i][j]);
}
}
printf("Enter the Request for each process: \n");
for (int i = 0; i < MAX_PROCESSES; i++) {
for (int j = 0; j < MAX_RESOURCES; j++) {
scanf("%d", &request[i][j]);
}
}
bool finish[MAX_PROCESSES];
int work[MAX_RESOURCES];
for (int i = 0; i < MAX_RESOURCES; i++) {
work[i] = available[i];
}
for (int i = 0; i < MAX_PROCESSES; i++) {
finish[i] = false;
}
allocation[i][j];
}
finish[i] = true;
}
}
bool deadlock = false;
for (int i = 0; i < MAX_PROCESSES; i++) {
if (!finish[i]) {
deadlock = true;
printf("Process %d is deadlocked. Releasing its resources.\n", i);
for (int j = 0; j < MAX_RESOURCES; j++) {
available[j] += allocation[i][j];
allocation[i][j] = 0;
request[i][j] = 0;
}
finish[i] = true;
}
}
deadlock = false;
for (int i = 0; i < MAX_PROCESSES; i++) {
if (!finish[i]) {
deadlock = true;
break;
}
}
if (deadlock) {
printf("The system is still in a deadlocked state after resolving.\n");

} else {
printf("The system is not in a deadlocked state after resolving.\n");
}
return 0;
}
bool isDeadlocked(int process, int MAX_RESOURCES, int request[][MAX_RESOURCES], int
work[], int allocation[][MAX_RESOURCES]) {
for (int i = 0; i < MAX_RESOURCES; i++) {
if (request[process][i] > work[i]) {
return true;
}
}
return false;
}

OUTPUT:
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Expt.No:16 MEMORY MANAGEMENT POLICIES Date: 24-05-2024


RESULT:
Thus the C program to implement deadlock detection and resolving algorithm is successfully
executed to verify the output.

A) C PROGRAM TO IMPLEMENT PAGE REPLACEMENT USING BEST FIT


AIM:
To execute C program to implement page replacement using best fit in linux operating system.

ALGORITHM:
1. Initialize: Keep a list of free memory blocks and allocated memory blocks.
2. Request Memory: When a process asks for memory of size requested_size:
3. Find the Best Fit: Search through the free blocks to find the smallest block that is big enough for
the request.
4. Allocate Memory: If a suitable block is found:
5. If the block size matches the requested size, allocate the entire block.
6. If the block is larger, split it, allocate the needed portion, and update the free list with the remaining
part.
7. If no suitable block is found, the allocation fails.
8. Return Result: Return the starting address of the allocated block if successful; otherwise, return an
error or None.

SOURCE CODE:
#include <stdio.h>
void bestFit(int blockSize[], int m, int processSize[], int n)
{
int allocation[n];
for (int i = 0; i < n; i++)
{
allocation[i] = -1;
}
for (int i = 0; i < n; i++)
{
int bestIdx = -1;
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIdx == -1 || blockSize[bestIdx] > blockSize[j])
{
bestIdx = j;
}
}
}
if (bestIdx != -1)
{
allocation[i] = bestIdx;
blockSize[bestIdx] -= processSize[i];
}
}
printf("\nProcess No.\tProcess Size\tBlock No.\n");
for (int i = 0; i < n; i++)
{
printf("%d\t\t%d\t\t", i + 1, processSize[i]);
if (allocation[i] != -1)
{
printf("%d\n", allocation[i] + 1);
}
else
{
printf("Not Allocated\n");
}
}
}
int main()
{
int m, n;
printf("Enter the number of blocks: ");
scanf("%d", &m);
int blockSize[m];
printf("Enter the sizes of the blocks: ");
for (int i = 0; i < m; i++)
{
scanf("%d", &blockSize[i]);
}
printf("Enter the number of processes: ");
scanf("%d", &n);
int processSize[n];
printf("Enter the sizes of the processes: ");
for (int i = 0; i < n; i++)
{
scanf("%d", &processSize[i]);
}
bestFit(blockSize, m, processSize, n);
return 0;
}

OUTPUT:
RESULT:
Thus the C program to implement page replacement using best fit is successfully compiled to verify
the output.

B) C PROGRAM TO IMPLEMENT PAGE REPLACEMENT USING WORST FIT

AIM:
To execute C program to implement page replacement using worst fit in linux operating system.

ALGORITHM:
1. Initialize: Keep a list of free memory blocks and allocated memory blocks.
2. Request Memory: When a process asks for memory of size requested_size:
3. Find the Worst Fit: Search through the free blocks to find the largest block that is big enough for
the request.
4. Allocate Memory: If a suitable block is found:
5. If the block size matches the requested size, allocate the entire block.
6. If the block is larger, split it, allocate the needed portion, and update the free list with the remaining
part.
7. If no suitable block is found, the allocation fails.
8. Return Result: Return the starting address of the allocated block if successful; otherwise, return an
error or None.

SOURCE CODE:
#include <stdio.h>
void worstFit(int blockSize[], int m, int processSize[], int n)
{
int allocation[n];
for (int i = 0; i < n; i++)
{
allocation[i] = -1;
}
for (int i = 0; i < n; i++)
{
int worstIdx = -1;
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (worstIdx == -1 || blockSize[worstIdx] < blockSize[j])
{
worstIdx = j;
}
}
}
if (worstIdx != -1)
{
allocation[i] = worstIdx;

blockSize[worstIdx] -= processSize[i];
}
}
printf("\nProcess No.\tProcess Size\tBlock No.\n");
for (int i = 0; i < n; i++)

{
printf("%d\t\t%d\t\t", i + 1, processSize[i]);
if (allocation[i] != -1)
{
printf("%d\n", allocation[i] + 1);
}
else
{
printf("Not Allocated\n");
}
}
}
int main()
{
int m, n;
printf("Enter the number of blocks: ");
scanf("%d", &m);
int blockSize[m];
printf("Enter the sizes of the blocks: ");
for (int i = 0; i < m; i++)
{
scanf("%d", &blockSize[i]);
}
printf("Enter the number of processes: ");
scanf("%d", &n);
int processSize[n];
printf("Enter the sizes of the processes: ");
for (int i = 0; i < n; i++)
{
scanf("%d", &processSize[i]);
}
worstFit(blockSize, m, processSize, n);
return 0;
}
OUTPUT:
RESULT:
Thus the C program to implement page replacement using worst fit is successfully executed.

C) C PROGRAM TO IMPLEMENT PAGE REPLACEMENT USING FIRST FIT

AIM:
To execute C program to implement page replacement using first fit in linux operating system.

ALGORITHM:
1. Initialize: Keep a list of free memory blocks and allocated memory blocks.
2. Request Memory: When a process asks for memory of size requested_size:
3. Find the First Fit: Search through the free blocks and find the first block that is big enough for the
request.
4. Allocate Memory: If a suitable block is found:
5. If the block size matches the requested size, allocate the entire block.
6. If the block is larger, split it, allocate the needed portion, and update the free list with the remaining
part.
7. If no suitable block is found, the allocation fails.
Return Result: Return the starting address of the allocated block if successful; otherwise, return an
error or None.

SOURCE CODE:
#include <stdio.h>
void firstFit(int blockSize[], int m, int processSize[], int n)
{
int allocation[n];
for (int i = 0; i < n; i++)
{
allocation[i] = -1;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
allocation[i] = j;
blockSize[j] -= processSize[i];
break;
}
}
}
printf("\nProcess No.\tProcess Size\tBlock No.\n");
for (int i = 0; i < n; i++)
{
printf("%d\t\t%d\t\t", i + 1, processSize[i]);
if (allocation[i] != -1)
{
printf("%d\n", allocation[i] + 1);
}
else
{
printf("Not Allocated\n");
}
}
}
int main()
{
int m, n;
printf("Enter the number of blocks: ");
scanf("%d", &m);
int blockSize[m];
printf("Enter the sizes of the blocks: ");
for (int i = 0; i < m; i++)
{
scanf("%d", &blockSize[i]);
}
printf("Enter the number of processes: ");
scanf("%d", &n);
int processSize[n];
printf("Enter the sizes of the processes: ");
for (int i = 0; i < n; i++)
{
scanf("%d", &processSize[i]);
}
firstFit(blockSize, m, processSize, n);
return 0;
}
OUTPUT:
RESULT:
Thus the C program to implement memory management policy - page replacement using first fit is
successfully executed to verify the output.

D) C PROGRAM TO IMPLEMENT PAGE REPLACEMENT USING NEXT BEST


FIT

AIM:
To execute C program to implement page replacement using next best fit in linux operating system.

ALGORITHM:
1. Initialize: Keep a list of free memory blocks and allocated memory blocks. Maintain a pointer to
track the last allocated position in the free list.
2. Request Memory: When a process asks for memory of size requested_size:
3. Find the Next Fit: Start searching from the block after the last allocated position.Continue
searching through the free blocks in a circular manner until a block that is big enough is found.
4. Allocate Memory: If a suitable block is found:
5. If the block size matches the requested size, allocate the entire block.
6. If the block is larger, split it, allocate the needed portion, and update the free list with the remaining
part.
7. Update the pointer to the position of the allocated block.
8. If no suitable block is found after a full cycle, the allocation fails.
9. Return Result: Return the starting address of the allocated block if successful; otherwise, return an
error or None.

SOURCE CODE:
#include <stdio.h>
#define MAX 25
void nextFit(int blockSize[], int m, int processSize[], int n) {
int allocation[n];
int currentBlock = 0;
for(int i = 0; i < n; i++) {
allocation[i] = -1;
}
for(int i = 0; i < n; i++) {
while (currentBlock < m) {
if (blockSize[currentBlock] >= processSize[i]) {
allocation[i] = currentBlock;
blockSize[currentBlock] -= processSize[i];
break;
}
currentBlock++;
}
if (currentBlock >= m) {
currentBlock = 0;
}
}
printf("\nProcess No.\tProcess Size\tBlock No.\n");
for(int i = 0; i < n; i++) {
printf("%d\t\t%d\t\t", i+1, processSize[i]);
if (allocation[i] != -1) {
printf("%d\n", allocation[i] + 1);
} else {
printf("Not Allocated\n");
}
}
}
int main() {
int blockSize[MAX], processSize[MAX];
int m, n;
printf("Enter the number of blocks: ");
if (scanf("%d", &m) != 1) {
printf("Invalid input. Exiting...\n");
return 1;
}
printf("Enter the size of each block:\n");
for(int i = 0; i < m; i++) {
printf("Block %d: ", i + 1);
if (scanf("%d", &blockSize[i]) != 1) {
printf("Invalid input. Exiting...\n");
return 1;
}
}
printf("Enter the number of processes: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input. Exiting...\n");
return 1;
}
printf("Enter the size of each process:\n");
for(int i = 0; i < n; i++) {
printf("Process %d: ", i + 1);
if (scanf("%d", &processSize[i]) != 1) {
printf("Invalid input. Exiting...\n");
return 1;
}
}
nextFit(blockSize, m, processSize, n);
return 0;
}

OUTPUT:

RESULT:
PUDUCHERRY TECHNOLOGICAL UNIVERSITY

Thus the C program


Expt.No:17 to implement
DISK page replacement
SCHEDULING using next best fit is successfully
ALGORITHM executed to
Date: 01-07-2024
verify the output.

A) C PROGRAM FOR FCFS IN DISK SCHEDULING ALGORITHM

AIM:
To execute c program for FCFS in disk scheduling in linux operating system.

ALGORITHM:
1. Queue Requests: Add disk I/O requests to a queue as they come in.
2. Process in Order: Handle each request in the order it arrived.
3. Move Disk Head: Move the disk head to the track requested by the first request in the queue.
4. Perform I/O: Execute the I/O operation.
5. Update Position: Set the current disk head position to the track of the last serviced request.
6. Continue: Repeat until all requests are serviced.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
void FCFS(int requests[], int n, int head) {
int seek_time = 0;
printf("\nFCFS Disk Scheduling:\n");
printf("Seek Sequence: %d", head);
for (int i = 0; i < n; i++) {
printf(" -> %d", requests[i]);
seek_time += abs(requests[i] - head);
head = requests[i];
}
printf("\nTotal Seek Time: %d\n", seek_time);
}
int main() {
int n, head;
printf("Enter the number of disk requests: ");
scanf("%d", &n);

int requests[n];
printf("Enter the disk requests (in sequence): ");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
printf("Enter the initial head position: ");
scanf("%d", &head);
FCFS(requests, n, head);
return 0;

OUTPUT:
RESULT:
Thus the C program to implement FCFS disk scheduling is successfully executed and output is
verified.

B) C PROGRAM FOR SSTF IN DISK SCHEDULING ALGORITHM

AIM:
To execute c program for SSTF in disk scheduling in linux operating system.

ALGORITHM:
1. Queue Requests: Add disk I/O requests to a queue as they come in.
2. Process in Order: Handle each request in the order it arrived.
3. Move Disk Head: Move the disk head to the track requested by the first request in the queue.
4. Perform I/O: Execute the I/O operation.
5. Update Position: Set the current disk head position to the track of the last serviced request.
6. Continue: Repeat until all requests are serviced.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
void SSTF(int requests[], int n, int head) {
int seek_time = 0;
int completed[n];
for (int i = 0; i < n; i++) completed[i] = 0;
printf("\nSSTF Disk Scheduling:\n");
printf("Seek Sequence: %d", head);
for (int i = 0; i < n; i++) {
int min_distance = 1000000;
int closest_request = -1;

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


if (!completed[j] && abs(requests[j] - head) < min_distance) {
min_distance = abs(requests[j] - head);
closest_request = j;
}
}
printf(" -> %d", requests[closest_request]);
seek_time += abs(requests[closest_request] - head);
head = requests[closest_request];
completed[closest_request] = 1;
}
printf("\nTotal Seek Time: %d\n", seek_time);
}
int main() {
int n, head;
printf("Enter the number of disk requests: ");
scanf("%d", &n);

int requests[n];
printf("Enter the disk requests (in sequence): ");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
printf("Enter the initial head position: ");
scanf("%d", &head);
SSTF(requests, n, head);
return 0;
}

OUTPUT:
RESULT:
Thus the C program to implement SSTF disk scheduling is successfully executed and output is
verified.

C) C PROGRAM FOR C-LOOK IN DISK SCHEDULING ALGORITHM

AIM:
To execute C program for C-LOOK in disk scheduling in linux operating system.

ALGORITHM:
1. Queue Requests: Add disk I/O requests to a queue as they come in.
2. Process in Order: Handle each request in the order it arrived.
3. Move Disk Head: Move the disk head to the track requested by the first request in the queue.
4. Perform I/O: Execute the I/O operation.
5. Update Position: Set the current disk head position to the track of the last serviced request.
6. Continue: Repeat until all requests are serviced.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
void C_LOOK(int requests[], int n, int head) {
int seek_time = 0;
int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (requests[j] > requests[j + 1]) {
temp = requests[j];
requests[j] = requests[j + 1];
requests[j + 1] = temp;
}
}
}
printf("\nC-LOOK Disk Scheduling:\n");
printf("Seek Sequence: %d", head);
for (int i = 0; i < n; i++) {
if (requests[i] >= head) {
for (int j = i; j < n; j++) {
printf(" -> %d", requests[j]);
seek_time += abs(requests[j] - head);
head = requests[j];
}
for (int j = 0; j < i; j++) {
printf(" -> %d", requests[j]);
seek_time += abs(requests[j] - head);
head = requests[j];
}
break;
}
}
printf("\nTotal Seek Time: %d\n", seek_time);
}
int main() {
int n, head;
printf("Enter the number of disk requests: ");
scanf("%d", &n);

int requests[n];
printf("Enter the disk requests (in sequence): ");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
printf("Enter the initial head position: ");
scanf("%d", &head);
C_LOOK(requests, n, head);
return 0;
}

OUTPUT:

RESULT:
Thus the C program to implement C- LOOK disk scheduling is successfully executed and output is
verified.

You might also like