KEMBAR78
Operating Systems Lab Manuel 3 | PDF | File System | Computer File
0% found this document useful (0 votes)
16 views72 pages

Operating Systems Lab Manuel 3

The Operating Systems Lab Manual provides practical guidance for students in an Operating Systems course, covering basic Linux commands, shell scripting, and user management. It includes exercises for hands-on learning, such as using commands like ls, cd, and grep, as well as creating and managing shell scripts. The manual emphasizes the importance of understanding user and group concepts in Linux system administration.

Uploaded by

moonkemo221
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)
16 views72 pages

Operating Systems Lab Manuel 3

The Operating Systems Lab Manual provides practical guidance for students in an Operating Systems course, covering basic Linux commands, shell scripting, and user management. It includes exercises for hands-on learning, such as using commands like ls, cd, and grep, as well as creating and managing shell scripts. The manual emphasizes the importance of understanding user and group concepts in Linux system administration.

Uploaded by

moonkemo221
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/ 72

Operating systems lab manuel http:��localhost:3000�print�html


Operating Systems Lab Manual

The practical manual for the Operating Systems Course.


By: Mr.Mohammad Al-aqua

Name : _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

Major: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

Group: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

1 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Chapter 1: Basic Linux commands


These are the basic Linux commands to move around in the terminal.

1. ls : List Directory Contents.

• Description : The ls command lists the files and directories in the current directory.
• Usage : ls [options] [directory]
• Examples :
◦ ls : Lists files and directories in the current directory.
◦ ls [directory] : Lists files and directories in the specified directory.
◦ ls -l : Lists files and directories with detailed information (permissions, owner,
size, etc.).
◦ ls -a : Lists all files, including hidden files (those starting with a dot).

Exercise :
Use the ls command to list the contents of the root directory / and write them
down.

2. cd : Change Directory.

• Description : The cd command changes the current working directory.


• Usage : cd [directory]
• Examples :
◦ cd /home/user : Changes the current directory to /home/user .
◦ cd .. : Moves up one directory level.
◦ cd ~ : Changes the current directory to the user's home directory.

Exercise:
Use the cd command to change the current directory to /usr/bin/ , try and guess
what is this directory?!

2 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

3. pwd : Print Working Directory.

• Description : The pwd command displays the current working directory path.
• Usage : pwd
• Examples :
◦ pwd : Prints the full path of the current directory, e.g., /home/user/Documents .

Exercise:
Use the pwd command to print the current working directory path and write it down.

4. mkdir : Create Directory.

• Description : The mkdir command creates a new directory.


• Usage : mkdir [options] directory
• Examples :
◦ mkdir new_folder : Creates a new directory named new_folder in the current
directory.
◦ mkdir -p /home/user/new_folder/sub_folder : Creates the directory structure,
including parent directories as needed.

Exercise:
Use the mkdir command to create a new directory named cyber and a new directory
named scripts inside it, in the home directory.

5. rmdir : Remove Directory.

• Description : The rmdir command removes an empty directory.


• Usage : rmdir [options] directory

3 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

• Examples :
◦ rmdir old_folder : Removes the directory named old_folder if it is empty.
◦ rmdir -p parent/child : Removes the directory child and its parent parent if
both are empty.

Exercise:
Use the rmdir command to remove the directory cyber/scripts .

6. touch : Change File Timestamps or Create Empty File.

• Description : The touch command changes file timestamps or creates an empty file if
it doesn't exist..
• Usage : touch [options] file
• Examples :
◦ touch file.txt : Creates an empty file named file.txt .
◦ touch -a file.txt : Changes the access timestamp of the file.
◦ touch -m file.txt : Changes the modification timestamp of the file.

Exercise:
Use the touch command to create a new file named notes.md in the home directory.

7. rm : Remove File.

• Description : The rm command removes a file or directory.


• Usage : rm [options] file/directory
• Examples :
◦ rm file.txt : Removes the file named file.txt .
◦ rm -r dir : Removes the directory named dir and its contents recursively.
◦ rm -i file.txt : Prompts for confirmation before removing file.txt .

Exercise:
Use the rm command to remove the file notes.md from the home directory.

8. cp : Copy Files and Directories.

• Description : The cp command copies files and directories.


• Usage : cp [options] source destination

4 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

• Examples :
◦ cp file.txt new_file.txt : Copies the file file.txt to new_file.txt .
◦ cp -r dir new_dir : Copies the directory dir and its contents recursively to
new_dir .

Exercise:
Use the cp command to copy the file .zshrc to a new directory named backups .

9. mv : Move/Rename Files and Directories

• Description : The mv command moves or renames files and directories.


• Usage : mv [options] source destination
• Examples :
◦ mv file.txt /home/user/Documents/ : Moves file.txt to the specified
directory
◦ mv oldname.txt newname.txt : Renames oldname.txt to newname.txt .

Exercise:
Make a new file in the home directory named notes.md and move it to the backups
directory and rename it to readme.md .

5 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Chapter 2: More Linux commands


More Linux commands to make you feel comfortable in the terminal.

1. grep : Global Regular Expression Print

• Description: grep searches for patterns within files and displays matching lines.
• Usage: grep [options] pattern [file...]
• Examples:
◦ grep 'search_term' file.txt : Searches for search_term in file.txt .
◦ grep -r 'search_term' directory/ : Recursively searches for search_term in
directory/ .

Exercise :
Use the grep command to search for the string touch in the .history file.

2. find : Search for Files in a Directory Hierarchy

• Description : find searches for files and directories based on conditions.


• Usage : find [path...] [expression]
• Examples :
◦ find . -name "filename.txt" : Searches for filename.txt in the current
directory
◦ find /home/user -type d : Searches for directories in /home/user

Exercise :
Use the find command to find the file named grub in the /etc directory, Do you
know what is this file?!

3. cat : Concatenate and Display Files

6 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

• Description : cat concatenates and displays files.


• Usage : cat [options] file...
• Examples :
◦ cat file.txt : Displays the contents of file.txt .
◦ cat -n file.txt : Displays the contents of file.txt with line numbers.
◦ cat file1.txt file2.txt : Concatenates the contents of file1.txt and
file2.txt and displays the result.
◦ cat file1.txt file2.txt > combined.txt : Combines file1.txt and
file2.txt into combined.txt .

Exercise :
Use the cat command to concatenate the .zshrc and .bashrc files into
combinedrc.txt , and display it.

4. whatis : Display One-line Manual Page Descriptions

• Description : whatis provides a brief description of a command.


• Usage : whatis [command]
• Examples :
◦ whatis which : Displays the description of the which command.

Exercise :
Use the whatis command to learn about the more and less commands, and write
down there brief description.

5. df : Display Disk Space Usage

• Description : df reports file system disk space usage.


• Usage : df [options] [path]
• Examples :
◦ df : Displays disk space usage for the current directory.

7 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

◦ df -h : Displays disk space usage in human-readable format.


◦ df -h / : Displays disk space usage for the root directory.

Exercise :
Use the df command to see how mush disk space is used in the home directory.

6. uptime : Tell How Long the System Has Been Running

• Description : uptime displays the current time, how long the system has been
running,the number of users, and system load averages.
• Usage : uptime
• Examples :
◦ uptime : Displays the current system uptime and load averages.
◦ uptime -p : Displays the current system uptime in pretty format.

Exercise :
Use the uptime command to find out how long the system has been running.

7. wget and curl : Download Files from the Internet

• Description : wget and curl are command-line tools for downloading files from the
internet.
• Usage : wget [options] url or curl [options] url
• Examples :
◦ wget https://example.com/file.zip : Downloads the file file.zip from the
internet.
◦ curl -O https://example.com/file.zip : Downloads the file file.zip from the
internet.

Exercise:
Use the wget or curl command to download the https://
raw.githubusercontent.com/Al-aqua/op-lab-man/main/absolutely-not-a-virus file
from the internet. what is the content of the file?

8 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

8. Package Management with apt in Debian based distros

• Description : apt is a package management system for Debian-based systems.


• Usage : apt [options] [command]
• Examples :
◦ sudo apt update : Updates the package list.
◦ sudo apt upgrade : Upgrades all installed packages.
◦ apt install [package] : Installs a package.
◦ apt remove [package] : Removes a package.

Exercise :
Use the apt command to install the vim package. what is vim ?

9 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Chapter 3: Shell Scripting in Linux

Introduction to Shell Scripting


Shell scripting allows you to automate repetitive tasks, manage system operations, and
customize your environment by writing scripts. Shell scripts are written for the shell, or
command line interpreter, which interprets and executes commands.

1. What is a Shell Script?

A shell script is a text file containing a series of commands that the shell can execute. Scripts
can include commands, variables, loops, and conditionals to perform complex tasks.

