5th Chapter
5th Chapter
A1:- The interpretive cycle of a Unix shell generally involves the following steps:
1. Read: The shell reads a command line entered by the user or from a script.
2. Parse: The shell breaks down the command line into individual words and tokens, identifying the command
name, arguments, and any special characters like redirection operators or pipes.
3. Expand: The shell performs expansions, such as variable substitution (e.g., replacing $HOME with the user's
home directory), command substitution (e.g., replacing $(date) with the output of the date command),
pathname expansion (globbing using wildcards like * and ? ), and brace expansion.
4. Execute: The shell executes the command. This might involve creating a new process (forking) and then
replacing the process's image with the requested program (executing). For built-in commands, the shell
executes them directly without creating a new process.
5. Wait: If the command was executed in the foreground, the shell waits for the command to complete before
prompting for the next command. For background commands (using & ), the shell does not wait.
6. Repeat: The shell then returns to the read step to process the next command.
Q2: What are some common types of shells available in Unix-like systems?
• Bash (Bourne-Again Shell): The most common default shell on many Linux distributions, an enhanced version
of the Bourne Shell.
• C Shell (csh): Known for its C-like syntax and job control features.
• Tcsh: An enhanced version of the C Shell, providing features like command-line completion and history editing.
• Korn Shell (ksh): A powerful shell with features from both the Bourne and C shells.
• Zsh: A modern shell that incorporates features from Bash, Tcsh, and Ksh, offering extensive customization.
Q3: Explain the concept of pattern matching (globbing) in the shell and provide examples.
A3: Pattern matching, or globbing, allows you to use special characters (wildcards) to select files or directories based
on their names. Common metacharacters include:
• []: Matches any single character within the specified range or set.
o Example: ls file[aeiou].c lists files starting with "file" followed by a vowel and ending with ".c".
• [!...] or [^...]: Matches any single character not within the specified range or set.
o Example: ls file[!0-9].txt lists files starting with "file" followed by a non-digit character and ending with
".txt".
Q4: What is the purpose of escaping and quoting in the shell? Provide examples.
A4: Escaping and quoting are used to prevent the shell from interpreting special characters in their usual way.
• Escaping: Using a backslash (\) before a special character removes its special meaning.
o Example: ls file\ with\ spaces.txt treats the spaces literally instead of separating words.
o Example: echo \$HOME prints the literal $HOME instead of the value of the HOME variable.
• Quoting: Enclosing text within single quotes (') or double quotes (") also prevents the shell from performing
certain expansions or interpretations.
o Single quotes ('): Preserve the literal meaning of all characters within them. No variable substitution
or command substitution occurs.
o Double quotes ("): Allow variable substitution and command substitution, but treat most other special
characters literally.
▪ Example: echo "The date is $(date)" prints "The date is Wed Apr 23 10:39:00 IST 2025".
Q5: Explain the concepts of redirection, standard input (stdin), standard output (stdout), and standard error (stderr).
Provide examples of redirection.
A5:
• Standard Input (stdin): The default source of input for a command, usually the keyboard (file descriptor 0).
• Standard Output (stdout): The default destination for the normal output of a command, usually the terminal
screen (file descriptor 1).
• Standard Error (stderr): The default destination for error messages and diagnostic output from a command,
usually the terminal screen (file descriptor 2).
Redirection allows you to change the default sources and destinations of these streams:
• >>: Redirects stdout to a file, appending the output to the end of the file.
o Example: mail -s "Subject" < message.txt sends an email with the content of message.txt.
o Example: find / -name "important_file" 2> errors.log saves any error messages from the find
command to errors.log.
• &> or >&: Redirects both stdout and stderr to a file (in some shells).
o Example: command &> output.log saves both normal output and errors to output.log.
Q6: What are /dev/null and /dev/tty used for?
A6:
• /dev/null: A special file that discards any data written to it and provides no output when read from. It's often
used to suppress unwanted output from commands.
o Example: ls non_existent_file 2> /dev/null suppresses the "No such file or directory" error message.
• /dev/tty: Represents the controlling terminal of the current process. It allows a process to interact directly
with the user's terminal, even if its standard input or output has been redirected.
o Example: A script might use echo "Enter your name: " > /dev/tty to display a prompt on the terminal,
and then read the input using < /dev/tty, regardless of any input redirection.
Q7: Explain the concepts of pipes (|) and the tee command.
A7:
• Pipe (|): A mechanism for passing the standard output of one command directly as the standard input of
another command. It allows you to chain commands together to perform complex operations.
o Example: cat logfile.txt | grep "error" | less displays lines containing "error" from logfile.txt one
screen at a time.
• tee command: Reads from standard input and writes to both standard output and one or more files. It allows
you to see the output of a command while also saving it to a file.
o Example: cat logfile.txt | grep "warning" | tee warnings.log | less displays lines containing "warning"
on the screen and also saves them to warnings.log.
A8: Command substitution allows you to embed the output of a command within another command line. There are
two common ways to perform command substitution:
• Backticks (`command`): The command enclosed in backticks is executed, and its standard output replaces the
backtick expression.
• Dollar sign and parentheses ($(command)): This is the preferred and more readable method. The command
inside the parentheses is executed, and its standard output is substituted.
Q9: What are shell variables? Differentiate between local and environment variables.
A9: Shell variables are named storage locations that hold values within the shell environment.
A10: In UNIX, a process is essentially a program in execution, representing an active instance of code being run by the
operating system. Each process is assigned a unique identifier (PID), and the system uses these processes to manage
multitasking and concurrent execution.
• Program Execution: A process embodies the execution of a program, including its code, data, and resources.
• Resource Allocation: The operating system allocates resources (like memory and CPU time) to each process.
• Unique Identification: Each process has a unique PID, allowing the system to track and manage it.
• Multi-tasking and Concurrency: UNIX supports multiple processes running concurrently, enabling efficient use
of system resources.
• Process States: Processes can exist in different states, such as running, waiting, or stopped, depending on their
activity.
• Process Management: The operating system uses tools like ps (process status) and kill to manage processes.
Q11: How can you display the attributes of running processes in UNIX? What is the purpose of the ps command?
A11: The ps (process status) command is used to display information about the currently running processes. Common
options provide different views and details:
• ps: Typically shows processes associated with the current user and terminal.
• ps aux: Shows a comprehensive list of all processes running on the system, including those owned by other
users and without a controlling terminal. The columns usually include USER, PID, %CPU, %MEM, VSZ, RSS, TTY,
STAT, START, TIME, and COMMAND.
• ps -ef: Another common way to see all processes, often providing information about the parent process ID
(PPID).
A12: The typical process creation cycle involves the following steps:
A unix process is created in the idle state, and is then moved between ready to run, running, and
possibly waiting (or sleeping), until it exits and becomes a zombie. Once a process, usually the parent process, reaps
the exit status of the zombie, then the process is destroyed.
Q13: Outline the shell creation steps starting from init.
A13: The typical shell creation process after system boot involves these steps:
1. init: The init process (PID 1) is the first process started by the kernel. It's the ancestor of all other processes.
2. getty (or a similar service): init starts one or more getty processes (or a modern equivalent like systemd-getty).
These processes listen for login attempts on virtual consoles or serial lines.
3. login: When a user connects, getty prompts for a username. The user's input is passed to the login program,
which authenticates the user by asking for a password and verifying it against the system's user database.
4. shell: Upon successful login, the login program executes the user's default shell (as specified in /etc/passwd).
This is the interactive shell that the user interacts with.
Q14: What are the different process states in UNIX? Briefly describe the zombie state.
• Sleeping (S): The process is waiting for an event to complete (e.g., I/O operation, signal).
• Disk Sleep (D): The process is in an uninterruptible sleep, usually waiting for disk I/O.
• Stopped (T): The process has been stopped, usually by a signal (e.g., SIGTSTP from Ctrl+Z).
• Zombie (Z): A process that has terminated, but its entry in the process table still exists because its parent
process has not yet collected its exit status using a wait() system call. Zombie processes consume minimal
resources but their presence indicates that the parent process is not properly cleaning up its children.
Q15: How can you run a job in the background in the shell? What is the purpose of the nohup command?
A15:
• Background jobs (& operator): To run a command in the background, append an ampersand (&) to the end of
the command line. The shell will start the command and immediately return to the prompt, allowing you to
continue working. The background job's PID will be displayed.
• nohup command: The nohup (no hang up) command allows a command to continue running even after the
user logs out. It redirects the command's standard output and standard error to a file named nohup.out (if not
otherwise specified) in the current directory.
o Example: nohup long_running_command & (This will run long_running_command in the background
and keep it running after logout).
Q16: Explain how to reduce the priority of a process using the nice command.
A16: The nice command allows you to set the niceness value of a process, which influences its scheduling priority.
Niceness values range from -20 (highest priority, requires root privileges) to 19 (lowest priority). A higher niceness
value means the process will be less likely to get CPU time compared to other processes.
o nice -n 10 command (starts command with a niceness of 10). If -n is omitted, nice defaults to an
increment of 10.
• To adjust the niceness of an already running process, you can use the renice command (requires the PID of the
process and may require root privileges to increase priority).
o renice 12 -p 1234 (sets the niceness of process with PID 1234 to 12).
Q17: How can you use signals to kill a process in UNIX? What are some common signals?
A17: Signals are asynchronous notifications sent to a process to inform it of an event. The kill command is used to send
signals to processes. You typically need the PID of the process you want to signal.
• SIGINT (2): Interrupt signal, usually generated by pressing Ctrl+C. Often terminates the process.
• SIGQUIT (3): Quit signal, usually generated by pressing Ctrl+\. Can cause a core dump.
• SIGTERM (15): Termination signal, the default signal sent by kill. Requests the process to terminate gracefully.
• SIGKILL (9): Kill signal. Forces immediate termination of the process without allowing it to perform any cleanup.
Should be used as a last resort.
• SIGHUP (1): Hangup signal. Often sent when the controlling terminal is closed. Can cause daemons to reload
their configuration.
• SIGTSTP (20): Terminal stop signal, usually generated by pressing Ctrl+Z. Suspends the process.
Examples:
Q18: How can you send a suspended job to the background and bring a background job to the foreground?
A18:
• Sending a suspended job to the background (bg command): If you suspend a running job using Ctrl+Z (which
sends SIGTSTP), you can resume it in the background using the bg command. You can optionally specify the
job ID (obtained using the jobs command).