Os Practical File

You might also like

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

Dr BR Ambedkar National Institute of

Technology Jalandhar (Punjab)-144027


Operating Systems
Practical File
(CSPC-232)

Submitted to- Submitted


by-
Dr. Prashant Sonam Saini

(2023)
1.Basics of OS
1.Define operating system.
An Operating System (OS) is a program that is used as an interface between a user and a computer
hardware. It also controls the execution of all programs in a computer. An operating system is a software
that performs all of the tasks in a computer like file management, memory management, process
management, handling input/output and controlling of the peripheral devices like disk drives, scanners and
printers.
2. Explain various types of Operating Systems.
Different types of Operating Systems are listed as follows:
a) Batch Operating System:
This operating system does not interact with the computer directly. There is an operator that takes
similar jobs having same requirements and group them into batches. It is the responsibility of operator to
sort the jobs with the similar needs.
b) Time-sharing Operating System:
In this OS, each task is given some time to execute, so that all the tasks work smoothly. Each user gets
time of CPU as they use single system. These systems are also known as Multitasking Systems. The task
can be from single user or from different users also. The time that each task gets to execute itself is
called quantum. After this interval of time is over, the OS switches over to the next task.

c) Distributed Operating System:


This type of operating system is a recent advancement in the computer technology and are being widely
accepted all-over the world with a great pace. Various autonomous interconnected computers
communicate each other using a shared communication network. Independent systems also possess their
own memory unit and CPU. These are referred as loosely coupled systems or distributed systems. These
system’s processors differ in size and function. The major benefit of working with these types of
operating system is that it is always possible that one user can access the files or software which are not
actually present on his system but on some other system connected within this network i.e., remote
access is enabled within the devices connected in that network.

d) Network Operating System:


These systems run on a server and provide the capability to manage data, users, groups, security,
applications, and other networking functions. These type of operating systems allow shared access of
files, printers, security, applications, and other networking functions over a small private network. One
more important aspect of Network Operating Systems is that all the users are well aware of the
underlying configuration, of all other users within the network, their individual connections etc. and
that’s why these computers are popularly known as tightly coupled systems.
e) Real-Time Operating System:
The real time OS serves the real-time systems. The time interval required to process and respond to
inputs is quite small. This time interval is called response time. These types of Real-time systems are
used when the time requirements are very strict like missile systems, air traffic control systems, robots
etc
2.To understand the UNIX/LINUX Operating Systems Environments .
1. Introduction to UNIX:
 The Unix operating system is a set of programs that act as a link between the computer and the user.
 The computer programs that allocate the system resources and coordinate all the details of the
computer's internals is called the operating system or the kernel.
 Users communicate with the kernel through a program known as the shell. The shell is a command
line interpreter; it translates commands entered by the user and converts them into a language that is
understood by the kernel.
 Several people can use a Unix computer at the same time; hence Unix is called a multiuser system.
 A user ca
 n also run multiple programs at the same time; hence Unix is a multitasking environment.
2. LINUX:
 Linux is a community of open-source Unix like operating systems that are based on the Linux
kernel.
 Linux distribution is an operating system that is made up of a collection of software based on
Linux kernel or you can say distribution contains the Linux kernel and supporting libraries and
software
Architecture of Linux:
Linux architecture has the following components:

1. Kernel: Kernel is the core of the Linux based operating system. It virtualizes the common
hardware resources of the computer to provide each process with its virtual resources. This
makes the process seem as if it is the sole process running on the machine. The kernel is also
responsible for preventing and mitigating conflicts between different processes. Different types
of the kernel are: 
 Monolithic Kernel
 Hybrid kernels
 Exo kernels
 Micro kernels
2. System Library: Is the special types of functions that are used to implement the functionality
of the operating system.
3. Shell: It is an interface to the kernel which hides the complexity of the kernel’s functions from
the users. It takes commands from the user and executes the kernel’s functions.
4. Hardware Layer: This layer consists all peripheral devices like RAM/ HDD/ CPU etc.
5. System Utility: It provides the functionalities of an operating system to the user.