2. How write Your First Shell Script

Step 1: Create a File

Create a new file with a .sh extension touch first_script.sh and open it in any text
editor.

Step 2: Add the Shebang

The shebang (#!) at the top of the file tells the system which interpreter to use. For bash,
use:

#!/bin/bash

Step 3: Add Commands

#!/bin/bash
echo "Hello, World!"

Step 4: Make the Script Executable

chmod +x first_script.sh

Step 5: Run the Script

10 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

./first_script.sh

3. Variables

Variables store data that can be used later in the script.

#!/bin/bash
name="John Doe"
echo "My name is $name"

4. User Input

User input is data that is provided by the user when the script is run.

#!/bin/bash
read -p "Enter your name: " name
echo "Hello, $name!"

5. Conditional Statements

Conditional statements allow you to perform different actions based on different conditions.

#!/bin/bash
read -p "Enter a number: " num
if [ $num -gt 0 ]; then
echo "$num is positive"
elif [ $num -lt 0 ]; then
echo "$num is negative"
else
echo "$num is zero"
fi

6. Loops

Loops allow you to repeat a block of code multiple times.

for Loops

11 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#!/bin/bash
for i in {1..10}; do
echo "Number: $i"
done

while Loops

#!/bin/bash
i=1
while [ $i -le 10 ]; do
echo "Number: $i"
i=$((i + 1))
done

7. Functions

Functions allow you to reuse code in your script.

#!/bin/bash
function greet() {
echo "Hello, $1!"
}
greet "John Doe"
greet "Joe Mama"

8. Script Arguments

Script arguments are data passed to the script when it is run.

#!/bin/bash
echo "Script name: $0"
echo "Argument 1: $1"
echo "Argument 2: $2"

9. Practical Examples

Backup Script

12 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#!/bin/bash
backup_dir="/backup"
mkdir -p $backup_dir
cp -r /home/user/documents $backup_dir
echo "Backup completed!"

Exercise :

1. Write a script that output your user name, uptime.


2. Write a guessing game where a user has to guess a number between 1 and 10
and the script will tell the user if their guess is too high or too low.

Assignment :

Do a research on how to pipe commands and redirect commands.

13 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

chapter 4 User Management in Linux

Introduction to User Management


User management is a fundamental aspect of Linux system administration. It involves
creating, modifying, and deleting user accounts and groups, managing user permissions,
and ensuring system security.

1. Understanding User and Group Concepts

• Users: Accounts used to log into the system. Each user has a unique ID (UID).
• Groups: Collections of users with common permissions. Each group has a unique ID
(GID).

2. Creating Users

adduser and useradd

• adduser : Higher-level command for adding users.


• useradd : Lower-level command with more options.

Usage:

• adduser [username] : Create a new user


• useradd -g [groupname] -d [homedir] -m [username] : Create a new user and add it
to a group and set its home directory

3. Managing Passwords

passwd : Change user passwords.

Usage:

• passwd : Change Your Own Password


• passwd [username] : Change Another User's Password

14 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

4. Modifying Users

usermod : Modify user attributes.

Usage:

• usermod -aG [groupname] [username] : Add a user to a group


• usermod -G [groupname] [username] : Remove a user from a group
• usermod -l [newusername] [username] : Rename a user
• usermod -p [newpassword] [username] : Change a user's password
• usermod -s [shell] [username] : Change a user's shell
• etc...

5. Deleting Users

deluser and userdel

• deluser : Higher-level command for deleting users.


• userdel : Lower-level command with more options.

Usage:

• deluser [username] : Delete a user


• userdel -r [username] : Delete a user and its home directory

6. Creating and Managing Groups

groupadd and groupdel

• groupadd : Create a new group


• groupdel : Delete a group

Usage:

• groupadd [groupname] : Create a new group


• groupdel [groupname] : Delete a group

7. Viewing User and Group Information

id : View user and group information.

15 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Usage:

• id : View your own user and group information


• id [username] : View another user's user and group information

who and w

• who : Show who is logged on.


• w : Show who is logged on and what they are doing.

finger

• finger : View user information

Usage:

• finger [username] : View user information


• finger : View your own user information

8. Best Practices

• Use Strong Passwords: Ensure all user accounts have strong, unique passwords.
• Regularly Audit User Accounts: Periodically review user accounts and permissions.
• Limit sudo Access: Only grant sudo access to trusted users.
• Remove Inactive Users: Delete or disable accounts that are no longer needed.

16 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Chapter 5: Linux File System and File


Security
1. Introduction to Linux File System The Linux file system is a fundamental component
of the operating system, providing a structured way to store and organize files on disk.
It enables users and applications to access, modify, and manage data efficiently. This
section introduces the core concepts of the Linux file system, its directory structure,
and the different types of files found in a Linux environment.

Overview of File Systems


A file system is a method and data structure that an operating system uses to control how
data is stored and retrieved. Without a file system, information placed in a storage medium
would be one large block with no way to tell where one piece of information stops and the
next begins. By separating the data into pieces and giving each piece a name, the
information is easily isolated and identified.

Common File Systems in Linux:

1. ext4 (Fourth Extended File System):

◦ The default file system for many Linux distributions.


◦ Offers high performance, reliability, and large storage capacity.
◦ Features include journaling, extents, and backward compatibility with ext3 and
ext2.

2. XFS

◦ Known for high performance and scalability.


◦ Particularly well-suited for systems with large files and high I/O workloads.
◦ Supports advanced features like quotas and defragmentation.

3. Btrfs (B-tree File System):

◦ Designed for high-capacity and high-performance storage.


◦ Features include snapshots, pooling, and checksums for data integrity.
◦ Focuses on fault tolerance, repair, and easy administration.

17 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Directory Structure

The Linux directory structure is hierarchical, resembling an inverted tree. The topmost
directory is called the root directory and is denoted by a forward slash (/). Below the root,
the file system branches into various directories, each serving a specific purpose.

Key Directories and Their Purposes:

• / (Root): The base of the file system hierarchy. All other directories and files
stem from here.
• /bin : Essential user binaries (executables) needed for system booting and
single-user mode.
• /boot : Files required for booting the system, including the kernel and
bootloader configuration files.
• /dev : Device files representing hardware components and peripherals.
• /etc : Configuration files for the system and installed applications.
• /home : Home directories for individual users. Each user has a personal directory
under /home .
• /lib : Shared libraries needed by binaries in /bin and /sbin .
• /mnt : Mount point for temporarily mounted file systems.
• /opt : Optional software packages and third-party applications.
• /proc : Virtual file system providing process and kernel information.
• /root : Home directory for the root (superuser).
• /sbin : System binaries essential for system administration.
• /srv : Data for services provided by the system.
• /tmp : Temporary files created by the system and applications.
• /usr : User programs and utilities.
• /var : Variable data files, such as logs, mail spools, and temporary files.

File Types

In Linux, everything is considered a file, including hardware devices and processes. The file
types are identified using the ls -l command, which lists files and their details.

Common File Types:

• Regular Files ( - ): The most common type, representing data files, text files, scripts,
and binaries.

18 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

• Directories ( d ): Special files that contain other files and directories.


• Symbolic Links ( l ): Pointers to other files or directories, allowing for flexible and
dynamic file system structures.
• Device Files ( b for block devices, c for character devices): Represent hardware
devices. Block devices allow random access (e.g., hard drives), while character devices
are accessed sequentially (e.g., keyboards).
• Sockets ( s ): Used for inter-process communication.
• Pipes ( p ): Enable data transfer between processes in a first-in, first-out (FIFO) manner.

File Permissions
File permissions in Linux are a critical aspect of system security and access control. They
determine who can read, write, or execute a file. Understanding how to view and modify
these permissions is essential for managing files and maintaining a secure system.

Understanding File Permissions

Each file and directory has a set of permissions associated with three categories of users:

• Owner: The user who owns the file.


• Group: A set of users who share access rights to the file.
• Others: All other users on the system.

Permissions are divided into three types:

• Read ( r ): Permission to read the contents of the file.


• Write ( w ): Permission to modify or delete the file.
• Execute ( x ): Permission to execute the file (if it is a script or binary).

These permissions are displayed using the ls -l command, which shows a 10-character
string representing the permissions and file type:

ls -l

Example output:

-rwxr-xr--

Explanation of the characters:

19 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

• The first character indicates the file type:

◦ - : Regular file
◦ d : Directory
◦ l : Symbolic link
◦ b : Block device
◦ c : Character device
◦ s : Socket
◦ p : Pipe

• The next nine characters are the permissions, divided into three groups of three:

◦ rwx for the owner


◦ r-x for the group
◦ r-- for others

In the example above, the file is a regular file ( - ), the owner has read, write, and execute
permissions ( rwx ), the group has read and execute permissions ( r-x ), and others have
read-only permissions ( r-- ).

Changing File Permissions

You can change file permissions using the chmod command in two modes: symbolic and
numeric.

Symbolic Mode:

• Uses letters to represent the user category ( u for owner, g for group, o for others, a
for all) and permissions ( r, w, x ).
• + adds a permission, - removes a permission, and = sets a permission.

Examples:

chmod u+x filename # Adds execute permission for the owner


chmod g-w filename # Removes write permission for the group
chmod o=r filename # Sets read-only permission for others
chmod a+rw filename # Adds read and write permissions for all

Numeric Mode:

• Uses a three-digit octal number to represent permissions. Each digit is a sum of values:
read (4), write (2), and execute (1).

20 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Example:

chmod 755 filename # Sets rwx for owner (4+2+1=7), r-x for group (4+1=5),
and r-x for others (4+1=5)
chmod 644 filename # Sets rw- for owner (4+2=6), r-- for group (4), and r--
for others (4)
chmod 700 filename # Sets rwx for owner (4+2+1=7), --- for group (0), and
--- for others (0)

Special Permissions

Special permissions add additional control for executable files and directories.

Set User ID (SUID):

• When applied to an executable file, allows users to execute the file with the file owner's
privileges.
• Represented by an s in the owner's execute position ( rws ).

Example:

chmod u+s filename

Set Group ID (SGID):

• When applied to an executable file, allows users to execute the file with the file group's
privileges.
• When applied to a directory, files created within the directory inherit the group
ownership.
• Represented by an s in the group's execute position ( r-s ).

Example:

chmod g+s directory

Sticky Bit:

• When applied to a directory, ensures that only the file owner can delete or rename files
within that directory.
• Represented by a t in the others' execute position ( rwt ).

Example:

21 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

chmod +t directory

Viewing and Modifying Permissions

Viewing Permissions:

ls -l displays the permissions, owner, group, and other details of files and directories.

Example:

ls -l
// Output
-rw-r--r-- 1 user group 1234 Jan 1 12:34 file.txt

Modifying Permissions:

• chmod command changes file permissions.


• chown command changes file ownership.
• chgrp command changes the group ownership.

Examples:

chmod 755 file.txt # Change permissions to rwxr-xr-x


chown user file.txt # Change owner to user
chgrp group file.txt # Change group to group

File Security and Access Control


File security and access control are essential components of a secure Linux system. They
ensure that sensitive data is protected and that only authorized users can access or modify
files. This section covers basic and advanced mechanisms for securing files, including umask,
Access Control Lists (ACLs), and Mandatory Access Control (MAC) systems like SELinux and
AppArmor.

Understanding umask

The umask (user file creation mode mask) command determines the default permissions for
new files and directories. It acts as a filter that removes specific permissions when new files
and directories are created.

22 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Calculating umask:

• The default permissions for new files are 666 (read and write for all).
• The default permissions for new directories are 777 (read, write, and execute for all).
• The umask value is subtracted from these defaults to determine the final permissions.

Viewing and Setting umask:

• Use the umask command to view the current umask value.

umask

• To set a new umask value, use the umask command followed by the desired value.

umask 022

Example Calculation:

• If the umask is 022, the default permissions for a new file will be 644 (666 - 022),
resulting in read and write permissions for the owner, and read-only permissions for
the group and others.
• For a new directory, the permissions will be 755 (777 - 022), resulting in read, write, and
execute permissions for the owner, and read and execute permissions for the group
and others.

Access Control Lists (ACLs)

ACLs provide a more flexible permission mechanism than the traditional file permissions.
They allow you to set permissions for individual users or groups on a per-file or per-
directory basis.

Using ACLs:

• getfacl : Displays the ACL of a file or directory.

getfacl filename

• setfacl : Sets or modifies the ACL of a file or directory.

23 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

setfacl -m u:username:rwx filename # Add/modify permissions for a user


setfacl -m g:groupname:rw filename # Add/modify permissions for a group
setfacl -x u:username filename # Remove ACL entry for a user

SELinux and AppArmor

SELinux (Security-Enhanced Linux) and AppArmor are MAC systems that provide additional
security by enforcing policies that restrict how programs can access files and resources.

SELinux:

• Enforces policies that define how processes interact with files, devices, and other
processes.
• Policies are defined in terms of contexts, consisting of user, role, type, and level.

Basic Commands:

• sestatus : Checks the status of SELinux.


• getenforce : Displays the current mode of SELinux (Enforcing, Permissive, or Disabled).
• setenforce : Sets the mode of SELinux.

setenforce 0 # Permissive mode


setenforce 1 # Enforcing mode

AppArmor:

• Uses profiles to restrict the capabilities of programs.


• Profiles define the file access permissions and capabilities for a program.

Basic Commands:

• aa-status : Displays the current status of AppArmor.


• aa-enforce : Sets a profile to enforcing mode.
• aa-complain : Sets a profile to complain mode (logs violations but does not enforce).

Encryption and Secure Deletion


Understanding the importance of data confidentiality and security is crucial in today's digital
world. This section explores the robust tools Linux provides for encrypting files, securing
entire file systems, and employing techniques for secure file deletion.

24 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

File Encryption

Encrypting files ensures that unauthorized users cannot access the data without the
appropriate decryption key. One of the most widely used tools for file encryption in Linux is
gpg (GNU Privacy Guard).

Using gpg for File Encryption and Decryption:

• Encrypting a File:

gpg -c filename

This command prompts you to enter a passphrase. The encrypted file is saved with a .gpg
extension.

• Decrypting a File:

gpg -d filename.gpg

Enter the passphrase used for encryption to decrypt the file.

Encrypting File Systems

Encrypting entire file systems provides a higher level of security by ensuring that all data
stored within the file system is encrypted. LUKS (Linux Unified Key Setup) is a standard for
disk encryption.

Secure Deletion

When files are deleted in a typical manner, the data is not completely erased from the disk
and can be recovered using forensic tools. Secure deletion ensures that data is
irrecoverable.

Using shred for Secure Deletion:

shred : Overwrites a file multiple times to make it harder to recover.

shred -u filename

The -u option removes the file after overwriting it.

Using wipe for Secure Deletion:

25 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

wipe : Securely erases files or entire disk partitions.

Note: Traditional secure deletion tools may not be effective on SSDs due to wear
leveling. Using encryption and secure erase commands provided by the SSD
manufacturer is recommended.

Backups and Recovery


Regular backups and the ability to recover data are essential components of maintaining a
reliable and secure Linux system. This section explores various tools and techniques for
creating backups and recovering data.

Creating Backups

Creating regular backups ensures that you can restore your system to a previous state in
case of data loss, hardware failure, or other unforeseen events. Linux offers several
powerful tools for this purpose.

• Using tar for Archiving:

◦ tar: Creates compressed archive files.

tar -czvf backup.tar.gz /path/to/directory

◦ -c : Create a new archive.


◦ -z : Compress the archive with gzip.
◦ -v : Verbose mode, shows the progress.
◦ -f : Specifies the archive file name.

• Using rsync for Incremental Backups:

◦ rsync : Synchronizes files and directories between two locations.

rsync -av --delete /source/directory /backup/directory

◦ -a : Archive mode, preserves permissions, timestamps, and symbolic links.


◦ -v : Verbose mode.

26 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

◦ --delete : Deletes files in the destination that are not present in the source.

Recovering Data

In the event of data loss, having a solid recovery strategy can help minimize downtime and
data loss.

• Restoring from tar Archives:

◦ tar: Extracts files from an archive.

tar -xzvf backup.tar.gz -C /path/to/restore

◦ -x : Extracts files from the archive.


◦ -z : Decompress the archive with gzip.
◦ -v : Verbose mode, shows the progress.
◦ -f : Specifies the archive file name.
◦ -C : Specifies the directory to extract files to.

• Restoring with rsync:

◦ rsync : Synchronizes files from the backup to the source location.

rsync -av /backup/directory /source/directory

There are a lot of tools that can streamline data backups recovery and automate it like
TimeShift.

Recovering Deleted Files:

• testdisk : A powerful tool for recovering lost partitions and making non-booting disks
bootable again.

sudo testdisk

Follow the interactive menu to analyze and recover partitions.

• photorec : Recovers lost files from hard disks and CD-ROMs.

27 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

sudo photorec

Follow the interactive menu to recover files.

28 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Chapter 6: Processes and Process Creation


Understanding processes and how they are created is fundamental to managing and
optimizing a Linux system. This chapter explores what processes are, how they are created,
and the tools available to manage them effectively.

What is a Process?
A process is a running instance of a program. It is an active entity that requires system
resources such as CPU time, memory, and input/output (I/O) operations to execute its
instructions. In Linux, every process is assigned a unique Process ID (PID), which is used to
identify and manage it.

Key Concepts:
• Parent and Child Processes: n Linux, every process is spawned by another process,
known as the parent process. The new process is called a child process. The init or
systemd process is the ancestor of all processes and has a PID of 1.

• Foreground and Background Processes: Foreground processes run in the terminal,


blocking input until they finish, while background processes run independently of the
terminal, allowing continued input.

Process creation
Process creation in Linux is a fundamental concept that involves duplicating an existing
process (the parent) to create a new process (the child). This is primarily achieved using
system calls like fork() , exec() , and wait() . Let's explore these in more detail with
examples.

29 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

[!NOTE] We will be using the c programming language to explore these concepts. The c
and c++ compiler( gcc ) comes installed by default in Linux. to compile the code, use

gcc source_filr.c -o exec_file

1. fork() - Creating a New Process

The fork() system call is used to create a new process by duplicating the current process.
The newly created process is called the child process, and the original process is called the
parent process. After a fork() call, two processes will execute: the parent and the child.

Basic Example of fork() in C:

#include <stdio.h>
#include <unistd.h>

int main() {
pid_t pid = fork();

if (pid < 0) {
// Error in fork
fprintf(stderr, "Fork Failed\n");
return 1;
} else if (pid == 0) {
// Child process
printf("This is the Child Process. PID: %d\n", getpid());
} else {
// Parent process
printf("This is the Parent Process. PID: %d, Child PID: %d\n",
getpid(), pid);
}

return 0;
}

Explanation:

• The fork() call returns twice: once in the parent process and once in the child
process.
◦ In the child process, fork() returns 0 .
◦ In the parent process, fork() returns the PID of the child process.
• The getpid() function returns the PID of the current process.
• The program prints different messages depending on whether it's running in the

30 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

parent or child process.

Expected Output:

This is the Parent Process. PID: 1234, Child PID: 1235


This is the Child Process. PID: 1235

2. exec() - Replacing a Process Image

After creating a child process, it is common to replace the child’s process image with a new
program using the exec() family of functions. This does not create a new process but
replaces the current process's memory with a new program.

Example Using exec() in C:

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

int main() {
pid_t pid = fork();

if (pid < 0) {
// Error in fork
fprintf(stderr, "Fork Failed\n");
return 1;
} else if (pid == 0) {
// Child process
printf("Child Process - Executing ls command\n");
execlp("/bin/ls", "ls", NULL);
// If exec fails
printf("Exec Failed\n");
} else {
// Parent process
wait(NULL);
printf("Child Complete\n");
}

return 0;
}

Explanation:

• After fork() , the child process uses execlp() to execute the ls command.
• If exec() succeeds, the original child process is replaced by ls , and the following
code ( printf("Exec Failed\n") ) is not executed.
• The parent process waits for the child to complete using wait() .

31 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Expected Output:

Child Process - Executing ls command


# Output of ls command
Child Complete

3. wait() - Synchronizing Processes

The wait() system call makes the parent process wait until all of its child processes have
finished executing. This is useful for ensuring that the parent does not exit before the child,
or to capture the child's exit status.

Example Using wait() in C:

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

int main() {
pid_t pid = fork();

if (pid < 0) {
// Error in fork
fprintf(stderr, "Fork Failed\n");
return 1;
} else if (pid == 0) {
// Child process
printf("Child Process - Executing ls command\n");
execlp("/bin/ls", "ls", NULL);
// If exec fails
printf("Exec Failed\n");
} else {
// Parent process
wait(NULL);
printf("Child Complete\n");
}

return 0;
}

Explanation:

• The child process prints its PID and then simulates some work by sleeping for 2
seconds.
• The parent process calls wait() , which pauses the parent until the child process
completes.
• After the child finishes, the parent resumes and prints a completion message.

32 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Expected Output:

Parent Process. Waiting for Child to Complete


Child Process. PID: 1235
Child Process Complete
Parent Process Resuming After Child Completion

4. exit() - Terminating a Process

The exit() system call is used to terminate a process. This is useful for terminating a
process in an orderly manner.

Example Using exit() in C:

33 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

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

int main() {
pid_t pid = fork();

if (pid < 0) {
// Error in fork
fprintf(stderr, "Fork Failed\n");
return 1;
} else if (pid == 0) {
// Child process
printf("Child Process. PID: %d\n", getpid());

// Simulate some work in the child process


// Now exit with a specific status code
exit(1); // Exit with status 1 to indicate an error or specific
condition
} else {
// Parent process
int status;
wait(&status); // Wait for the child and capture its exit status

// Check if the child terminated normally


if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status); // Get the child's exit
status
printf("Child Process Exited with Status: %d\n", exit_status);
} else {
printf("Child Process Did Not Terminate Normally\n");
}
}

