0% found this document useful (0 votes)
40 views40 pages

Linux File Management Essentials

The Comprehensive Linux Lab 4 Guide serves as a detailed reference for various Linux commands and concepts, covering topics such as file management, system monitoring, and process management. It includes sections on file rights management, file system management, and commands like 'chmod', 'ls', and 'mkdir'. The guide also provides troubleshooting tips and examples for practical usage of commands.
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)
40 views40 pages

Linux File Management Essentials

The Comprehensive Linux Lab 4 Guide serves as a detailed reference for various Linux commands and concepts, covering topics such as file management, system monitoring, and process management. It includes sections on file rights management, file system management, and commands like 'chmod', 'ls', and 'mkdir'. The guide also provides troubleshooting tips and examples for practical usage of commands.
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

Comprehensive Linux Lab 4 Guide

A Detailed Reference for Commands and Concepts

ENSIA
May 11, 2025
Contents

I File Right Management & Links 3

II File System Management 11


1 Descriptions of Common File System Management Applications 12

2 Creating Partitions 20
2.1 Exploring block storage devices . . . . . . . . . . . . . . . . . . . . . . . 20
2.2 Create a (fake) block device (Loop Device) . . . . . . . . . . . . . . . . . 21
2.3 Create partitions on the pseudo-block device . . . . . . . . . . . . . . . . 22

3 Creating file systems 23

4 Mounting 24
4.1 Creating mount point folders . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.2 ‘mount‘ command for attaching filesystems . . . . . . . . . . . . . . . . . 24
4.3 Displaying mounted VFAT filesystems . . . . . . . . . . . . . . . . . . . 25
4.4 ‘df‘ command for disk space usage . . . . . . . . . . . . . . . . . . . . . . 25
4.5 ‘mount –bind‘ option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.6 Making file system mounts persistent (‘/etc/fstab‘) . . . . . . . . . . . . 26

5 Machine preparation (real partitions) 27

6 Quotas 27
6.1 Commands for Quota Management . . . . . . . . . . . . . . . . . . . . . 28
6.2 Setup and Configuration Steps for Quotas . . . . . . . . . . . . . . . . . 29

III System and Process Monitoring 30


7 The first system process (PID 1) 30
7.1 Finding info about PID 1 using ‘/proc‘ . . . . . . . . . . . . . . . . . . . 30
7.2 Using ‘ps‘ command for PID 1 . . . . . . . . . . . . . . . . . . . . . . . . 31

8 Detailed process information using command ‘ps‘ 31

9 Foreground and background processes 32

10 Managing processes with command ‘kill‘ 33

11 Monitoring System Resources with command ‘top‘ 35

12 Changing Process Priority with ‘nice‘ and ‘renice‘ 36

13 Creating processes from a C/C++ program 37


Part I
File Right Management & Links
‘touch‘ - Create files / Update timestamps
Purpose
• Creates an empty file if it doesn’t exist.
• Updates the access and modification timestamps of an existing file to the
current time.

Syntax

1 touch [ OPTION ]... FILE ...


2

Relevant Options
• -a: Change only the access time.
• -c, –no-create: Do not create any files. If a specified file does not exist,
touch will do nothing.
• -d, –date=STRING: Parse STRING and use it instead of current time (e.g.,
"2 days ago", "2023-01-15 [Link]").
• -m: Change only the modification time.
• -r, –reference=RFILE: Use RFILE’s times instead of current time.
• -t STAMP: Use [[CC]YY]MMDDhhmm[.ss] format instead of current time.

Basic Usage Examples

1 touch myfile . txt # Create myfile . txt or


update its timestamp
2 touch file1 . txt file2 . txt report . doc # Work on multiple
files
3

Advanced Usage Examples

1 touch -c n on_exi stent_ file . txt # Does nothing , no error


if file doesn ’ t exist
2 touch -d " 1 day ago " old_log . txt # Set timestamp to
yesterday
3 touch -r reference_file . txt new_file . txt # Set new_file ’ s
timestamps to match reference_file ’ s
4

Underlying Concepts
• Timestamps: Files in Linux have three main timestamps:

3
– atime (Access Time): Last time the file was read.
– mtime (Modification Time): Last time the file’s content was changed.
– ctime (Change Time): Last time the file’s metadata (like permissions
or ownership) was changed. touch primarily affects atime and mtime.

Troubleshooting Tips
• "Permission denied": You lack write permission in the directory where
you’re trying to create the file. Check directory permissions with ls -ld .
• Timestamp not changing: Ensure you are not using options like -c if
you intend to create the file. Also, some filesystems might be mounted with
options (noatime, nodiratime) that prevent atime updates for performance
reasons.

‘chmod‘ - Change file modes (permissions)


Purpose
Modifies the access rights (read, write, execute) for the owner, group, and others
for files and directories.

Syntax

1 chmod [ OPTION ]... MODE [ , MODE ]... FILE ...


2 chmod [ OPTION ]... OCTAL - MODE FILE ...
3 chmod [ OPTION ]... -- reference = RFILE FILE ...
4

Modes of Operation
• Symbolic Mode: Uses letters to represent users and permissions.
– Who (Users): u (owner/user), g (group), o (others), a (all: u, g, and
o).
– Operator: + (add), - (remove), = (set exact permissions, overwriting
existing ones for the specified class).
– Permissions: r (read), w (write), x (execute/search), X (execute/search
if it’s a directory or already has execute permission for some user), s
(setuid/setgid), t (sticky bit).
• Octal (Numeric) Mode: Uses numbers (0-7) for each of owner, group, and
others. Each number is a sum of: 4 (read), 2 (write), 1 (execute).
– Example: rwx = 4+2+1 = 7; r-x = 4+0+1 = 5; rw- = 4+2+0 = 6. A
full permission set is three octal digits (e.g., 755).

Relevant Options
• -R, –recursive: Change files and directories recursively.
• -v, –verbose: Output a diagnostic for every file processed.
• -c, –changes: Like verbose but report only when a change is made.
• –reference=RFILE: Use RFILE’s mode instead of MODE values.

4
• -h, –no-dereference (less common, behavior varies): Affect symbolic links
themselves instead of what they point to. Typically, chmod follows symbolic
links.

Basic Usage Examples

1 chmod u + x myscript . sh # Owner gets execute


permission
2 chmod g -w ,o - w secret_document . txt # Group and Others lose
write permission
3 chmod a = r important_notice . txt # All get only read
permission
4 chmod 644 data . csv # Sets rw -r - -r - -
5 chmod 755 myprogram # Sets rwxr - xr - x
6 chmod g + w shared_file . txt # Group gets write
permission
7 chmod a + x some_script # All users get execute
permission
8

Advanced Usage Examples

1 chmod -R g +w ,o - w p roject _direc tory / # Recursively add group


write , remove other write
2 chmod u = rwx , g = rx , o = private_stuff # Sets rwxr -x - - -
3 chmod u = rw , g =r , o = # Sets rw -r - - - - -
4 chmod + t / shared_directory # Add sticky bit to a
directory
5 chmod u = rwx , g = rwx , o = rwx another_file # Sets rwxrwxrwx
6 chmod -- reference = fileA fileB # Set fileB ’ s
permissions to match fileA ’ s
7 chmod ug = rwx , o = rx dir1 # Set rwxrwxr - x for dir1
8

