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

Osc Lab Record

The document discusses gaining root privilege on Linux systems using the su and sudo commands. It explains how to unlock the root account, switch to the root user using su -, and use sudo to run commands with root privileges without switching users. Managing passwords and password policies for user accounts is also covered.

Uploaded by

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

Osc Lab Record

The document discusses gaining root privilege on Linux systems using the su and sudo commands. It explains how to unlock the root account, switch to the root user using su -, and use sudo to run commands with root privileges without switching users. Managing passwords and password policies for user accounts is also covered.

Uploaded by

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

SCHOOL OF ENGINEERING AND TECHNOLOGY

Record of Applied and Action Learning


(Programming Practice)

Subject Name:

Subject Code:

Semester:

Name:

Registration No.:

Program/Branch:

Specialization:

Academic Year:

Campus:
CENTURION UNIVERSITY OF TECHNOLOGY AND MANAGEMENT
ODISHA

Certificate
This is to certify that Mr./Ms. ............................................................................ having

Registration No. ............................................... of ........................................ Semester,

.................................................................... Program, ..........................................................

School, .................................................. Campus has completed ...................................

number of experiments in ............................................ Applied and Action

Learning Laboratory and fulfils the.........................................................course

requirements.

Signature of the HoD/Dean Signature of the Faculty

Of)ice Seal
INDEX
Sl. Page Faculty
Date Name of the Experiment Remark
No. No. Signature
1 Copy from one to another file
using unbuffered I/O system
2 Gaining Root privilege with
su and sudo
3 Login to remote system
through SSH
4 Demonstrate of Hierarchical
File System in Linux
5 Controlling Access to files
with ACL
6 Create, Edit, Save and Exit
using Vim by using VM Box
7 Write a script to demonstrate
decision making, loop control,
Arrays
8 Write a program to simulate
the following CPU scheduling
Algorithm [Round Robin]
9 Write a program to simulate
Banker’s Algorithm for
DeadLock prevention
10 Write a program to simulate
page replacement algorithm
[FIFO]
School: ............................................................................................................. Campus: .......................................................

Academic Year: ...................... Subject Name: ........................................................... Subject Code: ..........................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


Name of the Experiment : i) Copy a File Using unbuffered System Calls
ii) print contents of directory using system calls
iii) Infinite loop kill sending SIGINT signal through Ctrl + C

*As applicable according to the experiment.


One sheet per experiment (10-20) to be used.
Applied and Action Learning

One sheet per experiment (10-20) to be used.


1: pointer variable to store the result back from the function inside this variable
2: the dir name.
What does readdir() need from me?
1: it needs a struct to save the returned value from this function
2: the dir name to read
What does closedir() need from me?
just the dir name
so if we collect now what we want to use these three system calls, we will find that we need
1- initiate a pointer variable to store the returned value of the opendir function
2- initiate a struct to save the returned value of readdir function

One sheet per experiment (10-20) to be used.


Overall, the opendir, readdir, and closedir functions provide a handy set of tools for
working with directories in C, enabling you to iterate through directory entries, access their
contents, and securely shut the directory stream when your actions are finished.

One sheet per experiment (10-20) to be used.


Write a C program that doesn’t terminate when Ctrl+C is pressed. It prints a message
“Cannot be terminated using Ctrl+c” and continues execution. We can use signal handling
in C for this. When Ctrl+C is pressed, SIGINT signal is generated, we can catch this
signal and run our defined signal handler. C standard defines following 6 signals
in signal.h header file. SIGABRT – abnormal termination. SIGFPE – floating point
exception. SIGILL – invalid instruction. SIGINT – interactive attention request sent to the
program.

One sheet per experiment (10-20) to be used.


Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:


*As applicable according to the experiment.

One sheet per experiment (10-20) to be used.


Name of the Experiment : i) Gaining Root privilege with sudo and su
ii) Archiving and Compressing of File
iii) Creating user setting up password and managing
password policies

i) Gaining Root privilege with sudo and su

The "root" user account on Linux has full administrative privileges over the entire system. If
you want to edit system configuration files, install software, add users, or virtually anything
else outside of your home directory, you'll need root access. For most tasks, you won't need
to log or switch to the root user account—you can run your administrative tasks with
the sudo command to run them as root. This prevents you from doing damage while logged
in with full superuser permissions. If you're using Ubuntu, the root account is locked by
default to prevent this from happening. But if you need to keep root access while doing a
large amount of system tasks, you can enable the root user and become root with
the su command, or by signing in as root on console

One sheet per experiment (10-20) to be used.


Open the terminal. Ubuntu and several other distributers lock the root account automatically
to prevent you from using commands that can damage your system. You can unlock the root
account in the terminal. If you're in the desktop environment, you can press 'Ctrl + Alt +
T to start the terminal.

Type .sudo passwd root and press ↵ Enter. When prompted for a password, enter
your user password

One sheet per experiment (10-20) to be used.


Set a new password. You'll be prompted to create a new password and enter it twice. Once
a password has been set, the root account will be active

Lock the root account again. If you want to lock the root account, enter the following
command to remove the password and lock root:
sudo passwd -dl root

One sheet per experiment (10-20) to be used.


