Linux ESE Answer
Linux ESE Answer
1. Identify a command to find all files ending with ".txt" in a directory and copy
them to a new directory named "backup".
Ans:
To find all .txt files in a directory and copy them to a new directory called backup, we use the
following command:
mkdir -p backup:
This command creates a directory named backup. The -p option ensures that no error occurs
if the directory already exists.
-name "*.txt" filters files that end with .txt using a wildcard pattern.
Ans:
The command chmod u+x adds execute permission for the owner only, which is essential for
making a script or program executable without altering group or others' access.
KR
3. Name the command to create a symbolic link to a deeply nested directory from
your current working directory.
Ans:
4. Recognize the use of both relative and absolute paths in different scenarios.
Ans:
Absolute Path:
Gives the full path to a file or directory regardless of the current working directory.
Example: /home/user/documents/file.txt
Use when you want to specify a file/directory location unambiguously from anywhere
in the system.
Relative Path:
Use when working within a known directory structure and you want shorter paths.
Use absolute paths for scripts, commands, or programs needing fixed locations.
Use relative paths for quick access when inside related directories, making commands
shorter and flexible.
5. List the commands to display only the first 10 lines, and then the last 15 lines of
a large log file.
Ans:
KR
To display the first 10 lines of a file, use:
head filename.log
Ans:
7. Identify wildcards to locate a file when you only know part of its name.
Ans:
Wildcards help match filenames when you only know part of the name:
Example:
ls file*.txt
This lists all files starting with file and ending with .txt.
KR
8. Describe the difference between hard links and symbolic links in the Linux file
system.
Ans:
Points directly to the inode (file data) Points to the file name (path)
File remains accessible if original is deleted Link breaks if original file is deleted
Shares the same inode number as the original Has a different inode number
file
Ans:
ls -ltr
This command lists files with the oldest modified files at the top and the newest at the
bottom.
10. Name a command to create a new directory and its parent directories, if they do
not exist.
Ans:
mkdir -p /path/to/new/directory
-p: Creates parent directories as needed without error if they already exist.
KR
11. List the commands to list the shells available in your system, and the steps to
change your login shell to Zsh.
Ans:
This command displays the file /etc/shells which contains a list of all valid login shells
installed on the system.
chsh -s /bin/zsh
12. Recall a command to display a file’s content and number each line
Ans:
This command shows the file content with line numbers for easier reference.
13. Identify the use of `find` and `xargs` to search and delete specific file types
Ans:
The find command searches for files based on conditions like name, type, size, etc.
xargs takes the output of find and executes commands (like rm) on those files
efficiently.
find /path/to/dir -name "*.log": Finds all files ending with .log.
KR
14. Recall the `locate` and `updatedb` commands used to improve file search
efficiency.
Ans:
locate: Quickly searches for files by name using a pre-built database instead of scanning
the entire filesystem in real-time.
Example:
locate filename
updatedb: Updates the database used by locate to include the latest files and directories
on the system.
Run this command periodically or manually to keep the database current:
sudo updatedb
locate is faster than find because it searches a database; updatedb keeps that database up-
to-date.
15. List steps to construct a backup strategy using `cron` and `tar`.
Ans:
0 2 * * * /path/to/backup.sh
Ans:
1. ext3 (Third Extended Filesystem) – Supports journaling for better reliability, and is
backward compatible with ext2. It's stable but slower compared to newer file systems.
KR
2. ext4 (Fourth Extended Filesystem) – The default in many Linux distros. Offers faster
performance, journaling, support for large files, and better reliability than ext3.
3. XFS – A high-performance journaling file system, ideal for handling large files and
scalable systems. Often used in enterprise environments.
4. Btrfs (B-tree File System) – A modern Linux file system with advanced features like
snapshots, compression, and self-healing. It's still evolving but powerful.
6. NTFS – Developed by Microsoft. Linux can access it using tools like ntfs-3g. It
supports large files, permissions, and journaling.
17. Identify the output of commands that display file and directory information
Ans:
1. ls
2. ls -l
Long listing format: shows file permissions, owner, group, size, and modification date.
Example output:
3. ls -a
Displays all files, including hidden ones (those starting with .).
4. stat filename
5. file filename
6. du -sh directory/
18. List a sequence of commands to archive, compress, and then list the contents of
an archive.
Ans:
KR
1. Archive files using tar:
Creates archive.tar.gz
These steps first create an archive (tar), compress it (gzip), and then view its contents (tar -t).
Ans:
Environment variables are dynamic values stored in the shell's environment that affect the
behaviour of running processes and system configuration in Unix/Linux.
Significance:
1. Configuration:
They help configure the behavior of the system or applications (e.g., PATH, HOME).
2. Access Everywhere:
Environment variables are inherited by child processes, making them accessible
globally in scripts and programs.
3. Shell Customization:
Variables like PS1, HISTSIZE, and LANG allow users to personalize their shell
environment.
4. Scripting Use:
They allow dynamic handling of user-specific or system-specific paths, options, and
credentials in shell scripts.
5. Session Information:
Variables like USER, SHELL, and PWD store current user and session-specific
information.
KR
Common examples:
Ans:
Ans:
Aliases are shortcuts to longer commands, making them easier to type and remember.
Syntax:
Example:
alias ll='ls -l'
Then run:
source ~/.bashrc
KR
22. Describe the purpose of shell initialization files (e.g., `.bashrc`, `.bash_profile`)
Ans:
Shell initialization files are scripts that run automatically when a shell session starts. They help
set up the user environment in Unix/Linux systems.
1. .bashrc
Runs for interactive non-login shells (e.g., when you open a new terminal
window).
2. .bash_profile
Runs for login shells (e.g., when logging in via terminal or SSH).
23. Identify the use of inline command editing features in the Bash shell.
Ans:
Inline command editing in the Bash shell allows users to edit previously typed commands
directly at the prompt using keyboard shortcuts. This feature improves efficiency and speed
in command-line operations.
1. Arrow Keys:
o Left/Right Arrows – Move the cursor within the current command to edit.
2. Keyboard Shortcuts:
KR
o Ctrl + W – Delete the previous word.
3. History Expansion:
Purpose:
Inline editing makes Bash interactive, user-friendly, and efficient for working with past and
current commands.
Ans:
In the Bash shell, history commands allow users to view, recall, and re-execute previously
typed commands, improving efficiency and reducing repetitive typing.
2. !n
Example:
!45
3. !!
4. !string
Executes the most recent command that starts with the given string.
KR
Example:
!grep
Purpose:
25. Recognize the use of wildcards for flexible pattern matching in command
execution.
Ans:
Wildcards are special characters used in Unix/Linux to match file and directory names based
on patterns, making command execution more flexible and efficient.
1. * (Asterisk)
Example:
ls *.txt
2. ? (Question Mark)
Example:
ls file?.txt
3. [ ] (Square Brackets)
Example:
ls file[1-3].txt
KR
4. [! ] or [^ ]
Example:
ls file[!0].txt
Purpose:
Wildcards simplify working with groups of files by allowing flexible name matching in
commands like ls, cp, mv, and rm.
26. Define the concepts of redirection (`>`, `>>`, `<`) and their applications.
Ans:
Redirection in Unix/Linux allows you to change the standard input (stdin), standard output
(stdout), and standard error (stderr) streams. This is useful for saving output to files, reading
from files, or chaining commands.
>> Append Output echo "done" >> Appends output to a file (does not
log.txt overwrite).
Applications:
KR
2. Appending Logs
Ans:
A pipe (|) is used to pass the output of one command as input to another, enabling multiple
commands to work together efficiently.
Syntax:
command1 | command2
1. Filter Output:
ls -l | grep "^d"
cat notes.txt | wc -l
Benefits of Pipes:
KR
28. Describe the functionality of the `tee` command.
Ans:
It reads from standard input and writes to both a file and the terminal (output).
Syntax:
command | tee filename
Writes output to the terminal (screen) and saves it to the specified file.
Examples:
ls -l | tee output.txt
Saves all process details and filters for "firefox" at the same time.
Use Cases:
Ans:
Command substitution allows the output of a command to replace the command itself in a
shell command. It is used to embed command results directly within other commands.
Syntax:
KR
1. Using backticks:
`command`
2. Using $():
$(command)
Examples:
3. Nested substitution:
echo "Number of files: $(ls | wc -l)"
Use Cases:
Ans:
ps aux
KR
2. top / htop – Real-time process monitoring.
Shows CPU/memory usage and allows killing processes interactively.
jobs
command &
kill 1234
Ans:
Executing a command in the background allows the shell to continue accepting new
commands while the current one runs without blocking the terminal.
Example:
sleep 60 &
This runs the sleep command in the background and immediately returns control to the
terminal.
KR
Lists all background jobs started in the current shell session.
kill %1
Running commands in the background using & improves multitasking in Linux. It’s useful for
executing time-consuming processes without blocking your terminal.
Ans:
1. Ctrl + C
Sends the SIGINT (Interrupt) signal.
Immediately terminates a foreground process.
2. Ctrl + Z
Sends the SIGTSTP (Stop) signal.
Suspends (pauses) a foreground process and puts it into the background as a
stopped job.
3. kill PID
Sends a signal (default: SIGTERM) to a process using its Process ID (PID).
Example:
kill 1234
4. kill -9 PID
Sends SIGKILL to forcefully terminate a process (cannot be ignored).
Example:
kill -9 1234
KR
5. killall process_name
Kills all processes with the given name.
Example:
killall firefox
33. Recall how to configure the Bash shell to customize the command prompt.
Ans:
The command prompt in the Bash shell is controlled by the PS1 variable, which defines what
is displayed before each command input.
1. Temporary Customization
You can temporarily change the prompt using the PS1 variable:
\u → Username
\h → Hostname
\d → Date
Example:
PS1="(\u@\h:\w)\$ "
2. Permanent Customization
To make the prompt change permanent, add the line to your shell initialization file (like
~/.bashrc):
nano ~/.bashrc
Add:
KR
Then apply changes:
source ~/.bashrc
Custom prompts can display useful information like Git branches, working directory, or even
emojis to enhance productivity and clarity in terminal sessions.
34. Recognize the output of a complex command involving pipes and redirection
Ans:
Pipes (|) and redirection operators (>, >>, <) allow combining commands and controlling
input/output streams.
Command:
Explanation:
ps aux
Lists all running processes.
| grep python
Filters for processes related to Python.
| awk '{print $2, $11}'
Extracts and prints the Process ID ($2) and the command name ($11).
python_processes.txt
Saves the filtered and formatted output into the file python_processes.txt.
1234 python3
1240 /usr/bin/python3
Ans:
Wildcards (also called globbing patterns) help match filenames using partial names or
patterns.
KR
* Matches zero or more ls *.txt Lists all .txt files in the
characters directory
Examples:
rm *.bak
3. List files starting with "data" and ending with any 2 characters:
ls data??.*
36. Identify a sequence of commands using pipes and redirection to process data.
Ans:
Example Task:
Extract the usernames from /etc/passwd, sort them, and save the top 5 unique names to a
file.
Command Sequence:
Explanation:
cut -d: -f1 /etc/passwd extracts the first field (the username) from each line in
the /etc/passwd file, using the colon : as the delimiter.
The output is piped into sort, which sorts the usernames alphabetically.
uniq then removes any duplicate usernames from the sorted list.
head -n 5 selects only the first 5 entries from the resulting list.
Finally, the output is redirected using > into a file named usernames.txt.
KR
Output:
Creates a file usernames.txt containing the first 5 unique sorted usernames from
/etc/passwd.
37. Describe the function of the `tr` command and give an example
Ans:
Example:
Output:
HELLO WORLD
The tr command is simple but powerful for basic text transformations directly in the shell.
38. List how to use `head` and `tail` commands to view file sections.
Ans:
Example:
head -n 10 logfile.txt
KR
Shows the first 10 lines of logfile.txt.
Note: By default, head filename shows the first 10 lines if no -n option is given.
Example:
tail -n 15 logfile.txt
Note: By default, tail filename shows the last 10 lines if no -n option is given.
39. Define the purpose of the `cut` command and how to extract fields.
Ans:
The cut command is used to extract specific sections or fields from each line of a text file or
input based on delimiters or character positions. It helps to isolate columns or parts of data
for further processing.
-f field_numbers : Specifies which field(s) to extract (e.g., 1 for first field, 1,3 for
first and third fields, 1-4 for range).
Use the -d option to specify the delimiter (separator) that divides fields (e.g., : or ,).
Example:
To extract the first field (username) from /etc/passwd where fields are separated by ::
KR
40. Recall how to use the `paste` command to combine file contents.
Ans:
The paste command is used to combine corresponding lines from two or more files side by
side, separating them with tabs (by default). It merges files horizontally.
Syntax:
This combines the first line of file1 with the first line of file2, second line with second line,
and so on.
Example:
If file1 contains:
apple
banana
cherry
red
yellow
dark red
Running
paste file1 file2
outputs:
apple red
banana yellow
cherry dark red
Ans:
KR
The sort command in Linux is used to arrange lines in text files in a specified order (default is
ascending alphabetical).
Syntax
sort [options] [filename]
Common Options:
Example:
sort -n marks.txt
42. Recall how the `uniq` command helps identify and remove duplicate lines.
Ans:
The uniq command in Linux is used to filter out or detect duplicate lines in a file. It compares
adjacent lines and removes or displays duplicates based on options.
It is commonly used with sort because uniq only removes consecutive duplicates.
Basic Syntax:
KR
Purpose:
Useful in combination with sort, because uniq only removes adjacent duplicates.
Common Options:
-i - ignores case
Examples:
Ans:
Regular expressions (regex) are patterns used to match character combinations in strings. In
Unix/Linux, they are commonly used with tools like grep, sed, and awk to search, filter, and
manipulate text.
Examples:
KR
\? : Matches zero or one occurrence.
Examples:
() : Grouping.
Example:
Ans:
The grep command searches for patterns in files using basic regular expressions by default.
Syntax:
KR
5. [] – Matches any one character inside the brackets.
grep '[aeiou]' file.txt matches any vowel
Example:
Matches lines that start with H and end with d, with any characters in between.
Ans:
grep -E enables Extended Regular Expressions (ERE), allowing more powerful and flexible
pattern matching without needing to escape special characters.
Syntax:
or equivalently,
egrep 'pattern' filename
() : Grouping patterns.
Example: '(cat|dog)s?' matches "cat", "cats", "dog", or "dogs"
Example:
46. Define the concept of stream editing and syntax of the `sed` command.
Ans:
Stream editing means processing and transforming text data line-by-line from a stream (such
as a file or input) without opening it in an editor. It is useful for automated text manipulation
like search-and-replace, deletion, or insertion.
KR
sed Command
sed (Stream Editor) applies editing commands to text streams or files and outputs the
modified text.
Basic Syntax:
sed [options] 'command' filename
The output is sent to the terminal by default, but can be redirected or saved.
Example:
Ans:
The sed command can perform text substitution in files or input streams.
Syntax:
sed 's/pattern/replacement/flags' filename
Example:
sed 's/oldtext/newtext/g' file.txt
This replaces all occurrences of “oldtext” with “newtext” in each line of file.txt.
You can redirect output or use the -i option to modify the file in place.
KR
48. Describe the structure of `awk` and its syntax.
Ans:
awk is a powerful text-processing tool used to search, extract, and process patterns from files
or input.
Syntax:
pattern: A condition to match lines (can be omitted to apply action to all lines).
Structure:
Example:
This prints the 1st and 3rd fields (columns) of each line in data.txt.
49. Recall how to use `awk` to print fields from structured text.
Ans:
awk is commonly used to extract and print specific fields (columns) from structured text,
where fields are typically separated by spaces or a specified delimiter.
Basic Syntax:
awk '{ print $1, $3 }' filename
KR
$1, $2, $3, ... represent the first, second, third fields.
Prints the 2nd and 4th columns from each line of data.txt.
Ans:
Linux provides powerful text-processing commands to read, filter, format, and transform
data in files or streams.
Common Commands:
o Example: cut -d',' -f1 data.csv (gets the first field from a CSV file)
KR
o Example: sed 's/error/ERROR/g' log.txt (replaces "error" with "ERROR")
51. Identify the best commands to extract information from a given file.
Ans:
To extract specific data from a file, several powerful commands are commonly used in Linux:
o Example: cut -d',' -f2 students.csv (gets 2nd field from CSV)
Ans:
Regular expressions (regex) are patterns used to search, match, or manipulate text. They are
commonly used in tools like grep, sed, and awk.
KR
4. $ – Anchors the match at the end of the line
Example: end$ matches lines ending in "end"
8. \{n,m\} – Matches the preceding pattern between n and m times (basic regex with
grep requires \)
Example:
Ans:
sed (Stream Editor) is used to automate editing of text in files or streams. It processes input
line-by-line and applies editing commands.
1. Substitute text
Replace "old" with "new":
Delete line 3:
sed '3d' file.txt
KR
4. Insert a line before a match
54. Recall how to create `awk` scripts for summarizing structured data.
Ans:
awk is a powerful text-processing tool for scanning and analyzing structured data (like CSV
or whitespace-separated files).
Basic Syntax:
awk 'BEGIN {init_block} {main_block} END {end_block}' file.txt
2. Calculate Average:
KR
awk '{scores[$1] += $2} END {for (name in scores) print name,
scores[name]}' data.txt
Use Case:
Alice 90
Bob 75
Alice 85
Ans:
#!/bin/bash
chmod +x myscript.sh
./myscript.sh
Ans:
KR
Handling Command-Line Arguments in Shell Scripts
o $0 : Script name
Example:
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Total arguments: $#"
Ans:
In shell scripting, exit status helps in decision making (e.g., using if statements to
check if a command succeeded).
Example:
mkdir testdir
if [ $? -eq 0 ]; then
echo "Directory created successfully."
else
KR
echo "Failed to create directory."
fi
58. Identify the use of `if`, `elif`, `else` statements in shell logic.
Ans:
Purpose:
elif: (else if) Tests another condition if the previous if or elif was false.
Basic Syntax:
if [ condition1 ]; then
# commands if condition1 is true
Example:
num=10
if [ $num -gt 20 ]; then
echo "Number is greater than 20"
elif [ $num -eq 10 ]; then
echo "Number is exactly 10"
else
KR
echo "Number is less than 10 and not 10"
fi
Output:
Number is exactly 10
Ans:
The case statement is used to match a variable against a set of patterns, acting like a multi-
way if-else ladder. It's cleaner and more readable when you have many conditions to check.
Syntax:
case variable in
pattern1)
commands ;;
pattern2)
commands ;;
*)
default commands ;;
esac
Example:
case $num in
1)
echo "You chose One" ;;
KR
2)
echo "You chose Two" ;;
3)
Purpose:
Simplifies code when checking one variable against multiple possible values.
Ans:
The while loop is used to repeat a set of commands as long as a condition is true.
Syntax:
bash
CopyEdit
while [ condition ]
do
commands
done
Example:
count=1
while [ $count -le 5 ]
KR
do
echo "Count is $count"
count=$((count + 1))
done
Output:
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Purpose:
Use while when you don’t know exactly how many times to repeat.
Ans:
The for loop is used to iterate over a list of items, such as numbers, filenames, or command
outputs.
Syntax:
commands
done
do
echo "Fruit: $item"
done
Output:
KR
Fruit: apple
Fruit: banana
Fruit: cherry
for i in {1..5}
do
echo "Number $i"
done
Output:
Number 1
Number 2
Number 3
Number 4
Number 5
Use for when you know the list of values or a range you want to iterate through.
Ans:
he expr command can be used for basic string operations like length, extraction, and
comparison.
Output: 5
2. Extract Substring
Output: World
(starts at position 6, takes 5 characters)
KR
3. Index of a Character
Output: 5
(finds first occurrence of 'o')
4. String Comparison
Output: 1 (true)
Output: 1 (true)
Always put strings in quotes to avoid issues with spaces or special characters.
Ans:
The expr command supports basic arithmetic operations on integers. It evaluates expressions
and returns results.
Syntax
1. Addition
expr 5 + 3
Output: 8
2. Subtraction
expr 10 - 4
KR
Output: 6
3. Multiplication
expr 6 \* 7
Output: 42
(Escape the * using backslash \ to prevent shell expansion)
4. Division
expr 20 / 5
Output: 4
5. Modulus (Remainder)
expr 10 % 3
Output: 1
a=15
b=3
result=$(expr $a / $b)
Output: Result: 5
Ans:
File test operators are used in conditional expressions (like if statements) to check the
properties of files and directories.
KR
-d : Returns true if the file exists and is a directory.
Example: [ -d /home/user ]
if [ -f "myfile.txt" ]; then
echo "File exists and is a regular file."
else
echo "File does not exist."
fi
Ans:
The set command in shell scripting is used to change the value of shell options and
positional parameters. It allows fine control over the behaviour of the script.
Common Uses:
Example:
set -- apple banana cherry
echo $1 # Outputs: apple
KR
set -u: Treats unset variables as an error.
Example:
set -e
Ans:
The shift command in shell scripting is used to move positional parameters to the left. It
discards the current $1 and shifts all other arguments one position left. This is especially useful
when processing multiple command-line arguments in a loop.
Syntax:
shift [n]
Purpose:
Example:
#!/bin/bash
# Script to print all arguments one by one
while [ $# -gt 0 ]; do
echo "Argument: $1"
KR
shift
done
How It Works:
Argument: apple
Argument: banana
Argument: cherry
After each shift, $2 becomes $1, $3 becomes $2, and so on, until no arguments remain ($#
becomes 0).
Ans:
The trap command in Linux shell scripting is used to catch and handle signals or events,
allowing you to execute specific commands when certain signals are received (like
interrupting the script with Ctrl+C).
Purpose:
To perform cleanup actions (like deleting temporary files) before the script exits.
Syntax:
'commands' is the command or set of commands to run when the signal occurs.
Common signals:
Example:
#!/bin/bash
KR
trap 'echo "Caught Ctrl+C! Exiting now..."; exit' SIGINT
echo "Press Ctrl+C to test trap."
while true; do
sleep 1
done
Explanation:
When you press Ctrl+C, the script catches the SIGINT signal.
It runs the command inside the trap: prints a message and exits gracefully.
Ans:
Here-documents (<<) are used in shell scripting to provide multiline input directly to a
command from within a script or command line.
Purpose:
To feed a block of text or commands as input to a command without using an external file.
Syntax:
How it works:
command reads input until it encounters the line with only the delimiter.
All lines between the << delimiter and the ending delimiter are passed as input to
the command.
Example:
cat << EOF
This is line 1
This is line 2
EOF
This sends the two lines as input to the cat command, which outputs them.
KR
69. Identify basic debugging techniques using `set-x`.
Ans:
Basic debugging in shell scripts can be done using the set -x command.
Purpose:
set -x enables a mode where each command and its arguments are printed to the terminal
as they are executed. This helps track what the script is doing step-by-step.
How to use:
Example:
#!/bin/bash
set -x # Start debugging
echo "Hello"
ls /nonexistent
set +x # Stop debugging
echo "Done"
When running this script, the shell will print each command before executing it, making it
easier to identify where errors or unexpected behaviour happen.
70. Recall the use of the `export` command for environment variables.
Ans:
The export command in Unix/Linux is used to set environment variables so that they are
available to the current shell session and any child processes started from it.
Purpose:
Make a shell variable available to programs and scripts executed from the shell.
Syntax:
export VARIABLE_NAME=value
Example:
export PATH=$PATH:/usr/local/bin
KR
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk
Explanation:
export PATH=... appends a new directory to the existing PATH environment variable
and exports it.
After exporting, any program or script launched from this shell can access
JAVA_HOME.
Ans:
Creating Arrays:
Use parentheses () to define an array with elements separated by spaces.
Adding Elements:
Add elements by assigning a value to a new index.
my_array[3]=date
do
echo "$fruit"
done
Ans:
Defining Shell Functions:
KR
You define a function by giving it a name followed by parentheses and enclosing the
commands within braces {}.
Syntax:
function_name() {
commands
Example:
greet() {
echo "Hello, $1!"
}
greet Alice
Output:
Hello, Alice!
$1, $2, etc. inside the function represent arguments passed to the function.
73. Define system calls and their role between user space and kernel.
Ans:
System calls are special functions provided by the operating system that allow programs
running in user space to request services from the kernel (the core part of the OS). They act
as a controlled interface between user applications and the kernel, enabling safe access to
hardware and system resources.
Role:
User programs cannot directly access hardware or critical system resources for
security and stability reasons.
When a program needs to perform tasks like reading a file, creating a process, or
communicating over a network, it uses system calls.
The system call switches the CPU from user mode to kernel mode, allowing the kernel
to perform the requested operation.
KR
After completing the task, control returns to the user program.
Ans:
The open() system call is used to open a file and obtain a file descriptor, which is a reference
used for subsequent file operations like reading or writing.
Syntax:
Arguments:
o plus flags like O_CREAT (create file if it doesn’t exist), O_TRUNC (truncate file),
etc.
mode: (Optional) Sets the file permissions if a new file is created (used with O_CREAT).
Return Value:
Ans:
read() is used to read data from a file descriptor into a buffer in user space. It
transfers data from the kernel to the user program.
write() is used to write data from a user-space buffer to a file descriptor. It transfers
data from the user program to the kernel (e.g., to a file or device).
KR
Syntax:
Parameters:
buf: Pointer to a buffer where data is read into (for read) or written from (for write).
Return Value:
Returns -1 on error.
Ans:
The fork() system call is used to create a new child process by duplicating the
calling (parent) process.
When fork() is called, the operating system creates an exact copy of the parent
process’s address space, including code, data, and stack.
Syntax:
pid_t fork(void);
Process:
4. They can use the return value to determine their role (parent or child).
KR
77. Describe how `exec()` replaces the current process image
Ans:
The exec() family of system calls replaces the current process image with a new
program.
When a process calls exec(), its existing code, data, and stack are discarded, and the
new program is loaded into the process’s memory.
The process ID (PID) remains the same, but the process begins executing the new
program from its entry point.
If exec() is successful, it does not return to the old program; if it fails, it returns -1 and
sets an error.
Syntax Example:
How it works:
4. The process continues execution starting at the new program’s entry point.
78. Recall the concept of daemon processes and steps to create one.
Ans:
KR
Daemons are detached from controlling terminals and run silently in the background.
Characteristics of Daemons
No controlling terminal.
Ans:
Shared Memory: Processes share a memory area for fast data exchange.
KR
80. Identify how to use pipes for related process communication.
Ans:
Pipes connect the output of one process to the input of another, enabling related processes
to communicate by passing data streams.
Usage:
Symbol: |
Purpose:
Ans:
FIFOs, or named pipes, are special files used for inter-process communication (IPC) in
Unix/Linux. Unlike regular pipes, FIFOs have a name in the filesystem, allowing unrelated
processes to communicate by reading and writing through this named file.
Usage:
One process writes data to the FIFO, while another reads from it.
Example:
Process 1: echo "Hello" > myfifo
Process 2: cat < myfifo
This allows Process 2 to receive the message sent by Process 1 through the FIFO.
FIFOs provide a simple way to exchange data between independent processes using the
filesystem as a communication medium.
Ans:
KR
To develop a client-server model using IPC:
2. The server initializes by creating/opening the IPC channel and waits for client
requests.
4. Data is exchanged: the client sends a request, the server processes it and replies.
5. Both client and server close the IPC channel after communication is complete.
Ans:
Shared memory is an IPC technique where multiple processes access a common memory
area to exchange data directly.
Advantages:
Fastest IPC method because data is shared without copying between processes.
Ans:
A race condition occurs when two or more processes or threads access shared resources (like
memory or files) concurrently, and the final outcome depends on the timing of their
execution.
If these accesses are not properly synchronized, it can lead to unpredictable behavior, such
as corrupted data or unexpected results.
Example:
If two processes try to update the same variable at the same time without coordination, one
update might overwrite the other, causing a logic error.
KR
Solution:
Race conditions can be avoided by using synchronization techniques like mutexes,
semaphores, or locks to control access to shared resources.
Ans:
Mutex (short for Mutual Exclusion) is a synchronization primitive used to prevent race
conditions in concurrent processes or threads.
It ensures that only one process/thread can access a critical section (shared resource) at a
time.
1. Locking: Before accessing the shared resource, a thread must acquire (lock) the
mutex.
2. Access: Once locked, no other thread can enter the critical section until the mutex is
unlocked.
3. Unlocking: After the thread finishes its task, it releases (unlocks) the mutex so others
can proceed.
Example (Pseudocode):
mutex lock
thread1:
lock(mutex)
// critical section
unlock(mutex)
thread2:
lock(mutex)
// critical section
unlock(mutex)
Using mutexes helps ensure data integrity and prevents simultaneous access to shared
resources, thereby avoiding race conditions.
KR
Ans:
Inter-Process Communication (IPC) methods allow processes to exchange data. Different IPC
mechanisms have different characteristics:
1. Pipes
Unidirectional.
3. Message Queues
4. Shared Memory
Fastest method.
5. Sockets
Ans:
Common Scenarios:
2. File Access:
When multiple processes write to the same file, data can get mixed up.
KR
3. Producer-Consumer Problem:
One process adds data (producer) and another removes it (consumer). They must be
synchronized to avoid overflow or underflow.
4. Banking System:
If two threads change the balance of the same account, it may lead to incorrect
results.
5. Thread Coordination:
If one thread depends on another (e.g., waiting for input), synchronization ensures
they run in the correct order.
Synchronization helps avoid conflicts and keeps data correct when tasks run at the same
time.
Ans:
Pipes and FIFOs are inter-process communication (IPC) mechanisms used to transfer data
between processes.
Pipes:
Syntax: pipe(fd);
Example:
int fd[2];
pipe(fd);
fork();
// One process writes using write(fd[1], ...), other reads using
read(fd[0], ...)
FIFOs allow communication between unrelated processes using a named file in the
filesystem.
Example:
mkfifo mypipe
KR
echo "Hello" > mypipe # Writing to FIFO
cat < mypipe # Reading from FIFO
Pipes are suitable for related processes, while FIFOs enable communication between any
processes. Both are simple, efficient IPC methods for stream-based data transfer.
Ans:
Example Scenario:
Steps:
Ans:
A mutex (mutual exclusion) is used to prevent multiple processes or threads from accessing a
shared resource at the same time, avoiding race conditions.
How it works:
Steps:
KR
1. Initialize the mutex.
Purpose:
Ensures that only one process/thread accesses the resource at a time, maintaining data
consistency and preventing conflicts.
KR