return 0;
}

Explanation:

1. exit(1) in the Child Process:


◦ In the child process, the exit(1) function is called. This function terminates the
child process and returns an exit status code of 1 to the operating system.
◦ The exit status code can be any integer. A status of 0 usually indicates successful
completion, while non-zero values (like 1 ) are often used to indicate errors or
specific conditions.
2. wait(&status) in the Parent Process:
◦ The parent process calls wait(&status) , which makes it wait until the child
process finishes. The status variable is used to store the child's exit information.

34 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

◦ The wait() function captures more than just whether the child exited; it also
captures how the child exited, including whether it was terminated by a signal or
completed normally with an exit() call.
3. Checking the Exit Status:
◦ WIFEXITED(status) : This macro checks whether the child process terminated
normally via exit() or \_exit() . If it did, the macro returns a non-zero value.
◦ WEXITSTATUS(status) : If WIFEXITED(status) is true, this macro extracts the
actual exit status code provided by the child process via exit() . In this case, it
retrieves the 1 that was passed to exit(1) .

Expected Output:

Child Process. PID: 1235


Child Process Exited with Status: 1

Managing Processes
Linux provides several commands to manage and monitor processes:

1. ps : Displays a snapshot of the current processes.


◦ ps aux : Lists all processes running on the system, along with detailed
information.
2. top : Provides a dynamic, real-time view of running processes.
◦ Displays system resource usage and allows you to sort processes by CPU or
memory usage.
3. htop : An enhanced version of top with a more user-friendly interface.
◦ Allows you to interactively manage processes (e.g., kill processes, sort by different
metrics).
4. kill : Sends a signal to a process, typically used to terminate it.
◦ kill PID : Sends the default signal ( SIGTERM ) to terminate the process with the
given PID.
◦ kill -9 PID : Sends the SIGKILL signal to forcefully terminate the process.
5. nice and renice : Adjust the priority of a process.
◦ nice : Starts a process with a modified priority.
◦ renice : Changes the priority of an already running process.
◦ nice -n 10 ./cpu_task.sh : Increases the priority of the process by 10.
◦ renice -n -10 PID : Decreases the priority of the process with the given PID by
10.