Underlying Concepts
• Permission Bits: Standard Unix permissions involve 9 bits for read, write,
execute for user, group, other.
• Special Permissions:
– setuid (Set User ID - s in user execute field): If set on an executable,
the program runs with the owner’s privileges, not the user who ran it.
– setgid (Set Group ID - s in group execute field): If set on an exe-
cutable, it runs with the file’s group privileges. If set on a directory,
new files/directories created inside inherit the directory’s group.
– sticky bit (t in other execute field): On directories, it means only the
file owner, directory owner, or root can delete/rename files within that
directory, even if others have write permission to the directory (e.g.,
/tmp).
• Effect on Symbolic Links:

5
– By default, chmod operates on the target of a symbolic link, not the link
itself. The permissions of a symlink are generally lrwxrwxrwx and don’t
control access to the target.
– To attempt to change the link’s permissions (usually not useful
or possible for access control), some systems might have a -h or
–no-dereference option, but this is not universally standard or effec-
tive for access control.
• Effect on Hard Links: Changing permissions on one hard link changes it
for all hard links to the same inode (and the original file name), as they all
point to the same metadata.

Troubleshooting Tips
• "Operation not permitted": You are not the owner of the file and not
root.
• Octal confusion: Ensure correct octal sums. 777 is full access for all; 000
is no access.
• Recursive changes are powerful: Double-check the path when using -R
to avoid unintended widespread changes.

‘ls‘ - List directory contents


Purpose
Lists information about files and directories.

Syntax

1 ls [ OPTION ]... [ FILE ]...


2

Relevant Options (for permissions and file details)


• -l: Use a long listing format (shows permissions, links, owner, group, size,
date, name).
• -a, –all: Do not ignore entries starting with ..
• -A, –almost-all: Do not list implied . and ...
• -d, –directory: List directories themselves, rather than their contents. (e.g.,
ls -ld mydir/).
• -h, –human-readable: With -l, print sizes in human-readable format (e.g.,
1K, 234M, 2G).
• -i, –inode: Print the index number (inode) of each file.
• -F, –classify: Append indicator (one of */=>@|) to entries.

Interpreting ‘ls -l‘ Output


Example: -rwxr-xr– 1 user group 4096 May 10 15:30 filename
1. File Type & Permissions: (e.g., -rwxr-xr–)

6
• 1st char (Type): - (regular file), d (directory), l (symlink), c (char
device), b (block device), s (socket), p (pipe).
• Next 9 chars (Permissions): 3 sets of rwx (read, write, execute) for
Owner, Group, Others.
2. Number of Hard Links: (e.g., 1)
3. Owner: (e.g., user)
4. Group: (e.g., group)
5. Size: (e.g., 4096 bytes)
6. Last Modification Timestamp: (e.g., May 10 15:30)
7. File/Directory Name: (e.g., filename)

Basic Usage Examples

1 ls
2 ls -l
3 ls - la / etc /
4 ls - ld / usr / games / # Shows permissions of the / usr / games
directory itself
5 ls -l / tmp / file1 # Shows permissions of file1 in / tmp
6

Related Commands
• stat FILE: Displays very detailed file or file system status, including all
timestamps and permissions in octal.

‘mkdir‘ - Make directories


Purpose
Creates one or more new directories.

Syntax

1 mkdir [ OPTION ]... DIRECTORY ...


2

Relevant Options
• -p, –parents: Create parent directories as needed if they don’t exist. No
error if existing.
• -v, –verbose: Print a message for each created directory.
• -m MODE, –mode=MODE: Set file mode (as in chmod), not a=rwx - umask.

Basic Usage Examples

1 mkdir new_project
2 mkdir -p path / to / deep / directory
3

7
Advanced Usage Example (setting permissions at creation)

1 mkdir -m 750 secure_dir # Creates secure_dir with


rwxr -x - - -
2 mkdir -m u = rwx , g = rx , o = other_dir # Creates other_dir with
rwxr -x - - -
3

Underlying Concepts
• Directory Permissions:
– r (read): Allows listing directory contents (e.g., with ls).
– w (write): Allows creating, deleting, and renaming files within the direc-
tory (also requires x).
– x (execute/search): Allows entering (cd) the directory and accessing
files/subdirectories within it by name.

Troubleshooting Tips
• "Permission denied": You don’t have write permission in the parent direc-
tory where you are trying to create the new directory.
• "File exists": A file or directory with that name already exists. Using -p
can suppress this error if the directory already exists as part of the path.

‘ln‘ - Create links


Purpose
Creates links (alternative names) for files.

Syntax

1 ln [ OPTION ]... [ - T ] TARGET LINK_NAME (1 st form : link


LINK_NAME to TARGET )
2 ln [ OPTION ]... TARGET (2 nd form : link
TARGET into current dir )
3 ln [ OPTION ]... TARGET ... DIRECTORY (3 rd form : link
TARGETs into DIRECTORY )
4

Relevant Options
• -s, –symbolic: Make symbolic links instead of hard links.
• -f, –force: Remove existing destination files/links before creating the new
one.
• -v, –verbose: Print name of each linked file.
• -T: Treat LINK_NAME as a normal file always (useful if LINK_NAME could be a
directory).

8
Types of Links & Key Differences
• Hard Link (default):
– Acts as a direct reference (another name) to the file’s data (inode).
– All hard links to a file are indistinguishable from the "original" filename.
– Deleting one hard link does not delete the file’s data until all hard links
to that inode are removed.
– Cannot span across different filesystems.
– Cannot be created for directories (by normal users; . and .. are
system-managed hard links).
• Symbolic Link (Soft Link or Symlink):
– A special file whose content is the path to another file or directory (the
target).
– Like a shortcut in other OSes.
– Can span across different filesystems.
– Can link to directories.
– Can point to non-existent targets (becoming a "broken" or "dangling"
link).
– Has its own inode. Deleting the symlink does not affect the target.
Deleting the target breaks the symlink.
– Permissions of the symlink itself are usually lrwxrwxrwx and don’t di-
rectly control access; access is determined by the target’s permissions
and the path to the target.

Basic Usage Examples

1 touch original . txt


2 ln original . txt h a r d l i n k _ t o _ o r i g i n a l . txt # Create a hard
link
3 ln -s original . txt s y ml i n k_ t o _o r i gi n a l . txt # Create a
symbolic link
4 ln -s / var / log / syslog my_syslog_link # Symbolic link
to a system file
5 mkdir mydir
6 ln -s ../ original . txt mydir / relative_symlink # Relative
symbolic link
7

Usage for examining link behavior

1 # To test linking to / tmp ( which is often a separate


filesystem or special )
2 # from your home directory
3 touch / tmp / testfile_in_tmp
4 ln / tmp / testfile_in_tmp ~/ h a r d l i n k _ t o _ t m p _ f i l e # May
fail if / tmp is cross - device
5 ln -s / tmp / testfile_in_tmp ~/ s y ml i n k_ t o _t m p _f i l e # Should
work
6 ln / tmp ~/ h ar d l in k _ t o_ t m p_ d i r # Fails (
hard link to directory )

9
7 ln -s / tmp ~/ sy ml in k_ to_ tm p_ di r # Should
work
8

Underlying Concepts
• Inodes: Data structures that store metadata about files (permissions, owner,
size, data block locations) but not the filename. Filenames are in directory
entries mapping names to inode numbers. ls -i shows inodes.
• Hard links share the same inode. Symbolic links have their own distinct
inode.

Troubleshooting Tips
• ln: failed to create hard link ’...’: Invalid cross-device
link: Tried to hard link across filesystems.
• ln: ...: hard link not allowed for directory: Tried to hard link
to a directory.
• Broken symlink: Target moved/deleted. ls -l often highlights them.
Check the path stored in the symlink.

