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

8. Write a Java Program to show the use of semaphore.

import java.util.concurrent.Semaphore;

public class SemaphoreExample {

public static void main(String[] args) {

// Create a semaphore with 3 permits

Semaphore semaphore = new Semaphore(3);

// Create 5 threads

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

new Thread(() -> {

// Acquire a permit

semaphore.acquire();

// Critical section

System.out.println("Thread " + Thread.currentThread().getName() + " is in the critical section");

// Release the permit

semaphore.release();

}).start();

2. Write a Java Program to show inter thread communication.

// Java program to demonstrate inter-thread communication

// (wait(), join() and notify())

import java.util.Scanner;

public class threadexample

public static void main(String[] args) throws InterruptedException

final PC pc = new PC();

// Create a thread object that calls pc.produce()

Thread t1 = new Thread(new Runnable()


{

@Override

public void run()

try

pc.produce();

catch(InterruptedException e)

e.printStackTrace();

});

// Create another thread object that calls

// pc.consume()

Thread t2 = new Thread(new Runnable()

@Override

public void run()

try

pc.consume();

catch(InterruptedException e)

e.printStackTrace();

});

// Start both threads

t1.start();
t2.start();

// t1 finishes before t2

t1.join();

t2.join();

// PC (Produce Consumer) class with produce() and

// consume() methods.

public static class PC

// Prints a string and waits for consume()

public void produce()throws InterruptedException

// synchronized block ensures only one thread

// running at a time.

synchronized(this)

System.out.println("producer thread running");

// releases the lock on shared resource

wait();

// and waits till some other method invokes notify().

System.out.println("Resumed");

// Sleeps for some time and waits for a key press. After key

// is pressed, it notifies produce().

public void consume()throws InterruptedException

// this makes the produce thread to run first.

Thread.sleep(1000);

Scanner s = new Scanner(System.in);


// synchronized block ensures only one thread

// running at a time.

synchronized(this)

System.out.println("Waiting for return key.");

s.nextLine();

System.out.println("Return key pressed");

// notifies the produce thread that it

// can wake up.

notify();

// Sleep

Thread.sleep(2000);

4. Write a Java Program to show deadlock occurrence and prevention.


import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class DeadlockExample {

public static void main(String[] args) {

// Create two locks

Lock lock1 = new ReentrantLock();

Lock lock2 = new ReentrantLock();

// Create two threads

Thread thread1 = new Thread(() -> {

// Acquire lock1

lock1.lock();

System.out.println("Thread 1 acquired lock 1");


// Try to acquire lock2

try {

lock2.lock();

System.out.println("Thread 1 acquired lock 2");

} catch (Exception e) {

System.out.println("Thread 1 failed to acquire lock 2");

// Release lock1

lock1.unlock();

});

Thread thread2 = new Thread(() -> {

// Acquire lock2

lock2.lock();

System.out.println("Thread 2 acquired lock 2");

// Try to acquire lock1

try {

lock1.lock();

System.out.println("Thread 2 acquired lock 1");

} catch (Exception e) {

System.out.println("Thread 2 failed to acquire lock 1");

// Release lock2

lock2.unlock();

});

// Start the threads

thread1.start();

thread2.start();

// Wait for the threads to finish

try {

thread1.join();

thread2.join();
} catch (InterruptedException e) {

e.printStackTrace();

1. a) Write a shell script sum.sh that takes an unspecified number of command line arguments (upto 9)
of integer and finds their average. Modify the code to add a number to the sum only if the number is
greater than 10.

#!/bin/bash

# Check if the number of arguments is more than 9

if [ "$#" -gt 9 ]; then

echo "Error: Too many arguments. Please provide up to 9 integers."

exit 1

fi

sum=0

count=0

# Loop through the command line arguments

for arg in "$@"; do

# Check if the argument is an integer

if ! [[ "$arg" =~ ^-?[0-9]+$ ]]; then

echo "Error: $arg is not an integer."

exit 1

fi

# Add the number to the sum only if it is greater than 10

if [ "$arg" -gt 10 ]; then

sum=$((sum + arg))

count=$((count + 1))

fi

done

# Calculate the average if count is greater than 0


if [ "$count" -gt 0 ]; then

average=$(echo "scale=2; $sum / $count" | bc)

echo "Sum: $sum"

echo "Average: $average"

else

echo "No numbers greater than 10 were provided."

fi

b) Write a shell script that takes a filename as input and counts the occurrences of a specific word in
that file.
#!/bin/bash

# Check if exactly two arguments are provided

if [ "$#" -ne 2 ]; then

echo "Usage: $0 <filename> <word>"

exit 1

fi

filename=$1

word=$2

# Check if the file exists

if [ ! -f "$filename" ]; then

echo "Error: File '$filename' not found."

exit 1

fi

# Count the occurrences of the word

count=$(grep -o -w "$word" "$filename" | wc -l)

echo "The word '$word' occurs $count times in the file '$filename'."

3.a) Write a Shell Script for output a specified directory’s size.

#!/bin/bash

# Check if exactly one argument is provided

if [ "$#" -ne 1 ]; then


echo "Usage: $0 <directory>"

exit 1

fi

directory=$1

# Check if the provided argument is a directory

if [ ! -d "$directory" ]; then

echo "Error: '$directory' is not a directory or does not exist."

exit 1

fi

# Get the size of the directory

dir_size=$(du -sh "$directory" | cut -f1)

echo "The size of the directory '$directory' is $dir_size."

b) Write a Shell Bash Script for evaluate the status of a file/directory.

#!/bin/bash

# Check if exactly one argument is provided

if [ "$#" -ne 1 ]; then

echo "Usage: $0 <file_or_directory>"

exit 1

fi

path=$1

# Check if the file or directory exists

if [ -e "$path" ]; then

# Check if it's a regular file

if [ -f "$path" ]; then

echo "'$path' is a regular file."

echo "File details:"

echo "Size: $(stat -c%s "$path") bytes"

echo "Permissions: $(stat -c%A "$path")"


echo "Owner: $(stat -c%U "$path")"

echo "Last modified: $(stat -c%y "$path")"

# Check if it's a directory

elif [ -d "$path" ]; then

echo "'$path' is a directory."

echo "Directory details:"

echo "Size: $(du -sh "$path" | cut -f1)"

echo "Permissions: $(stat -c%A "$path")"

echo "Owner: $(stat -c%U "$path")"

echo "Last modified: $(stat -c%y "$path")"

# Check if it's a symbolic link

elif [ -L "$path" ]; then

echo "'$path' is a symbolic link."

echo "Link details:"

echo "Points to: $(readlink "$path")"

echo "Permissions: $(stat -c%A "$path")"

echo "Owner: $(stat -c%U "$path")"

echo "Last modified: $(stat -c%y "$path")"

else

echo "'$path' exists but is neither a regular file nor a directory nor a symbolic link."

fi

else

echo "'$path' does not exist."

fi

5. a) Create an Employee file (Eid, Ename, Designation, Salary) Enter 10 records.

I. show first 5 records.

II show first 2 highest paid employee details.

III. show Eid, Ename and Salary

employees.txt

101 John Manager 75000


102 Alice Developer 65000

103 Bob Designer 62000

104 Carol Developer 72000

105 David Manager 80000

106 Eve Designer 60000

107 Frank Developer 68000

108 Grace Manager 77000

109 Heidi Developer 71000

110 Ivan Designer 63000

employee_operations.sh

#!/bin/bash

# File containing employee records

employee_file="employees.txt"

# Check if the file exists

if [ ! -f "$employee_file" ]; then

echo "Error: '$employee_file' not found."

exit 1

fi

echo "I. Showing the first 5 records:"

echo "------------------------------"

head -n 5 "$employee_file"

echo

echo "II. Showing the details of the 2 highest paid employees:"

echo "-------------------------------------------------------"

sort -k4,4nr "$employee_file" | head -n 2

echo

echo "III. Showing Eid, Ename, and Salary:"

echo "------------------------------------"

awk '{print $1, $2, $4}' "$employee_file"


b) Write a shell script to check a number is positive or negative.
#!/bin/bash