Open the terminal. If the terminal is not already open, open it. Many distributions allow you
to open it by pressing Ctrl + Alt + T

Type .su - and press ↵ Enter. This will attempt to log you in as "super user." You can
actually use this command to log in as any user on the machine, but when left blank it will
attempt to log in as root

Enter the root password when prompted. After typing "su -" and pressing Enter. You'll be
prompted for the root password.
If you get an "authentication error" message, your root account is likely locked. You will
need to unlock the root account.

* One sheet per learning record to be used


Check the command prompt. When you are logged in as root, the command
prompt will end with # instead of $ (if you're using the bash, bourne, or korn shell)
or % (if you're using csh, tcsh, or zsh).

Enter the commands that require root access. Once you've used su - to log in
as root, you can run any commands that require root access. The su command is
preserved until the end of the session, so you don't need to keep re-entering the
root password every time you need to run a command

* One sheet per learning record to be used


.
Consider using .sudo instead of su -. sudo ("super user do") is a command that lets you run
other commands as root temporarily. This is the best way for most users to run root
commands, as the root environment is not maintained, and the user doesn't need to know the
root password. Instead, the user will enter their own user password for temporary root
access.
Type sudo command and press ↵ Enter (e.g. sudo ifconfig). When prompted for the
password, enter your user password, not the root password.
sudo is the preferred method for distributions like Ubuntu, where it will work even when the
root account is locked.
This command is limited to users with administrator privileges. Users can be added or
removed from /etc/sudoers.

II. Archiving and Compressing A File


Archiving is the process of combining multiple files into a single package called an archive.
This archive can then be easily distributed to another machine, backed up in a repository
somewhere, or simply kept on your own machine as a way to organize and cleanup your file
system. Archives are also an essential component of the Linux ecosystem, because all the
software you install via your distribution’s package manager will initially be downloaded as
a compressed archive from a remote repository. Therefore, working with archives is an
important aspect of using a Linux based operating system effectively.
This article will introduce the standard archiving tool used on Linux — which is
the tar software utility — and demonstrate its usage on the command line to create and work
with archives, or tarballs. The tar utility is also able to compress an archive via a
compression tool. This usage pattern of firstly creating an archive and then compressing it
using a compression tool is often adopted for distributing packages remotely.

* One sheet per learning record to be used


The tar File Archiver

Tar was initially released in January 1979 and has since evolved into the
standard file archiver on Linux. As of writing this article in November 2020,
the latest stable version of tar was released on February 23, 2019 and therefore
is still in active development to this day.

If tar is not on your system already, go ahead and install it via your Linux
distribution’s package manager:
$ sudo pacman -S tar # Arch
$ sudo apt install tar # Debian and Ubuntu
$ sudo dnf install tar # CentOS and Fedora

I won’t dive into the intricacies of how tar works under the hood too much in
this article, but I will mention some important points to be aware of as we
progress through the commands in subsequent sections.

Compression Tools

There are quite a few compression tools available on Linux, with each one
implementing a specific compression algorithm. The compression tools
introduced in this article all have a very similar command line interface and
usage pattern, which means that if you know how to use one of the tools, you
can use them all.

Go ahead and install the gzip, bzip2, xz and zstd compression tools via your
Linux distribution’s package manager:
$ sudo pacman -S gzip bzip2 xz zstd # Arch
$ sudo apt install gzip bzip2 xz-utils zstd # Debian and Ubuntu
$ sudo dnf install gzip bzip2 xz zstd # Fedora

3.Password Policies In Linux

* One sheet per learning record to be used


The Pluggable Authentication Modules (PAM) is installed by default in DEB-
based systems.
Usually, the password and authentication-related configuration files are stored
in /etc/pam.d/ directory in Debian-based systems. And the password policies
are defined in /etc/pam.d/common-password file. Before making any changes
in it, backup this file, just in case.

$ sudo cp /etc/pam.d/common-password /etc/pam.d/common-passwo


rd.bak

To set minimum password length, edit /etc/pam.d/common-password file:

$ sudo nano /etc/pam.d/common-password

Find the following line:

password [success=2 default=ignore] pam_unix.so obscure sha51


2

* One sheet per learning record to be used


Save and close the file. Now the users can't use less than 8 characters for their password .

* One sheet per learning record to be used


Name of the Experiment : i) Login to remote system through SSH
ii) Monitoring process using top and ps
iii) communication between process using pipe

Set up public key authentication using SSH on a Linux


1. Log into the computer you'll use to access the remote host, and then use command-line
SSH to generate a key pair using the RSA algorithm.

To generate RSA keys, on the command line, enter:

ssh-keygen -t rsa

2. You will be prompted to supply a filename (for saving the key pair) and a password
(for protecting your private key):

o Filename: To accept the default filename (and location) for your key pair,
press Enter or Return without entering a filename.

Alternatively, you can enter a filename (for example, my_ssh_key) at the


prompt, and then press Enter or Return. However, many remote hosts are
configured to accept private keys with the default filename and path
(~/.ssh/id_rsa for RSA keys) by default. Consequently, to authenticate with a
private key that has a different filename, or one that is not stored in the default
location, you must explicitly invoke it either on the SSH command line or in an
SSH client configuration file (~/.ssh/config); see below for instructions.

