0% found this document useful (0 votes)
31 views47 pages

Task of Lab - 01

The document outlines a series of lab tasks focused on installing Ubuntu, executing Linux commands, managing files and directories, and writing shell scripts. Each task includes objectives, abstractions, and conclusions that emphasize practical skills in Linux environments, such as file management, user administration, and scripting. The exercises aim to provide foundational knowledge for effective Linux system management and automation.

Uploaded by

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

Task of Lab - 01

The document outlines a series of lab tasks focused on installing Ubuntu, executing Linux commands, managing files and directories, and writing shell scripts. Each task includes objectives, abstractions, and conclusions that emphasize practical skills in Linux environments, such as file management, user administration, and scripting. The exercises aim to provide foundational knowledge for effective Linux system management and automation.

Uploaded by

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

TASK OF LAB: 01

Install Ubuntu and take the screenshots.

Objective:

The objective of this task is to install Ubuntu, a popular open-source Linux distribution, on a
computer or virtual machine. The installation process involves setting up partitions, selecting
installation options, and ensuring that the operating system runs correctly.

Abstraction:

1.​ Download the Ubuntu ISO:


○​ First, you need to download the Ubuntu ISO file from the official website
(https://ubuntu.com/download/desktop).
2.​ Create a Bootable USB Drive:
○​ Use a tool like Rufus (Windows) or Startup Disk Creator (Ubuntu) to create a bootable USB
drive with the Ubuntu ISO.
3.​ Boot from USB:
○​ Insert the bootable USB into the computer and restart it. During boot-up, enter the
BIOS/UEFI settings and set the boot priority to the USB device.
4.​ Start the Ubuntu Installer:
○​ Once Ubuntu loads from the USB, select "Install Ubuntu" from the options. You can try
Ubuntu before installing it to ensure that your hardware is supported.
5.​ Partitioning:
○​ Choose the installation type. You can select "Erase disk and install Ubuntu" for a clean
installation or use "Something else" if you want to manually create partitions.
6.​ Choose Location and Keyboard Layout:
○​ Select your location, time zone, and keyboard layout.
7.​ Create User Account:
○​ Create a username, password, and choose whether you want to log in automatically or
require a password at startup.
8.​ Installation Process:
○​ After confirming all the installation settings, Ubuntu will start copying files and installing the
system. This may take some time.
9.​ Finish Installation:
○​ Once installation is complete, you’ll be asked to restart your computer. Remove the USB
drive when prompted.
10.​ Final Setup:
●​ After rebooting, you can log in to your newly installed Ubuntu system.
Screenshots:

Conclusion:

In conclusion, installing Ubuntu is a straightforward process that involves downloading the


installation ISO, creating a bootable USB drive, and following the prompts for installation. After the
system is installed, you will have a fully functional Ubuntu operating system, ready to use. The
process is beginner-friendly, but advanced users may opt for customized partitioning and installation
options.

After completing the installation, you should take screenshots of the different stages, such as:

1.​ The boot menu with the installation options.


2.​ The partitioning and installation setup.
3.​ The user account creation screen.
4.​ The final screen when Ubuntu has finished installing and asks you to reboot.
TASK OF LAB: 02
Execute some of the most frequently used Linux commands.

Objective:

The objective of this lab exercise is to execute a series of common Linux commands to familiarize
yourself with the terminal and the various file management, search, and user administration tasks in
Linux. The goal is to demonstrate how to list files, search directories, display file contents, and
manage user and group-related operations effectively using common Linux commands.

Abstraction:

In this lab exercise, various frequently used Linux commands were executed to perform tasks
related to file management, searching, and user/group administration. The tasks included listing
files in directories, searching for specific files based on patterns, displaying file contents, and
manipulating file attributes. Key commands such as ls, find, cat, grep, and groupadd were
used to handle different operations like listing files, searching for files based on name or
modification time, counting files, and viewing file contents. The exercise also covered user and
group management commands, demonstrating how to create groups, assign users to them, and set
passwords. These operations provide foundational knowledge necessary for managing files,
performing system searches, and administering users in a Linux environment.

●​ List all files (and subdirectories) in the home directory.

●​ List all files named chapter1 in the /work directory.


●​ List all files beginning with memo owned by ann.

●​ Display the content of the/etc/passwd file with as many lines at a time as the last digit of
your roll number.

●​ Search the current directory, look for filenames that don’t begin with a capital letter.
●​ Search the system for files that were modified within the last two days.
Search the system for files that were modified within the last two days:

●​ Recursively grep for your name down a directory tree.


Recursively grep for your name down a directory tree:
●​ List all file names containing your roll number in the end.
List all file names containing your roll number in the end:

●​ List files in your home folder in human readable format.


List files in your home folder in human-readable format:

●​ List all files in the current directory and their sizes; use multiple columns and mark special
files.
List all files in the current directory and their sizes; use multiple columns and
mark special files:

●​ List the contents of directories /bin and /etc.


List the contents of directories /bin and /etc:
●​ List C source files in the current directory, showing larger file first.
List C source files in the current directory, showing larger files first:

●​ Count all files in the current directory.


Count all files in the current directory:

●​ Page through file in “clear” mode and display prompts.


Page through a file in "clear" mode and display prompts:

●​ Format doc to screen removing underlines.


. Format doc to screen removing underlines:

CONCLUSION: In this lab, we explored essential Linux commands for file


management, searching, and user/group administration. By executing commands
like find, grep, and usermod, we gained hands-on experience in navigating the
system and performing common tasks. These exercises provided a strong
foundation for effective Linux system management and troubleshooting.
TASK OF LAB: 03
EXECUTE Managing Files & Directories in Linux
Managing Files & Directories in Linux

Objective:

The objective of this lab session was to practice essential Linux commands for managing
files and directories. These commands include creating, modifying, sorting, archiving, and
managing files through various tools. We also aimed to understand file attributes,
checksum verification, file splitting, and the practical use of the tar, cp, and cpio
commands, which are fundamental for file management and system administration in
Linux.

Abstraction:

In this lab session, we practiced using several Linux commands to manage files and
directories. The commands we explored include lockfile, cksum, comm, csplit,
chattr, and touch, each serving distinct purposes related to file manipulation, checksum
calculation, file splitting, and setting file attributes. Additionally, we executed commands
such as cat, cpio, sort, fuser, and file to manage and process files in various ways.
The session also covered understanding the tar command’s -z option and the difference
between the cp and cpio commands, helping us understand how files are copied,
archived, and extracted in Linux. By completing these tasks, we developed practical skills
for efficiently managing files and directories within the Linux environment.

PRACTICE the following commands (with examples)

Lockfile cksum comm. csplit chattr touch

Lockfile: The lockfile command is used to create a lock file, typically for ensuring that only one instance
of a script or process can run at a time. It's useful for preventing race conditions.
Cksum: The cksum command calculates and displays the checksum and byte size of a file. It can be used
to verify file integrity.

Comm: The comm command is used to compare two sorted files line by line. It outputs three
columns: lines only in the first file, lines only in the second file, and lines common to both files.

Csplit: The csplit command splits a file into multiple files based on context patterns or specific
line numbers.

Chattr: The chattr command is used to change file attributes on a Linux file system. It can be
used to make files immutable (cannot be modified or deleted).

Touch: The touch command is used to create an empty file or to update the access and modification times
of an existing file.
EXECUTE FOLLOWING COMMANDS?

Practice the following commands and explain each:

echo: Displays a line of text or a variable value to the terminal, commonly used for printing
messages or setting variables.

fuser: Identifies processes using a specified file or socket, and can kill those processes.

file: Determines and displays the file type based on its content, not just the file
extension.
sort: Sorts lines of text files or input based on various criteria such as alphabetical,
numerical, or reverse order.

What does the z option of the tar command do? Explain with examples.

The -z option of the tar command is used to compress the archive using gzip
compression.

Explanation:

●​ The -z option tells tar to compress the archive it creates or extracts using the gzip
utility, which reduces the size of the archive by compressing it.

Examples:

1.​ Creating a Compressed Archive with tar -z:


○​ To create a compressed archive of a directory or files using gzip:

tar -czf archive.tar.gz directory/

○​ Explanation:
■​ -c creates a new archive.
■​ -z compresses it using gzip.
■​ -f specifies the filename of the archive.
○​ This creates a gzip-compressed archive called archive.tar.gz containing
the contents of the directory/.
2.​ Extracting from a Compressed Archive with tar -z:
○​ To extract a .tar.gz file:​
tar -xzf archive.tar.gz
○​ Explanation:
■​ -x extracts the archive.
■​ -z decompresses it using gzip.
■​ -f specifies the archive filename (archive.tar.gz).
○​ This will extract the contents of archive.tar.gz to the current directory.

Differentiate between cp and cpio command?

1.​ cp Command:
○​ The cp command is used to copy individual files and directories from one
location to another.
○​ It is a simple command that handles copying of files or directories without
involving any archiving or compression.
○​ Usage: Typically used for basic copying tasks like copying a file from one
directory to another.
○​
2.​ cpio Command:
○​ The cpio command is used for copying files into or out of archives. It is
typically used for bulk copying or creating backups.
○​ cpio reads and writes files in archive formats, which can include
compressed files.
○​ Usage: Commonly used for archiving multiple files or directories at once or
○​
○​ Feature: It is especially useful for backups and restoring files, and can
handle file lists or directories as input

ConclusionThrough this session, we learned various commands for file


management and directory manipulation in Linux. We gained practical
experience with tasks like file copying, sorting, archiving, and checking file
integrity.
TASK OF LAB: 04
Execute shell scripting in Linux operating system terminal.

Objective:

The objective of this shell program is to demonstrate the process of writing a script that multiplies
two numbers and calculates the average of three numbers in a Linux environment. This exercise
helps in understanding basic shell scripting concepts, including user input, arithmetic operations,
and output.

Abstraction:

1.​ Multiplication of Two Numbers:


○​ A shell script is written that accepts two numbers from the user and multiplies them.
The program takes user input, performs the multiplication, and displays the result on
the terminal.
2.​ Average of Three Numbers:
○​ Another shell script is created to calculate the average of three numbers. The
program takes input for three numbers, calculates the sum, and then computes the
average by dividing the sum by 3.

Multiplication 2 numbers
Average of three numbers

Conclusion:

In this exercise, we successfully created two shell programs: one to multiply two numbers
and another to calculate the average of three numbers. The programs demonstrate basic
shell scripting concepts, such as reading user input, performing arithmetic operations, and
displaying the output. This helps in building a foundation for more complex shell scripting
tasks, such as data processing and automation in Linux environments.
TASK OF LAB: 05
To Execute shell scripting for finding large numbers and factorial of numbers.

Objective:

The objective of this exercise is to create two shell scripts:

1.​ A script that takes a number (1-3) as input and uses the case statement to display the
corresponding month name.
2.​ A script that defines a function which takes a number (1-7) as input and displays the
corresponding day of the week starting from Sunday. If the number provided is outside the
valid range, an error message is displayed.

Abstraction:

1.​ Month Display Using case:


○​ The first script uses the case statement to take a number (1-3) as input and display
the corresponding month. For example:
■​ 1 corresponds to January
■​ 2 corresponds to February
■​ 3 corresponds to March
○​ If the input is outside the range of 1-3, an appropriate error message is displayed.
2.​ Day of the Week Function:
○​ The second script defines a function that, based on a user input (number between 1
and 7), will display the corresponding day of the week starting from Sunday. If the
number is not within the range of 1-7, the function will output an error message.

-Make a script that takes a number (parameter) from 1-3 as input and uses the case
to display the name of the corresponding month.
-Make a function that displays the name of the week days starting from Sunday if the
user passes a day number. If a number provided is not between 1 and 7 an error
message is displayed.

conclusion:

In this exercise, we created two shell scripts:

1.​ A script that uses the case statement to display the month name corresponding to
a given number between 1 and 3.
2.​ A function that displays the day of the week starting from Sunday based on a given
number between 1 and 7.

These exercises helped demonstrate the use of the case statement in shell scripting,
which is useful for handling multiple conditions based on user input.
TASK OF LAB: 06
Using conditional, branching and looping MAKE statements in shell scripting

Objective:

The objective of this exercise is to:

1.​ Create a script that compares two strings provided by the user and prints a message based
on the result of the comparison (e.g., whether they are equal, one is greater, or one is
smaller).
2.​ Create a script that backs up each file in the user's home directory to a subdirectory called
backup using a for loop. If the backup operation fails, the script should display an error
message.

Abstraction:

1.​ String Comparison Script:


○​ The first script will prompt the user for two strings and compare them using
conditional statements. Depending on the result of the comparison, it will print
whether the strings are equal, or if one is lexicographically greater or smaller than
the other.
2.​ Backup Script Using for Loop:
○​ The second script will iterate over all files in the user's home directory, using a for
loop to copy each file to a backup directory. If any file fails to copy, the script will
output an error message.

-Make a script that takes two strings as input compares them and depending upon the
results of the comparison prints the results.
Make a script that creates a backup version of each file in your home directory toa
subdirectory called backup using for statement. If the operation fails an error messageis to
be displayed.

Conclusion:

In this exercise, two shell scripts were created:

1.​ The first script compared two strings and printed the result of the comparison,
demonstrating the use of conditional statements in shell scripting.
2.​ The second script used a for loop to back up each file in the user's home directory to a
backup subdirectory, checking for success or failure of each file backup.
Open-Ended Lab - 01
Perform the below-mentioned exercises of shell scripting and show its
output as well.

Objective:

The objective of this exercise is to:

1.​ Create a script that compares two strings provided by the user and prints a message based
on the result of the comparison (e.g., whether they are equal, one is greater, or one is
smaller).
2.​ Create a script that backs up each file in the user's home directory to a subdirectory called
backup using a for loop. If the backup operation fails, the script should display an error
message.

Abstraction:

1.​ String Comparison Script:


○​ The first script will prompt the user for two strings and compare them using
conditional statements. Depending on the result of the comparison, it will print
whether the strings are equal, or if one is lexicographically greater or smaller than
the other.
2.​ Backup Script Using for Loop:
○​ The second script will iterate over all files in the user's home directory, using a for
loop to copy each file to a backup directory. If any file fails to copy, the script will
output an error message.

Tasks

●​ Make a shell script that prints “Shell Scripting is Fun!” on the screen.

●​ Modify the shell script from exercise 1 to include a variable. The variable
will hold the contents of the message “Shell Scripting is Fun!”

●​ Store the output of the command “hostname” in a variable. Display “This


script is running on _.” where “_” is the output of the “hostname” command.

Conclusion:

In this lab exercise, we successfully created and tested three shell scripts:

1.​ A simple script that prints a message.


2.​ A script that uses a variable to store and print the message.
3.​ A script that captures the output of the hostname command and displays it in a
sentence.

These exercises helped develop the understanding of basic shell scripting concepts such
as text printing, using variables, and capturing the output of commands. This knowledge is
fundamental for automating tasks and working effectively in a shell environment.
TASK OF LAB: 08
Demonstrate CPU Scheduling Algorithms FCFS Using GCC Compiler In Linux.

Objective:

The objective of this lab task is to simulate the First Come First Serve (FCFS) processor
scheduling algorithm in C. This task will allow students to:

1.​ Understand how process scheduling works and how different scheduling algorithms impact
process execution.
2.​ Learn how to implement FCFS scheduling with additional considerations such as process
priorities and sorting by priority.
3.​ Compute the waiting time, turnaround time, and average waiting/turnaround time for
processes.
4.​ Display the Gantt chart to visually represent the execution of processes.

Abstraction:

1.​ Process Structure:


○​ We will define a structure to store information about each process, including the
process id, burst time, priority, waiting time, and turnaround time.
2.​ Input Handling:
○​ The program will prompt the user for the number of processes (n), and for each
process, the user will input the burst time and priority. This will be stored in an array
of structures.
3.​ Sorting Processes:
○​ After taking input, we will sort the processes by priority in ascending order. If two
processes have the same priority, FCFS will be applied (i.e., they will be scheduled
in the order they appear in the input).
4.​ Calculating Waiting Time and Turnaround Time:
○​ The waiting time for the first process will be 0. For each subsequent process, the
waiting time is calculated as the sum of the burst times of all previous processes.
The turnaround time is the sum of the burst time and the waiting time for each
process.
5.​ Average Waiting and Turnaround Time:
○​ After computing the individual waiting and turnaround times, the average values will
be calculated and displayed.
6.​ Gantt Chart:
○​ The Gantt chart will display the execution order of processes, showing the start and
finish times of each process.
5.​ Develop proficiency in handling data structures like arrays and structures in C.
CODE:
output

Conclusion:

This program demonstrates how the FCFS Scheduling Algorithm works, including sorting
processes by priority, calculating waiting and turnaround times, and displaying a Gantt chart for
process execution. You can easily run this code on any online compiler by following the above
steps.
TASK OF LAB: 09
Try implementation of SJF scheduling algorithm using c programming

Objective:

The goal of this lab task is to simulate the Shortest Job First (SJF) CPU Scheduling Algorithm in
C. This algorithm schedules jobs based on the shortest burst time, meaning that the process with
the smallest burst time is given priority to execute first. The task requires calculating the waiting
time, turnaround time, and displaying the Gantt chart for the processes involved. This exercise
aims to help in understanding how CPU scheduling works, especially when the burst time of each
process is known in advance.

Abstraction:

The Shortest Job First (SJF) Scheduling algorithm selects the process with the smallest burst time
to execute first. This algorithm is optimal in terms of minimizing the average waiting time, but it
requires knowing the burst time of each process beforehand. This simulation involves the following
steps:

1.​ Input the number of processes and their respective burst times.
2.​ Sort the processes based on burst time in ascending order.
3.​ Calculate the waiting time and turnaround time for each process.
4.​ Display the Gantt chart, which visually shows the sequence of execution.
5.​ Compute average waiting time and average turnaround time.

Code:
Explanation of the Code:

1.​ Structure Definition (struct process): This structure stores the process ID, burst time,
waiting time, and turnaround time for each process.
2.​ Sorting by Burst Time: The sort_processes() function sorts the processes in
ascending order based on their burst times to simulate the SJF algorithm.
3.​ Calculating Waiting Time and Turnaround Time: The calculate_times() function
calculates the waiting time and turnaround time for each process. The first process has a
waiting time of 0, and subsequent processes have their waiting times calculated based on
the burst times of previous processes.
4.​ Displaying Results: After calculating the necessary times, the program displays the
process details and the average waiting time and turnaround time.
5.​ Displaying Gantt Chart: The Gantt chart is displayed to visualize the execution sequence
of processes.
OUTPUT:

Conclusion:

The Shortest Job First (SJF) Scheduling algorithm is an efficient scheduling algorithm that
minimizes the average waiting time, especially when the burst time of each process is known
beforehand. This simulation in C demonstrates how to apply SJF scheduling by sorting processes
based on burst times, calculating the necessary times, and displaying the results in a Gantt chart.
The program successfully computes the average waiting time and turnaround time, helping to
understand the theoretical concepts in CPU scheduling.
TASK OF LAB: 10
Try implementation of Priority scheduling algorithms (primitive and non-

primitive).

Objective

The objective of this lab task is to simulate the First Come First Serve (FCFS) Processor
Scheduling Algorithm while incorporating Priority Scheduling. The goal is to:

●​ Implement the scheduling algorithm in C using an array of structures.


●​ Define process properties like process ID, burst time, waiting time, and turnaround
time.
●​ Calculate and display the waiting time and turnaround time for each process.
●​ Compute the average waiting time (awat) and average turnaround time (atur).
●​ Display the Gantt chart for the given scheduling.

Abstraction

This lab task simulates the FCFS scheduling algorithm with priority scheduling in C. The user is
asked to input the number of processes, burst times, and priorities of processes. The program
calculates waiting times and turnaround times for each process and displays the results. It also
calculates the average waiting and turnaround times, followed by a Gantt chart to visualize the
execution order of the processes. This simulation helps in understanding the CPU scheduling
process, its performance metrics, and how scheduling algorithms like FCFS affect overall system
performance.

Explanation of the Code:

1.​ Input: The program accepts the number of processes and for each process, it asks for the
burst time and priority.
2.​ Sorting: The processes are sorted based on their priority. If two processes have the same
priority, FCFS is applied to resolve the tie.
3.​ Calculation: The waiting time for the first process is 0. Then, for each process, the waiting
time is calculated as the sum of the burst times of all previous processes. The turnaround
time for each process is calculated as the sum of its burst time and waiting time.
4.​ Average Calculation: The average waiting time and turnaround time are calculated and
displayed.
5.​ Gantt Chart: The Gantt chart is displayed showing the processes in the order they are
executed along with their respective times
C Code for FCFS Scheduling with Priority

Here is the C program that simulates the First Come First Serve (FCFS) scheduling with Priority
output:
Conclusion:

This program simulates the FCFS (First Come First Serve) processor scheduling algorithm
using priority scheduling. The processes are first sorted by priority, and then FCFS is
applied to resolve ties. The program calculates the waiting time and turnaround time for
each process, and displays the results, including the average waiting time and average
turnaround time. Additionally, the program displays the Gantt chart to help visualize the
execution order of processes. This simulation demonstrates the importance of scheduling
algorithms in operating systems to optimize resource utilization and process management.
TASK OF LAB: 11
Execute C Program To Implement Round Robin Scheduling

Objective

The objective of this lab task is to simulate the Round Robin (RR) Processor Scheduling
Algorithm in C. Round Robin is a preemptive scheduling algorithm in which each process is
assigned a fixed time slice (quantum) in a cyclic order. The task is to:

●​ Implement the Round Robin scheduling algorithm.


●​ Calculate and display the waiting time and turnaround time for each process.
●​ Compute the average waiting time and average turnaround time.
●​ Display the Gantt chart for the given scheduling.
●​ Understand how Round Robin scheduling impacts the execution of processes in a system.

Abstraction

In Round Robin scheduling, the CPU scheduler assigns a fixed time slice or quantum to each
process in a cyclic order. If a process does not complete its execution within its time quantum, it is
placed back in the ready queue, and the next process gets its turn. This is done until all processes
are finished. The program calculates and displays the waiting time and turnaround time for each
process, as well as their averages. The Gantt chart is displayed to help visualize the order of
process execution.

This task helps in understanding the Round Robin scheduling algorithm's application in process
management and how it is used to ensure fairness in CPU allocation.

Explanation of the Code:

1.​ Input:
○​ The user is asked to input the number of processes.
○​ Then, for each process, the burst time is provided.
○​ Finally, the user enters the time quantum (fixed time slice).
2.​ Round Robin Scheduling:
○​ The algorithm simulates the Round Robin scheduling by assigning a fixed time
quantum to each process.
○​ If a process doesn't finish in one time slice, it is preempted and placed back in the
queue.
○​ The remaining time for each process is updated after every cycle.
3.​ Waiting Time and Turnaround Time:
○​ After the processes complete execution, the waiting time and turnaround time for
each process are calculated.
○​ The average waiting time and average turnaround time are displayed.
4.​ Output:
○​ The program outputs the waiting time and turnaround time for each process, the
average waiting time, and the average turnaround time.

C Code for Round Robin Scheduling

Here is a C program to simulate the Round Robin scheduling algorithm:


output;

Conclusion

This program simulates the Round Robin (RR) CPU scheduling algorithm. The algorithm
ensures fairness by providing each process a fixed time slice (quantum) and executing
them in a cyclic order. The program calculates the waiting time and turnaround time for
each process, as well as the average waiting time and average turnaround time for the
entire system. Additionally, it displays the Gantt chart that helps visualize the execution of
processes.

This exercise helps understand how Round Robin scheduling works and how it impacts
the performance of the system, specifically in terms of average waiting time and average
turnaround time. The task also reinforces key concepts related to process scheduling in
operating systems.
TASK OF LAB: 12
Execute C Program To Implement Bankers Algorithm For Deadlock Avoidance.

Objective

The objective of this lab task is to simulate the Banker's Algorithm for resource allocation and
deadlock avoidance in an operating system. The Banker's Algorithm checks whether the system is
in a safe state or not by ensuring that there are enough resources available to allow all processes
to complete without causing a deadlock. The system is said to be in a safe state if there exists a
sequence of processes that can be executed without exceeding the available resources. If the
system is in an unsafe state, deadlock might occur.

Abstraction

The Banker's Algorithm works by keeping track of the resources allocated to each process and the
remaining resources needed for each process to finish its execution. It uses the following steps:

1.​ Inputs: The number of processes, number of resources, available resources, and the
resources allocated to each process.
2.​ Safety Check: The algorithm calculates whether the system can safely execute all
processes without running into a deadlock. It does this by checking if there is a sequence of
processes that can be completed with the available resources.
3.​ Output: If the system is in a safe state, the Banker's Algorithm will display the sequence in
which processes will be executed. If the system is in an unsafe state, it will indicate that a
deadlock might occur.
C Code for Banker's Algorithm

Here is the C program that simulates the Banker's Algorithm:


output:

Explanation of the Code:

1.​ Input:
○​ Number of processes (n) and number of resources (m).
○​ Allocated resources matrix: Each process's allocated resources.
○​ Maximum resources matrix: The maximum resources each process may need.
○​ Available resources vector: The number of available resources in the system.
2.​ isSafe Function:
○​ It checks whether the system is in a safe state or not by attempting to find a
sequence of processes that can complete using available resources.
○​ It loops through all processes and tries to execute those that can finish based on the
current available resources.
○​ If a process can finish, its allocated resources are added back to the available
resources, and the process is marked as finished.
○​ If all processes can finish in a valid order, the system is in a safe state.
3.​ Output:
○​ The program outputs whether the system is in a safe state or unsafe state.
○​ If in a safe state, the safe sequence of process execution is displayed.

Conclusion

This program simulates the Banker's Algorithm for deadlock avoidance and resource allocation in
an operating system. By checking whether the system is in a safe state or not, the Banker's
Algorithm ensures that resources are allocated in such a way that no deadlock will occur. The
algorithm calculates whether a safe sequence of processes exists, which can be executed without
exhausting the available resources.

This task provides an understanding of how operating systems manage resources and prevent
deadlock by using algorithms like the Banker's Algorithm. By simulating this, students can learn
how resource allocation works in a concurrent system and the importance of maintaining a safe
state.
TASK OF LAB: 13
Execute C program to implement algorithm for deadlock detection.

Objective

The objective of this lab task is to implement an algorithm for Deadlock Detection in
an operating system. The program will simulate a system where multiple processes
request and release resources. The algorithm will detect if there is a deadlock in the
system by evaluating the resource allocation matrix, maximum resources matrix,
and available resources. The deadlock detection algorithm will ensure that
processes either complete their execution or remain in a deadlock state.

Abstraction

In a multiprogramming environment, deadlock occurs when processes are blocked


because they are waiting for resources that are held by other processes. Deadlock
detection algorithms help identify such situations and take actions to resolve them.
The Banker's Algorithm can be adapted to check for deadlock in the system by
comparing the needs of each process with the available resources.

The Deadlock Detection Algorithm works as follows:

1.​ Input: The program takes the number of processes, number of resources,
resource allocation matrix, maximum resource matrix, and available resource
vector as input.
2.​ Matrix Calculation: The program calculates the need matrix by subtracting
the allocation matrix from the maximum matrix for each process.
3.​ Deadlock Detection: The algorithm checks whether each process can finish
by comparing its need matrix with the available resources. If all processes
can finish, there is no deadlock; if not, the system is in a deadlock state.
4.​ Output: The system will display the processes involved in the deadlock (if
any), otherwise indicate that there is no deadlock.

Explanation of the Code:

1.​ Input Function:


○​ This function takes the number of processes, number of resources, the
maximum matrix (maximum resources each process can claim), the
allocation matrix (currently allocated resources), and the available
resources vector as input.
2.​ Show Function:
○​ This function displays the Process IDs, Allocation Matrix, Max Matrix,
and Available Resources.
3.​ Calculation Function (cal):
○​ The function computes the Need Matrix (which is max[i][j] -
alloc[i][j] for each process).
○​ It then checks whether each process can finish using the available
resources. If all the processes can finish, the system is in a safe state,
otherwise, deadlock is detected.
○​ The function also updates the available resources and tracks the
processes that are in deadlock.
4.​ Deadlock Detection:
○​ If there are any unfinished processes after trying to complete them in
the available order, the system is considered in a deadlock state, and
the processes involved are displayed.

Output of the code

Conclusion

This program successfully simulates deadlock detection using a simple algorithm to


determine whether the system is in a safe state or a deadlock state. By comparing
the Need Matrix with the Available Resources and attempting to finish processes,
the system can detect deadlock and report which processes are involved.
Open-Ended Lab - 02
To make a c program to implement Threading and Synchronization Applications.

Objective

The objective of this task is to implement threading and synchronization in C. We aim to


demonstrate the use of multiple threads, synchronization techniques, and how threads are
managed to avoid errors and conflicts in a concurrent programming environment. The program will
handle creating and managing threads, checking thread states, and synchronizing threads to
ensure proper execution and prevent race conditions.

Abstraction

In multi-threaded programs, threads run concurrently, allowing efficient CPU utilization. However,
without synchronization, threads can interfere with each other, leading to race conditions and
incorrect results. To solve these issues, synchronization mechanisms like mutexes, semaphores,
or condition variables are used.

The program will:

1.​ Create threads using the pthread_create() function.


2.​ Use pthread_join() to synchronize threads.
3.​ Handle thread states and detect errors using proper error checking functions.
4.​ Display the results after all threads have completed.

This program demonstrates basic threading, synchronization, and error checking in C using the
POSIX threads library (pthread).
output

Explanation of the Code

1.​ Global Variables:


○​ pthread_t threads[THREAD_COUNT]: An array to hold the thread IDs for each
thread.
○​ pthread_mutex_t lock: A mutex used for synchronization. Mutex ensures that
only one thread can access a critical section at a time, avoiding race conditions.
2.​ Main Function:
○​ The main function first initializes the mutex using pthread_mutex_init().
○​ Then it creates THREAD_COUNT threads using pthread_create(). Each thread
will execute the function threadFunction().
○​ After thread creation, the main thread waits for each thread to finish by calling
pthread_join() on each thread.
○​ After all threads are joined, the mutex is destroyed with
pthread_mutex_destroy() to free the resources.
3.​ Thread Function (threadFunction):
○​ Each thread receives its ID as an argument.
○​ Inside the function, a mutex lock is applied using pthread_mutex_lock() to
ensure that only one thread enters the critical section at a time.
○​ After some simulated work (a sleep for 1 second), the thread prints that it has
completed and unlocks the mutex using pthread_mutex_unlock() to allow
other threads to proceed.

Conclusion

This program successfully demonstrates basic threading and synchronization using POSIX
threads (pthreads) in C. The synchronization is achieved through the use of a mutex to ensure that
threads do not interfere with each other in critical sections. Proper error handling is implemented to
check for thread creation and joining failures. This approach helps in managing concurrent threads
in a multi-threaded environment while preventing race conditions.

You might also like