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

Operating System

os file
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Operating System

os file
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Operating System

Name - Ruchira Dnyanoba


Devane PRN - 202201104040

Comparison between Linux and Windows

Sr. Attributes Linux Windows


no
1 User Linux Operating Windows offers
interfac Systems provide users a consistent
e customisable desktop and
environments such as user-friendly interface
GNOME and KDE. These across its different
desktop environments editions. Its interface
allow users to provides a familiar
personalize their layout and workflow,
interface, adjust making it accessible
themes, and tweak for users transitioning
settings according to from previous
their preferences. Its versions. It prioritizes
users have the ease of use and aims
flexibility to create a for a streamlined
unique desktop experience across
experience tailored to devices, ensuring a
their needs. consistent look and
feel.
2 cost Linux is known for In contrast, the
its open-source Windows Operating
nature, making it System requires a
typically free. license for most
Users can freely editions. The cost of its
download, use, modify, licenses varies
and distribute Linux depending on the
distributions without version and usage
licensing costs. rights, with different
Additionally, a editions catering to
significant portion of the different user needs.
software available for While free editions of
Linux is free and open Windows are
source, allowing you to available, such as
access various Windows 10 Home,
applications without certain features and
additional expenses. functionalities may be
restricted or require
additional payments.
Moreover, commercial
software on Windows
often comes with
separate costs, which
users need to consider
when calculating the
overall expenses
associated with using
it.
3 security Linux provides the best On the contrary,
security features. It is Windows users cannot
very difficult to break fix the issue by
through Linux, and this themselves, as they
is one of the reasons do not have access to
why it is so popular the source code. Since
among developers. It they cannot check the
also has a strong user vulnerability of the
community, which system, it becomes
helps identify and fix more susceptible to
issues. hackers. In Windows,
Linux’s user base has since users have full
access to the source admin access over the
code. This makes it accounts, the entire
easier to monitor for system gets quickly
issues that can impact corrupted when any
the software and makes virus attacks the
it less vulnerable to system. The Windows
hacking. Moreover, OS is also not
Linux users have limited segmented, more
access, which makes vulnerable to
them less vulnerable threats.which makes it
when a virus attacks the
system.
4 Software Linux is renowned for Compared to Linux,
availabili its robust security and Windows has
ty stability features. With significantly improved
a strong user security over the
permissions system years, and it remains a
and regular updates, it frequent target for
offers enhanced malware due to its
protection against larger user base. It
malware and incorporates security
unauthorised access. measures such as
Additionally, the Windows Defender and
open-source nature of regular updates to
Linux allows for quick mitigate risks and
identification and ensure system
resolution of security stability. However, you
vulnerabilities. are advised to employ
This feature makes it a additional security
reliable and secure measures and exercise
choice for users caution while browsing
concerned about their the internet to
data and privacy. safeguard your
systems effectively.
5 Hardware
compatibi Linux: Windows:
lit y
Community-Driven Plug-and-Play with
Compatibility for a Modern Hardware
Wider Range
Windows
Linux takes a different prioritizes user-
approach. Known for its friendliness and
open-source nature, it boasts excellent
enjoys a vast compatibility with
community that modern hardware.its
actively develops plug-and-play
drivers for a wider functionality
range of hardware automatically
compared to Windows. recognizes and
configures new
components,driver
hunting might be
necessary.
6 performan The server domain has On the other hand, the
c
e long favoured Linux for user-friendly Windows
its efficient resource server offers
management, stability, compatibility with
and scalability. Its other Microsoft
lightweight nature products, making it a
allows it to run convenient choice for
smoothly on various organisations already
hardware using Windows-based
configurations, making infrastructure. Its
it a reliable server servers provide
choice. Linux's robust several tools and
command-line features that simplify
interface and extensive server management
support for scripting and administration.
and automation also While it may require
contribute to its more system
popularity among resources than Linux,
Server Administrators. Windows Server is
Additionally, Linux's known for its polished
open-source nature user experience and
encourages rapid extensive
bug fixes, updates, compatibility with
and optimisations, commercial software.
ensuring high
performance.
7 customiz Linux provides In contrast, Windows
ati on extensive offers a standardised
customisation and experience across all
flexibility options to its editions, ensuring
users. With a plethora consistency and
of desktop familiarity for users.
environments to choose While it provides
from, such as GNOME, customisation options
KDE, Xfce, and more, like changing
Linux users can wallpapers, themes,
personalise their and arranging icons, it
interface, modify has limited flexibility
themes, and customise than Linux. It focuses
their system's overall on delivering a
look and feel. cohesive and user-
Additionally, Linux friendly interface
users can tweak system consistent across
settings, tailor different devices and
workflows, and adapt editions,
the operating system to
suit their specific making it easier for
requirements. This, in users to navigate and
turn provides a highly operate their
adaptable and flexible systems.
computing environment.

8 Support Linux: Due to its Windows: Windows