o Password: Enter a password that contains at least five characters, and then
press Enter or Return. If you press Enter or Return without entering a password,
your private key will be generated without password-protection.
Important:
If you don't password-protect your private key, anyone with access to your
computer conceivably can SSH (without being prompted for a password) to your
account on any remote system that has the corresponding public key

* One sheet per learning record to be used


1. Use SFTP or SCP to copy the public key file (for example, ~/.ssh/id_rsa.pub) to your account on the
remote system (for example, darvader@deathstar.empire.gov); for example, using command-line SCP:

scp ~/.ssh/id_rsa.pub darvader@deathstar.empire.gov:

You'll be prompted for your account password. Your public key will be copied to your home
directory (and saved with the same filename) on the remote system.

2. Log into the remote system using your account username and password.

Note:

If the remote system is not configured to support password-based authentication, you will need to ask
system administrators to add your public key to the ~/.ssh/authorized_keys file in your account (if your
account doesn't have ~/.ssh/authorized_keys file, system administrators can create one for you). Once
your public key is added to your ~/.ssh/authorized_keys file on the remote system, the setup process is
complete, and you should now be able to SSH to your account from the computer that has your
private key.
3. If your account on the remote system doesn't already contain a ~/.ssh/authorized_keys file, create one;
on the command line, enter the following commands:

4. mkdir -p ~/.ssh

5. touch ~/.ssh/authorized_keys

Note:
If your account on the remote system already has a ~/.ssh/authorized_keys file, executing these
commands will not damage the existing directory or file.
6. On the remote system, add the contents of your public key file (for example, ~/id_rsa.pub) to a new
line in your ~/.ssh/authorized_keys file; on the command line, enter:

cat ~/id_rsa.pub >> ~/.ssh/authorized_keys

You may want to check the contents of ~/.ssh/authorized_keys to make sure your public key was added
properly; on the command line, enter:

more ~/.ssh/authorized_keys

7. You may now safely delete the public key file (for example, ~/id_rsa.pub) from your account on the
remote system; on the command line, enter:

rm ~/id_rsa.pub

Alternatively, if you prefer to keep a copy of your public key on the remote system, move it to
your .ssh directory; on the command line, enter:

mv ~/id_rsa.pub ~/.ssh/

* One sheet per learning record to be used


1. Optionally, repeat steps 3-7 to add your public key to other remote systems that you want to
access from the computer that has your private key using SSH public key authentication.
2. You now should be able to SSH to your account on the remote system (for
example, username@host2.somewhere.edu) from the computer (for example, host1) that has
your private key (for example, ~/.ssh/id_rsa):
o If your private key is password-protected, the remote system will prompt you for the
password or passphrase (your private key password/passphrase is not transmitted to
the remote system):

o [username@host1 ~]$ ssh username@host2.somewhere.edu

o Enter passphrase for key '/username/Host1/.ssh/id_rsa':

o Last login: Mon Oct 20 09:23:17 2014 from host1.somewhere_else.edu

o If your private key is not password-protected, the remote system will place you on the
command line in your home directory without prompting you for a password or
passphrase:

o [username@host1 ~]$ ssh username@host2.somewhere.edu

o Last login: Mon Oct 20 09:23:17 2014 from host1.somewhere_else.edu

If the private key you're using does not have the default name, or is not stored in the default
path (not ~/.ssh/id_rsa), you must explicitly invoke it in one of two ways:
o On the SSH command line: Add the -i flag and the path to your private key.

For example, to invoke the private key host2_key, stored in


the ~/.ssh/old_keys directory, when connecting to your account on a remote host
(for example, username@host2.somewhere.edu), enter:

ssh -i ~/.ssh/old_keys/host2_key username@host2.somewhere.edu

o In an SSH client configuration file: SSH gets configuration data from the following
sources (in this order):
1. From command-line options
2. From the user's client configuration file (~/.ssh/config), if it exists
3. From the system-wide client configuration file (/etc/ssh/ssh_config)

The SSH client configuration file is a text file containing keywords and arguments. To
specify which private key should be used for connections to a particular remote host,
use a text editor to create a ~/.ssh/config that includes
the Host and IdentityFile keywords.

For example, for connections to host2.somewhere.edu, to make SSH automatically


invoke the private key host2_key, stored in the ~/.ssh/old_keys directory, create
a ~/.ssh/config file with these lines included:

* One sheet per learning record to be used


Once you save the file, SSH will use the specified private key for future connections to that
host.

You can add multiple Host and IdentityFile directives to specify a different private key for
each host listed; for example:

Host host2.somewhere.edu
IdentityFile ~/.ssh/old_keys/host2_key

Host host4.somewhere.edu

IdentityFile ~/.ssh/old_keys/host4_key

Host host6.somewhere.edu

IdentityFile ~/.ssh/old_keys/host6_key

Alternatively, you can use a single asterisk ( * ) to provide global defaults for all hosts
(specify one private key for several hosts); for example:

Host *.somewhere.edu
IdentityFile ~/.ssh/old_keys/all_hosts_key

* One sheet per learning record to be used


ii) How to Check Running Process in Linux Using the “ps” Command

The ps (process statuses) command produces a snapshot of all running processes. Therefore,
unlike the Windows task manager, the results are static.