# Check if exactly one argument is provided

if [ "$#" -ne 1 ]; then

echo "Usage: $0 <number>"

exit 1

fi

# Input number

number=$1

# Check if the input is a valid number

if ! [[ "$number" =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then

echo "Error: '$number' is not a valid number."

exit 1

fi

# Check if the number is positive, negative, or zero

if (( $(echo "$number > 0" | bc -l) )); then

echo "$number is positive."

elif (( $(echo "$number < 0" | bc -l) )); then

echo "$number is negative."

else

echo "$number is zero."

fi

6. a) Write a shell script to say good morning/afternoon/evening/ night according to system time.

#!/bin/bash

# Get the current hour (24-hour format)

current_hour=$(date +%H)

# Determine the greeting based on the current hour


if [ "$current_hour" -ge 0 ] && [ "$current_hour" -lt 12 ]; then

greeting="Good Morning"

elif [ "$current_hour" -ge 12 ] && [ "$current_hour" -lt 17 ]; then

greeting="Good Afternoon"

elif [ "$current_hour" -ge 17 ] && [ "$current_hour" -lt 21 ]; then

greeting="Good Evening"

else

greeting="Good Night"

fi

# Print the greeting

echo $greeting

b) Write a shell script to check a year is leap year or not. (User input)

#!/bin/bash

# Prompt the user to enter a year

read -p "Enter a year: " year

# Check if the input is a valid year (a non-negative integer)

if ! [[ "$year" =~ ^[0-9]+$ ]]; then

echo "Error: Please enter a valid year (a non-negative integer)."

exit 1

fi

# Check if the year is a leap year

if (( (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) )); then

echo "$year is a leap year."

else

echo "$year is not a leap year."

fi

7. a) Write a shell script to count how many prime numbers are given through command line.

#!/bin/bash
# Function to check if a number is prime