‘umask‘ - User file-creation mode mask


Purpose
Sets or displays the default permissions for newly created files and directories. The
umask "masks off" (removes) permissions from the system’s default maximums.

System Defaults (before umask)


• Files: Typically 666 (rw-rw-rw-).
• Directories: Typically 777 (rwxrwxrwx). (Execute bit is needed for directory
access).

How ‘umask‘ Works


The umask value is an octal number. Permissions specified in the umask are re-
moved from the default permissions.
• Example: umask 022
– File: 666 (rw-rw-rw-) MINUS 022 (-wx-wx) = 644 (rw-r–r–)
– Directory: 777 (rwxrwxrwx) MINUS 022 (-wx-wx) = 755 (rwxr-xr-x)
• The subtraction is a bitwise "AND NOT": default_permissions AND (NOT
umask_value).

Syntax

1 umask [ - S ] [ mask ]
2

10
Relevant Options
• No options: Display current umask in octal.
• -S: Display umask in symbolic form (e.g., u=rwx,g=rx,o=rx).
• [mask]: An octal number to set the umask to.

Basic Usage Examples

1 umask # Show current umask ( e . g . , 0022)


2 umask -S # Show in symbolic form ( e . g . , u = rwx , g = rx ,
o = rx )
3
4 umask 002 # Set umask : files =664 ( rw - rw -r - -) , dirs
=775 ( rwxrwxr - x )
5 touch file_umask002
6 mkdir dir_umask002
7 ls -l file_umask002 dir_umask002
8
9 umask 027 # Set umask : files =640 ( rw -r - - - - -) , dirs
=750 ( rwxr -x - - -)
10 touch file_umask027
11 mkdir dir_umask027
12 ls -l file_umask027 dir_umask027
13
14 umask 077 # Set umask : files =600 ( rw - - - - - - -) , dirs
=700 ( rwx - - - - - -) ( very private )
15 touch file_umask077
16 mkdir dir_umask077
17 ls -l file_umask077 dir_umask077
18

Underlying Concepts
• Default Permissions: umask controls the initial permissions. They can be
changed later with chmod.
• Shell Setting: umask is usually set in shell startup files (e.g., /etc/profile,
~/.bashrc) to apply to user sessions. Changes via the umask command are
typically for the current shell session and its children.

Troubleshooting Tips
• Permissions not as expected: Double-check octal math and remember it
removes permissions. Common values are 0022, 0002.
• System-wide vs. User: /etc/[Link] might define default umask for
new users, but shell profiles can override it.

Part II

11
1 Descriptions of Common File System Management Applications

File System Management


Important Note
Commands in this part generally require root privileges. Use sudo before them
(e.g., sudo fdisk -l).

1 Descriptions of Common File System Management


Applications
‘sfdisk‘
Purpose
Scriptable utility for partition table manipulation (MBR and GPT). Good for back-
ing up, restoring, or programmatically altering partition layouts.

Syntax
sfdisk [options] device [parameters]

Relevant Options
• -l, –list [device]: List partitions.
• -d, –dump device: Dump partition table in a script-friendly format.
• device < MBR_backup_file: Restore partition table from file (use with ex-
treme caution).
• –delete device [partition_number]: Delete a partition.
• -N partition_number: Create a new partition.
• –label type: Specify disk label type (e.g., dos, gpt).
• -A, –activate device [partition_number]: Activate bootable flag
(MBR).

Basic Usage Examples

1 sudo sfdisk -l / dev / sdb


2 sudo sfdisk -- dump / dev / sda > s d a _ p a r t i t i o n _ l a y o u t . txt
3 # sudo sfdisk / dev / sdb < s d a _ p a r t i t i o n _ l a y o u t . txt Careful:
Restores layout to sdb
4

Underlying Concepts
Partition tables (MBR/GPT), sectors. sfdisk is less interactive than fdisk or
parted.

12
1 Descriptions of Common File System Management Applications

‘badblocks‘
Purpose
Scans a device (like a partition) for bad blocks or physical defects.

Syntax
badblocks [options] device [last-block] [start-block]

Relevant Options
• -v: Verbose mode.
• -s: Show progress.
• -w: Write-mode test (destructive: writes patterns, then reads back.
ERASES DATA).
• -n: Non-destructive read-write test.
• -o file: Write list of bad blocks to file.
• -b block-size: Specify block size in bytes.
• -p num_passes: Number of passes for checking.

Basic Usage Examples

1 sudo badblocks -v / dev / sdb1 > / tmp / sdb1_badblocks . txt # Read


- only test
2 # sudo badblocks - wsv / dev / sdb1 # Destructive write test -
VERY DANGEROUS
3 sudo badblocks - nsv / dev / sdb1 # Non - destructive read - write
test
4

Underlying Concepts
Physical disk sectors can fail. Output can be used by tools like mke2fs or e2fsck
(with -l option) to avoid using these blocks.

‘dosfsck‘ (also ‘[Link]‘)


Purpose
Checks and repairs MS-DOS FAT-based file systems (FAT12, FAT16, VFAT/-
FAT32).

Syntax
dosfsck [options] device or [Link] [options] device

Relevant Options
• -a: Automatically repair.
• -r: Interactively repair.

13
1 Descriptions of Common File System Management Applications

• -V, –verbose: Verbose output.


• -l: List path names.
• -t: Test for bad clusters.
• -y: Assume "yes" to all questions.

Basic Usage Examples

1 sudo dosfsck / dev / sdc1


2 sudo dosfsck -a / dev / sdc1 # Auto - repair ( use with care )
3 sudo fsck . vfat -r / dev / sdc1 # Interactive repair
4

Underlying Concepts
File Allocation Table (FAT), clusters, directory entries, file system consistency for
FAT.

‘mkdosfs‘ (also ‘[Link]‘)


Purpose
Creates (formats) an MS-DOS FAT file system (FAT12, FAT16, VFAT/FAT32).

Syntax
mkdosfs [options] device [blocks] or [Link] [options] device
[blocks]

Relevant Options
• -F fat-size: Specify FAT size (12, 16, or 32).
• -n volume-name: Set volume name/label.
• -I: Create filesystem on a whole disk (dangerous for system disks).
• -s sectors-per-cluster: Specify sectors per cluster.
• -c: Check for bad blocks before creating.
• -v: Verbose output.

Basic Usage Examples

1 sudo mkdosfs -F 32 / dev / sdb1 # Format / dev / sdb1


as FAT32
2 sudo mkfs . vfat -n " USB_STICK " / dev / sdb1 # Format with a
volume name
3

Underlying Concepts
Formatting, FAT structure, boot sector, volume label.

14
1 Descriptions of Common File System Management Applications

‘fdisk‘
Purpose
Interactive, menu-driven utility for creating and manipulating MBR and GPT par-
tition tables.

Syntax
fdisk [options] device

Relevant Options (Command Line)


• -l [device...]: List partition tables and exit.
• -V: Display version.
• -t type: Change partition type (when used with -l, filters by type).

Interactive Commands (single key presses at fdisk prompt)


• m: Print help menu.
• p: Print the current partition table.
• n: Add a new partition.
• d: Delete a partition.
• t: Change a partition’s system ID/type.
• l: List known partition types.
• w: Write changes to disk and exit.
• q: Quit without saving changes.
• g: Create a new empty GPT partition table.
• o: Create a new empty DOS (MBR) partition table.
• v: Verify the partition table.
• a: Toggle bootable flag (for MBR).

Basic Usage Examples

1 sudo fdisk -l / dev / sda # List partitions on / dev /