When this command is used without any additional argument or option, it will return a list of
running processes along with four crucial columns: the PID, terminal name (TTY), running
time (TIME), and the name of the command that launches the process (CMD). You can
use ps aux to get more in-depth information about your running processes. Here’s a
breakdown of each argument:

• a option outputs all running processes of all users in the system.


• u option provides additional information like memory and CPU usage percentage, the
process state code, and the owner of the processes.

* One sheet per learning record to be used


x option lists all processes not executed from the terminal. A perfect example of this
are daemons, which are system-related processes that run in the background when the system
is booted up.

If you want to list Linux processes in a hierarchical view, use the ps -axjf command. In this
format, the shell will put child processes under their parent processes. Aside from those two
options, here are some other common examples of the ps command that list running
processes in Linux:

• ps -u [username] lists all running processes of a certain user.


• ps -e or ps -A displays active Linux processes in the generic UNIX format.
• ps -T prints active processes that are executed from the terminal.
• Ps -C process_name will filter the list by the process name. In addition, this
command also shows all child processes of the specified process.

* One sheet per learning record to be used


The top command is used to discover resource-hungry processes. This Linux command
will sort the list by CPU usage, so the process which consumes the most resources will be
placed at the top. It’s also useful to check if a specific process is running.

Unlike the ps command, the output of the top command is updated periodically. That
means you’ll see real-time updates for CPU usage and running time

Program to write and read two messages using pipe.

Algorithm

Step 1 − Create a pipe.

Step 2 − Send a message to the pipe.

Step 3 − Retrieve the message from the pipe and write it to the standard output.

Step 4 − Send another message to the pipe.

Step 5 − Retrieve the message from the pipe and write it to the standard output.

Note − Retrieving messages can also be done after sending all messages.

* One sheet per learning record to be used


* One sheet per learning record to be used
* One sheet per learning record to be used
Name of the Experiment : i) Demonstration of Hierarchical File Sytem in Linux
ii) Controlling Access to Files using Linux File
Permissions
Linux File Permissions
Every file and directory in your UNIX/Linux system has following 3 permissions defined
for all the 3 owners discussed above.

• Read: This permission give you the authority to open and read a file. Read permission
on a directory gives you the ability to lists its content.
• Write: The write permission gives you the authority to modify the contents of a file.
The write permission on a directory gives you the authority to add, remove and rename
files stored in the directory. Consider a scenario where you have to write permission
on file but do not have write permission on the directory where the file is stored. You
will be able to modify the file contents. But you will not be able to rename, move or
remove the file from the directory.
• Execute: In Windows, an executable program usually has an extension “.exe” and
which you can easily run. In Unix/Linux, you cannot run a program unless the execute
permission is set. If the execute permission is not set, you might still be able to
see/modify the program code(provided read & write permissions are set), but not run
it.
File Permissions in Linux/Unix
Let’s see file permissions in Linux with examples:
ls – l on terminal gives
ls - l

Here, we have highlighted ‘-rw-rw-r–‘and this weird looking code is the one that tells
us about the Unix permissions given to the owner, user group and the world.
Here, the first ‘–‘ implies that we have selected a file.p>

Else, if it were a directory, d would have been shown.


The characters are pretty easy to remember.
r= read permission
w= write permission
x= execute permission
– = no permission
Let us look at it this way.
The first part of the code is ‘rw-‘. This suggests that the owner ‘Home’ can:

• Read the file


• Write or edit the file
• He cannot execute the file since the execute bit is set to ‘-‘.
By design, many Linux distributions like Fedora, CentOS, Ubuntu, etc. will add users
to a group of the same group name as the user name. Thus, a user ‘tom’ is added to a
group named ‘tom’.
The second part is ‘rw-‘. It for the user group ‘Home’ and group-members can:

• Read the file


• Write or edit the file
The third part is for the world which means any user. It says ‘r–‘. This means the user
can only:

• Read the file

Changing file/directory permissions in Linux Using ‘chmod’ command


Say you do not want your colleague to see your personal images. This can be achieved
by changing file permissions.
We can use the ‘chmod’ command which stands for ‘change mode’. Using the
command, we can set permissions (read, write, execute) on a file/directory for the
owner, group and the world.
Syntax:
chmod permissions filename
There are 2 ways to use the command –

1. Absolute mode
2. Symbolic mode

Permission
Number Symbol
Type
0 No Permission —
1 Execute –x
2 Write -w-
3 Execute + Write -wx
4 Read r–
5 Read + Execute r-x
6 Read +Write rw-
Read + Write
7 rwx
+Execute

Absolute(Numeric) Mode in Linux


In this mode, file permissions are not represented as characters but a three-digit
octal number.
The table below gives numbers for all for permissions types.
Let’s see the chmod permissions command in action.

In the above-given terminal window, we have changed the permissions of the file
‘sample to ‘764’.

‘764’ absolute code says the following:

• Owner can read, write and execute


• Usergroup can read and write
• World can only read
This is shown as ‘-rwxrw-r–
This is how you can change user permissions in Linux on file by assigning an absolute
number.

Symbolic Mode in Linux


In the Absolute mode, you change permissions for all 3 owners. In the symbolic mode,
you can modify permissions of a specific owner. It makes use of mathematical symbols
to modify the Unix file permissions.
Operator Description