and open-source nature, boasts a robust official
documen Linux support takes a support system
ta tion different approach. directly from Microsoft.
Official support from Users can access
the Linux kernel itself is online documentation,
limited. However, the knowledge base
strength lies in its articles, and
vibrant community. troubleshooting
Numerous online guides. Additionally,
forums, user groups, Microsoft offers paid
and wikis offer a wealth support options for
of information and more complex issues.
troubleshooting The downside? These
assistance. The vast resources are primarily
number of Linux focused on the latest
distributions can be Windows versions,
overwhelming for leaving older versions
beginners, but most with potentially limited
distributions have their official support.
own dedicated
communities and
documentation specific
to their version.
9 Software Linux: Embraces Windows: Relies on a
managem open-source software centralized app store
e nt and a decentralized model similar to
package management mobile devices. Users
system. find and install
Users install and software through the
update applications Microsoft Store or
through package download installers
managers like APT directly from vendors'
(Advanced Package websites. Software on
Tool) or Yum. These Windows often has
tools handle licensing costs
dependencies and associated with it.
ensure software
compatibility. Many
applications in Linux
are free and open-
source, reducing costs.
10 File Linux: Utilizes a Windows:Windows
system hierarchical structure utilizes a file system
with a single root structure similar to
directory ("/") from Linux, employing a
which all other hierarchical
directories and files organization with a
branch out. This tree- single root directory.
like structure offers This root directory,
flexibility and allows for denoted by a
clear organization. backslash (), acts as
Permissions are the foundation from
assigned to control which all other folders
access to files and and files branch out.
directories, enhancing Subdirectories can be
security. created within these
folders to further
organize your data.
11 Comman Linux is known for its Windows also offers
d line powerful command-line a command-line
interface interface (CLI), often interface tool called
referred to as a Command Prompt
terminal or shell. This (cmd.exe).
text-based interface However, compared to
allows users to interact Linux, the CLI plays a
with the operating less prominent role in
system directly by the overall Windows
issuing commands. The experience. While it
CLI offers a high degree provides access to
of control over the basic system functions
system, enabling users and configuration
to perform a wide options, most users
range of tasks, from interact with Windows
managing files and primarily through the
processes to graphical user
configuring system interface (GUI).
settings and
automating complex
operations.
12 Serve While Linux dominates
r While Windows can be the server world,
usage Windows
used for servers, Linux Server caters to
reigns supreme. Its businesses already
stability, security, and invested in the
efficient resource Windows ecosystem.
management make it It offers easy
ideal for web hosting, integration with Active
cloud computing, Directory,
database servers, email compatibility with
servers, and more. Microsoft server
software, and a
familiar graphical user
interface for
management.
13 Gaming
(process Gaming on Linux has Windows is the
or speed) come a long way, but it undisputed king of PC
still faces challenges gaming. It boasts a
compared to Windows. vast library of games,
While the from casual titles to
open-source nature of the latest AAA
Linux fosters releases. Most game
development of developers prioritize
gaming compatibility Windows
tools like Proton and compatibility, ensuring
Steam Deck optimal performance
compatibility layer, the and a smooth gaming
overall selection of experience.
available games is
significantly smaller Processor speed plays
than on Windows. a critical role in
Additionally, some determining gaming
games may experience performance on
performance issues Windows. Games rely
due to compatibility on the processor to
layers or lack of native handle complex
Linux portsProcessor calculations, physics
speed remains a simulations, and AI
crucial factor for tasks. A faster
gaming performance processor allows for
on Linux, just as it is on smoother gameplay,
Windows. especially in
However, some games demanding titles with
may exhibit lower
performance on Linux high frame rates and
due to the overhead intricate graphics.
introduced by
compatibility layers.
14 Syste Linux updates are Windows updates are
m decentralized. delivered centrally,
update Distributions manage offering a streamlined
s them with package experience. However,
managers (APT, Yum) users have less control
offering user control over the update
over installation schedule and may be
(manual or automatic). forced to restart at
The inconvenient times.
open-source model Additionally, older
allows faster patching versions of Windows
of security eventually lose official
vulnerabilities and support, leaving them
frequent updates, vulnerable.
contributing to Linux's
stability and security.
15 Communi Linux enjoys a Windows, backed by
ty and passionate and Microsoft, offers
ecosyste dedicated community extensive official
m of users and support and resources.
developers. Online Microsoft provides
forums, user-driven documentation,
support channels, and knowledge bases, and
extensive official support
documentation are channels. This feature
readily available ensures that users find
resources for its users. their systems'
The vibrant Linux assistance. The
community fosters widespread usage of
collaboration, this OS also means
knowledge-sharing, and that users can find a
troubleshooting. Thus, wealth of online
users can easily find resources, tutorials,
solutions to their and user forums where
queries and receive they can seek help and
support when needed. engage with the
Windows community.
16 Developm Open-source nature: User-friendliness:
e nt Many development Windows offers a
environm tools and libraries familiar graphical user
e are built for interface
nt Linux, and the open- (GUI) that many users
source nature allows for are already
easy customization and comfortable with. This
troubleshooting. can make it easier to
Package managers like navigate and manage
apt or yum make files and applications
installing and managing compared to the
software efficient. command-line-centric
Command line approach of Linux.
proficiency: Linux relies Popular development
heavily on the tools: Many popular
command line, which IDEs (Integrated
gives developers Development
granular control over Environments) like
their systems and Visual Studio have
teaches valuable skills robust features
that translate well to specifically designed
server administration for Windows
and many development development. These
workflows. tools can streamline
Efficient resource the development
management: Linux is process and offer
generally lightweight features like code
and uses fewer completion and
resources compared to debugging.
Windows. Game development: If
This allows developers your focus is on game
to work on even less development, some
powerful machines and popular game engines
dedicate more like Unity and Unreal
processing power to Engine have their
their applications. primary development
environments built for
Windows.
17 virtualizat
io n Linux excels in Windows offers
virtualization due to virtualization
its inherent open- capabilities as well,
source nature and catering to a different
focus on efficiency. set of users:
Here's how:
● Hyper-V:
● Kernel-based Microsoft's Hyper-
V is a native
Virtual Machine hypervisor built
(KVM): Linux into Windows
offers KVM, a Server and Pro
powerful built-in editions. It
hypervisor that provides a robust
allows creating platform for
and managing creating and
virtual machines managing virtual
directly from the machines for
kernel. This tight various purposes.
integration ● Third-party
provides high options:
performance and Popular
hardware-assisted virtualization
virtualization software like
features. VMware
● Open-source Workstation
alternatives: also functions
Several open- well on
source virtual Windows.
machine These tools
managers like offer
VirtualBox and cross-platform
Proxmox VE are compatibility
readily available and additional
for Linux. These features for
tools offer user- managing
friendly interfaces complex virtual
for creating and environments.
managing virtual
machines with
various guest
operating systems.
18 Recover Built-in tools: Linux System Restore:
y and distributions come with System Restore allows
repair a variety of command- you to revert your
line tools for diagnosing system to a previous
and repairing disk working state using
problems, file system restore points created
errors, and permission automatically or
issues. Tools like fsck, manually.
e2fsck, and chkdsk can Startup Repair: This
help fix corrupted file built-in tool
systems. attempts to
diagnose and fix
problems
Live distributions: Many that prevent Windows
Linux distributions offer from booting properly.
live environments that Command Prompt: The
boot from a USB drive command prompt
or CD. These live offers access to
environments provide advanced recovery
access to recovery tools like chkdsk and
tools without needing bootrec.exe for
to boot the main repairing disk errors
system. and fixing boot loader
Popular options issues.
include
SystemRescueCD
and Rescatux.
pen_spark
19 networkin Command-line power: User-friendly GUI: A
g Tools like iptables graphical interface
and netstat offer simplifies managing
granular control for basic network settings.
network Active Directory
configuration and Integration: Seamless
troubleshooting. integration with
Open-source options: Active Directory for
Diverse tools like centralized user and
OpenSSH (secure access control. Built-
access) and Samba in Tools: Essential
(file sharing) cater to tools like Network
various needs. and Sharing Center
Security focus: Inherent and Remote Desktop
security features like come pre-installed.
user permissions and
firewalls make Linux
ideal for network
servers.
20 Releas Unlike Windows, Linux Windows follows a
e cycle doesn't have a single predictable release
release cycle. cycle with major
Distributions (like feature updates
Ubuntu or Fedora) typically arriving once
choose their own a year. Additionally,
approach. Some offer security updates are
frequent updates with delivered monthly on
the latest software "Patch Tuesday." This
(rolling release), while approach offers a
others balance
release major versions between new features
with long-term support and system stability.
(LTS) for stability.
21 Installati Installing Linux Installing Windows
on typically involves usually involves
process downloading an ISO creating a bootable
file, creating a USB drive or using
bootable USB drive, installation media
booting from the USB, provided with your
and following an on- computer. The process
screen installer. is often straightforward
Distributions offer and guided by an
varying levels of intuitive interface.
difficulty, with some
catering to beginners.
22 Driver Linux driver support Windows typically has
suppo can vary. Mainline good driver support for
rt kernels often have a wide range of
drivers for common hardware due to
hardware, but some manufacturer focus on
specialized devices Windows compatibility.
might require manual Updates for these
installation or drivers are often
compilation from delivered through
external sources. The Windows Update.
open-source
community plays a big
role in driver
development.
23 Boot time Boot time on Linux can Windows boot time
vary depending on can also depend on
hardware, installed hardware and startup
services, and desktop programs.
environment. While improvements
Generally, Linux can be have been made,
faster to boot, Windows boot times
especially with a tend to be slower than
lightweight desktop Linux, particularly on
and SSD storage, due HDDs, due to its
to its less resource- heavier resource
intensive nature. usage during startup.
24 multitask Linux excels at Windows also allows
in g multitasking due to its multitasking, but
efficient resource resource limitations on
management and focus heavier systems can
on the command line. slow things down.
Users can easily switch Users primarily rely on
between tasks using the graphical user
the terminal or interface (GUI) to
keyboard shortcuts, manage applications,
keeping multiple which can be less
applications running efficient for managing
smoothly. multiple tasks
simultaneously.
25 Resource Linux is known for its Windows can be
managem efficient resource resource-intensive,
e nt management. It has a especially with
lightweight core and graphical user
allocates resources like interface elements
CPU and memory more and background
efficiently compared to processes. While
Windows. This allows improvements have
you to run multiple been
applications smoothly, made, managing
even on older resource allocation can
hardware. be more challenging
on Windows, especially
for power users
running demanding
applications.
Practical: 03
Title: Hands on Unix / Linux command