sda
2 sudo fdisk / dev / sdb # Start interactive session
for / dev / sdb
3 Inside fdisk (example sequence):
4 m (then Enter)
5 p (then Enter)
6 n (then Enter, then follow prompts)
7 t (then Enter, then select partition, then enter type hex code)
8 w (then Enter - writes changes, be sure!)
9

Underlying Concepts
MBR (Master Boot Record), GPT (GUID Partition Table), primary/extended/-
logical partitions (MBR), partition types/IDs, CHS vs LBA addressing.

15
1 Descriptions of Common File System Management Applications

‘fsck‘ (FileSystem ChecK)


Purpose
A front-end utility to check and repair Linux file systems. Calls file system specific
checkers.

Syntax
fsck [options] [-t fstype] device | mountpoint

Relevant Options
• -A: Check all filesystems in /etc/fstab.
• -t fstype: Specify filesystem type (e.g., ext4, xfs).
• -a or -p: Automatically repair without prompting (safe changes for -p).
• -y: Assume "yes" to all questions.
• -r: Interactively repair (often default for specific fsck tools).
• -N: Don’t execute, just show what would be done.
• -C [fd]: Display completion/progress bar.

Basic Usage Examples

1 sudo fsck / dev / sdb1 # Check / dev / sdb1 , auto -


detects type
2 sudo fsck -t ext4 / dev / sdb1 # Explicitly specify ext4
3 sudo fsck -y / dev / sdb1 # Attempt to auto - repair
( use with caution )
4 IMPORTANT: Run fsck on UNMOUNTED filesystems.
5 For root FS: sudo touch /forcefsck; sudo reboot

Underlying Concepts
Filesystem consistency, superblocks, inodes, data blocks, journaling. fsck tries to
bring a corrupted filesystem back to a consistent state.

‘mkfs‘ (Make FileSystem)


Purpose
A front-end utility to create (format) a Linux file system. Calls file system specific
utilities.

Syntax
mkfs [-t fstype] [fs-options] device [size]

Relevant Options
• -t fstype: Specify filesystem type (e.g., ext4, xfs, vfat).
• [fs-options]: Options specific to the filesystem type.

16
1 Descriptions of Common File System Management Applications

• -V: Verbose output.

File System Specific mkfs tools


• mkfs.ext4 [options] device: Creates ext4. Options: -L label, -j, -m
percentage, -O feature.
• [Link] [options] device: Creates XFS. Options: -L label, -f (force),
-s size=value.
• [Link]: (see mkdosfs).

Basic Usage Examples

1 sudo mkfs -t ext4 / dev / sdb1 # Format / dev /


sdb1 as ext4
2 sudo mkfs . ext4 -L " DATA_PARTITION " / dev / sdb1 # Format as
ext4 with a label
3 sudo mkfs . xfs -L " XFS_VOL " / dev / sdc1 # Format / dev /
sdc1 as XFS with a label
4

Underlying Concepts
Formatting, creating metadata structures (superblocks, inode tables, etc.). This
process erases all data on the target partition.

‘parted‘
Purpose
Powerful program for creating, deleting, resizing, checking, and copying partitions
and file systems. Supports MBR and GPT. Interactive or script mode.

Syntax
parted [options] [device [command [args]...]]

Relevant Options (Command Line)


• -l, –list: Lists partition layout on all block devices.
• -s, –script: Never prompt for user intervention.
• -a alignment-type: Set alignment for new partitions (min, opt).

Interactive Commands (within parted prompt)


• help [command]: Help.
• print [devices|free|list,all|NUMBER]: Display partition table/free
space.
• mklabel label-type: Create new disk label (e.g., msdos, gpt).
• mkpart [part-type name fs-type] start end: Create partition.
• rm NUMBER: Delete partition NUMBER.

17
1 Descriptions of Common File System Management Applications

• resizepart NUMBER end: Resize partition.


• select DEVICE: Choose device.
• quit: Exit.
• unit UNIT: Set default unit (e.g., s, MB, GB, %).

Basic Usage Examples

1 sudo parted -l # List all partition


tables
2 sudo parted / dev / sdb # Start interactive
session for / dev / sdb
3 Inside parted (example sequence):
4 (parted) help
5 (parted) print
6 (parted) mklabel gpt

Scripted Example

1 sudo parted -s / dev / sdb mklabel gpt


2 sudo parted -s / dev / sdb mkpart primary ext4 0% 100%
3

Underlying Concepts
More modern than fdisk for some tasks, especially GPT and resizing. Often needs
mkfs after making a partition.

‘mount‘
Purpose
Attaches a file system to a specific directory (mount point) in the main file system
hierarchy.

Syntax
(simplified) mount [options] device directory or mount -t type [options]
device directory

Relevant Options
• No arguments: List all currently mounted filesystems.
• -a, –all: Mount all filesystems specified in /etc/fstab.
• -t vfstype: Specify filesystem type (e.g., ext4, xfs, vfat).
• -o options: Comma-separated mount options:
– ro (read-only), rw (read-write).
– defaults (rw,suid,dev,exec,auto,nouser,async).
– noexec, nouser, user, auto, noauto.
– remount: Remount an already mounted filesystem.
– bind: Perform a bind mount.

18
1 Descriptions of Common File System Management Applications

– loop: Used with loop devices.


– usrquota, grpquota: Enable disk quotas.
• –bind: Perform a bind mount. mount –bind olddir newdir.

Basic Usage Examples

1 sudo mount / dev / sdb1 / mnt / mydata # Mount / dev / sdb1


at / mnt / mydata
2 sudo mount -t vfat / dev / sdc1 / media / usb # Mount FAT32
device
3 mount # List all mounted
filesystems
4 sudo mount -o ro / dev / sdb1 / mnt / mydata # Mount read - only
5 sudo mount -o remount , ro / mnt / mydata # Remount / mnt /
mydata as read - only
6 sudo mount -- bind / var / www / srv / webmirror # Bind mount
7

Underlying Concepts
Mount points (empty directories), VFS (Virtual Filesystem Switch), /etc/fstab.

‘umount‘ (Unmount)
Purpose
Detaches a mounted file system. Crucial before removing a device or running fsck.

Syntax
umount [options] device|mountpoint

Relevant Options
• -a: Unmount all filesystems in /etc/fstab.
• -f, –force: Force unmount (dangerous).
• -l, –lazy: Lazy unmount (detach now, cleanup when no longer busy; risky).
• -t type: Unmount only filesystems of this type.
• -r: If unmounting fails, try to remount read-only.

Basic Usage Examples

1 sudo umount / dev / sdb1


2 sudo umount / mnt / mydata
3 If device is busy:
4 sudo fuser -km /mnt/mydata

Troubleshooting Tips
• "target is busy" or "device is busy": Processes are using the filesystem,
or a shell’s current directory is on it.

19
2 Creating Partitions

• Use fuser -vm MOUNTPOINT or lsof +D MOUNTPOINT to find processes.

2 Creating Partitions
2.1 Exploring block storage devices
‘lsblk‘ (List Block Devices)
Purpose
Lists information about block devices in a tree-like format.

Syntax
lsblk [options]

Relevant Options
• -f, –fs: Display filesystem information (type, label, UUID).
• -l, –list: Use list format instead of tree.
• -p, –paths: Print full device paths.
• -o columns: Specify output columns (e.g.,
NAME,FSTYPE,MOUNTPOINT,SIZE,UUID).

Basic Usage Examples