System calls:
A system call is a function that allows a process to communicate with the Linux kernel. It’s just a
programmatic way for a computer program to order a facility from the operating system’s kernel. System
calls expose the operating system’s resources to user programs through an API (Application Programming
Interface). System calls can only access the kernel framework. System calls are needed for all the services
that need resources.
In Linux, making a system call involves transferring control from unprivileged user mode to privileged
kernel mode; the details of this transfer vary from architecture to architecture. The libraries take care of
collecting the system-call arguments and, if necessary, arranging those arguments in the special form
necessary to make the system call.
System calls are divided into 5 categories mainly:

System call execution:


In Linux, a system call is a programmatic way for user space applications to request services from the
kernel. System calls provide an interface between a user process and the operating system, allowing
processes to perform tasks such as file input/output, process management, networking, and other system-
related tasks.
When a user process requests a system call, it transitions from user mode to kernel mode, allowing it to
execute privileged instructions that it would not be allowed to execute otherwise. The system call is
identified by a unique system call number, and the arguments for the system call are passed via registers or
the process stack.
The process of executing a system call involves the following steps:
1. The user process executes a software interrupt (int 0x80) or a system call instruction (syscall),
triggering a transition from user mode to kernel mode.
2. The kernel determines which system call the user process is requesting based on the system call
number passed in the appropriate register.
3. The kernel checks the validity of the arguments passed by the user process to ensure they are within
the process's address space and have the correct type.
4. If the arguments are valid, the kernel executes the requested system call and returns the result to the
user process. If the arguments are invalid, the kernel returns an error code to the user process.
5. After the system call has completed, the user process resumes execution in user mode.
Overall, system calls provide a crucial interface between user space applications and the kernel, allowing
programs to interact with the operating system in a safe and controlled manner.
Command structure:
A command is a program that tells the Unix system to do something. UNIX uses a special program,
called the shell or the command line interpreter, to interpret what you have typed into what you want to
do.
The structure of a Linux command consists of three parts: the command itself, options or flags, and
arguments.
 command: The name of the command you want to execute.
 -option: An optional flag that modifies the behaviour of the command.
 argument: Required information that the command operates on.
The general structure of a Linux/UNIX command line looks like:
command [-flag(s)] [-option(s) [value]] [argument(s)]
3. To understand the concept of shell and related commands.
a. Concept of shell:
A Shell provides you with an interface to the Unix/LINUX system. It gathers input from you and executes
programs based on that input. When a program finish executing, it displays that program's output. These
shells could either be command-line interfaces (CLI) or graphical user interfaces (GUI).
Shell is an environment in which we can run our commands, programs, and shell scripts. There are different
flavours of a shell, just as there are different flavours of operating systems. Each flavour of shell has its own
set of recognized commands and functions.

OR
Shell is a macro processor that allows for an interactive or non-interactive command execution. It is
completely based on the graphical user interface so that the user can interact with the underlying operating
system.  
b. Types of shell:
1. Bash (Bourne-Again SHell): This is the default shell for most Linux distributions. It is a command-
line interface that provides a powerful and flexible environment for interacting with the system.
However, the Bourne shell has some major drawbacks:
 It doesn’t have in-built functionality to handle logical and arithmetic operations.
 Also, unlike most different types of shells in Linux, the Bourne shell cannot recall previously
used commands.
 It also lacks comprehensive features to offer a proper interactive use.