1. Is:
The ls command is commonly used to identify the files and directories in the working directory.
This command is one of the many often-used Linux commands that you should know.
$ls

2. pwd :
The pwd command is mostly used to print the current working directory on your terminal. It is
also one of the most commonly used commands.
$pwd
Output:

3. mkdir :
This mkdir command allows you to create fresh directories in the terminal itself. The default
syntax is mkdir <directory name> and the new directory will be created.
$mkdir mgmu
Output:

4. cd:
The cd command is used to navigate between directories. It requires either the full path or the
directory name, depending on your current working directory. If you run this command without
any options, it will take you to your home folder. Keep in mind that it can only be executed by
users with sudo privileges.
$pwd
$cd <directory name>
$pwd
Output:

5. rmdir:
The rmdir command is used to delete permanently an empty directory. To perform this command
the user running this command must be having sudo privileges in the parent directory.
$ls
$rmdir <directory name>
$ls
Output:

6. cp:
The cp command of Linux is equivalent to copy-paste and cut-paste in Windows.
$cp Src_file Dest_file
$gedit a.txt ( Insert some text in file and save)
$gedit b.txt (Leave bank and same file)
$cat a.txt (see content of a.txt)
$cat b.txt (no content in b.txt)
$cp a.txt b.txt (copy of a.txt to b.txt)
$cat a.txt (see content of a.txt)
$cat b.txt (see content of b.txt)
Output:

7. mv:
The mv command is generally used for renaming the files in Linux.
$mv [options(s)] [source_file_name(s)] [Destination_file_name]
Here,
source_file_name(s) = The name of the files that we want to rename or move.
Destination_file_name = The name of the new location or the name of the file.
$ls
$ touch first.txt ( To create file first.txt)
$mv first.txt renamed.txt
$ls
Output:

8. rm:
rm command in Linux is generally used to delete the files created in the directory.
$rm [OPTION]... FILE...
Let us consider 5 files having name a.txt, b.txt and so on till e.txt.

$touch a.txt b.txt c.txt d.txt e.txt


$ ls
a.txt b.txt c.txt d.txt e.txt
Removing one file at a time
$ rm a.txt
$ ls
b.txt c.txt d.txt e.txt
Removing more than one file at a time
$ rm b.txt c.txt
$ ls
d.txt e.txt
Output:

9. uname:
The uname command is used to check the complete OS information of the system.
uname [OPTIONs]
Options :
-a or --all : Displays all available information.
-s or --kernel-name : Shows the kernel name.
-n or --nodename : Displays the network (domain) name of the machine.
-r or --kernel-release : Shows the kernel release.
-v or --kernel-version : Displays the kernel version.
-m or --machine : Shows the machine hardware name.
-p or --processor : Displays the processor type or “unknown.”
-i or --hardware-platform :Shows the hardware platform or “unknown.”
-o or --operating-system: Displays the operating system.
$uname -a
$uname -s
$uname -n
$uname -r
$uname -v
$uname -m
$uname -p
Output:

10. locate:
The locate command is generally used to locate the files in the database. Use an asterisk (*) to
search for content that contains two or more words.
locate [OPTION]... PATTERN...
$locate "*.html" -n 20 (It will show 20 results for the searching of file ending with .html.)
$locate -c .txt (It will count files ending with .txt.)
$ locate -i *SAMPLE.txt* ( Ignore Case Sensitive Locate Outputs Using locate Command)
Output:

11. touch:
The touch command creates an empty file when put in the terminal in this format as touch <file
name>
touch [options] file_name
Options :
-a :This option changes the access time only.
-c : Suppresses file creation if the file does not exist.
-d : Sets the access and modification times using the specified STRING.
-m : This option changes the modification time only.
-r : Uses the access and modification times from the reference file.
$touch -a filename
$touch -c filename
$touch -c-d filename
Output:
12. ln:
The ln command is used to create a shortcut link to another file. This is among the most
important Linux commands to know if you want to operate as a Linux administrator.

$mkdir demo
$mkdir Linked
$ln -s demo Linked
Output:

13. cat:
The cat command is the simplest command to use when you want to see the contents of a
particular file. The only issue is that it simply unloads the entire file to your terminal. If you want
to navigate around a huge file, should use less command alternatively.
cat [OPTION] [FILE]
1. View the Content of a Single File in Linux : $cat file_name
2. View the Content of Multiple Files in Linux : $cat file_name1 file_name2
3. View Contents of a File preceding with Line Numbers in Linux : $cat -n file_name
4. Create a file and add content in Linux Using `cat` Command : $cat > newfile_name
5. Copy the Contents of One File to Another File in Linux : $cat file1.txt file2.txt >
merged_file.txt
Output:

14. clear:
The clear command is a standard command to clear the terminal screen
Clearing our terminal using `clear -x` in Linux System : $clear -x
Using `reset` command to clear our terminal in Linux System : $reset
Output:

15. ps:
ps command in Linux is used to check the active processes in the terminal.
ps [options]
Simple process selection : Shows the processes for the current shell : $ ps
To view all running processes, use either of the following options with the `ps` command: $ps -A
View all processes except both session leaders and processes not associated with a terminal : $ps
-a
A session leader is a process that initiates other processes. View processes except session
leaders: $ps -d
List All Processes Associated with this Terminal in Linux :$ps -
T Output:

16. man:
The man command displays a user manual for any commands or utilities available in the
Terminal, including their name, description, and options.
man [option] [command]
Options:
man [command]: Display the manual page for the specified command.
-f, –whatis: Display a concise one-line description of the command.
-k, –apropos: Search for commands related to a given keyword.
-a, –all: Display all matching manual pages for the specified command.
Spacebar: Move forward one page in the manual.
Enter: Move forward one line in the manual.
B: Move backward one page in the manual.
Q: Quit the manual viewer.
$man ls
$man 2 intro
$man -f ls
Output:

17. grep:
The grep command is used to find a specific string in a series of outputs. For example, if you
want to find a string in a file, you can use the syntax: <Any command with output> | grep
“<string to find> “
$cat Files.txt | grep “new”
Case insensitive search : $grep -i "UNix" mgmfile.txt
Displaying the Count of Number of Matches Using grep :$grep -c "unix" mgmfile.txt
Output:

18. echo:
echo command in Linux is specially used to print something in the terminal
$echo [string]
$echo "MGM University"
Output:

19. wget:
The wget command in the Linux command line allows you to download files from the internet. It
runs in the background and does not interfere with other processes.
Here is the basic syntax: $wget [option] [url]
$wget http://sample.com/sample-menu.php
Output:

20. whoami:
The whoami command provides basic information that is extremely useful when working on
multiple systems. In general, if you are working with a single computer, you will not require it as
frequently as a network administrator.
$whoami
$whoami --help
$whoami --version
$whoami -u
$whoami -e
Output:

21. sort :
The sort command is used generally to sort the output of the file. Let’s use the command and see
the output.
$cat multiple.txt
$sort multiple.txt
Here first we checked the file content using the cat command and then we sorted it alphabetically
using the sort command.
Output:

22. cal :
The cal command is not the most famous command in the terminal but it functions to view the
calendar for a particular month in the terminal. Let’s see how this works.
$cal [ [ month ] year]
$cal June 2024
$cal : Shows current month calendar on the terminal with the current date highlighted.
$cal -y : Shows the calendar of the complete current year with the current date highlighted.
$cal 08 2000 : Shows calendar of selected month and
year. 4cal 2018 : Shows the whole calendar of the year.
Output:

23. whereis:
whereis command in Linux is generally used to see the exact location of any command typed
after this. Let’s see how this performs.
$whereis [options] filename...
$whereis printf
Output:

24. df :
df command in Linux gets the details of the file system.
$df -h
Output:

25. wc :
wc command in Linux indicates the number of words, characters, lines, etc using a set of options.
wc -w shows the number of words
wc -l shows the number of lines
wc -m shows the number of characters present in a file
$touch file.txt
$echo -e "This file has only six words" > file.txt
$wc -w file.txt
Here we used the touch command to create a text file and then used the echo command to input a
sentence that contains six words and we used the wc -w command to calculate the number of
words in it.
Output:

Conclusion : hence we studied the all commands

Name of Student -Ruchira Devane

Class- TY -03

Batch-C4

Roll no-4040
Practical: 04
Title : Basic of Shell programming

Shell is an interface of the operating system. It accepts commands from users and
interprets them to the operating system. If you want to run a bunch of commands
together, you can do so by creating a shell script.

Creating a Shell Script :

Login to your Linux machine and open the terminal, navigate to the folder where
you want to store the shell script.Shell scripts end with the extension “.sh”. Let’s
create our first shell script. Type in
$touch script.sh

Now, this script file is not executable by default, we have to give the executable
permission to this file. Type in

$chmod +x script.sh

Now, we will add some commands to this shell script. Open this shell script with any
text editor of your choice (command-line based or GUI based) and add some
commands. We will use nano. Type in

$nano script.sh

Add the following commands to test this shell script

echo This is my first shell script


touch testfile
ls
echo End of my shell script

Save the changes, and run the shell script by typing in

$./script.sh

Comments in the shell script


Any line which starts with “#” in the shell script is treated as a comment and is
ignored by the shell during execution, except the shebang line, which we will see
later in this article. Let’s see an example. A shell script is created with the following
content.

# This is a comment
echo Testing comments in shell script
Variables in Shell Script
There are two types of variables:

● System Defined variables


● User-Defined Variables.

System-defined variables, also called environment variables, are generally


Capitalised. You can view all the current environment variables using the printenv
command. User-Defined variables are set by the user, and they exist only during
script execution. You can define a variable by simply typing its name and assigning
a value with = sign and access a variable by adding a $ before the variable name.
Variables are demonstrated in the following example script.

# Accessing an Environment Variable


echo $USER

# Creating and accessing User defined Variable


variable_name="JNEC MGMU"
echo $variable_name

Defining the Shell Script interpreter


There are many Shells available in Linux, such as The bourne shell(sh), The Korn
Shell(ksh), and GNU Bourne-Again Shell(bash). Scripts written for the sh shell are
called shell scripts, and they can be interpreted by both, the ksh and bash shells.
ksh and Bash are improved versions of the original sh shell and they have more
features than sh. Bash is generally the default shell in most of the Linux
Distributions and scripts written specifically for bash shell are called bash scripts.

You can specify which shell the script will use, even if the script is executed from
another shell terminal. To do this, add “#!” on top of the script file, followed by the
absolute path of the shell of choice. To specify bash as an interpreter, Add the
following line on top of the shell script.

You can specify which shell the script will use, even if the script is executed from
another shell terminal. To do this, add “#!” on top of the script file, followed by the
absolute path of the shell of choice. To specify bash as an interpreter, Add the
following line on top of the shell script.

#!/bin/bash

This line is called the shebang line.

Note: This will only work if bash is installed on your system.

Conditional statements
IF THAN :
#!/bin/sh
x=10
y=11
if [ $x -ne $y ]
then
echo "Not equal"
fi