1 lsblk
2 lsblk -f
3 lsblk - fp
4 lsblk -o NAME , SIZE , FSTYPE , MOUNTPOINT / dev / sda
5

Output Description
Shows device names, partitions, sizes, types, and mount points. -f adds FS type,
label, UUID.

‘df‘ (Disk Free)


Purpose
Reports file system disk space usage.

Syntax
df [options] [file...]

20
2 Creating Partitions 2.2 Create a (fake) block device (Loop Device)

Relevant Options
• -h, –human-readable: Print sizes in human-readable format (1K, 234M, 2G).
• -T, –print-type: Print filesystem type.
• -i: Display inode information.
• –total: Produce a grand total.

Basic Usage Examples

1 df
2 df -h
3 df - hT
4 df -h / home # Show usage for the filesystem / home is on
5

Output Description
Columns: Filesystem, Size, Used, Avail, Use%, Mounted on.

2.2 Create a (fake) block device (Loop Device)


Loop Device Concept
A pseudo-device (or "loopback device") that makes a regular file accessible as a
block device. Allows treating a file as a hard disk or partition, useful for mounting
disk images or testing partitioning/formatting.

‘truncate‘
Purpose
Shrink or extend the size of a file to a specified size.

Syntax
truncate -s desired_size filename

Relevant Options
• -s, –size=SIZE: Set file to SIZE bytes. Suffixes: K, M, G, T.
• -c, –no-create: Do not create if file does not exist.

Basic Usage Example

1 sudo truncate -- size 10 GiB / tmp /10 G - fake - disk . img


2 ls - lh / tmp /10 G - fake - disk . img
3

21
2 Creating Partitions 2.3 Create partitions on the pseudo-block device

‘losetup‘ (Loop Device Setup)


Purpose
Sets up and controls loop devices.

Syntax
losetup [options] [loop_device] [file]

Relevant Options
• No options: List all active loop devices.
• -f, –find: Find the first unused loop device.
• -d loop_device: Detach the file from the loop device.
• –show: If attaching, print the name of the loop device used.
• -P, –partscan: Force kernel to scan for partitions on the loop device.
• –nooverlap: Avoid reusing an existing loop device.

Basic Usage Examples

1 sudo losetup # Show active loop


devices
2 sudo losetup -f # Find first unused
loop device name
3 LOOP_DEV = $ ( sudo losetup -f -- show -- partscan / tmp /10 G - fake -
disk . img )
4 echo " Image attached to $LOOP_DEV "
5 # To detach :
6 # sudo losetup -d / dev / loop0 (replace /dev/loop0 with actual loop
device)
7

2.3 Create partitions on the pseudo-block device


Use fdisk or parted on the loop device (e.g., /dev/loop0).

Example using ‘fdisk‘


1 sudo fdisk / dev / loop0 (assuming /dev/loop0 is your loop device)
2 Inside fdisk:
3 m (for help)
4 g (to create a new GPT label) or o (for MBR/DOS)
5 n (to add a new partition, follow prompts for number, first/last sector)
6 (Last sector can be +SIZE like +2G for a 2GB partition)
7 p (to print partition table and verify)
8 t (to change partition type if needed)
9 w (to write changes and exit)
10

After creating partitions, the kernel might need a re-read if –partscan wasn’t used
or triggered: sudo partprobe /dev/loop0. Then lsblk /dev/loop0 should show

22
3 Creating file systems

partitions like /dev/loop0p1.

3 Creating file systems


Once partitions like /dev/loop0p1 are created, format them.

Formatting Partitions
VFAT ([Link])

1 sudo mkfs . vfat -F 32 -n " VFAT_PART " / dev / loop0p1 (Replace X


with partition number)
2

EXT4 (mkfs.ext4)

1 sudo mkfs . ext4 -L " EXT4_PART " / dev / loop0p2


2

XFS ([Link])

1 sudo mkfs . xfs -L " XFS_PART " / dev / loop0p3


2

Querying filesystem info after creation

1 sudo lsblk -f / dev / loop0


2 sudo blkid / dev / loop0p * (shows UUIDs, LABELS, TYPEs)
3

File System Descriptions and Comparison


VFAT (FAT32)
• Description: Virtual File Allocation Table. Widely supported (Windows,
macOS, Linux).
• Characteristics: Simple, no journaling, no fine-grained permissions, 4GB
max file size, 2TB max partition size. Case-insensitive.
• Pros: Excellent interoperability.
• Cons: No journaling, limited file/partition size, lacks modern FS features.
• Use Cases: USB drives, SD cards, EFI System Partition.

EXT4 (Fourth Extended Filesystem)


• Description: Default for many Linux distributions. Successor to ext3.
• Characteristics: Journaling, large file/volume support, backward compati-
bility, extents, delayed allocation. Unix permissions.

23
4 Mounting

• Pros: Mature, stable, good all-round performance.


• Cons: Journaling overhead, can suffer from fragmentation over time.
• Use Cases: Root filesystems, data partitions on Linux systems.

XFS (Extent File System)


• Description: High-performance 64-bit journaling filesystem.
• Characteristics: Journaling (metadata default), excellent for large files/-
many files, efficient space allocation, online resizing. Unix permissions.
• Pros: Very good for large files, high concurrency, scales well.
• Cons: Metadata ops can be slower for many small files vs ext4. Shrinking
not directly supported online.
• Use Cases: Large file servers, media storage, databases, HPC.

Comparative Study Points


• Journaling: ext4, xfs have; vfat does not.
• Permissions: ext4, xfs support full Unix permissions; vfat does not.
• File/Partition Size Limits: vfat most limited; ext4/xfs support very large
sizes.
• Performance: Workload dependent. XFS excels with large files; Ext4 is
good generalist.
• Interoperability: VFAT for cross-OS; ext4/xfs primarily Linux.

4 Mounting
4.1 Creating mount point folders
‘mkdir‘ for Mount Points
Mount points are just empty directories.
1 sudo mkdir / mnt / my_vfat_part
2 sudo mkdir / mnt / my_ext4_part
3 sudo mkdir / mnt / my_xfs_part
4 sudo mkdir / mnt / my_bind_target
5

4.2 ‘mount‘ command for attaching filesystems


Mounting Filesystems
Syntax: sudo mount -t type -o options device mount_point
1 sudo mount / dev / loop0p1 / mnt / my_vfat_part # Auto - detects
type
2 Or more explicitly:
3 sudo mount -t vfat / dev / loop0p1 / mnt / my_vfat_part
4 sudo mount -t ext4 / dev / loop0p2 / mnt / my_ext4_part

24
4 Mounting 4.3 Displaying mounted VFAT filesystems

5 sudo mount -t xfs / dev / loop0p3 / mnt / my_xfs_part


6

4.3 Displaying mounted VFAT filesystems


Listing VFAT Mounts
1 mount | grep -i ’ vfat ’
2 lsblk -f -o NAME , FSTYPE , MOUNTPOINT | grep -i ’ vfat ’
3 findmnt -t vfat
4

4.4 ‘df‘ command for disk space usage


‘df‘ for Mounted Filesystems
1 df -h
2 df - hT / mnt / my_vfat_part / mnt / my_ext4_part # Show specific
mounts
3

4.5 ‘mount –bind‘ option


Bind Mounts
Purpose
Makes a file or directory subtree visible at another point in the file hierarchy.

Syntax
sudo mount –bind old_directory new_directory or sudo mount -o bind
old_directory new_directory

Example

1 sudo mount -- bind / mnt / my_vfat_part / mnt / my_bind_target


2 ls / mnt / my_vfat_part
3 ls / mnt / my_bind_target Should show the same content
4