The complete path-name for the Bourne shell is /bin/sh and /sbin/sh. By default, it uses the
prompt # for the root user and $ for the non-root users.
2. Korn shell (ksh): Korn shell is another popular shell that is compatible with the Bourne shell (sh) and
includes some additional features.  It also supports scripts which were written for the C shell.
Further, it is faster than most different types of shells in Linux, including the C shell.
The complete path-name for the Korn shell is /bin/ksh. By default, it uses the prompt # for the root
user and $ for the non-root users.
3. C shell (csh): C shell is a shell designed for the C programming language. It includes features such as
command-line completion and history. It includes many features such as command line editing, error
status, fatal errors, history, and job control.
4. Z shell (zsh): Z shell is a powerful shell that includes features such as command-line completion,
spelling correction, and more. The Z Shell or zsh is a sh shell extension with tons of improvements
for customization. If you want a modern shell that has all the features a much more, the zsh shell is
what you’re looking for.
5. Fish shell (Friendly Interactive SHell): This is a modern feature-rich shell that aims to be user-
friendly and interactive. It includes features such as syntax highlighting, auto suggestions, and tab
completion.
1. ls command and its options:
ls is a Linux shell command that lists directory contents of files and directories. The syntax is $ ls [options]
[file|dir]. Different options along with implementation are shown in following table:
ls -a list all files including hidden file starting with '.'.
ls -d list directories - with ' */'.
ls -l list with long format - show permissions.
ls -F Append indicator (one of */=>@|) to entries.
ls -lh This command will show you the file sizes in human readable format.
ls -r list in reverse order.
ls -i list file's inode(index) number.
ls -ltr View Reverse Output Order by Date.
ls -t sort by time & date.
ls -n It is used to print group ID and owner ID instead of their names.
ls -m A list of entries separated by commas should fill the width.
ls -g This allows you to exclude the owner and group information columns.
ls -q Force printing of non-graphic characters in file names as the character `?';.
ls -Q Place double quotations around the entry names.

2. Here are some common options that can be used with the "cat" command:
1. cat [filename]: This command will display the contents of a single file on the terminal.
2. cat [filename1] [filename2]: This command will display the contents of two files together on the terminal.
3. cat [filename] > [newfilename]: This command will create a new file with the contents of the file
mentioned in the command.
4. cat -n [filename]: This option will display the contents of a file with line numbers added for every line.
5. cat -b [filename]: This option will display the contents of a file with line numbers added for every non-
blank line.
76. cat -s [filename]: This option will remove all the extra blank lines from the file and display its contents.
7. cat -w [filename]: This option will wrap long lines in the file and display it.

3. Pipe is used to combine two or more commands, and in this, the output of one command acts as input to
another command, and this command’s output may act as input to the next command and so on. It can also
be visualized as a temporary connection between two or more commands/ programs/ processes. The
command line programs that do the further processing are referred to as filters. This direct connection
between commands/ programs/ processes allows them to operate simultaneously and permits data to be
transferred between them continuously rather than having
to pass it through temporary text files or through the display screen.
Pipes are unidirectional i.e data flows from left to right through the pipeline.

4. There are several ways to sign off or log out from a Linux system, including:
1. Using the exit command: This is the most common way to log out from a Linux terminal. Simply type
"exit" in the terminal and hit Enter.
2. Using the logout command: This command is similar to "exit" and does the same job. Type "logout" in
the terminal and hit Enter.
3. Using the Ctrl + D key combination: This is a shortcut key to log out from a terminal. Simply press Ctrl
and D at the same time.
4. Using the shutdown command: This command can be used to shut down or reboot the system. To shut
down the system, type "sudo shutdown -h now" in the terminal and hit Enter. To reboot the system, type
"sudo reboot" in the terminal and hit Enter.
5. Using the GUI: If you are using a graphical interface, you can log out by clicking on the "Log Out" or
"Sign Off" option in the menu or by pressing the power button, which will give you the option to shut down
or log out.
8) The locating command in an operating system is used to search for files and directories on the system.
The most common command used for this purpose is 'locate' on Linux and Unix systems. This command
searches for files and directories based on their names and provides a list of matching files or directories
with their full paths. The locate command uses a database of files and directories that is updated periodically
to ensure that the search results are accurate and up-to-date. Other locating commands include 'find' and
'whereis'. The 'find' command searches for files and directories based on specified criteria such as file size or
modification time. The 'whereis' command returns the location of executable files, source files, and manual
pages for a given command.

9) - Path: A path is a list of directories that the operating system searches when looking for an executable
file. When a user-types a command in a terminal, the operating system searches for the command in the
directories specified in the PATH environment variable.
- Shell Variables: Shell variables are variables used by the shell or command-line interface to store
temporary or permanent data. These variables are used for various purposes such as holding user input,
setting environment variables, and storing output from commands.

10) There are several simple ways you can combine several commands on a single command line:
 You can run a series of commands, one after the other:
 Using a semicolon (;)
 Using && and ||
 You can run more than one command concurrently:
 Using a pipe (|) or a filter with a pipe
The output from the first command is piped to the next command as the first command is running.
11) echo is a command in Unix/Linux operating systems that displays a string or message on the terminal
window. It is commonly used to print the value of a variable or to display informational messages to
users.echo -e is a command that lets you use backslash escape sequences to format the output of the echo
command. For example, you can use \n to insert a new line, \t to insert a tab, or \b to insert a backspace.
12) cal command:
The cal command displays the calendar of the current month in the terminal. The basic syntax of the cal
command is:
cal [options] [month] [year]
date command:
The date command displays the current date and time in the terminal. The basic syntax of the date command
is:
date [options]
13) The "man" command is short for manual, which means it provides a detailed description of almost any
command or utility available on the system. It is useful for learning about a specific application or utility and
its usage syntax to perform commands. By typing "man <command>", the user can access and browse the
manual page of that specific command.
The "help" command provides help information about built-in commands of Bash shell. It is a feature of
bash shell that offers almost the same function as the man command but provides help documentation of
Bash shell built-in commands. The usage of the help command is simply "help <command>".
14)
Escape sequences are a special type of terminal input. They're designed to make it possible for you to enter
characters or events that you may not have on your physical keyboard.

15)
the Printf command inserts arguments into a user-defined string of text, creating formatted output.
4. To understand internal and external commands in Linux Os:
1)
 Internal Commands: Commands which are built into the shell. For all the shell built-in commands,
execution of the same is fast in the sense that the shell doesn’t have to search the given path for them
in the PATH variable, and also no process needs to be spawned for executing it.
Examples: source, cd, fg, etc.
 External Commands: Commands which aren’t built into the shell. When an external command has
to be executed, the shell looks for its path given in the PATH variable, and also a new process has to
be spawned and the command gets executed. They are usually located in /bin or /usr/bin. For
example, when you execute the “cat” command, which usually is at /usr/bin, the executable
/usr/bin/cat gets executed.
Examples: ls, cat etc.

2)

1. passwd: The passwd command is used to change or update the password for a user account on a Linux
system. It is commonly used by system administrators or individual users to keep their accounts secure.

2. who: The who command shows all of the users who are currently logged into the system. It displays
information about the users' names, login times, and terminal names or IP addresses. This command is
useful for system administrators who need to keep track of system users and their activities.

3. uname: The uname command is used to display basic information about the operating system on a Linux
system, such as the kernel version, network node name, and processor type. It can be used to check system
details before running specific tasks or installing software.

4. tty: The tty command displays the name of the terminal that you are currently using on the system. It also
shows basic information about the terminal, such as its type and device number.

5. stty: The stty command is used to change the settings of a Linux terminal. It can be used to adjust the
terminal's display, input, and output settings, including settings for line endings, tabs, and other control
characters. This command is commonly used by system administrators who need to customize the terminal
settings to match their specific needs.

3)
1. Regular files - contain data or text and can be read or edited by users.
2. Directories - containers for other files and directories.
3. Device files - represent hardware devices such as disks, printers, and sound cards.
4. Symbolic Links - act as shortcuts to other files and directories.
5. Named pipes – special files used for inter-process communication (IPC) between software processes.
6. Sockets - special files used for network communications.
7. Block-special files – used for accessing blocks of data, typically used for hard drives and other storage
devices.
8. Character-special files - used for accessing data in a continuous stream, typically used for devices such as
keyboards and sound cards.

Some common file systems in Linux are:


1. Ext4.
2. Btrfs
3. XFS
6)
1. pwd- The pwd command stands for "Print Working Directory". It is used to display the current working
directory or folder in the command line interface.

2. cd - The cd command stands for "Change Directory". It is used to navigate between different directories
or folders in the command line interface. For example, "cd Desktop" will take you to the Desktop directory.

3. mkdir - The mkdir command stands for "Make Directory". It is used to create a new directory or folder in
the current directory. For example, "mkdir myfolder" will create a new folder named "myfolder" in the
current directory.

4. rmdir - The rmdircommand stands for "Remove Directory". It is used to delete a directory or folder in the
current directory. For example, "rmdir myfolder" will delete the folder named "myfolder" in the current
directory.

7)
An absolute pathname specifies the complete path of a file or directory from the root directory, starting with
a forward slash (/).
A relative pathname specifies the path of a file or directory relative to the current working directory. It does
not start with a forward slash (/) and may use special characters such as .. (parent directory) and . (current
directory).
8) A relative pathname specifies the path of a file or directory relative to the current working directory. It
does not start with a forward slash (/) and may use special characters such as .. (parent directory) and .
(current directory).

9)
1. Cat: This command is used to concatenate and display the contents of one or more files on the
terminal.Example: cat file1.txt file2.txt
2. Cp: This command is used to copy a file or directory from one location to another.Example: cp file1.txt
/home/user/Desktop
3. Rm: This command is used to delete a file or directory.Example: rm file1.txt
4. Mv: This command is used to move or rename a file or directory.Example: mv file1.txt
/home/user/Documents/file2.txt
5. Wc: This command is used to count the number of lines, words, and characters in a file.Example: wc
file1.txt
6. Comm: This command is used to compare two sorted files line by line and display the common and
unique lines.Example: comm file1.txt file2.txt
7. Cmp: This command is used to compare two files byte by byte and display the first mismatch.Example:
cmp file1.txt file2.txt
8. Diff: This command is used to compare two files line by line and display the changes made.Example: diff
file1.txt file2.txt

10)
Compressing a file essentially means reducing its size by removing unnecessary or redundant data from the
file. This is done by using a file compression algorithm that will pack the data into a smaller size.
Compressed files can then be transmitted or stored more efficiently.

Archiving is the process of grouping files and directories together into one file or directory. This can be used
for backup purposes or to transfer a bunch of files as a single package. The archived file will retain file
metadata and information about the original files, making it easier to locate a particular file within the
archive.

Archive formats like ZIP or TAR can compress multiple files into one file, creating an archive. This archive
can then be compressed again to further reduce its size.
5. To understand the basic file attribute
1)
The 'ls' command is used to list the contents of a directory. The '-l' option stands for 'long format', which
displays detailed information about the files in the directory. The output of 'ls -l' includes the following basic
file attributes:

- The first character indicates whether the file is a regular file, directory, symbolic link, etc.
- The next nine characters represent the file permissions for the owner, group, and others.
- The next field indicates the number of hard links to the file.
- The fourth field is the name of the owner of the file.
- The fifth field is the name of the group that owns the file.
- The sixth field is the size of the file in bytes.
- The seventh field is the date and time that the file was last modified.
- The final field is the name of the file.

The '-d' option is used to display information about the directory itself, rather than its contents. When used
with the '-l' option ('ls -ld'), it displays the basic attributes of the directory itself, rather than the files
contained within it, including its permissions, owner, group, size, and modification date.
2)
File permissions are a way to control who can access a file and what level of access they have. There are
three types of permissions: read (r), write (w), and execute (x). These permissions can be set for three
different groups: the owner of the file, the group that the file belongs to, and others.

File permissions can be viewed using the 'ls -l' command in Unix-based systems. The permissions are
displayed as a series of nine characters, with the first character indicating the type of file and the next nine
characters indicating the permissions.

To change the access rights for a file, you can use the 'chmod' command. The 'chmod' command allows an
owner or administrator to change the permissions of a file or a directory.
3)
In relative permission it changes the permission specified in command and leave other permission
unchanged.
Absolute permission: permission specified by setting all nine permission bits explicitly.in the chmod we
used three octal number.
4)
Directory permission commands are used in the Linux operating system to set the access rights or
permissions for directories. These permissions control who can access the directory, what actions can be
performed on the directory, and whether files can be created or deleted within the directory.
The three basic types of permissions are:

1. Read permission (r): allows users to view the contents of a directory.


2. Write permission (w): allows users to create, modify, or delete files within a directory.
3. Execute permission (x): allows users to access the files or subdirectories within a directory.
To set directory permissions, the chmod command is used. The command has the following syntax:
chmod [options] permissions file/directory
5)
In Linux, file ownership determines which user or group has rights to access or modify a file. The command
used to change the ownership of a file or directory is chown (short for "change owner"). This command is
typically used by system administrators to change the owner of a file or directory, when it is necessary to
restrict or allow access to other users.
The basic syntax of the chown command is:
chown [options] ownername filename
where ownername is the user or group to which you want to assign the file, and filename is the name of the
file you want to modify.
6.To understand concept of vim editor and related commands
1)
The vi editor is elaborated as visual editor. It is installed in every Unix system. In other words, it is
available in all Linux distros. It is user-friendly and works same on different distros and platforms. It is a
very powerful application. An improved version of vi editor is vim.
The vi editor has two modes:
o Command Mode: In command mode, actions are taken on the file. The vi editor starts in command
mode. Here, the typed words will act as commands in vi editor. To pass a command, you need to be
in command mode.
o Insert Mode: In insert mode, entered text will be inserted into the file. The Esc key will take you to
the command mode from insert mode.
By default, the vi editor starts in command mode. To enter text, you have to be in insert mode, just
type 'i' and you'll be in insert mode. Although, after typing i nothing will appear on the screen but you'll be
in insert mode. Now you can type anything.
To exit from insert mode press Esc key, you'll be directed to command mode.
If you are not sure which mode you are in, press Esc key twice and you'll be in command mode.
2)
The repeat factor refers to the number of times a specific pattern or sequence is repeated in a given context.
It is a measure of the frequency with which a particular event or phenomenon occurs. In the context of data
analysis, the repeat factor can be used to identify trends or patterns in a dataset that may indicate a specific
relationship or causal factor.
3)
Input mode is the mode in which a user can enter text or commands into their computer or device. In this
mode, the computer is waiting for input from the user.
Insertion of text is the process of adding new text to an existing document. In input mode, the user can move
the cursor to the desired location and start typing to insert new text.
4)
Saving text is the process of storing the text entered by the user into a file or document. This is usually done
by selecting the "save" option from the menu or pressing a specific keyboard shortcut. Saving the text
ensures that the user does not lose their work and can access it later.

Quitting text involves exiting out of the input mode and closing the document or file. This is usually done by
selecting the "quit" or "exit" option from the menu or pressing a specific keyboard shortcut. When the user
quits the text, any unsaved changes will be lost unless they have been previously saved.
6)
Editing text refers to making changes to a written or typed document. Editing can include correcting spelling
or grammar mistakes, adding, deleting or moving words or paragraphs, formatting text, or making other
revisions to improve the clarity, flow, or style of the writing.
7)
Undo last editing allows you to reverse the previous action that you made to the text. This is useful for
correcting errors or mistakes that you have made while editing a document.
8)
Repeating last command is a shortcut feature that saves time by allowing you to repeat the last action you
performed. This is particularly useful when performing repetitive tasks such as formatting text or moving
objects on the page.
10)
Substitution- search and replace is a feature that allows you to find specific text within a document and
replace it with something else. This is particularly helpful when correcting mistakes or changing a
commonly used phrase throughout a document. For example, you could replace all instances of "colour"
with "color" in an entire document.
7. To understand shell scripting using variable passing arguments
Shell scripting is a powerful tool for automating repetitive tasks and streamlining complex workflows. To
fully utilize shell scripting, it's important to understand how to pass arguments and variables between
different parts of your script. Here's a basic introduction to variable passing and argument handling in shell
scripting:

1. The $ symbol
In shell scripting, the $ symbol is used to reference the value of a variable. For example, if you have a
variable named "my_variable" with a value of "Hello, world!", you can reference its value using the $
symbol like this: $my_variable.

2. Positional parameters
Positional parameters are arguments that are passed to a script when it is executed. They are numbered
starting with $1 for the first argument, $2 for the second argument, and so on. For example, if you run a
script like this: ./myscript.sh argument1 argument2, $1 will be "argument1" and $2 will be "argument2"
inside the script.

3. Handling arguments
In order to handle arguments in your script, you can use special variables like $#, which gives you the
number of arguments passed, and $@, which gives you all the arguments as separate values. For example,
you can use a for loop like this to iterate over all the arguments and print them:
for arg in "$@"
do
echo "$arg"
done
4. Declaring and using variables
To declare a variable in your script, use the syntax variable_name=value. For example, to create a variable
named "my_variable" with a value of "Hello, world!", use the following code:
my_variable="Hello, world!"
echo $my_variable
You can also use variables and arguments together to build more complex code. For example:
#!/bin/bash
# This script takes two arguments and concatenates them
arg1=$1
arg2=$2
result="$arg1$arg2"
echo $result
By understanding how to declare and use variables, and how to handle arguments and positional parameters,
you can create powerful shell scripts to automate complex tasks and streamline everyday workflows.
8.To understand shell scripting using while loops, arithmetic and logical and append .

While Loops-
It is possible to use a while loop as part of the body of another while loop.
Syntax
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true

while command2 ; # this is loop2, the inner loop


do
Statement(s) to be executed if command2 is true
done

Statement(s) to be executed if command1 is true


Done
Example
Here is a simple example of loop nesting. Let's add another countdown loop inside the loop that you used to
count to nine −
#!/bin/sh

a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
This will produce the following result. It is important to note how echo -n works here. Here -n option lets
echo avoid printing a new line character.
0
10
210
3210
43210
543210
6543210
76543210
876543210
9876543210
9. To understand shell scripting using file text operators and other basic operators.
Shell scripting is a programming language that allows you to automate tasks in a Unix or Linux
environment. It uses a combination of commands, utility programs, and shell programming constructs to
accomplish various tasks.

One aspect of shell scripting is the use of file text operators. These operators allow you to manipulate text
files in various ways.

The most common file text operators are:

- "<" - redirects input from a file to a command


- ">" - redirects output from a command to a file, overwriting any existing file
- ">>" - appends output from a command to a file, preserving the existing file
- "|" - passes output from one command to another command as input

For example, you can use the "<" operator to redirect input from a file to a command like this:

$ cat < input.txt

This will display the contents of the file "input.txt" on the screen.

You can also use the ">" operator to create a new file or overwrite an existing file with the output of a
command like this:

$ echo "Hello, world!" > output.txt

This will create a new file called "output.txt" with the text "Hello, world!".

To append output to an existing file, you can use the ">>" operator like this:

$ echo "Goodbye, world!" >> output.txt

This will add the text "Goodbye, world!" to the end of the "output.txt" file.

Finally, you can use the "|" operator to pass the output of one command as input to another command like
this:

$ ps aux | grep firefox

This will display a list of all processes running on your system and then filter out only the processes that
contain the word "firefox" in their name.

In addition to file text operators, shell scripting also makes use of other basic operators like arithmetic,
comparison, and logical operators. These operators allow you to perform calculations, compare values, and
create conditional statements in your scripts.
Some common basic operators are:

- "+" - addition
- "-" - subtraction
- "*" - multiplication
- "/" - division
- "%" - modulo (remainder)
- "==" - equal to
- "!=" - not equal to
- "<" - less than
- ">" - greater than
- "<=" - less than or equal to
- ">=" - greater than or equal to
- "&&" - logical AND
- "||" - logical OR
- "!" - logical NOT

For example, you can use an if statement to check if a variable is greater than 10 like this:

if [ $num -gt 10 ]
then
echo "The number is greater than 10."
fi

This will evaluate the condition inside the square brackets and only execute the echo command if the
condition is true.

Overall, shell scripting is a powerful tool for automating tasks and managing your Unix or Linux
environment. By using file text operators and basic operators, you can create complex scripts that perform a
wide range of tasks with ease.
10. Write a program in C/C++ to demonstrate these Process Scheduling Algorithms:

a) FCFS

#include<stdio.h>

int main()

int n,bt[30],wait_t[30],turn_ar_t[30],av_wt_t=0,avturn_ar_t=0,i,j;

printf("Please enter the total number of processes(maximum 30):"); // the maximum process that be used
to calculate is specified.

scanf("%d",&n);

printf("\nEnter The Process Burst Timen");

for(i=0;i<n;i++) // burst time for every process will be taken as input

printf("P[%d]:",i+1);

scanf("%d",&bt[i]);

wait_t[0]=0;

for(i=1;i<n;i++)

wait_t[i]=0;

for(j=0;j<i;j++)

wait_t[i]+=bt[j];

printf("\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time");

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

turn_ar_t[i]=bt[i]+wait_t[i];

av_wt_t+=wait_t[i];

avturn_ar_t+=turn_ar_t[i];

printf("\nP[%d]\t\t%d\t\t\t%d\t\t\t\t%d",i+1,bt[i],wait_t[i],turn_ar_t[i]);

av_wt_t/=i;

avturn_ar_t/=i; // average calculation is done here

printf("\nAverage Waiting Time:%d",av_wt_t);

printf("\nAverage Turnaround Time:%d",avturn_ar_t);

return 0;

Output:
b) SJF
#include<string.h>

#include<stdio.h>

int main()

int bt[20],at[10],n,i,j,temp,st[10],ft[10],wt[10],ta[10];

int totwt=0,totta=0;

double awt,ata;

char pn[10][10],t[10];

//clrscr();

printf("Enter the number of process:");

scanf("%d",&n);

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

printf("Enter process name, arrival time& burst time:");

scanf("%s%d%d",pn[i],&at[i],&bt[i]);

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


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

if(bt[i]<bt[j])

temp=at[i];

at[i]=at[j];

at[j]=temp;

temp=bt[i];

bt[i]=bt[j];

bt[j]=temp;

strcpy(t,pn[i]);

strcpy(pn[i],pn[j]);

strcpy(pn[j],t);

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

if(i==0)
st[i]=at[i];

else

st[i]=ft[i-1];

wt[i]=st[i]-at[i];

ft[i]=st[i]+bt[i];

ta[i]=ft[i]-at[i];

totwt+=wt[i];

totta+=ta[i];

awt=(double)totwt/n;

ata=(double)totta/n;

printf("\nProcessname\tarrivaltime\tbursttime\twaitingtime\tturnaroundtime");

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

printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],bt[i],wt[i],ta[i]);

printf("\nAverage waiting time: %f",awt);


printf("\nAverage turnaroundtime: %f",ata);

return 0;

}
OUTPUT:
b) Sjrf

#include <stdio.h>
int main()
{
int at[10],bt[10],rt[10],endTime,i,smallest;
int remain=0,n,time,sum_wait=0,sum_turnaround=0;
printf("Enter no of Processes : ");
scanf("%d",&n);
for(i=0;i<n;i++)

printf("Enter arrival time for Process P%d : ",i+1);

scanf("%d",&at[i]);

printf("Enter burst time for Process P%d : ",i+1);

scanf("%d",&bt[i]);

rt[i]=bt[i];

printf("\n\nProcess\t|Turnaround Time| Waiting Time\n\n");

rt[9]=9999;

for(time=0;remain!=n;time++)

{
smallest=9;

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

if(at[i]<=time && rt[i]<rt[smallest] && rt[i]>0)

smallest=i;

rt[smallest]--;

if(rt[smallest]==0)

remain++;

endTime=time+1;

printf("\nP[%d]\t|\t%d\t|\t%d",smallest+1,endTime-at[smallest],endTime-bt[smallest]-at[smallest]);
sum_wait+=endTime-bt[smallest]-at[smallest];

sum_turnaround+=endTime-at[smallest];

printf("\n\nAverage waiting time = %f\n",sum_wait*1.0/n);

printf("Average Turnaround time = %f",sum_turnaround*1.0/5);

return 0;

}
Ouput:
Lab 11. Write a program in C/C++ to demonstrate these Process Scheduling
Algorithms
(a) round robin

#include<stdio.h>
int main()

int cnt,j,n,t,remain,flag=0,tq;

int wt=0,tat=0,at[10],bt[10],rt[10];

printf("Enter Total Process:\t ");

scanf("%d",&n);

remain=n;

for(cnt=0;cnt<n;cnt++)

printf("Enter Arrival Time and Burst Time for Process Process Number %d :",cnt+1);

scanf("%d",&at[cnt]);

scanf("%d",&bt[cnt]);

rt[cnt]=bt[cnt];

printf("Enter Time Quantum:\t");

scanf("%d",&tq);

printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");

for(t=0,cnt=0;remain!=0;)

if(rt[cnt]<=tq && rt[cnt]>0)

t+=rt[cnt];

rt[cnt]=0;

flag=1;
}

else if(rt[cnt]>0)

rt[cnt]-=tq;

t+=tq;

if(rt[cnt]==0 && flag==1)

remain--;

printf("P[%d]\t|\t%d\t|\t%d\n",cnt+1,t-at[cnt],t-at[cnt]-bt[cnt]);

wt+=t-at[cnt]-bt[cnt];

tat+=t-at[cnt];

flag=0;

if(cnt==n-1)

cnt=0;

else if(at[cnt+1]<=t)

cnt++;

else

cnt=0;

printf("\nAverage Waiting Time= %f\n",wt*1.0/n);

printf("Avg Turnaround Time = %f",tat*1.0/n);

return 0;

}
Output:

:
(a) Priority (Non-Preemptive)

You might also like