IF THEN ELSE:

#!/bin/sh
x=10
y=10
if [ $x -ne $y ]
then
echo "Not equal"
else
echo "They are equal"
fi

Loops
Using loops, you can a set of commands over and over again, until a certain

condition is met. WHILE LOOP:

#!/bin/sh
x=2
while [ $x -lt 6 ]
do
echo $x
x=`expr $x + 1`
done

FOR LOOP :

#!/bin/sh
for var in 2 4 5 8
do
echo $var
done
Positional Arguments
Positional arguments are the arguments or values which we pass to the shell script
while executing the script. They are accessed by variables $0, $1, $2 … $9. Beyond
that, they are referenced by ${10}, ${11} and so on. $# stores the no of passed
arguments and $0 stores the name of the script. Let’s see an example to
understand all this.

bin/sh
eco "No of arguments is $#"
echo "Name of the script is $0"
echo "First argu#!/ment is $1"
echo "Second argument is $2"h

Storing the output of commands


You can store the output of commands inside a variable in a shell script. There are
two ways to do so.

Syntax

#Syntax 1
var=$(a valid linux command)
#Syntax 2
var2=`a valid linux

command` Let’s see an

example.

#!/bin/sh
b=$(pwd)
c=`pwd`
echo $b
echo $c
d=$(ls /bin | grep bash)
echo $d

Exit Codes of shell commands


Whenever a command ends and returns the control to the parent process, it returns exit
codes between 0 and 255. Exit code 0 means the command was successful, and
any other exit code means, the command was unsuccessful. You can view the exit
code after running any command by accessing the $? variable.
$pwd
$ echo $?
$pwds
$echo $?

You can manually set an exit code for your shell script. This can be used with
conditional statements to convey if the script’s purpose was achieved or not.

Example

#!/bin/sh
read x
if [ $x -ne 10 ]
then
echo failed
exit 1
else
echo passed
exit 0
fi

Conclusion : Study about basic shell programming

Name of Student -Ruchira Devane

Class-TY -03

Batch-CSE

Roll no-4040
Practical-5
Title : Shell Script programming using grep, awk, sed

Shell Script programming using grep :


Suppose you have a directory structure like this:

/home/cse40/lab5

|-- file1.txt
|-- file2.txt
|-- lab5subdir
|-- file3.txt

And the content of the files are:


- `file1.txt`: "Hello world"
- `file2.txt`: "This is a test"
- `file3.txt`: "Hello again"

Now, if you want to search for the word "Hello" in the `/lab5`, you can use
the script as follows:
$touch grep_script.sh

#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <pattern> <directory>"
exit 1
fi
pattern=$1
directory=$2
# Search for the pattern in the specified directory and its subdirectories
grep -r "$pattern" "$directory"

1. Save the script in a file named `grep_script.sh`.


2.Make the script executable: $chmod +x grep_script.sh
3. Run the script with the pattern "Hello" and the directory `/lab5`:
./grep_script.sh "Hello" /home/cse40/lab5

Expected Output:
/home/cse40/lab5/file1.txt:Hello world
/home/cse40/lab5/lab5subdir/file3.txt:Hello again

This output shows the lines containing the word "Hello" along with the file
names where the pattern was found.
Shell Script programming using awk :

Awk is a scripting language used for manipulating data and generating


reports. The awk command programming language requires no compiling
and allows the user to use variables, numeric functions, string functions, and
logical operators.

Here is a simple `awk` script example to extract and print specific columns from
a file:
$touch awk_script.sh
$nano awk_script.sh

#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <column1> <column2> <file>"
exit 1
fi
column1=$1
column2=$2
file=$3
# Use awk to print the specified columns
awk -v col1="$column1" -v col2="$column2" '{print $col1, $col2}' "$file"

Suppose you have a file `data.txt` with the following content:


1 Raj 25
2 Sunil 30
3 Vinit 22
4 Rahul 28

If you want to extract and print the first and third columns (ID and age), you
can use the script as follows:

1. Save the script as `awk_script.sh`.


2. Make the script executable: $chmod +x awk_script.sh
3. Create the `data.txt` file:
echo -e "1 Raj 25\n2 Sunil 30\n3 Vinit 22\n4 Rahul 28" > data.txt
4. Run the script: ./awk_script.sh 1 3 data.txt

Expected Output:
1 25
2 30
3 22
4 28
This output shows the first and third columns of each line from the `data.txt` file.
Shell Script programming using sed :

SED command in UNIX stands for stream editor and it can perform lots of functions on file like
searching, find and replace, insertion or deletion. Though most common use of SED command in
UNIX is for substitution or for find and replace. By using SED you can edit files even without
opening them, which is much quicker way to find and replace something in file, than first
opening that file in VI Editor and then changing it.
● SED is a powerful text stream editor. Can do insertion, deletion, search and
replace(substitution).
● SED command in unix supports regular expression which allows it perform complex
pattern matching.

$touch awk_script.sh
$nano awk_script.sh

#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <pattern> <replacement> <file>"
exit 1
fi
pattern=$1
replacement=$2
file=$3
# Use sed to replace the pattern with the replacement string in the specified file
sed -i "s/$pattern/$replacement/g" "$file"

Suppose you have a file `example.txt` with the following content:


Hello world
This is a test
Hello again

If you want to replace the word "Hello" with "Hi", you can use the script as
follows:

1. Save the script as “sed_script.sh”.


2. Make the script executable:$ chmod +x sed_script.sh
3. Create the `example.txt` file:
echo -e "Hello world\nThis is a test\nHello again" > example.txt
4. Run the script:
./sed_script.sh "Hello" "Hi" example.txt
Expected Output in “example.txt”:

Hi world
This is a
test Hi
again

This script replaces all occurrences of the word "Hello" with "Hi" in the
`example.txt` file.

Conclusion : hence we studied about the shell programming using sed awk and
grep

Output
Practical-o6
Title : Demonstration of fork, execve and wait system calls

Prerequisite :Handling C programs in Linux :

Step 1: Write the C Program


$gedit hello.c
write your C code:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}

Save

Step 2: Compile the C Program


$ sudo apt update
$ sudo apt install gcc
$ gcc -o hello hello.c
This command tells GCC to compile `hello.c` and output an executable named `hello`.

Step 3: Run the Executable


$./hello
This should output:
Hello, World!

Step 4: Debugging (Optional)


If your program has issues, you may need to debug it. `gdb` (GNU Debugger) is a powerful debugging
tool for C programs.
$sudo apt update
$sudo apt install gdb
Compile the program with the `-g` flag to include debugging information:
$gcc -g -o hello hello.c
Run `gdb` with the compiled executable:
gdb ./hello
Inside `gdb`, you can use commands like `run` to start the program, `break` to set breakpoints, `step` and
`next` to step through the code, and `print` to inspect variables.