25
4 Mounting 4.6 Making file system mounts persistent (‘/etc/fstab‘)

4.6 Making file system mounts persistent (‘/etc/fstab‘)


‘/etc/fstab‘ - Persistent Mounts
What it means
Persistent mounts are automatically mounted at boot time or when mount -a is
run. Configured in /etc/fstab.

Backup ‘/etc/fstab‘ before editing

1 sudo cp / etc / fstab / etc / fstab . backup . $ ( date +% Y % m % d )


2

Printing content of ‘/etc/fstab‘

1 cat / etc / fstab


2 less / etc / fstab
3

Structure and Usage of ‘/etc/fstab‘


A system configuration file defining how disk partitions/devices are mounted. Each
line has six fields:
1. device-spec (Field 1 - File system): Device name (e.g., /dev/sda1),
or recommended: UUID=uuid_string or LABEL=label_string. Use sudo
blkid to find these.
2. mount-point (Field 2): Directory where the filesystem will be mounted
(e.g., /mnt/mydata). Must exist.
3. fs-type (Field 3): Filesystem type (e.g., ext4, xfs, vfat, auto).
4. options (Field 4): Mount options, comma-separated (e.g., defaults,
rw, ro, noauto, user, nofail, usrquota, grpquota). defaults means
rw,suid,dev,exec,auto,nouser,async.
5. dump (Field 5): Used by dump utility (0 = disable, 1 = enable). Rarely used
now.
6. pass (Field 6 - FSCK order): Order for fsck at boot (0 = no check, 1 =
root FS, 2 = other FS).

Example entries (use actual UUIDs from sudo blkid)

1 # < file system > < mount point > < type > < options
> < dump > < pass >
2 UUID = YOUR _ VFAT _ UUID _ HERE / mnt / my _ vfat _ part vfat
defaults , utf 8 , nofail 0 2
3 UUID = YOUR _ EXT 4_ UUID _ HERE / mnt / my _ ext 4_ part ext 4
defaults , nofail 0 2
4 UUID = YOUR _ XFS _ UUID _ HERE / mnt / my _ xfs _ part xfs
defaults , nofail 0 2
5

26
6 Quotas

Important: After editing, test with sudo mount -a. For loop devices, losetup
itself is not persistent; /etc/fstab entries for them rely on the loop device being
active.

5 Machine preparation (real partitions)


Working with Real Partitions
Tools
gparted (graphical), fdisk, parted, cfdisk.

Installation of gparted

1 sudo apt update


2 sudo apt install gparted
3

General Process
1. BACKUP DATA!
2. Identify free space or partition to shrink.
3. Unmount partitions to be modified (use Live CD/USB for system partitions).
4. Use tools to shrink/create partitions.
5. Format new partition (sudo mkfs.ext4 /dev/sdaX).
6. Create mount point (sudo mkdir /mnt/new_real_partition).
7. Mount it (sudo mount /dev/sdaX /mnt/new_real_partition).
8. Optionally add to /etc/fstab.

6 Quotas
Disk Quota Concepts
Disk quotas limit disk space or number of files a user/group can use.
• Hard Limit: Absolute maximum. Operations exceeding it fail.
• Soft Limit: Warning threshold. Can be exceeded temporarily for a grace
period. Acts as hard limit after grace period expires if still over.
• Grace Period: Time a user can stay above soft limit before enforcement.

27
6 Quotas 6.1 Commands for Quota Management

6.1 Commands for Quota Management


‘quotacheck‘
Purpose
Scans a filesystem, checks disk usage, creates/updates quota files ([Link],
[Link]).

Syntax
quotacheck [options] filesystem or quotacheck -a [options]

Relevant Options
-a (all fstab), -c (create), -u (user), -g (group), -v (verbose), -m (no remount ro),
-f (force).

Example
sudo quotacheck -avcug (check All, Verbose, Create, User, Group)

‘edquota‘
Purpose
Edits user or group quotas via an editor.

Syntax
edquota [options] -u username or edquota [options] -g groupname or
edquota -t

Relevant Options
-u username, -g groupname, -t (grace periods), -p protoname (duplicate quo-
tas).

Example

1 sudo edquota -u someuser


2 sudo edquota -t
3

Editor shows blocks (space in KB) and inodes (files) with soft/hard limits and
current usage.

‘repquota‘
Purpose
Prints a summary of disk usage and quotas.

28
6 Quotas 6.2 Setup and Configuration Steps for Quotas

Syntax
repquota [options] filesystem or repquota -a [options]

Relevant Options
-a (all fstab), -u (user), -g (group), -v (verbose), -s (human-readable).

Example
sudo repquota -avus

‘quotaon‘
Purpose
Turns disk quotas on for filesystem(s).

Syntax
quotaon [options] filesystem or quotaon -a [options]

Relevant Options
-a, -u, -g, -v.

Example
sudo quotaon -avug

‘quotaoff‘
Purpose
Turns disk quotas off.

Syntax
quotaoff [options] filesystem or quotaoff -a [options]

Relevant Options
(Similar to quotaon: -a, -u, -g, -v).

Example
sudo quotaoff -avug

6.2 Setup and Configuration Steps for Quotas


1. Install quota tools: sudo apt update; sudo apt install quota

29
7 The first system process (PID 1)

2. Edit /etc/fstab: Add usrquota,grpquota to mount options for the target filesys-
tem. Example: UUID=YOUR_DEVICE_UUID /mnt/data ext4 defaults,usrquota,grpquota
0 2 (Backup first: sudo cp /etc/fstab /etc/[Link])
3. Inform systemd (modern systems) & Remount:
1 sudo systemctl daemon - reload
2 sudo mount -o remount / mnt / data (or umount/mount)
3

4. Create quota files and scan filesystem:


1 sudo quotacheck - avcugm / mnt / data (-c for first run)
2

This creates [Link] and/or [Link] in filesystem root.


5. Turn quotas on: sudo quotaon -avug /mnt/data
6. Assign quotas:
• Create user (if needed): sudo useradd -m userme; sudo passwd userme
• Edit user quota: sudo edquota -u userme Set block limits (soft/hard, e.g.,
50000KB for 50MB) and inode limits.
• Edit grace periods: sudo edquota -t (e.g., "7 days", "5 minutes").
7. Verify quotas: sudo repquota /mnt/data; user runs quota -u userme.
8. Testing quota limits: As user, create large files on the quota-enabled filesystem
using dd or fallocate to exceed soft/hard limits.

Part III
System and Process Monitoring
7 The first system process (PID 1)
PID 1: The Init Process
• Process ID (PID): Unique number for each running process. PID 1 is
special.
• It’s the first process started by the kernel at boot.
• Ancestor of all other user-space processes; adopts orphaned processes.
• Responsible for starting/managing system services and system shutdown.
• Historically init, now commonly systemd.
• If PID 1 dies, the system will panic.

7.1 Finding info about PID 1 using ‘/proc‘


Exploring ‘/proc/1‘
The /proc filesystem provides an interface to kernel data structures.

Name of process with PID 1

30
8 Detailed process information using command ‘ps‘7.2 Using ‘ps‘ command for PID 1

1 cat / proc /1/ comm # Shows command name ( e . g . , " systemd ")
2 cat / proc /1/ status | grep Name
3

Path to executable for PID 1

1 ls -l / proc /1/ exe # ’exe ’ is a symlink to the actual


executable
2 readlink -f / proc /1/ exe # Resolves the symlink
3

Command-line arguments for PID 1