35 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

6. bg and fg : Resume background jobs or bring them to the foreground.


◦ bg : Moves a suspended job to the background.
◦ fg : Brings a background job to the foreground.

Monitoring Process Performance


Monitoring process performance is key to ensuring efficient system operation. Tools like
top , htop , and vmstat provide real-time data on process performance, helping identify
resource-intensive processes.

Understanding Load Average:

• The load average represents the average number of processes waiting for CPU time
over 1, 5, and 15-minute intervals.
• High load averages indicate that processes are spending more time waiting for CPU
resources, which may signal a need for optimization or resource scaling.

Using strace for Debugging:

• strace : Traces system calls and signals received by a process, useful for debugging
and understanding process behavior.

strace -p PID

36 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Chapter 7: Introduction to Threads


Programming

1. What is a Thread?
A thread is the smallest unit of execution within a process. Unlike processes, which are
independent execution units containing their own memory space, threads are part of a
process and share the same memory space. This shared environment makes threads more
lightweight than processes because they require fewer resources to create and maintain.

2. Threads vs. Processes


• Processes
◦ A process is a self-contained execution environment.
◦ Each process has its own memory space, including code, data, and system
resources like file descriptors.
◦ Processes are isolated from each other, which provides a high level of security
but comes with the overhead of context switching.
• Threads
◦ A thread, often referred to as a "lightweight process," exists within a process.
◦ Threads within the same process share the same memory space, making
communication between threads faster.
◦ While threads share resources, they can also lead to issues like race conditions if
not managed properly.

3. The Role of Threads in Operating Systems and


Programming
Threads play a crucial role in modern operating systems and programming because they
allow multiple tasks to be performed simultaneously within the same process. This is
especially important in applications requiring concurrency, such as web servers, real-time
systems, and applications with a graphical user interface (GUI).

37 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Advantages of Threads:

• Responsiveness: Threads allow a program to remain responsive by performing


background tasks while the main program is running.
• Resource Sharing: Since threads share memory and resources, they are more efficient
than processes in performing tasks that require frequent communication.
• Parallelism: Threads can be executed in parallel on multi-core processors, improving
the performance of CPU-bound tasks.

4. Creating and Managing Threads in Linux using C


In Linux, threads are created and managed using the POSIX threads (pthreads) library. This
library provides a set of functions for creating, synchronizing, and managing threads.

Creating a Thread

To create a thread in Linux using C, you use the pthread_create function:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void *threadFunction(void *arg) {


printf("Thread is running!\n");
return NULL;
}

int main() {
pthread_t thread;
int result;

result = pthread_create(&thread, NULL, threadFunction, NULL);


if (result != 0) {
printf("Thread creation failed!\n");
return -1;
}

pthread_join(thread, NULL);
printf("Thread has finished execution.\n");
return 0;
}

• pthread_create : This function creates a new thread. It takes four arguments:

38 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

◦ A pointer to the pthread_t variable where the thread ID will be stored.


◦ Thread attributes (can be NULL for default attributes).
◦ The function the thread will execute.
◦ An argument to the thread function (can be NULL ).
• pthread_join : This function waits for the specified thread to terminate.

5. Thread Synchronization
Thread synchronization is critical in multi-threaded programming to ensure that threads do
not interfere with each other while accessing shared resources. Synchronization techniques
help maintain data integrity and prevent race conditions.

1. Race Condition

A race condition occurs when two or more threads attempt to change shared data at the
same time, leading to unexpected and incorrect results. Consider the following example
where multiple threads increment a shared counter:

39 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#include <pthread.h>
#include <stdio.h>

int counter = 0;

void *incrementCounter(void *arg) {


for (int i = 0; i < 100000; i++) {
counter++; // Not synchronized
}
return NULL;
}

int main() {
pthread_t threads[10];

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


pthread_create(&threads[i], NULL, incrementCounter, NULL);
}

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


pthread_join(threads[i], NULL);
}

printf("Final counter value: %d\n", counter); // Expect 1000000


return 0;
}

Problem: Here, you might expect the final counter value to be 1000000 , but due to the race
condition, it might be less. This is because threads can interrupt each other while modifying
the counter, leading to lost updates.

2. Using Mutex for Synchronization

To prevent race conditions, you can use a mutex (short for "mutual exclusion"). A mutex
ensures that only one thread can execute a piece of code at a time.

40 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#include <pthread.h>
#include <stdio.h>

int counter = 0;
pthread_mutex_t lock;

void *incrementCounter(void *arg) {


for (int i = 0; i < 100000; i++) {
pthread_mutex_lock(&lock); // Lock the mutex before accessing the
shared resource
counter++;
pthread_mutex_unlock(&lock); // Unlock the mutex after the operation
}
return NULL;
}

int main() {
pthread_t threads[10];
pthread_mutex_init(&lock, NULL); // Initialize the mutex

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


pthread_create(&threads[i], NULL, incrementCounter, NULL);
}

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


pthread_join(threads[i], NULL);
}

printf("Final counter value: %d\n", counter); // Should be 1000000


pthread_mutex_destroy(&lock); // Destroy the mutex when done
return 0;
}

Solution: Using a mutex ensures that only one thread can increment the counter at a time,
preventing race conditions. Now, the final counter value should be 1000000 as expected.

3. Deadlock

A deadlock occurs when two or more threads are waiting for each other to release a
resource, causing them to be stuck forever. Consider this example:

41 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

pthread_mutex_t lock1, lock2;

void *thread1(void *arg) {


pthread_mutex_lock(&lock1);
printf("Thread 1: Locked lock1\n");

// Simulate some work


sleep(1);

pthread_mutex_lock(&lock2);
printf("Thread 1: Locked lock2\n");

pthread_mutex_unlock(&lock2);
pthread_mutex_unlock(&lock1);
return NULL;
}

void *thread2(void *arg) {


pthread_mutex_lock(&lock2);
printf("Thread 2: Locked lock2\n");

// Simulate some work


sleep(1);

pthread_mutex_lock(&lock1);
printf("Thread 2: Locked lock1\n");

pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
return NULL;
}

int main() {
pthread_t t1, t2;
pthread_mutex_init(&lock1, NULL);
pthread_mutex_init(&lock2, NULL);

pthread_create(&t1, NULL, thread1, NULL);


pthread_create(&t2, NULL, thread2, NULL);

pthread_join(t1, NULL);
pthread_join(t2, NULL);

pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
return 0;
}

42 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Explanation:

• Thread 1 locks lock1 and then tries to lock lock2 .


• Thread 2 locks lock2 and then tries to lock lock1 .
• Both threads are now waiting for the other to release the lock they need, leading to a
deadlock.

How to Avoid Deadlock:

• Avoid Nested Locks: Minimize the use of nested locks and ensure that all threads
acquire locks in a consistent order.

• Lock Ordering: Always acquire locks in a fixed global order to prevent circular waiting.

• Try-Lock: Use pthread_mutex_trylock to attempt locking a mutex without blocking,


allowing the thread to back off if it cannot acquire the lock.

if (pthread_mutex_trylock(&lock2) == 0) {
// Successfully locked lock2
} else {
// Could not lock lock2, handle accordingly
}

4. Condition Variables

Condition variables are used to signal between threads. They allow one or more threads to
wait until a particular condition occurs. Condition variables are always used with a mutex to
avoid race conditions.

Example: Producer-Consumer Problem

In the producer-consumer problem, one or more producer threads generate data and put it
into a buffer, while one or more consumer threads take data out of the buffer and process
it.

43 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 10

int buffer[BUFFER_SIZE];
int count = 0;

pthread_mutex_t mutex;
pthread_cond_t cond_producer, cond_consumer;

void *producer(void *arg) {


int item;
while (1) {
item = rand() % 100; // Produce a random item

pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(&cond_producer, &mutex); // Wait if buffer is
full
}

buffer[count] = item;
count++;
printf("Produced: %d\n", item);

pthread_cond_signal(&cond_consumer); // Signal consumer


pthread_mutex_unlock(&mutex);
}
return NULL;
}

void *consumer(void *arg) {


int item;
while (1) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&cond_consumer, &mutex); // Wait if buffer is
empty
}

item = buffer[--count];
printf("Consumed: %d\n", item);

pthread_cond_signal(&cond_producer); // Signal producer


pthread_mutex_unlock(&mutex);
}
return NULL;
}

int main() {

44 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

pthread_t prod, cons;

pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond_producer, NULL);
pthread_cond_init(&cond_consumer, NULL);

pthread_create(&prod, NULL, producer, NULL);


pthread_create(&cons, NULL, consumer, NULL);

pthread_join(prod, NULL);
pthread_join(cons, NULL);

pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond_producer);
pthread_cond_destroy(&cond_consumer);

return 0;
}

Explanation:

• Producer: Produces an item and places it into the buffer. If the buffer is full, the
producer waits until there is space.
• Consumer: Consumes an item from the buffer. If the buffer is empty, the consumer
waits until there is data to consume.
• Condition Variables: cond_producer is used to signal the producer that there is space
in the buffer, and cond_consumer is used to signal the consumer that there is data to
consume.

This ensures smooth operation without overfilling the buffer or consuming non-existent
data.

Assignment: Write a basic multi-threaded program in any programming language of


your choice.

45 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Chapter 8: CPU Scheduling and Scheduling


Algorithms

1. Introduction to CPU Scheduling


CPU scheduling is a fundamental aspect of multitasking operating systems. It determines
the order in which processes run on the CPU, maximizing resource utilization and ensuring
system responsiveness. Since a computer can only have one CPU execute a single task at
any given moment, the operating system must efficiently decide which process to run next.

In this chapter, we will explore different scheduling algorithms, how they work, and their
practical applications in a Linux environment.

2. CPU Burst and IO Burst


Processes alternate between CPU bursts (performing computations) and IO bursts (waiting
for input/output operations). The CPU scheduling decisions are made during these
transitions:

• CPU-bound processes: Spend more time performing calculations (CPU bursts).


• IO-bound processes: Spend more time waiting for input/output operations (IO bursts).

Efficient scheduling ensures that CPU and IO-bound processes don't unnecessarily wait for
each other, optimizing overall system performance.

3. Types of CPU Scheduling


• Preemptive Scheduling: The CPU can interrupt a running process and allocate it to
another process. Preemption is key in ensuring that no single process monopolizes the
CPU. This is critical in time-sharing systems where multiple users or applications need
the CPU at frequent intervals.
• Non-preemptive Scheduling: A running process retains control of the CPU until it

46 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