+ Adds a permission to a file or directory


– Removes the permission
= Sets the permission and overrides the permissions set earlier.
The various owners are represented as –
User Denotations
u user/owner
g group
o other
a all
We will not be using permissions in numbers like 755 but characters like rwx. Let’s
look into an example

Changing Ownership and Group in Linux


For changing the ownership of a file/directory, you can use the following command:
chown user filename
In case you want to change the user as well as group for a file or directory use the
command
chown user:group filename
Let’s see this in action

In case you want to change group-owner only, use the command


chgrp group_name filename
‘chgrp’ stands for change group.
Tip

• The file /etc/group contains all the groups defined in the system
• You can use the command “groups” to find all the groups you are a member o

• You can use the command newgrp to work as a member a group other than your default
group

• You cannot have 2 groups owning the same file.


• You do not have nested groups in Linux. One group cannot be sub-group of other
• x- eXecuting a directory means Being allowed to “enter” a dir and gain possible access
to sub-dirs
Name of the Experiment : i) Controlling access to files using ACL

What is ACL ?
Access control list (ACL) provides an additional, more flexible permission mechanism for file
systems. It is designed to assist with UNIX file permissions. ACL allows you to give permissions
for any user or group to any disc resource.
Use of ACL :

Think of a scenario in which a particular user is not a member of group created by you but still
you want to give some read or write access, how can you do it without making user a member of
group, here comes in picture Access Control Lists, ACL helps us to do this trick.
Basically, ACLs are used to make a flexible permission mechanism in Linux.
From Linux man pages, ACLs are used to define more fine-grained discretionary access rights
for files and directories.
setfacl and getfacl are used for setting up ACL and showing ACL respectively.
For example :
getfacl test/declarations.h
Output:
# file: test/declarations.h
# owner: mandeep
# group: mandeep
user::rw-
group::rw-
other::r--
List of commands for setting up ACL :
1) To add permission for user
setfacl -m "u:user:permissions" /path/to/file

2) To add permissions for a group


setfacl -m "g:group:permissions" /path/to/file

3) To allow all files or directories to inherit ACL entries from the directory it is within
setfacl -dm "entry" /path/to/dir

4) To remove a specific entry


setfacl -x "entry" /path/to/file

5) To remove all entries


setfacl -b path/to/file
For example :
setfacl -m u:mandeep:rwx test/declarations.h
Modifying ACL using setfacl :
To add permissions for a user (user is either the user name or ID):
# setfacl -m "u:user:permissions"
To add permissions for a group (group is either the group name or ID):
# setfacl -m "g:group:permissions"
To allow all files or directories to inherit ACL entries from the directory it is within:
# setfacl -dm "entry"

Example :
setfacl -m u:mandeep:r-x test/declarations.h
See below image for output :

setfacl and getfacl

View ACL :
To show permissions :
# getfacl filename
Observe the difference between output of getfacl command before and after setting up
ACL permissions using setfacl command.
There is one extra line added for user mandeep which is highlighted in image above.
Output:
change permissions

The above command change permissions from rwx to r-x


Remove ACL :
If you want to remove the set ACL permissions, use setfacl command with -b option.
For example :

remove set permissions

If you compare output of getfacl command before and after using setfacl command with -
b option, you can observe that there is no particular entry for user mandeep in later output.
You can also check if there are any extra permissions set through ACL using ls command.
check set acl with ls

Observe the first command output in image, there is extra “+” sign after the permissions
like -rw-rwxr–+, this indicates there are extra ACL permissions set which you can check
by getfacl command.
Using Default ACL :
The default ACL is a specific type of permission assigned to a directory, that doesn’t
change the permissions of the directory itself, but makes so that specified ACLs are set by
default on all the files created inside of it. Let’s demonstrate it : first we are going to
create a directory and assign default ACL to it by using the -d option:
$ mkdir test && setfacl -d -m u:dummy:rw test
Name of the Experiment : i) Create, Edit, Save And Exit File
ii) Edit A System File Using Vim

Steps to create and edit a file using vim


Log into your server using SSH command: ssh user@cloud-vm-ip
Type vim command to create a file named demo.txt: vim demo.txt

Vim started with a new blank file


To enter insert mode and to append text type the letter i (usually you do this by
press Esc followed by i)

Enter INSERT mode in vim

1. Start entering text


2. When done editing press the Esc key to go back to command mode
3. Once in command mode to save and exit the file type a colon ( : ) followed
by x . Press the Enter key.

To save the file and exit the vim

Saving the text in any new file

You can write the specified lines by passing the filename to the :w . For example,
start Vim without a filename:
$ vim
Next, enter the insert mode by pressing the i key and add desired text. Finally, press
the Esc key to return to command mode. Then type a colon ( : ) followed by w
filename . Press the Enter key. For example, save to a file named demo.txt:

:w demo.txt
OR give full path:

:w /home/vivek/projects/demo.txt
Name of the Experiment : i) Write a Script to demonstrate decision making and
loop Control
ii) Write a script demonstrate arrays