1 cat / proc /1/ cmdline # Arguments are null - separated .


2 # To display them nicely :
3 xargs -0 echo < / proc /1/ cmdline
4 tr ’ \0 ’ ’ ’ < / proc /1/ cmdline ; echo
5

7.2 Using ‘ps‘ command for PID 1


‘ps‘ for PID 1
Name of process

1 ps -p 1 -o comm =
2

Full path and arguments

1 ps -p 1 -o cmd =
2 ps -p 1 -o args =
3 ps -p 1 -o comm , args
4 ps - fp 1 # Full format listing for PID 1
5

8 Detailed process information using command ‘ps‘


‘ps‘ (Process Status)
Purpose
Reports a snapshot of current processes. Highly configurable output.

Syntax Forms
• BSD style (no hyphens): ps aux

31
9 Foreground and background processes

• System V style (with hyphens): ps -ef


• GNU long options: ps –forest

Displaying all running processes in a tree structure

1 ps auxf
2 ps - efH
3 ps axjf
4 ps -e -- forest
5 ps - eo pid , ppid , user , cmd -- forest
6

Information Displayed (common columns): USER, PID, %CPU, %MEM, VSZ, RSS,
TTY, STAT (R, S, Z, T, D), START, TIME, COMMAND/CMD, PPID.

Filter by user (e.g., "root")

1 ps -u root
2 ps -f -u root
3 ps aux | grep ’^ root ’
4 pgrep -u root -l
5

Detailed format, including process tree and threads


Threads are often shown as LWP (Light Weight Process).
1 ps - eLf # Shows threads ( LWP column )
2 ps axms # BSD style , shows threads
3 ps - eo pid , ppid , tid , user , stat , psr , cmd -- forest # With TID ,
PSR
4

Additional details: LWP/TID (Thread ID), NLWP (Number of threads), CLS


(Scheduling class), PRI (Priority), NI (Nice value), PSR (Processor).

Display processes sorted by CPU or Memory usage

1 ps aux -- sort = -% cpu # Sort by CPU descending


2 ps aux -- sort = -% mem # Sort by Memory descending
3 ps - eo pid , ppid ,% cpu ,% mem , cmd -- sort = -% cpu | head -n 10 #
Top 10 CPU
4

9 Foreground and background processes


Process States
• Foreground Process: Interacts with user via terminal, receives keyboard
input. One per terminal.

32
10 Managing processes with command ‘kill‘

• Background Process: Runs independently of terminal. Many can run.


• Job Control: Shell feature to manage multiple processes (jobs) from that
shell.

Job Control Commands & Keystrokes


sleep DURATION
Pauses for a specified time. Syntax: sleep NUMBER[s|m|h|d]. Ex: sleep 300.

Ctrl+Z (Suspend)
Sends SIGTSTP (Terminal Stop) to foreground process. Process pauses (state T).

jobs
Lists active jobs (background or suspended). Syntax: jobs [-lrs]. Output: Job
number, status, command.

bg [%job_id]
Resumes a suspended job in the background. No %job_id acts on current job.

fg [%job_id]
Brings a background/suspended job to foreground. No %job_id acts on current
job.

& (Ampersand Operator)


Appended to a command, starts it directly in background. Ex: sleep 1000 &.

Example Workflow
1. Start: sleep 600
2. Suspend: Ctrl+Z (Shell: [1]+ Stopped sleep 600)
3. List: jobs (Shows "Stopped")
4. Foreground: fg %1 (Resumes in foreground)
5. Suspend: Ctrl+Z
6. Background: bg %1 (Shell: [1]+ sleep 600 &)
7. List: jobs (Shows "Running")

10 Managing processes with command ‘kill‘


‘kill‘
Purpose
Sends a signal to a process, usually to terminate it.

33
10 Managing processes with command ‘kill‘

Syntax
kill [options] [-signal] PID...

Common Signals (name without SIG or number)


• 1 or HUP (Hang Up): Reload config / terminate.
• 2 or INT (Interrupt): From Ctrl+C / terminate.
• 9 or KILL (Kill): Unconditional termination (last resort).
• 15 or TERM (Terminate): Default. Polite request to terminate.
• 18 or CONT (Continue): Resume a stopped process.
• 19 or STOP (Stop): Suspend process (cannot be caught).
List all signals: kill -l or man 7 signal.

Basic Usage Examples


(Assume MYSLEEPPROC holds PID of sleep 3600 &)
1 kill $MYSLEEPPROC # Sends SIGTERM (15)
2 kill - SIGHUP $MYSLEEPPROC # Sends SIGHUP (1)
3 kill -1 $MYSLEEPPROC # Same as SIGHUP
4 kill - SIGKILL $MYSLEEPPROC # Sends SIGKILL (9)
5 kill -9 $MYSLEEPPROC # Same as SIGKILL
6

Significance: Prefer SIGTERM for graceful shutdown. Use SIGKILL if unresponsive.

‘killall‘
Purpose
Kills processes by name.

Syntax
killall [options] [-signal] name...

Relevant Options
-u user, -i (interactive), -v (verbose), -e (exact name), -w (wait). Signal options
same as kill.

Example

1 # Start a few sleep processes


2 sleep 1000 &
3 sleep 1000 &
4 sudo killall sleep # Sends SIGTERM
5 sudo killall -9 sleep # Sends SIGKILL
6 sudo killall -i firefox # Interactively kill firefox
7

34
11 Monitoring System Resources with command ‘top‘

Troubleshooting
• "Operation not permitted": Trying to kill process of another user (and
not root).
• Zombie processes (Z state): Already dead. Parent must wait(), or
init/systemd will clean up.

11 Monitoring System Resources with command ‘top‘


‘top‘
Purpose
Dynamic real-time view of running system processes.

Syntax
top [options]

Key Output Areas


1. Summary Area (first few lines): Time, uptime, users, load average. Tasks
(total, running, sleeping, stopped, zombie). CPU states (%us, %sy, %ni, %id,
%wa, etc.). Memory (KiB Mem: total, free, used, buff/cache). Swap.
2. Process List Area (columns): PID, USER, PR (Priority), NI (Nice), VIRT
(Virtual Mem), RES (Resident Mem), SHR (Shared Mem), S (Status), %CPU,
%MEM, TIME+ (CPU Time), COMMAND.

Interactive ‘top‘ Commands (case-sensitive)


• h or ?: Help.
• q: Quit.
• Spacebar: Refresh.
• P (Shift+p): Sort by CPU usage.
• M (Shift+m): Sort by Memory usage (RES).
• N (Shift+n): Sort by PID.
• T (Shift+t): Sort by CPU Time (TIME+).
• 1: Toggle individual CPU core states display.
• u then username then Enter: Filter by user.
• k then PID [then signal]: Kill process.
• r then PID [then nice_value]: Renice process.
• f: Fields management screen.
• W (Shift+w): Write current configuration to ~/.toprc.
• c: Toggle command name vs full command line.
• V (Shift+v): Toggle forest view (process tree).
• H: Toggle display of individual threads.

35
12 Changing Process Priority with ‘nice‘ and ‘renice‘

Usage

1 top
2 Inside top: P (CPU), M (Mem), 1 (cores), u (user), q (quit)
3

Related: htop, atop, vmstat, iostat.

12 Changing Process Priority with ‘nice‘ and ‘renice‘


Process Priority Concepts
• Priority (PRI): Kernel scheduling priority. Lower number = higher priority.
• Niceness (NI): User-space value (-20 to +19) influencing PRI.
– -20: Highest priority (least "nice"). Requires root.
– 0: Default niceness.
– +19: Lowest priority (most "nice").
• Generally, PRI (new) = PRI (old) + NI. Higher NI = lower effective prior-
ity.