Step 5: Profiling (Optional)


Profiling helps you analyze the performance of your program. `gprof` is a profiling tool you can use.
Compile with Profiling Information
$gcc -pg -o hello hello.c
Run the executable to generate profiling data:
$./hello
Analyze the Profiling Data
gprof ./hello gmon.out > analysis.txt
Inspect `analysis.txt` to see the profiling results.

Demonstration of the `fork`, `execve`, and `wait` system calls in C :

These are used for process control in Unix-like operating systems.

1. `fork` is used to create a new process by duplicating the calling process.


2. `execve` is used to execute a new program in the current process.
3. `wait` is used to wait for a state change in a child process, typically its termination.

Below is a C program that demonstrates these system calls:


$gedit fork_exec_wait.c

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

int main() {
pid_t pid;
int status;

// Fork a child process


pid = fork();

if (pid < 0) {
// Fork failed
perror("Fork failed");
exit(1);
} else if (pid == 0) {
// Child process
printf("Child process (PID: %d)\n", getpid());

// Arguments for execve


char *argv[] = { "/bin/ls", "-l", NULL };
char *envp[] = { NULL };

// Replace the child process image with a new process image


if (execve("/bin/ls", argv, envp) < 0) {
perror("execve failed");
exit(1);
}
} else {
// Parent process
printf("Parent process (PID: %d)\n", getpid());

// Wait for the child process to finish


if (wait(&status) < 0) {
perror("wait failed");
exit(1);
}

if (WIFEXITED(status)) {
printf("Child exited with status %d\n", WEXITSTATUS(status));
} else {
printf("Child did not exit successfully\n");
}
}

return 0;
}

Explanation:
1. Forking:
- `pid = fork();` creates a new process. The new process is the child process, which is a copy of the
parent process. The return value of `fork` is zero in the child process and the child's PID in the parent
process.

2. Executing a new program:


- In the child process, we use `execve("/bin/ls", argv, envp);` to replace the child process image with a
new process image (in this case, the `ls` command). The first argument is the path to the new program,
the second is the argument list, and the third is the environment list.

3.Waiting for the child process:


- In the parent process, `wait(&status);` waits for the child process to change state. This usually means
waiting for it to terminate. `wait` returns the PID of the child that changed state and stores the termination
status in the integer pointed to by `status`.

Compile and Run:


$gcc -o fork_exec_wait fork_exec_wait.c
$./fork_exec_wait
This program will create a child process, replace its image with the `ls` command, and the parent process
will wait for the child to finish execution and then print the child's exit status.

Expected Output
When you compile and run this program, the output should look something like this:

Explanation:
1. Parent process (PID: 3015):- This line is printed by the parent process immediately after the `fork`
system call.
2. Child process (PID: 3016): This line is printed by the child process immediately after the `fork` system
call.
3. Output of `ls -l` command: The child process executes the `ls -l` command, listing the directory
contents in long format. The exact output will depend on the contents of the directory where the program
is run.
4. Child exited with status 0: This line is printed by the parent process after the child process has finished
executing and terminated with an exit status of 0, indicating successful execution.

Conclusion : Hence we studied about of fork, execve and wait system calls
Output -
Practical 07
Title : Inter-process Communication (IPC) in Linux
=======================================================================
Inter-process Communication (IPC) in Linux is crucial for allowing processes to communicate with each
other.

1. Pipes : Simple Parent-Child

Communication pipe_example.c
#include <stdio.h> // For printf and perror
#include <unistd.h> // For pipe, fork, read, write, and
close #include <string.h> // For strlen