Decision Making
Control structures are structures that are used in decision making.
A condition is checked and different execution paths can be defined based on whether the condition is
true or false.
In Shell Scripts, we have two control structures:
• If Elif Else fi
• Switch cases
1. If-Else Statement
If-else Statements in Shell Scripts act as a decision statement defining alternate execution paths based on
whether the condition is true or false.
• If the condition specified is true, statements in if block are executed.
• If the condition specified is false, statements in the else block are executed.
• Unlike programming languages like C++, Java etc, Shell does not use {} to define the scope of
the if statement. Shell uses if to begin if else statement and fi to close it.
Code:

Output:
Here, the code is executed two times:
When input is anything other than "admin", code prints "Access Denied" in standard output.
When input is "admin", code prints "Access Granted" in standard output.
2. If-Elif-Else Statement
When we want to check multiple conditions and define more than two alternate paths of execution based
on decision, if elif (else if) and else statements are used.
Syntax:
if [ (Condition) ]
then
Statements...
elif [ (Condition) ]
then
Statements...
elif [ (Condition) ]
then
Statements...
...
else
Statements...
fi
Code:

• When first input is greater than second input, if statement executes.


• When both inputs are equal, elif statement executes.
• When second input is greater than first input, else statement executes.
Output:
Here, the code is executed three times:
1. If statement executes because num1 > num2.
2. Elif statement executes because num1 = num2.
3. Else statement executes because num2 > num1.

Shell Scripting for loop


The for loop moves through a specified list of values until the list is exhausted.
1) Syntax:
Syntax of for loop using in and list of values is shown below. This for loop contains a number of variables
in the list and will execute for each item in the list. For example, if there are 10 variables in the list, then
loop will execute ten times and value will be stored in varname.

o Keywords are for, in, do, done


o List is a list of variables which are separated by spaces. If list is not mentioned in the for
statement, then it takes the positional parameter value that were passed into the shell.
o Varname is any variable assumed by the user.
Example for:
We have shown an example to count 2's table within for loop.

Look at the above snapshot, our varname is table, list is specified under curly braces. Within the curly
braces, first two will initialize the table from 2, 20 represents maximum value of $table and last 2 shows
the increment by value 2.
Look at the above snapshot, it displays the 2's table as the output.
2) Syntax:
Syntax of for like C programming language.

Look at the above snapshot, condition1 indicates initialization, cond2 indicates condition and cond3
indicates updation.
Example for:
We have shown an example to count the number in reverse direction.

Look at the above snapshot, this is the loop script. $i will initialize with 10 and will go till 1, decrementing
with 1 value.

Creating Arrays in Shell Scripts


There are two types of arrays that we can work with, in shell scripts.
• Indexed Arrays - Store elements with an index starting from 0
• Associative Arrays - Store elements in key-value pairs
The default array that’s created is an indexed array. If you specify the index names, it
becomes an associative array and the elements can be accessed using the index names
instead of numbers.

Declaring Arrays:
root@ubuntu:~# declare -A assoc_array
root@ubuntu:~# assoc_array[key]=value
OR
root@ubuntu:~# declare -a indexed_array
root@ubuntu:~# indexed_array[0]=value
Notice the uppercase and lowercase letter a. Uppercase A is used to declare an associative array
while lowercase a is used to declare an indexed array.
The declare keyword is used to explicitly declare arrays but you do not really need to use them.
When you’re creating an array, you can simply initialize the values based on the type of array you
want without explicitly declaring the arrays.

Working with Arrays in Shell Scripts

Now that you know how to create arrays, let’s learn how to work with arrays. Since these are
collections of data elements, we can work with loops and arrays at the same time to extract the
required data points.

1. Accessing Array Elements Individually

Since we know that each data point is being indexed individually, we can access all the array
elements by specifying the array index as shown below:

assoc_array[element1]="Hello World"
echo ${assoc_array[element1]}
Copy

Associative Arrays In
Shell Script

Similarly, let’s access some indexed array elements. We can specify all the elements for the index
array by delimiting with spaces because the index is automatically generated for each of those
elements.

index_array=(1 2 3 4 5 6)
echo ${index_array[0]}

Index Arrays In Shell Scripts

As you can see, the first element is automatically printed based on index 0.

2. Reading Array Elements Sequentially


This is going to be an easy task if you know for loops already. If you don’t we’ll cover them in a
future tutorial. We’ll make use of the while or for loops in shell scripts to work through the array
elements. Copy the script below and save it as <filename>.sh
#!/bin/bash
index_array=(1 2 3 4 5 6 7 8 9 0)

for i in ${index_array[@]}
do
echo $i
done

The above script will output the following:


Name of the Experiment : i) Write a program to simulate CPU Scheduling
Algorithm [ROUND ROBIN]

Round Robin Program in C with Output


A round-robin is a CPU scheduling algorithm that shares equal portions of resources in circular orders
to each process and handles all processes without prioritization. In the round-robin, each process gets a
fixed time interval of the slice to utilize the resources or execute its task called time quantum or time
slice. Some of the round-robin processes are pre-empted if it executed in a given time slot, while the
rest of the processes go back to the ready queue and wait to run in a circular order with the scheduled
time slot until they complete their task. It removes the starvation for each process to
achieve CPU scheduling by proper partitioning of the CPU.

Round Robin CPU Scheduling Algorithm