‘nice‘ command
Purpose
Runs a command with a modified niceness value.

Syntax
nice [OPTION] [COMMAND [ARG]...]

Relevant Options
-n adjustment or –adjustment=adjustment: Add adjustment to niceness.

Basic Usage

1 nice COMMAND # Run COMMAND with default nice


increment (+10)
2 nice -n 15 l ow_pri ority_ task # Run with niceness +15
3 sudo nice -n -5 hi gh _p ri or ity _t as k # Run with niceness -5 (
needs root )
4 # Example CPU - intensive processes :
5 # bash -c ’ while true ; do echo " Default priority : PID $$ ";
done ’
6 # sudo nice -n -20 bash -c ’ while true ; do echo " High
priority ( -20) : PID $$ "; done ’ &
7 # nice -n 19 bash -c ’ while true ; do echo " Low priority
(+19) : PID $$ "; done ’ &
8

36
13 Creating processes from a C/C++ program

‘renice‘ command
Purpose
Alters niceness of *already running* processes.

Syntax
renice [-n] priority [[-p] pid...] [[-g] pgrp...] [[-u] user...]

Relevant Options
priority: New absolute niceness value (-20 to 19). -p pid, -g pgrp, -u user.

Basic Usage

1 # Get PID first , e . g . , ps aux | grep ’ my_script ’


2 sudo renice -5 -p < PID_OF_PROCESS > # Set niceness to -5
3 sudo renice 10 -p < PID_OF_PROCESS > # Set niceness to +10
4 sudo renice 19 -u someuser # Set niceness of all
someuser ’ s processes to +19
5

Checking Niceness/Priority with ‘ps‘


1 ps -o pid , ni , pri , comm -p <PID > # Shows PID , Niceness ,
Priority , Command
2 ps axl | grep <PID > # ’l ’ format includes NI and
PRI
3

Behavior: Lower niceness = larger CPU share under load. Does not directly affect
I/O priority (see ionice).

13 Creating processes from a C/C++ program


C Programming for Process Creation
Required Headers (C)

1 # include < stdio .h > // For printf


2 # include < unistd .h > // For fork , exec , getpid , getppid
3 # include < sys / types .h > // For pid_t
4 # include < sys / wait .h > // For wait
5 # include < stdlib .h > // For exit , EXIT_SUCCESS ,
EXIT_FAILURE
6

37
13 Creating processes from a C/C++ program

Key System Calls / Functions (C)


fork()
• Purpose: Creates new child process by duplicating parent.
• Syntax: pid_t fork(void);
• Return Value:
– Child process: 0.
– Parent process: PID of child.
– Failure: -1.
• Both parent/child continue from instruction after fork(). Separate memory
(Copy-on-Write), shared open file descriptors initially.

getpid() and getppid()


• getpid(): Returns PID of calling process.
• getppid(): Returns PID of parent of calling process.
• Syntax: pid_t getpid(void); pid_t getppid(void);

exec family (e.g., execlp, execvp)


• Purpose: Replaces current process image with a new one.
• If successful, does not return to calling program.
• Common variants:
– execlp(const char *file, const char *arg0, ..., (char *)
NULL); (l=list args, p=use PATH).
– execvp(const char *file, char *const argv[]); (v=vector/array
args, p=use PATH).
• Return Value: Only returns if error (-1).
• Usage: Often called by child after fork() to run a different program.

wait() and waitpid()


• Purpose: Parent process waits for child termination/stop. Gets exit status,
prevents zombies.
• wait(int *wstatus): Waits for any child. Status in wstatus. Returns
child PID or -1.
• waitpid(pid_t pid, int *wstatus, int options): More flexible (spe-
cific child, process group, WNOHANG). Returns child PID, 0 (if WNOHANG), or
-1.

C Program Structure for fork()


1 # include < stdio .h >
2 # include < unistd .h >
3 # include < sys / types .h >
4 # include < sys / wait .h >
5 # include < stdlib .h >
6
7 int main () {

38
13 Creating processes from a C/C++ program

8 pid_t pid_val ; // Renamed from pid to avoid conflict with


other uses
9

10 pid_val = fork () ; // Create a child process


11
12 if ( pid_val < 0) { // Fork failed
13 fprintf ( stderr , " Fork failed \ n " ) ;
14 return EXIT_FAILURE ;
15 } else if ( pid_val == 0) { // This block is executed by the
Child process
16 printf ( " I am the Child process .\ n " ) ;
17 printf ( " My PID is % d \ n " , getpid () ) ;
18 printf ( " My Parent ’s PID is % d \ n " , getppid () ) ;
19 // Child specific tasks here ...
20 // exit ( EXIT_SUCCESS ) ; // Child typically exits or execs
21 } else { // This block is executed by the Parent process
22 printf ( " I am the Parent process .\ n " ) ;
23 printf ( " My PID is % d \ n " , getpid () ) ;
24 printf ( " My child ’s PID is % d \ n " , pid_val ) ;
25 // Parent specific tasks here ...
26 // int child_status ;
27 // waitpid ( pid_val , & child_status , 0) ; // Wait for this
specific child
28 // if ( WIFEXITED ( child_status ) ) {
29 // printf (" Parent : Child exited with status % d \ n " ,
WEXITSTATUS ( child_status ) ) ;
30 // }
31 printf ( " Parent process is finishing .\ n " ) ;
32 }
33 return EXIT_SUCCESS ;
34 }

C Program: Child executes ‘ls‘


1 # include < stdio .h >
2 # include < stdlib .h >
3 # include < unistd .h >
4 # include < sys / types .h >
5 # include < sys / wait .h >
6
7 int main () {
8 pid_t pid = fork () ;
9
10 if ( pid < 0) {
11 perror ( " fork failed " ) ;
12 exit ( EXIT_FAILURE ) ;
13 } else if ( pid == 0) {
14 // Child process
15 printf ( " Child ( PID % d ) : Executing ’ ls -l ’ in current
directory .\ n " , getpid () ) ;
16 // Arguments for execlp : path , arg0 , arg1 , ... , NULL
17 execlp ( " ls " , " ls " , " -l " , ( char *) NULL ) ;
18 // If execlp returns , it must have failed
19 perror ( " execlp failed in child " ) ;
20 exit ( EXIT_FAILURE ) ; // Exit if exec fails

39
13 Creating processes from a C/C++ program

21 } else {
22 // Parent process
23 printf ( " Parent ( PID % d ) : Waiting for child ( PID % d ) to
complete .\ n " , getpid () , pid ) ;
24 int status ;
25 waitpid ( pid , & status , 0) ; // Wait for the specific child
26
27 if ( WIFEXITED ( status ) ) {
28 printf ( " Parent : Child ( PID % d ) exited with status % d .\ n " ,
pid , WEXITSTATUS ( status ) ) ;
29 } else if ( WIFSIGNALED ( status ) ) {
30 printf ( " Parent : Child ( PID % d ) killed by signal % d .\ n " ,
pid , WTERMSIG ( status ) ) ;
31 }
32 printf ( " Parent : Child has terminated . Parent exiting .\ n " ) ;
33 }
34 return EXIT_SUCCESS ;
35 }

Compiling and Running (C)


1 gcc myprogram . c -o myprogram # Compile
2 ./ myprogram # Run
3 # For C ++ , use g ++ instead of gcc
4 # g ++ myprogram . cpp -o myprogram

40

You might also like