voluntarily releases it by either terminating or switching to a waiting state. It's simpler


but can lead to inefficient CPU usage if a process takes too long.

Example: Linux uses preemptive scheduling, but for specific system calls or critical tasks, it may
temporarily switch to non-preemptive mode.

4. Scheduling Algorithms
Let’s dive into the most common CPU scheduling algorithms, how they work, and their
practical implementation:

4.1. First-Come, First-Served (FCFS)

• How it works: Processes are scheduled in the order they arrive in the ready queue.
• Type: Non-preemptive.
• Pros: Simple and easy to implement.
• Cons: Can lead to long wait times, particularly if the first process in the queue is CPU-
bound (known as the "convoy effect").

Example in C:

47 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#include <stdio.h>

int main() {
int n, i;
printf("Enter number of processes: ");
scanf("%d", &n);

int burst_time[n], waiting_time[n], turnaround_time[n];


int total_waiting_time = 0, total_turnaround_time = 0;

// Input burst times


for (i = 0; i < n; i++) {
printf("Enter burst time for process P%d: ", i + 1);
scanf("%d", &burst_time[i]);
}

waiting_time[0] = 0;

// Calculate waiting time


for (i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i - 1] + burst_time[i - 1];
total_waiting_time += waiting_time[i];
}

// Calculate turnaround time


for (i = 0; i < n; i++) {
turnaround_time[i] = burst_time[i] + waiting_time[i];
total_turnaround_time += turnaround_time[i];
}

// Output results
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", i + 1, burst_time[i], waiting_time[i],
turnaround_time[i]);
}

printf("\nAverage Waiting Time: %.2f", (float)total_waiting_time / n);


printf("\nAverage Turnaround Time: %.2f", (float)total_turnaround_time /
n);

return 0;
}

Explanation:

1. Input Burst Times: Collect burst times for each process.


2. Calculate Waiting Time: Waiting time for each process is computed based on
previous processes.
3. Calculate Turnaround Time: Turnaround time is the sum of burst time and waiting

48 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

time.
4. Output Results: Display process details along with average waiting and turnaround
times.

4.2. Shortest Job Next (SJN)

• How it works: The process with the shortest burst time is selected next.
• Type: Non-preemptive.
• Pros: Minimizes average waiting time.
• Cons: Can lead to starvation of longer processes.

Example in C:

49 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#include <stdio.h>

int main() {
int n, i, j;
printf("Enter number of processes: ");
scanf("%d", &n);

int burst_time[n], waiting_time[n], turnaround_time[n];


int total_waiting_time = 0, total_turnaround_time = 0;

// Input burst times


for (i = 0; i < n; i++) {
printf("Enter burst time for process P%d: ", i + 1);
scanf("%d", &burst_time[i]);
}

// Sort processes by burst time


for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (burst_time[i] > burst_time[j]) {
int temp = burst_time[i];
burst_time[i] = burst_time[j];
burst_time[j] = temp;
}
}
}

waiting_time[0] = 0;

// Calculate waiting time


for (i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i - 1] + burst_time[i - 1];
total_waiting_time += waiting_time[i];
}

// Calculate turnaround time


for (i = 0; i < n; i++) {
turnaround_time[i] = burst_time[i] + waiting_time[i];
total_turnaround_time += turnaround_time[i];
}

// Output results
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", i + 1, burst_time[i], waiting_time[i],
turnaround_time[i]);
}

printf("\nAverage Waiting Time: %.2f", (float)total_waiting_time / n);


printf("\nAverage Turnaround Time: %.2f", (float)total_turnaround_time /
n);

50 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

return 0;
}

Explanation:

1. Input Burst Times: Collect burst times for each process.


2. Sort Processes: Sort processes based on burst times.
3. Calculate Waiting Time: Waiting time is calculated based on the sorted order.
4. Calculate Turnaround Time: Compute turnaround time as the sum of burst time and
waiting time.
5. Output Results: Display sorted process details and average times.

4.3. Priority Scheduling

• How it works: Each process is assigned a priority. The process with the highest priority
is selected next.
• Type: Can be preemptive or non-preemptive.
• Pros: Allows important tasks to be completed first.
• Cons: Can lead to starvation of lower-priority processes.

Example in C

51 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#include <stdio.h>

#define MAX 10

int main() {
int n, i, j;
printf("Enter number of processes: ");
scanf("%d", &n);

int burst_time[MAX], priority[MAX], waiting_time[MAX],


turnaround_time[MAX];
int total_waiting_time = 0, total_turnaround_time = 0;

// Input burst times and priorities


for (i = 0; i < n; i++) {
printf("Enter burst time and priority for process P%d: ", i + 1);
scanf("%d %d", &burst_time[i], &priority[i]);
}

// Sort processes by priority


for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (priority[i] < priority[j]) {
int temp = burst_time[i];
burst_time[i] = burst_time[j];
burst_time[j] = temp;

temp = priority[i];
priority[i] = priority[j];
priority[j] = temp;
}
}
}

waiting_time[0] = 0;

// Calculate waiting time


for (i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i - 1] + burst_time[i - 1];
total_waiting_time += waiting_time[i];
}

// Calculate turnaround time


for (i = 0; i < n; i++) {
turnaround_time[i] = burst_time[i] + waiting_time[i];
total_turnaround_time += turnaround_time[i];
}

// Output results
printf("\nProcess\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\t\t%d\n", i + 1, burst_time[i],

52 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

priority[i], waiting_time[i], turnaround_time[i]);


}

printf("\nAverage Waiting Time: %.2f", (float)total_waiting_time / n);


printf("\nAverage Turnaround Time: %.2f", (float)total_turnaround_time /
n);

return 0;
}

Explanation:

1. Input Burst Times and Priorities: Collect burst times and priorities for each process.
2. Sort Processes: Sort processes based on priority.
3. Calculate Waiting Time: Compute waiting time based on sorted order.
4. Calculate Turnaround Time: Calculate turnaround time.
5. Output Results: Display process details, including priorities, and average times.

4.4. Round Robin Scheduling

• How it works: Each process is assigned a fixed time slice (quantum). The CPU cycles
through processes, allocating each a turn.
• Type: Preemptive.
• Pros: Fair distribution of CPU time among processes.
• Cons: Time quantum must be carefully chosen to avoid excessive context switching.

Example in C:

53 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#include <stdio.h>

#define MAX 10

int main() {
int n, i, time_quantum, time = 0, remaining;
printf("Enter number of processes: ");
scanf("%d", &n);

int burst_time[MAX], remaining_time[MAX], waiting_time[MAX],


turnaround_time[MAX];
int total_waiting_time = 0, total_turnaround_time = 0;

// Input burst times and time quantum


for (i = 0; i < n; i++) {
printf("Enter burst time for process P%d: ", i + 1);
scanf("%d", &burst_time[i]);
remaining_time[i] = burst_time[i];
}

printf("Enter time quantum: ");


scanf("%d", &time_quantum);

remaining = n;

// Simulate Round Robin Scheduling


while (remaining > 0) {
for (i = 0; i < n; i++) {
if (remaining_time[i] > 0) {
if (remaining_time[i] > time_quantum) {
remaining_time[i] -= time_quantum;
time += time_quantum;
} else {
time += remaining_time[i];
waiting_time[i] = time - burst_time[i];
remaining_time[i] = 0;
remaining--;
}
}
}
}

// Calculate waiting time


for (i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i - 1] + burst_time[i - 1];
total_waiting_time += waiting_time[i];
}

// Calculate turnaround time


for (i = 0; i < n; i++) {
turnaround_time[i] = burst_time[i] + waiting_time[i];
total_turnaround_time += turnaround_time[i];

54 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

// Output results
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", i + 1, burst_time[i], waiting_time[i],
turnaround_time[i]);
}

printf("\nAverage Waiting Time: %.2f", (float)total_waiting_time / n);


printf("\nAverage Turnaround Time: %.2f", (float)total_turnaround_time /
n);

return 0;
}

Explanation:

1. Input Burst Times and Time Quantum: Collect burst times and time quantum.
2. Round Robin Simulation: Allocate CPU time in fixed slices.
3. Calculate Waiting and Turnaround Times: Compute times based on the simulation.
4. Output Results: Display process details and average times.

4.5. Multilevel Feedback Queue Scheduling

• How it works: Processes are managed in multiple queues based on their behavior and
requirements. The system adjusts process priorities dynamically.

Example in C:

55 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

#include <stdio.h>

#define MAX 10