Step 1: Organize all processes according to their arrival time in the ready queue. The queue structure of
the ready queue is based on the FIFO structure to execute all CPU processes.

Step 2: Now, we push the first process from the ready queue to execute its task for a fixed time, allocated
by each process that arrives in the queue.

Step 3: If the process cannot complete their task within defined time interval or slots because it is
stopped by another process that pushes from the ready queue to execute their task due to arrival time of
the next process is reached. Therefore, CPU saved the previous state of the process, which helps to
resume from the point where it is interrupted. (If the burst time of the process is left, push the process
end of the ready queue).

Step 4: Similarly, the scheduler selects another process from the ready queue to execute its tasks. When
a process finishes its task within time slots, the process will not go for further execution because the
process's burst time is finished.

Step 5: Similarly, we repeat all the steps to execute the process until the work has finished.

Characteristics of Round Robin


• It is a pre-emptive algorithm.
• It shares an equal time interval between all processes to complete their task.
• It is a starvation free CPU scheduling algorithm. Hence it is known as the fairest and simple
algorithm.

Completion Time: It defines the time when processes complete their execution.
Turn Around Time: It defines the time difference between the completion time (CT) and the arrival
time (AT).
Turn Around Time (TAT) = Completion Time (CT) - Arrival Time (AT)
1. Waiting Time: It defines the total time between requesting action and acquiring the resource.
Waiting Time (WT) = Turn Around Time (TAT) - Burst Time (BT)
2. Response Time: It is the time that defines at which time the system response to a process.
Output:
Name of the Experiment : i) Write a program to simulate Banker’s Algorithm for
Deadlock prevention

Deadlock Prevention using Banker's Algorithm in C


The banker's algorithm is a resource allocation and deadlock avoidance algorithm that simulates
resource allocation for predetermined maximum possible amounts of all resources before performing
an "s-state" check to look for potential activities and determining whether allocation should be
permitted to continue.

Why the Banker's Algorithm is called that?

The reason the banker's algorithm is so titled is because it is employed in the banking sector to
determine whether or not to authorize a loan to an individual. Assume a bank has n account holders,
each of whom has an individual balance of S. When someone requests for a loan, the bank first
deducts the loan amount from the total amount of money it possesses, and only approves the loan if
the balance is more than S. It is done because the bank can simply do it if every account holder shows
up to get their money. In other words, the bank would never arrange its funds in a way that would
prevent it from meeting the demands of all of its clients. The bank would strive to maintain safety at
all times.

The Banker's Algorithm is implemented using the following data structures:

Let n be the number of processes in the system and m be the number of resource kinds.

Available:
o This 1-d array of size 'm' lists the number of resources of each category that are currently available.
o There are 'k' instances of the resource type if Available[j] = Rj

Max:
o The maximum demand of each process in a system is specified by a 2-d array of size 'n*m'.
o Process Pi may request a maximum of 'k' instances of resource type Rj if Max[i, j] = k.

Allocation:
o The quantity of resources of each kind currently assigned to each process is specified by a 2-d array
of size 'n*m'.
o Process is shown by Allocation[i, j] = k. Pi has been given 'k' instances of the resource type at this
time. Rj

Need:
o The remaining resource needs of each process are shown in a 2-d array of size 'n*m'.
o Process is shown by Need[i, j] = k. Right now, Pi requires "k" instances of the resource type. Rj
o Allocation[i, j] - Maximum[i, j] = Need[i, j]

The resources that are now allotted to process Pi are identified by Allocationi, while the extra
resources that process Pi could yet need in order to do its work are identified by Needi.

The safety algorithm and the resource request algorithm make up the banker's algorithm.

Algorithm for Safety


The following is a description of the method for determining if a system is in a safe state:

1. 1) Assume Work and Finish are two vectors, each with lengths of m and n.
2. Initialize: Work = Available
3. Finish[i] is false when i=1, 2, 3, 4...n
4. 2) Find an I such that both
5. a) Finish[i] = false
6. b) Needi <= Work
7. if such an I does not exist. goto step (4)
8. 3) Work = Work + Allocation[i]
9. Finish[i] = true
10. go to step (2)
11. 4) If Finish[i] = true for each and every i
12. then system is in a secure state.
Algorithm for Resource Requests
Let Requesti represent the process Pi request array. Process Pi requests k instances of resource type
Rj, which is indicated by Requesti [j] = k. The following things happen when process Pi makes a
request for resources:

1. 1) Proceed to step 2 if Requesti >= Needi; otherwise, report an error condition because the process
has made more claims than it can handle.
2. 2) Proceed to step (3) if Requesti <= Accessible; otherwise, Pi will have to wait since the resources
are not available.
3. 3) Change the state in such a way that the system appears to have given Pi the required resources:
4. Requested - Available = Available
5. Allocationi = Allocationi + Requesti
6. Needi = Needi - Requesti

Below is the implementation of Banker's Algorithm


Output :

Explanation:
o The processes must anticipate the maximum number of resources required as they enter the system,
which may be done in a reasonable amount of time.
o In contrast to interactive systems, this method maintains a fixed number of processes.
o A specific number of resources must be available to distribute in order for this technique to work. The
algorithm would not function if a gadget broke and went unexpectedly offline.
o The method will incur overhead costs since it must be invoked for each process when there are several
processes and resources.
Name of the Experiment : i) Write a program to simulate
page replacement algorithm[FIFO]