is_prime() {

num=$1

if [ "$num" -le 1 ]; then

return 1 # 1 and negative numbers are not prime

fi

if [ "$num" -eq 2 ]; then

return 0 # 2 is prime

fi

if (( num % 2 == 0 )); then

return 1 # Even numbers greater than 2 are not prime

fi

# Check for factors from 3 to sqrt(num)

limit=$(( num / 2 ))

for (( i = 3; i <= limit; i += 2 )); do

if (( num % i == 0 )); then

return 1 # num is divisible by i, so not prime

fi

done

return 0 # num is prime

# Initialize count of prime numbers

prime_count=0

# Loop through each command line argument

for num in "$@"; do

if is_prime "$num"; then

echo "$num is prime."

(( prime_count++ ))

fi

done

echo "Total prime numbers: $prime_count"


b) Write a shell script to find the smallest between three numbers. (user input)

#!/bin/bash

# Function to find the smallest number among three

find_smallest() {

if [ "$1" -le "$2" ] && [ "$1" -le "$3" ]; then

smallest=$1

elif [ "$2" -le "$1" ] && [ "$2" -le "$3" ]; then

smallest=$2

else

smallest=$3

fi

echo "The smallest number is: $smallest"

# Prompt the user to enter three numbers

read -p "Enter the first number: " num1

read -p "Enter the second number: " num2

read -p "Enter the third number: " num3

# Check if the inputs are valid integers

if ! [[ "$num1" =~ ^[0-9]+$ ]]; then

echo "Error: '$num1' is not a valid integer."

exit 1

fi

if ! [[ "$num2" =~ ^[0-9]+$ ]]; then

echo "Error: '$num2' is not a valid integer."

exit 1

fi

if ! [[ "$num3" =~ ^[0-9]+$ ]]; then

echo "Error: '$num3' is not a valid integer."

exit 1

fi
# Call the function to find the smallest number

find_smallest "$num1" "$num2" "$num3"

9. a) Write a shell script that takes a name of a folder as a command line argument, and produce a file
that contains the names of all sub folders with size 0 (that is empty sub folders

#!/bin/bash

# Check if exactly one argument is provided

if [ "$#" -ne 1 ]; then

echo "Usage: $0 <folder>"

exit 1

fi

# Assign the folder name from command line argument

folder="$1"

# Check if the provided folder exists and is a directory

if [ ! -d "$folder" ]; then

echo "Error: '$folder' is not a valid directory."

exit 1

fi

# Find empty subfolders recursively and write their names to a file

find "$folder" -type d -empty > empty_subfolders.txt

# Check if any empty subfolders were found

if [ -s "empty_subfolders.txt" ]; then

echo "Empty subfolders found:"

cat empty_subfolders.txt

else

echo "No empty subfolders found in '$folder'."

fi

# Clean up the temporary file


rm -f empty_subfolders.txt

b) Write a shell script that will print only even numbers from the command line arguments.

#!/bin/bash

# Loop through each command line argument

for num in "$@"; do

# Check if the argument is a valid integer

if [[ "$num" =~ ^[0-9]+$ ]]; then

# Check if the number is even

if (( num % 2 == 0 )); then

echo "$num"

fi

fi

done

10. a) Create a student file (Sid, Sname, DeptName, Marks) Enter at least 10 records.

Show last 5 records.

Show Sname and Deptname sorted name wise.

students.txt

101 Alice Computer Science 85

102 Bob Electrical Engineering 78

103 Carol Mechanical Engineering 90

104 David Computer Science 82

105 Eve Electronics 88

106 Frank Civil Engineering 79

107 Grace Computer Science 91

108 Heidi Electronics 84

109 Ivan Mechanical Engineering 87

110 Jack Electrical Engineering 89


student_operations.sh

#!/bin/bash

# File containing student records

student_file="students.txt"

# Check if the file exists

if [ ! -f "$student_file" ]; then

echo "Error: '$student_file' not found."

exit 1

fi

echo "I. Showing the last 5 records:"

echo "------------------------------"

tail -n 5 "$student_file"

echo

echo "II. Showing Sname and DeptName sorted by name:"

echo "---------------------------------------------"

sort -k2,2 "$student_file" | awk '{print $2, $3}'

b) Write a shell script to print Fibonacci series upto n terms. (user input)

#!/bin/bash

# Function to generate Fibonacci series up to n terms

fibonacci_series() {

n=$1

a=0

b=1

count=1

# Print the first two terms manually

echo "Fibonacci Series up to $n terms:"


echo -n "$a "

while [ $count -lt $n ]; do

echo -n "$b "

next=$((a + b))

a=$b

b=$next

((count++))

done

echo # Move to the next line after printing the series

# Prompt user to enter the number of terms

read -p "Enter the number of terms for Fibonacci series: " num_terms

# Check if the input is a valid positive integer

if ! [[ "$num_terms" =~ ^[1-9][0-9]*$ ]]; then

echo "Error: Please enter a valid positive integer."

exit 1

fi

# Call the function to generate Fibonacci series

fibonacci_series "$num_terms"

You might also like