int main() {
int fd[2]; // Array to hold the file descriptors for the pipe
pid_t pid; // Variable to hold the process ID
char write_msg[] = "Hello, world!"; // Message to be written to the pipe
char read_msg[20]; // Buffer to hold the message read from the pipe

// Create a pipe
if (pipe(fd) == -1) {
perror("pipe"); // Print an error message if pipe creation fails
return 1; // Exit with a non-zero status to indicate an
error
}

// Create a child process


pid = fork();

// Check for errors during fork


if (pid < 0) {
perror("fork"); // Print an error message if fork fails
return 1; // Exit with a non-zero status to indicate an error
} else if (pid == 0) { // Child process code
close(fd[0]); // Close the unused read end of the pipe
write(fd[1], write_msg, strlen(write_msg) + 1); // Write the message to the pipe; +1 to include the
null terminator
close(fd[1]); // Close the write end of the pipe after writing
} else { // Parent process code
close(fd[1]); // Close the unused write end of the pipe

`
Compilation and Execution:
$gcc -o pipe_example pipe_example.c
$./pipe_example

Expected Output:
Parent read: Hello, world!

2. Message Queues : Sending and Receiving

Messages msg_queue_example.c
#include <stdio.h> // For printf and perror
#include <stdlib.h> // For exit()
#include <sys/ipc.h> // For ftok() and key_t
#include <sys/msg.h> // For msgget(), msgsnd(), msgrcv(),
msgctl() #include <string.h> // For strcpy()

// Define the message buffer structure


struct msg_buffer {
long msg_type; // Message type (must be of type
long) char msg_text[100]; // Buffer to hold the message
text
} message;

int main() {
key_t key; // Variable to hold the IPC key
int msgid; // Variable to hold the message queue ID

// Generate a unique key for the message queue


key = ftok("progfile", 65); // "progfile" is a file used to generate the key; 65 is a project-specific
identifier
// Create or access the message queue
msgid = msgget(key, 0666 | IPC_CREAT); // 0666 sets read and write permissions;
IPC_CREAT creates the queue if it doesn't exist

// Prepare the message for sending


message.msg_type = 1; // Set the message type to 1
strcpy(message.msg_text, "Hello, world!"); // Copy the message text into the message buffer

// Send the message to the queue


msgsnd(msgid, &message, sizeof(message), 0); // Send the message; 0 means no special flags
printf("Sent message: %s\n", message.msg_text); // Print the sent message

// Receive the message from the queue


msgrcv(msgid, &message, sizeof(message), 1, 0); // Receive a message of type 1; 0 means no special
flags
printf("Received message: %s\n", message.msg_text); // Print the received message

// Remove the message queue from the system


msgctl(msgid, IPC_RMID, NULL); // IPC_RMID is the command to remove the message queue;
NULL means no additional arguments

return 0; // Exit the program successfully


}

Compilation and Execution:


$gcc -o msg_queue_example msg_queue_example.c
$./msg_queue_example

Expected Output:
Sent message: Hello, world!
Received message: Hello, world!
3. Shared Memory : Writing and Reading Shared

Memory shm_example.c

#include <stdio.h> // For printf


#include <sys/ipc.h> // For ftok() and key_t
#include <sys/shm.h> // For shmget(), shmat(), shmdt(),
shmctl() #include <string.h> // For strcpy()

int main() {
// Generate a unique key for the shared memory segment
key_t key = ftok("shmfile", 65); // "shmfile" is a file used to generate the key; 65 is a project-specific
identifier

// Create or access a shared memory segment


int shmid = shmget(key, 1024, 0666 | IPC_CREAT); // 1024 is the size of the shared memory segment;
0666 sets read and write permissions; IPC_CREAT creates the segment if it doesn't exist

// Attach the shared memory segment to the process's address space


char *str = (char*) shmat(shmid, (void*)0, 0); // (void*)0 indicates that the system should choose the
address; 0 means no special flags

// Write data to the shared memory segment


strcpy(str, "Hello, world!"); // Copy the string "Hello, world!" into the shared memory segment
printf("Data written in memory: %s\n", str); // Print the data written to the shared memory

// Detach the shared memory segment from the process's address space
shmdt(str); // Detach the shared memory segment

// Remove the shared memory segment from the system


shmctl(shmid, IPC_RMID, NULL); // IPC_RMID is the command to remove the shared memory
segment; NULL means no additional arguments

return 0; // Exit the program successfully


}

Compilation and Execution:

$gcc -o shm_example shm_example.c


$./shm_example

Expected Output:
Data written in memory: Hello, world!
`

Conclusion: practical implementations of various IPC mechanisms in Linux. You can build more
complex applications by combining these techniques as needed.
Practical 08
Title : Linux Commands for System Administrators

Linux System Administrator involves the installation, configuration, maintenance and management
of Linux-based systems.

1. Uptime Command
The Linux uptime command shows how long your system is running and the number of users who are
currently logged in and also displays the load average of a system for 1, 5, and 15 minutes intervals.

# uptime
08:16:26 up 22 min, 1 user, load average: 0.00, 0.03, 0.22

● Check Uptime Version

Uptime command don’t have other options other than uptime and version. It gives information
only in hours:mins:sec if it is less than 1 day.

# uptime -V
procps version 3.2.8

2. W Command

The w command will display users currently logged in and their process along with showing load
averages, login name, tty name, remote host, login time, idle time, JCPU, PCPU, command, and
processes.

#w
08:27:44 up 34 min, 1 user, load average: 0.00, 0.00, 0.08 TTYFROM USER
LOGIN@ IDLE JCPU PCPU WHAT tecmint pts/0
192.168.50.1 07:590.00s 0.29s 0.09s w

● Available Options
● -h : displays no header entries.
● -s : without JCPU and PCPU.
● -f : Removes from the field.
● -V : (upper letter) – Shows versions.

3. Users Command

Users command displays currently logged-in users. This command doesn’t have other parameters other
than help and version.
# users
tecmint

4. Who Command

Who command returns the user name, date, time, and host information. who command is similar to w
command. Unlike the w command who doesn’t print what users are doing. Let’s illustrate and see the
difference between who and w commands.

# who
tecmint pts/0 2012-09-18 07:59 (192.168.50.1)

#w
08:43:58 up 50 min, 1 user, load average: 0.64, 0.18, 0.06 USERTTYFROM
LOGIN@ IDLE JCPU PCPU WHAT
tecmint pts/0192.168.50.1 07:590.00s 0.43s 0.10s w

● Who command Options


○ -b: Displays last system reboot date and time.
○ -r: Shows current runlet.
○ -a, –all: Displays all information cumulatively.

5. ls Command

Ls command displays a list of files in a human-readable format.

# ls -l
total 114
dr-xr-xr-x. 2 root root 4096 Sep 18 08:46 bin
dr-xr-xr-x. 5 root root 1024 Sep 8 15:49 boot
Sort file as per last modified time.

# ls -ltr
total 40
-rw-r--r--. 1 root root 6546 Sep 17 18:42 install.log.syslog
-rw-r--r--. 1 root root 22435 Sep 17 18:45 install.log
-rw-------. 1 root root 1003 Sep 17 18:45 anaconda-ks.cfg
6. Crontab Command

List scheduled jobs for current users with crontab command and -l option.

# crontab -l
00 10 * * * /bin/ls >/ls.txt

Edit your crontab with -e the option. The below example will open scheduled jobs in VI
editor. Make necessary changes and quit pressing :wq keys that save the setting
automatically.

# crontab -e

7. Less Command

less command allows quickly viewing the file. You can page up and down. Press ‘q‘
to quit from less window.

# less install.log

Installing setup-2.8.14-10.el6.noarch
warning: setup-2.8.14-10.el6.noarch: Header V3 RSA/SHA256 Signature, key ID
c105b9de: NOKEY
Installing filesystem-2.4.30-2.1.el6.i686
Installing ca-certificates-2010.63-
3.el6.noarch Installing xml-common-
0.6.3-32.el6.noarch Installing tzdata-
2010l-1.el6.noarch
Installing iso-codes-3.16-2.el6.noarch
8. More Command

more command allows quickly view file and shows details in percentage. You can
page up and down. Press ‘q‘ to quit out from more window.

# more install.log

Installing setup-2.8.14-10.el6.noarch
warning: setup-2.8.14-10.el6.noarch: Header V3 RSA/SHA256 Signature, key ID
c105b9de: NOKEY
Installing filesystem-2.4.30-2.1.el6.i686
Installing ca-certificates-2010.63-
3.el6.noarch Installing xml-common-
0.6.3-32.el6.noarch
Installing tzdata-2010l-1.el6.noarch
Installing iso-codes-3.16-2.el6.noarch
--More--(10%)

9. SSH Command (Secure Shell)

SSH command is used to login into the remote host. For example, the below ssh
command will connect to the remote host (192.168.50.2) using the user as Narad.

# ssh
[email protected]

10. ps command

The ps command displays processes running in the system. The below example show the
init
to process only.

# ps -ef | grep init

root root10 0 07:53 ? 00:00:04 /sbin/init


7508 6825 0 11:48 pts/1
00:00:00 grep init

11. Systemctl Command


Systemctl command is a systemd management tool that is used to manage services, check running
statuses, start and enable services and work with the configuration files.

# systemctl start httpd.service


# systemctl enable httpd.service
# systemctl status httpd.service

12. kill command


Use the kill command to terminate the process. First, find process id with ps
command as shown below and kill the process with kill -9 command.

# ps -ef | grep init


root root1 0 0 07:53 ? 00:00:04 /sbin/init
7508 6825 0 11:48 pts/1
00:00:00 grep init

# kill- 9 7508
Conclusion: successfully executed command for Linux Commands for System Administrator
Practical: 09
Title : Implementation of CPU scheduling using the FCFS Algorithm, SJF Algorithm, and
Round Robin Algorithm, Priority Algorithm

Implementing CPU scheduling algorithms like FCFS (First-Come, First-Served), SJF (Shortest Job First), Round Robin,
and Priority Scheduling can be a great way to understand how operating systems manage process execution.

1. First-Come, First-Served (FCFS) Algorithm


algorithm schedules processes in the order they arrive in the ready queue. It's straightforward but not optimal for
minimizing waiting time or turnaround time.

Function FCFS_Scheduling(processes):

# processes is a list of tuples (process_id, arrival_time,

burst_time) Initialize waiting_time array to 0 for all

processes

Initialize turnaround_time array to 0 for all

processes Set total_waiting_time to 0

Set total_turnaround_time to

0 Sort processes by

arrival_time

for i from 1 to number of processes:

if i is 1:

# First process, waiting time is

zero waiting_time[i] = 0

else # Calculate waiting time as the sum of burst times of all previous

processes waiting_time[i] = waiting_time[i-1] + burst_time[i-1]

# Calculate turnaround time

turnaround_time[i] = waiting_time[i] +

burst_time[i] # Update total waiting time

and turnaround time total_waiting_time +=

waiting_time[i]The FCFS

total_turnaround_time +=

turnaround_time[i]

# Calculate average waiting time and turnaround time

avg_waiting_time = total_waiting_time / number of processes

avg_turnaround_time = total_turnaround_time / number of


processes return avg_waiting_time, avg_turnaround_time
2. Shortest Job First (SJF) Algorithm

The SJF algorithm selects the process with the shortest burst time from the ready queue. It can be either
preemptive or non-preemptive.

Function SJF_Scheduling(processes):

# processes is a list of tuples (process_id,

burst_time) Initialize waiting_time array to 0 for