FIFO Page Replacement Algorithm in C


A page replacement algorithm is required in an operating system that uses paging to manage memory in
order to determine which page needs to be replaced when a new page is received.

Page Fault

A page fault occurs when an active application tries to access a memory page that is loaded in virtual
memory but not physically in the system. Page errors occur because actual physical memory is
substantially less than virtual memory. In the event of a page fault, the operating system might have to
swap out one of the current pages for the one that is now required. Different page replacement
algorithms offer various suggestions for selecting the appropriate replacement page. All algorithms
strive to lower the number of page faults.

FIFO

The simplest algorithm for replacing pages is this one. The operating system maintains a queue for all of
the memory pages in this method, with the oldest page at the front of the queue. The first page in the
queue is chosen for removal when a page has to be replaced.

Example1: Take page reference strings 1, 3, 0, 3, 5, and 6 and three page slots as an example. All
of the spaces are initially vacant, thus when 1, 3, and 0 arrived, they were allotted to the empty
slots, which led to 3 Page Faults.

Since 3 are already in memory when it arrives, there are no page faults. Then page number 5 appears; it
cannot fit in memory, therefore it takes the position of the oldest page slot, which is 1. ->1Page Fault.

Finally, page 6 appears; however, it is likewise not in memory, thus it takes the position of the oldest
page slot, which is 3 ->1 Page Fault.

Total page faults thus equal 5.

Example2: Consider the reference string 0, 2, 1, 6, 4, 0, 1, 0, 3, 1, 2, 1. making use of the FIFO


page replacement algorithm

Therefore, there were 9 total page defects. Write a function to find the number of page
faults given the memory capacity (measured in the number of pages it can carry) and a
string representing the pages to be referred to.

Implementation
Let the amount of pages that memory can store serve as the capacity. Set, the current
collection of memory pages, shall be.

1. 1. Begin turning the pages.


2. i) If the set can hold no more pages.
3. a) Add pages one at a time into the collection until it is full or all requests for
pages have been fulfilled.
4. b) Maintain the pages in the queue simultaneously to carry out FIFO.
5. b) Increased page error
6. ii) Other
7. Do nothing if the current page is included in the collection.
8. If not, either a) the current page in the string should be substituted for the first page in the
queue since it was the first to be placed into memory, or b) the first page in the queue shou
ld be removed.
9. b) Add the currently viewing page to the queue.
10. d) Page faults that increase.
11. 2. Return page errors.

Below is the code for the above approach:


Output :
ASSESSMENT
Experiment Full Mark Marks Obtained Experiment Full Mark Marks Obtained

Experiment - 1 50 Experiment - 12 50
Experiment - 2 50 Experiment - 13 50
Experiment - 3 50 Experiment - 14 50
Experiment - 4 50 Experiment - 15 50
Experiment - 5 50 Experiment - 16 50
Experiment - 6 50 Experiment - 17 50
Experiment - 7 50 Experiment - 18 50
Experiment - 8 50 Experiment - 19 50
Experiment - 9 50 Experiment - 20 50
Experiment - 10 50 Average
50
Experiment - 11 50 Total

Date: Signature of the Faculty

* LEARNING OUTCOMES:
How the Applied and Action Learning encourages Critical Thinking, Problem
Solving, Idea Generation and Skill Development etc.?

How the Applied and Action Learning encourages Leadership, Team Work,
Reflection and Decision Making Capability etc.?

Date: Signature of the Student

* One sheet per learning record to be used


COURSE OUTCOMES (COs) ATTAINMENT
➢ Expected Course Outcomes (COs):
(Refer to COs Statement in the Syllabus)

➢ Course Outcomes (COs) Attained:


How would you rate your learning of the subject based on the specified COs?

1 2 3 4 5 6 7 8 9 10
LOW HIGH

➢ Learning Gap (If any):

➢ Books/Manuals Referred:

Date: Signature of the Student


➢ Suggestions / Recommendations:
(by the Course Faculty)

Date: Signature of the Faculty

* One sheet per learning record to be used


CENTURION UNIVERSITY OF TECHNOLOGY AND MANAGEMENT, ODISHA

CAMPUSES:
Paralakhemundi Campus Bhubaneswar Campus Balangir Campus Rayagada Campus Balasore Campus Chatrapur Campus
Village Alluri Nagar Ramchandrapur Behind BSNL Office IDCO Industrial Area Gopalpur, Ramchandrapur,
P.O. – R Sitapur, Via- Uppalada P.O. – Jatni, Bhubaneswar IDCO land, Rajib Nagar Pitamahal, Rayagada P.O.-Balasore Kaliabali Chhak,
Paralakhemundi, Dist.- Gajapati Dist.- Khurda, Odisha, Dist.- Balangir, Odisha Dist.-Rayagada, Odisha Dist.-Balasore, Odisha P.O-Chatrapur, Dist.-Ganjam
Odisha, India. PIN– 761211 India, PIN– 752050 India, PIN-767001 India, PIN-765001 India, PIN-756044 Odisha, India, PIN-761020

You might also like