int main() {
int n, i, time_quantum, time = 0, remaining;
printf("Enter number of processes: ");
scanf("%d", &n);

int burst_time[MAX], waiting_time[MAX], turnaround_time[MAX];


int remaining_time[MAX], process_queue[MAX];
int total_waiting_time = 0, total_turnaround_time = 0;
remaining = n;

printf("Enter time quantum: ");


scanf("%d", &time_quantum);

// Input burst times


for (i = 0; i < n; i++) {
printf("Enter burst time for process P%d: ", i + 1);
scanf("%d", &burst_time[i]);
remaining_time[i] = burst_time[i];
}

// Simulate Multilevel Feedback Queue


while (remaining > 0) {
for (i = 0; i < n; i++) {
if (remaining_time[i] > 0) {
if (remaining_time[i] > time_quantum) {
remaining_time[i] -= time_quantum;
time += time_quantum;
} else {
time += remaining_time[i];
waiting_time[i] = time - burst_time[i];
total_waiting_time += waiting_time[i];
remaining_time[i] = 0;
remaining--;
}
}
}
}

// Calculate turnaround time


for (i = 0; i < n; i++) {
turnaround_time[i] = burst_time[i] + waiting_time[i];
total_turnaround_time += turnaround_time[i];
}

// Output results
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", i + 1, burst_time[i], waiting_time[i],

56 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

turnaround_time[i]);
}
printf("\nAverage Waiting Time: %.2f", (float)total_waiting_time / n);
printf("\nAverage Turnaround Time: %.2f", (float)total_turnaround_time
/ n);

return 0;
}

Explanation:

1. Input Burst Times: Collect burst times for each process.


2. Multilevel Feedback Queue Simulation: Processes are managed with a fixed time
quantum.
3. Calculate Waiting and Turnaround Times: Compute these times after the simulation.
4. Output Results: Display results for each process.

Linux uses a CPU scheduling algorithm called Completely Fair Scheduler (CFS). CFS is
designed to provide fair CPU time to processes while considering their priority and
ensuring that all processes get a reasonable amount of CPU time.

5. Key Considerations in CPU Scheduling


• Starvation: Processes may be indefinitely delayed if they are always preempted by
higher-priority processes. Algorithms like Round Robin and Multilevel Feedback Queue
help mitigate this issue.
• Throughput: The rate at which processes are completed. A good scheduling algorithm
improves throughput by reducing waiting and turnaround times.
• Fairness: Ensuring that all processes get a fair share of the CPU. Fairness can be
improved by using algorithms that avoid indefinite delays.
• Complexity: Some algorithms, like Multilevel Feedback Queue, can be complex to
implement but provide better performance in dynamic environments.

6. Summary
CPU scheduling is fundamental to operating systems, affecting how efficiently processes are

57 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

executed and how resources are allocated. Understanding different algorithms allows
system designers to choose the best approach based on specific needs and constraints. The
choice of scheduling algorithm impacts system performance, user experience, and overall
system efficiency.

• FCFS: Simple but can lead to long wait times for short processes.
• SJN: Reduces average waiting time but may lead to process starvation.
• Priority Scheduling: Can prioritize important tasks but risks starving lower-priority
processes.
• Round Robin: Ensures fair allocation of CPU time among processes but requires
careful selection of time quantum.
• Multilevel Queue: Allows flexibility in scheduling different types of processes but can
be complex to manage.
• Multilevel Feedback Queue: Dynamically adjusts priorities, balancing responsiveness
and fairness.

58 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Chapter 9: Main Memory Management

1. Introduction to Memory Management


Memory management is a crucial function of any operating system. It refers to the process
of coordinating and managing computer memory, ensuring that each running program has
enough memory to execute and that memory is used efficiently. The operating system is
responsible for allocating memory to different processes and ensuring memory protection
so that one process cannot interfere with another.

In modern systems, memory management involves various techniques to manage both


physical memory (RAM) and virtual memory. It also handles the movement of processes
between main memory and disk storage.

Key responsibilities of memory management include:

• Allocation of memory to processes.


• Protection to prevent unauthorized access.
• Efficient use of memory resources.
• Swapping processes between main memory and disk as needed.

2. Memory Hierarchy
Memory in a system can be categorized into multiple levels of hierarchy, each with different
speeds and sizes. At the top is the fastest but smallest memory, and at the bottom is the
slowest but largest.

1. Registers and Cache Memory: Extremely fast, small memory spaces inside the CPU
used to store temporary data.
2. Main Memory (RAM): The physical memory where processes are loaded for
execution.
3. Secondary Storage (HDD/SSD): Used when RAM is not sufficient. This is much slower
but significantly larger in size.
4. Virtual Memory: A technique that allows the system to use part of the secondary
storage as if it were RAM, enabling processes to use more memory than physically
available.

59 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

3. Memory Allocation Techniques


The OS can allocate memory to processes in different ways:

1. Single Contiguous Allocation: A simple technique where all memory is allocated to


one program. This was used in very early systems but is impractical in multi-tasking
environments.
2. Partitioned Allocation: Memory is divided into multiple partitions. There are two
types:
◦ Fixed Partitioning: Memory is divided into fixed-size blocks. If a process needs
less memory than the block size, some memory is wasted (internal
fragmentation).
◦ Dynamic Partitioning: Partitions are created dynamically to fit the exact needs
of a process, but this can lead to external fragmentation where free memory is
scattered in small blocks.

4. Paging
Paging is one of the most commonly used memory management techniques in modern
operating systems. It eliminates the problem of fragmentation by dividing memory into
fixed-size blocks called pages (for virtual memory) and frames (for physical memory).

• Page Table: The operating system maintains a page table to track which pages of a
process are in which frames of physical memory.
• Page Faults: If a process accesses a page that is not currently in memory, a page fault
occurs, and the operating system must load the page from disk.

Advantages of Paging:

• It avoids both internal and external fragmentation.


• Provides flexibility since processes can be allocated non-contiguous memory blocks.

In Linux, a multi-level paging system is used for virtual memory management. Processes are
not aware of physical memory addresses, and the kernel handles mapping between virtual
and physical memory.

60 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

5. Segmentation
In segmentation, memory is divided into logical segments such as the code, data, and
stack of a process. Each segment has a varying size based on the process's needs.

• Segment Table: Similar to the page table, the segment table keeps track of the base
and limit addresses for each segment of a process.

In contrast to paging, segmentation is concerned with dividing programs into logical units
that reflect how the programmer views memory (e.g., a code segment, a data segment).

6. Virtual Memory
Virtual memory allows an operating system to use secondary storage (like an SSD or HDD)
as an extension of RAM. This allows systems to run processes that exceed the size of
physical memory.

• Demand Paging: Pages are only loaded into memory when they are needed by the
process.
• Page Replacement Algorithms: When memory is full, the OS needs to decide which
pages to swap out. Some common page replacement algorithms are:

1. FIFO (First-In-First-Out): The oldest page is replaced first.


2. LRU (Least Recently Used): The page that hasn’t been used for the longest time is
replaced.
3. Optimal Page Replacement: Replaces the page that will not be used for the longest
time in the future (though this is mostly theoretical as it requires knowledge of future
memory access).

7. Memory Fragmentation
Fragmentation occurs when memory is used inefficiently, leading to wasted memory space.
There are two types of fragmentation:

61 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

1. External Fragmentation: Occurs when free memory is scattered in small blocks


across the system, making it difficult to allocate large contiguous memory blocks to
new processes.
2. Internal Fragmentation: Happens when fixed-size memory blocks are allocated to
processes, but the processes do not fully utilize them.

8. Memory Protection
Memory protection is vital to ensure that one process cannot interfere with the memory
space of another process. Operating systems enforce memory protection through
techniques such as base and limit registers.

In Linux, hardware mechanisms like segmentation and paging are used to protect memory.

9. Conclusion
Memory management is essential for the efficient operation of any system. Operating
systems use a variety of techniques to allocate, protect, and optimize memory usage.
Understanding how paging, segmentation, virtual memory, and page replacement
algorithms work is critical for optimizing system performance and resource allocation.

By implementing the memory allocator and understanding these concepts, students can
appreciate the real-world challenges operating systems face in managing memory
efficiently.

62 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Chapter 10: Virtual Memory Management

1. Introduction to Virtual Memory


Virtual memory is a fundamental concept in modern operating systems that allows a system
to use more memory than is physically available. It creates the illusion of a large addressable
memory space by using a combination of physical memory (RAM) and disk storage. This
makes it possible for programs to execute even if they require more memory than the
available RAM.

Virtual memory provides several benefits:

• Multitasking: Multiple processes can run simultaneously, each believing it has its own
isolated address space.
• Efficient Memory Utilization: Unused memory portions of a program can be kept on
disk until needed, freeing up RAM for other processes.
• Memory Protection: Each process operates in its own virtual address space,
preventing one process from interfering with another.

2. How Virtual Memory Works


Virtual memory relies on two primary concepts:

1. Paging: Dividing virtual memory into fixed-size blocks called pages and physical
memory into frames of the same size. A page from virtual memory can be loaded into
any free frame in physical memory. The operating system manages this mapping using
a page table.
2. Swapping: When physical memory is full, the OS swaps inactive pages from RAM to
disk storage, which is slower but much larger. This space on disk is called the swap
space.

Virtual Memory Address Translation

Every memory address that a program uses is a virtual address, which the operating

63 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

system translates into a physical address using the page table. This translation process
happens during every memory access via the Memory Management Unit (MMU).

3. Paging in Virtual Memory


Paging is a critical component of virtual memory. In this system, both virtual memory and
physical memory are divided into equal-sized units.

• Page: A fixed-size block of virtual memory.


• Frame: A fixed-size block of physical memory.

When a program runs, its pages are loaded into available frames in RAM. The page table
keeps track of which page is stored in which frame. If a page is not in memory, it results in a
page fault.

Page Fault Handling

A page fault occurs when a process tries to access a page that is not currently in physical
memory. When this happens:

1. The OS pauses the process.


2. The required page is loaded from disk (swap space) into a free frame.
3. The process is resumed once the page is loaded.

Page faults introduce latency since accessing the disk is much slower than accessing RAM, so
the OS aims to minimize them.

4. Page Replacement Algorithms


When physical memory is full, and a new page needs to be loaded, the operating system
must decide which page to remove from RAM. This decision is made using page
replacement algorithms. Common algorithms include:

1. FIFO (First-In-First-Out): The oldest page in memory is removed first.

2. LRU (Least Recently Used): The page that hasn’t been used for the longest time is

64 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

removed.

3. Optimal Page Replacement: Replaces the page that will not be used for the longest
time in the future. Though this provides the best results, it is generally theoretical since
future page accesses are unknown.

4. Second-Chance Algorithm: A variation of FIFO, where pages are given a second


chance before being removed if they have been accessed recently.

Each algorithm has its strengths and weaknesses, and different operating systems use
different approaches based on their requirements.

5. Benefits of Virtual Memory


1. Process Isolation: Each process runs in its own virtual memory space, preventing one
process from accessing the memory of another. This increases security and system
stability.

2. Efficient Use of Memory: Programs don’t need to be fully loaded into physical
memory. Only the necessary pages are loaded on demand, allowing more processes to
run concurrently.

3. Larger Address Space: Virtual memory allows processes to use more memory than is
physically available by using the swap space on disk.

4. Swapping: Less frequently used pages are swapped to disk, freeing up RAM for more
critical tasks.

6. Drawbacks of Virtual Memory


While virtual memory provides many benefits, there are also trade-offs:

1. Performance Overhead: Accessing a page from disk is much slower than accessing it
from RAM, leading to a performance hit when too many page faults occur. This
condition is known as thrashing.

2. Disk I/O Bottleneck: Heavy reliance on swap space can lead to increased disk input/
output operations, slowing down the system.

65 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

3. Complexity: Managing virtual memory adds complexity to the operating system, as it


requires careful tracking of page tables and page faults.

7. Segmentation in Virtual Memory


Segmentation is another memory management technique that can be used in combination
with or instead of paging. In segmentation, memory is divided into segments of varying
sizes, which correspond to logical divisions of a program, such as the code segment, data
segment, and stack segment.

Unlike paging, segmentation presents the memory to processes in a way that aligns with
how programmers structure programs, making it more intuitive. However, segmentation can
lead to external fragmentation, where free memory is scattered across the system.

8. Virtual Memory in Linux


Linux uses virtual memory extensively, leveraging paging and swapping to manage memory
efficiently. Some key features of Linux's virtual memory management include:

• Demand Paging: Pages are only loaded into memory when they are needed by the
program.
• Swappiness: This parameter controls the tendency of the Linux kernel to use swap
space. A lower value reduces swapping, while a higher value increases it.
• Multi-Level Page Tables: Linux uses a multi-level page table structure to map large
amounts of virtual memory to physical memory efficiently.

9. Practical Example: Implementing a Simple Page


Replacement System
To illustrate the workings of virtual memory, we can simulate a page replacement system
where pages are loaded into memory on demand, and when memory is full, a page is
replaced based on a specific algorithm (e.g., FIFO).

66 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

The steps involved would include:

1. Simulating Virtual Memory: Set up an array to represent the virtual memory and
another array for physical memory (frames).
2. Page Table Management: Maintain a page table to map virtual pages to physical
frames.
3. Page Fault Handling: When a page fault occurs, load the required page from virtual
memory into a free frame or replace an existing page using a chosen page
replacement algorithm.
4. Swapping: If no free frames are available, the page replacement algorithm selects a
page to be swapped out.

10. Conclusion
Virtual memory is an essential component of modern operating systems, allowing them to
run programs that require more memory than what is physically available. By using
techniques like paging and segmentation, virtual memory ensures efficient use of resources,
isolates processes, and provides a flexible environment for multitasking.

Understanding how virtual memory works, including page replacement algorithms and
swapping, is crucial for optimizing system performance and effectively managing memory
resources.

67 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

Chapter 14: Security and Protection

1. Introduction to OS Security
Security in an operating system (OS) is crucial for protecting system resources like files,
processes, and hardware from unauthorized access and malicious activities. In Linux,
security is enforced through access control, user authentication, and network security.

Key security principles:

• Confidentiality: Ensures sensitive data is accessible only to authorized users.


• Integrity: Protects data from unauthorized modifications.
• Availability: Ensures that system resources are available to legitimate users.

2. Access Control Models


Access control in Linux determines how users interact with files, directories, and other
system resources. Linux primarily uses Discretionary Access Control (DAC), where the
owner of a file or directory sets access permissions.

2.1 File Permissions in Linux

Linux employs a permission system that defines access for the owner, group, and others.
Permissions include:

• Read (r): View file contents.


• Write (w): Modify file contents.
• Execute (x): Run the file as a program.

To view permissions, use the ls -l command:

ls -l filename

To modify permissions, use the chmod command:

68 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

chmod 755 filename

This allows the owner to read, write, and execute the file, while others can only read and
execute it.

2.2 File Ownership

Files and directories have an owner and an associated group. Ownership can be modified
using the chown command:

chown user:group filename

Properly managing file permissions and ownership is critical for maintaining system security.

3. User Authentication
User authentication ensures that only authorized users can access the system.

3.1 Password Authentication

Linux stores password hashes in the /etc/shadow file. Authentication occurs by comparing
the user's input with the stored hash.

3.2 SSH Authentication

SSH (Secure Shell) provides a secure method for remote login to a Linux system. SSH can be
configured for password-based or key-based authentication, with key-based authentication
being more secure.

Configuring SSH Key-Based Authentication:

1. Generate an SSH key pair on the client machine:

ssh-keygen -t rsa

69 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

2. Copy the public key to the server:

ssh-copy-id username@server

3. Verify that SSH is running on the server:

sudo systemctl status sshd

4. Connect to the server using the public key:

ssh username@server

By default, SSH listens on port 22, but you can change this for additional security by editing
the /etc/ssh/sshd_config file.

4. Firewalls in Linux
A firewall controls incoming and outgoing network traffic, enhancing system security by
allowing or denying access based on predefined rules. Linux supports multiple firewall tools,
including iptables and ufw (Uncomplicated Firewall).

4.1 Introduction to ufw (Uncomplicated Firewall)

ufw is a user-friendly firewall tool available on many Linux distributions. It simplifies the
process of managing firewall rules.

Basic ufw Commands:

• Enable the firewall:

sudo ufw enable

• Check the status:

sudo ufw status

• Allow SSH traffic (port 22):

70 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

sudo ufw allow ssh

• List all rules:

sudo ufw status numbered

• Disable the firewall:

sudo ufw disable

• Deny all incoming connections:

sudo ufw default deny incoming

4.2 Advanced Firewall Configuration with iptables

For more granular control over network traffic, iptables can be used. It is a powerful
firewall tool that allows administrators to set specific rules for handling traffic based on IP
addresses, ports, and protocols.

For example, to allow SSH traffic using iptables:

sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

While ufw is easier to manage, iptables offers more flexibility for advanced users.

5. Threats and Common Attacks


There are several common threats that can target a Linux system:

• Brute-force attacks: Automated attempts to guess passwords or SSH keys.


• Denial-of-Service (DoS) attacks: Overloading the system with traffic, making it
unavailable to legitimate users.
• Privilege escalation: Exploiting vulnerabilities to gain unauthorized access to higher
privilege levels.

71 of 72 6�29�25, 12:42 PM
Operating systems lab manuel http:��localhost:3000�print�html

By properly configuring firewalls and SSH, these threats can be mitigated effectively.

72 of 72 6�29�25, 12:42 PM

You might also like