all processes Initialize turnaround_time array to

0 for all processes Set total_waiting_time to 0

Set total_turnaround_time to

0 Sort processes by

burst_time

for i from 1 to number of processes:

if i is 1:

# First process, waiting time is

zero waiting_time[i] = 0

else:

# Calculate waiting time as the sum of burst times of all previous

processes waiting_time[i] = waiting_time[i-1] + burst_time[i-1]

# Calculate turnaround time

turnaround_time[i] = waiting_time[i] +

burst_time[i] # Update total waiting time

and turnaround time total_waiting_time +=

waiting_time[i] total_turnaround_time +=

turnaround_time[i]

# Calculate average waiting time and turnaround time

avg_waiting_time = total_waiting_time / number of processes

avg_turnaround_time = total_turnaround_time / number of

processes return avg_waiting_time, avg_turnaround_time

3. Round Robin (RR) Algorithm


The Round Robin algorithm assigns a fixed time quantum to each process in the ready queue Function
Round_Robin_Scheduling(processes, time_quantum):

# processes is a list of tuples (process_id, burst_time)


# time_quantum is the fixed time slice for each

process Initialize remaining_time array with burst_time

of each process Initialize waiting_time array to 0 for all

processes

Initialize turnaround_time array to 0 for all

processes Set time to 0

while True:

done = Trueand cycles through them until all processes are complete.

for i from 1 to number of processes:

if remaining_time[i] > 0:

done = False

if remaining_time[i] > time_quantum:

# Process still has time left after

quantum time += time_quantum

remaining_time[i] -=

time_quantum else:

# Process can finish within the

quantum time +=

remaining_time[i] waiting_time[i]

= time - burst_time[i]

remaining_time[i] = 0

if done:

break

for i from 1 to number of processes:

# Calculate turnaround time

turnaround_time[i] = waiting_time[i] +

burst_time[i] # Calculate average waiting time

and turnaround time

avg_waiting_time = sum of waiting_time / number of processes

avg_turnaround_time = sum of turnaround_time / number of

processes return avg_waiting_time, avg_turnaround_time


4. Priority Scheduling Algorithm
The Priority Scheduling algorithm assigns each process a priority and schedules processes based on their priority.
Lower priority numbers indicate higher priority.

Function Priority_Scheduling(processes):
# processes is a list of tuples (process_id, burst_time, priority)

Initialize waiting_time array to 0 for all


processes Initialize turnaround_time array to 0
for all processes Set total_waiting_time to 0
Set total_turnaround_time to
0 Sort processes by priority
for i from 1 to number of processes:
if i is 1:
# First process, waiting time is zero
waiting_time[i] = 0
else:
# Calculate waiting time as the sum of burst times of all previous
processes waiting_time[i] = waiting_time[i-1] + burst_time[i-1]
# Calculate turnaround time
turnaround_time[i] = waiting_time[i] + burst_time[i]

# Update total waiting time and turnaround time


total_waiting_time += waiting_time[i]
total_turnaround_time += turnaround_time[i]
# Calculate average waiting time and turnaround time
avg_waiting_time = total_waiting_time / number of processes
avg_turnaround_time = total_turnaround_time / number of
processes

return avg_waiting_time, avg_turnaround_time

Conclusion: implemented the different types of algo

First come first serve code\


#include<stdio.h>
// Function to find the waiting time for all
void findWaitingTime(int processes[], int n,
int bt[], int wt[])
{
// waiting time for first process is 0
wt[0] = 0;

// calculating waiting time


for (int i = 1; i < n ; i++ )
wt[i] = bt[i-1] + wt[i-1] ;
}

// Function to calculate turn around time


void findTurnAroundTime( int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

//Function to calculate average time


void findavgTime( int processes[], int n, int bt[])
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt);

//Function to find turn around time for all processes


findTurnAroundTime(processes, n, bt, wt, tat);

//Display processes along with all details


printf("Processes Burst time Waiting time Turn around time\n");

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
printf(" %d ",(i+1));
printf(" %d ", bt[i] );
printf(" %d",wt[i] );
printf(" %d\n",tat[i] );
}
float s=(float)total_wt / (float)n;
float t=(float)total_tat / (float)n;
printf("Average waiting time = %f",s);
printf("\n");
printf("Average turn around time = %f ",t);
}

// Driver code
int main()
{
//process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

//Burst time of all processes


int burst_time[] = {10, 5, 8};

findavgTime(processes, n, burst_time);
return 0;
}

Output-

Processes Burst time Waiting time Turn around time


1 10 0 10
2 5 10 15
3 8 15 23
Average waiting time = 8.333333
Average turn around time =
16.000000

You might also like