Unit5 - Subjective Questions
INT249 • Practice Questions with Detailed Answers
Describe the three distinct modes of operation in the vi/vim editor. How do you switch between them?
The vi/vim editor operates in three main modes:
-
Command Mode (Normal Mode):
- This is the default mode when
vistarts. - Keys pressed in this mode are interpreted as editor commands (e.g., copying lines, deleting text, moving the cursor).
- You cannot type text directly into the file in this mode.
- This is the default mode when
-
Insert Mode:
- This mode is used for modifying text and typing content.
- To enter: Press
i(insert before cursor),a(append after cursor),o(open new line below), etc. - To exit: Press
Escto return to Command Mode.
-
Last Line Mode (Ex Mode):
- Used for file management operations like saving, quitting, and search/replace.
- To enter: Press
:while in Command Mode. - Examples:
:w(save),:q(quit),:wq(save and quit),:%s/old/new/g(replace).
Differentiate between Hard Links and Soft (Symbolic) Links in Linux. Provide the commands to create each.
Differences between Hard Links and Soft Links:
| Feature | Hard Link | Soft (Symbolic) Link |
|---|---|---|
| Reference | Points directly to the inode of the file. | Points to the path/filename of the original file. |
| Inode Number | Same inode number as the original file. | Different inode number from the original file. |
| Filesystem | Cannot span across different filesystems (partitions). | Can link to files on different filesystems. |
| Deletion | The file content remains accessible as long as one hard link exists. | If the original file is deleted, the link becomes 'broken' (dangling). |
| Directories | Generally cannot link directories (to prevent loops). | Can link to directories. |
Commands:
- Hard Link:
ln target_file link_name - Soft Link:
ln -s target_file link_name
Explain the Linux file permission system using the Octal (Numeric) method. Calculate the numeric value for the permission string -rwxr-x--x.
Linux permissions are defined for three categories: User (u), Group (g), and Others (o). In the Octal method, permissions are assigned numeric values:
- Read (r): 4
- Write (w): 2
- Execute (x): 1
- No permission (-): 0
To set permissions, the values are summed for each category.
Calculation for -rwxr-x--x:
- User (
rwx): - Group (
r-x): - Others (
--x):
The resulting octal permission code is 751.
Command example:
chmod 751 filename
Discuss the usage of the find command. Provide syntax examples to search for files based on name, size, and modification time.
The find command searches the directory tree rooted at a given starting point.
General Syntax: find [path] [expression]
Examples:
-
Search by Name:
- Find files ending in
.confinside/etc: find /etc -name "*.conf"
- Find files ending in
-
Search by Size:
- Find files larger than 100MB:
find / -size +100M- Find files exactly 10KB:
find . -size 10k
-
Search by Modification Time:
- Find files modified in the last 7 days:
find /home -mtime -7- Find files accessed more than 30 days ago:
find /var/log -atime +30
Explain the concept of I/O Redirection and Piping in Linux with suitable examples.
I/O Redirection:
Linux allows changing the source of standard input (stdin) and destinations of standard output (stdout) and standard error (stderr).
- Output Redirection (
>and>>):>: Overwrites the file. E.g.,ls > filelist.txtsaves the directory list tofilelist.txt.>>: Appends to the file. E.g.,date >> log.txtadds the date to the end oflog.txt.
- Input Redirection (
<):- Feeds a file content as input to a command. E.g.,
wc -l < file.txtcounts lines infile.txt.
- Feeds a file content as input to a command. E.g.,
- Error Redirection (
2>):- Redirects error messages. E.g.,
find / -name "test" 2> errors.txt.
- Redirects error messages. E.g.,
Piping (|):
The pipe operator takes the standard output of the command on the left and passes it as standard input to the command on the right.
- Example:
cat /etc/passwd | sort | head -n 5- This reads the password file, sorts the lines alphabetically, and then displays only the first 5 lines.
What is grep? Explain its usage with at least three different options (flags) and a Regular Expression example.
grep (Global Regular Expression Print) is a command-line utility used to search for specific text patterns within files.
Common Options:
-i(Ignore Case): Searches case-insensitively.grep -i "error" logfile.txt
-r(Recursive): Searches files in the specified directory and all subdirectories.grep -r "config" /etc/
-v(Invert Match): Displays lines that do not match the pattern.grep -v "#" config.txt(Hides comments starting with #)
Regular Expression Example:
To find lines starting with 'root' in /etc/passwd:
grep "^root" /etc/passwd
( indicates the start of a line).
Describe the purpose of the cut, sort, and uniq commands when processing text files.
These commands are essential for text processing pipelines:
-
cut:- Used to extract specific sections (columns or character positions) from each line of a file.
- Example: Extract the first column (usernames) from
/etc/passwdwhere fields are delimited by a colon: cut -d ":" -f 1 /etc/passwd
-
sort:- Arranges lines of text files in a specified order (alphabetical by default).
- Options:
-nfor numeric sort,-rfor reverse order. - Example:
sort -r names.txt
-
uniq:- Filters out adjacent duplicate lines. It is often used after
sortbecause it only detects duplicates if they are next to each other. - Example: Count occurrences of unique lines:
sort access.log | uniq -c
- Filters out adjacent duplicate lines. It is often used after
Explain the role of the sed command. Provide an example of how to perform a substitution operation on a file.
sed (Stream Editor) is a non-interactive text editor used to perform basic text transformations on an input stream (a file or input from a pipeline).
Role:
- It reads input line by line, applies a specified operation, and outputs the result.
- It is widely used for find-and-replace operations, deletion, and insertion without opening the file in an interactive editor.
Substitution Example:
The most common usage is the substitute command s.
- Syntax:
sed 's/search_pattern/replacement_string/flags' filename - Command: Replace the first occurrence of "linux" with "Linux" in each line:
sed 's/linux/Linux/' file.txt
- Global Replacement: To replace all occurrences in the file, use the
gflag:sed 's/linux/Linux/g' file.txt
Detail the Linux Boot Process step-by-step, from the moment the power button is pressed until the login prompt appears.
The Linux boot process involves the following sequential stages:
-
BIOS/UEFI (Basic Input/Output System):
- Performs the POST (Power-On Self-Test) to check hardware.
- Identifies the bootable device (HDD, USB, etc.) and searches for the Master Boot Record (MBR) or EFI partition.
-
MBR (Master Boot Record):
- The first sector of the disk (512 bytes). It contains the primary bootloader code and the partition table. It loads the bootloader into memory.
-
GRUB2 (Grand Unified Bootloader):
- The bootloader allows the user to select an Operating System or kernel version.
- It loads the selected Linux Kernel and the
initramfs(Initial RAM Filesystem) into memory.
-
Kernel:
- The kernel initializes hardware drivers, mounts the
initramfs, and eventually mounts the actual root filesystem (/) in read-only mode. - It starts the first process, usually
systemd(orinit), with Process ID (PID) 1.
- The kernel initializes hardware drivers, mounts the
-
Init / Systemd:
- PID 1 is the parent of all processes.
- It reads configuration files (targets for
systemdor runlevels for SysVinit) to start necessary services (network, GUI, background daemons).
-
Runlevel/Target:
- The system reaches the target state (e.g.,
multi-user.targetorgraphical.target), presenting the login screen to the user.
- The system reaches the target state (e.g.,
What are Kernel Modules? Why is the modular kernel approach preferred over a monolithic static kernel?
Kernel Modules are pieces of code (usually device drivers or filesystem drivers) that can be loaded and unloaded into the kernel upon demand. They usually have the .ko extension.
Preference for Modular Approach:
- Dynamic Loading: Modules can be loaded only when the hardware is detected or the feature is needed, rather than being compiled permanently into the kernel.
- Memory Efficiency: By not loading unused drivers, the system saves RAM (Physical Memory).
- Flexibility: Adding support for new hardware does not require recompiling the entire kernel and rebooting the system. You simply compile the module and load it.
- Smaller Kernel Size: The core kernel image (
vmlinuz) remains small and fast to boot.
Differentiate between the commands insmod and modprobe. Which one is recommended and why?
insmod (Insert Module):
- It inserts a single module into the kernel.
- It requires the full path to the
.kofile. - Crucial Limitation: It does not resolve dependencies. If module A relies on module B,
insmod Awill fail if B is not already loaded.
modprobe:
- It intelligently loads a module and all its dependencies.
- It uses the
modules.depfile (created bydepmod) to understand relationships. - It does not require the full file path, just the module name.
Recommendation:
modprobe is highly recommended because it handles dependency resolution automatically, reducing errors and manual effort in loading prerequisite drivers.
Explain the significance of the /proc filesystem in Linux. How is it different from standard filesystems?
Significance of /proc:
The /proc directory is a virtual filesystem (pseudo-filesystem) that provides an interface to kernel data structures. It does not contain real files stored on the hard disk; instead, it contains runtime system information.
Key Characteristics:
- Kernel Window: It allows users and applications to view the state of the kernel and running processes (e.g.,
/proc/cpuinfo,/proc/meminfo). - Process Information: Every running process has a directory named after its PID (e.g.,
/proc/1234/) containing details about that process. - Kernel Tuning: Files in
/proc/sysare writable and can be used to modify kernel parameters on the fly (e.g., enabling IP forwarding) without rebooting. - Volatility: Since it resides in memory, all contents of
/procdisappear when the system shuts down.
Write the commands to:
- List currently loaded kernel modules.
- Remove a module from the kernel.
- Display information about a specific module file.
-
List loaded modules:
- Command:
lsmod - (This reads from
/proc/modulesand formats the output nicely).
- Command:
-
Remove a module:
- Command:
rmmod [module_name] - Alternatively:
modprobe -r [module_name](which also removes unused dependent modules).
- Command:
-
Display module information:
- Command:
modinfo [module_name] - This displays details such as the author, description, license, parameter types, and dependencies.
- Command:
Explain the role of GRUB2 configuration files. How do you regenerate the main configuration file after making changes?
GRUB2 Configuration:
-
/boot/grub2/grub.cfg:- This is the main configuration file read by GRUB at boot time.
- Important: You should not edit this file manually as it is automatically generated and changes will be overwritten.
-
/etc/default/grub:- This is the user-editable file containing global settings like the boot timeout (
GRUB_TIMEOUT), default kernel (GRUB_DEFAULT), and kernel command line arguments (GRUB_CMDLINE_LINUX).
- This is the user-editable file containing global settings like the boot timeout (
-
/etc/grub.d/:- A directory containing scripts (e.g.,
40_custom) that are executed to build the final config.
- A directory containing scripts (e.g.,
Regenerating Configuration:
After editing /etc/default/grub, you must apply the changes by running:
- BIOS Systems:
grub2-mkconfig -o /boot/grub2/grub.cfg - UEFI Systems:
grub2-mkconfig -o /boot/efi/EFI/[distro]/grub.cfg
What is initramfs? Why is it required during the Linux boot process?
initramfs (Initial RAM Filesystem) is a compressed cpio archive that is loaded into memory by the bootloader (GRUB) alongside the Linux kernel.
Why it is required:
- Chicken-and-Egg Problem: The real root filesystem (where the OS lives) is often on a storage device (like LVM, RAID, or encrypted disk) that requires specific drivers to be accessed.
- Driver Availability: These drivers are located on the root filesystem. The kernel cannot read the root filesystem without the drivers, but the drivers are inside the root filesystem.
- Solution:
initramfscontains a minimal filesystem with just enough modules and scripts to mount the real root filesystem. Once the real root is mounted, the kernel pivots to it and executes the init process.
Compare Systemd targets with SysVinit runlevels. List the Systemd equivalents for runlevels 1, 3, and 5.
Comparison:
- SysVinit uses Runlevels (numbered 0-6) to define the state of the machine (e.g., single-user, multi-user). It processes scripts sequentially.
- Systemd uses Targets (files ending in
.target) to group units. Targets are more flexible and can handle dependencies and parallel execution of services.
Equivalents:
| State | SysVinit Runlevel | Systemd Target |
|---|---|---|
| Rescue / Single User | Runlevel 1 | rescue.target |
| Multi-User (Text Mode) | Runlevel 3 | multi-user.target |
| Graphical Mode | Runlevel 5 | graphical.target |
| Reboot | Runlevel 6 | reboot.target |
Describe how to perform advanced text processing using awk. Provide a syntax example to print specific columns based on a condition.
awk is a powerful programming language designed for text processing and data extraction. It operates on a record (line) and field (column) basis.
Key Concepts:
$0: Represents the whole line.2, ...: Represent the first, second, etc., fields.FS: Field Separator (default is whitespace).
Syntax Example:
Assume a file data.txt with content: Name Age Dept.
-
Print specific columns:
awk '{print $1, $3}' data.txt- (Prints the Name and Dept).
-
Condition-based printing:
- Print the line only if the Age (2nd column) is greater than 30:
awk '0}' data.txt
-
Custom Delimiter:
- Processing
/etc/passwd(colon-separated): awk -F ":" '{print $1}' /etc/passwd
- Processing
How would you persistently blacklist a kernel module so that it does not load during boot? Explain the steps.
Blacklisting a module prevents it from loading automatically during the boot process.
Steps:
- Identify the module: Use
lsmodto find the exact name of the module you wish to block. - Create/Edit configuration file:
- Navigate to
/etc/modprobe.d/. - Create a new file ending in
.conf, e.g.,blacklist.conf.
- Navigate to
- Add the blacklist directive:
- Open the file and add the line:
blacklist [module_name]- Example:
blacklist nouveau(often done when installing NVIDIA drivers).
- Update initramfs (Optional but recommended):
- If the module is included in the initial ramdisk, you must regenerate it (e.g., using
dracutorupdate-initramfs) to ensure the module is blocked during the early boot stage.
- If the module is included in the initial ramdisk, you must regenerate it (e.g., using
- Reboot: Restart the system to apply changes.
Explain the usage of the locate command. How does it differ from find in terms of performance and database usage?
Usage of locate:
locate searches for files by name. It is very fast and simple to use.
- Example:
locate myfile.txt
Difference from find:
-
Mechanism:
find: Searches the actual directory tree in real-time. It is slower but provides current results.locate: Searches a pre-built database (mlocate.db). It does not scour the hard drive during the search.
-
Performance:
locateis significantly faster thanfindbecause it queries an indexed database.
-
Accuracy/Freshness:
locaterelies on the database being up-to-date. If a file was created recently (after the last database update),locatewill not find it until the database is updated (usually via theupdatedbcommand).findalways sees the current state of the file system.
What are kernel parameters? How can you temporarily modify kernel parameters during the boot process using the GRUB menu?
Kernel Parameters:
These are arguments passed to the Linux kernel at boot time to customize system behavior (e.g., disabling quiet mode, forcing a specific runlevel, or disabling hardware drivers).
Modifying via GRUB (Temporary):
- Reboot the system.
- When the GRUB menu appears, use arrow keys to highlight the desired kernel entry.
- Press the
ekey to edit the entry. - Locate the line starting with
linux,linux16, orlinuxefi. - Append the desired parameter to the end of this line.
- Example: Append
rd.breakto stop boot at initramfs, orsystemd.unit=rescue.targetto boot into rescue mode.
- Example: Append
- Press
Ctrl + xorF10to boot with the modified parameters.
Note: These changes are not saved permanently.