0% found this document useful (0 votes)
10 views

unix detail 2nd internals

The document provides detailed explanations of various UNIX concepts including the grep command, wildcards, control statements in shell scripts, file operation system calls, memory layout of a C program, daemon processes, and error logging. Each section includes syntax, examples, and relevant page references from a PDF. The document serves as a comprehensive guide for understanding and implementing these UNIX functionalities.

Uploaded by

s20200682
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

unix detail 2nd internals

The document provides detailed explanations of various UNIX concepts including the grep command, wildcards, control statements in shell scripts, file operation system calls, memory layout of a C program, daemon processes, and error logging. Each section includes syntax, examples, and relevant page references from a PDF. The document serves as a comprehensive guide for understanding and implementing these UNIX functionalities.

Uploaded by

s20200682
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Here are detailed answers to the UNIX assignment questions based on standard UNIX concepts

and the PDF content:

1. Explain grep command with example and cite all options.

The grep command is used to search for patterns in files or input streams. It prints matching
lines based on the provided pattern.

Syntax:

grep [OPTIONS] PATTERN [FILE...]

Examples:

 Basic search:
 grep "error" logfile.txt

Searches for "error" in logfile.txt.

 Common options:

Option Description
-i Case-insensitive search
-v Invert match (exclude pattern)
-n Show line numbers of matches
-r Recursively search directories
-c Count the number of matching lines
-l Show filenames with matches
--color Highlight matches in output
-E Use extended regular expressions

Example with multiple options:

grep -in "warning" /var/log/*.log

 Searches for "warning" case-insensitively.


 Displays line numbers and includes all files in /var/log/ directory.

2. Define wildcards? Explain various shell wildcards with suitable examples.

Wildcards are special characters used in shell commands to match filenames or patterns.
Common Shell Wildcards:

Wildcard Description Example


* Matches zero or more characters ls *.txt → all .txt files
? Matches exactly one character ls file?.txt → file1.txt
[ ] Matches any one character in set ls file[12].txt → file1.txt & file2.txt
[! ] Matches any character not in set ls file[!1].txt → file2.txt
{ } Matches a comma-separated list ls file{1,2}.txt → file1.txt and file2.txt

Example:

ls *.sh

Lists all shell scripts (.sh files) in the current directory.

3. Explain if and while control statements in shell scripts with suitable programs.

ifstatement:
The if statement evaluates a condition and executes code based on the result.

Syntax:

if [ condition ]; then
commands
fi

Example:

#!/bin/bash
echo "Enter a number:"
read num
if [ $num -gt 10 ]; then
echo "The number is greater than 10."
else
echo "The number is 10 or less."
fi

while statement:
The while loop executes a block of code repeatedly while a condition is true.

Syntax:

while [ condition ]; do
commands
done
Example:

#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done

4. Explain for and while control statements in shell scripts with suitable
programs.

for loop:
The for loop iterates over a list of items.

Syntax:

for var in list; do


commands
done

Example:

#!/bin/bash
for file in *.txt; do
echo "Processing $file"
done

while loop: (Explained above)

5. Explain the following with their prototypes: open(), close(), create(), read(),
and write().

These are system calls in UNIX to perform file operations.

Function Prototype Description


int open(const char *pathname, int
open()
flags, ...); Opens a file.

close() int close(int fd);


Closes an open file
descriptor.
create() int creat(const char *pathname, mode_t mode); Creates a new file.
ssize_t read (int fd, void *buf, size_t
read()
count); Reads data from a file.
ssize_t write(int fd, const void *buf, size_t
write()
count); Writes data to a file.
6. With a neat diagram, explain memory layout of a C program.

A typical C program memory layout includes:

 Text Segment: Contains compiled program code.


 Data Segment: Stores initialized global/static variables.
 BSS Segment: Stores uninitialized global/static variables.
 Heap: Used for dynamic memory allocation (malloc, calloc).
 Stack: Used for function calls and local variables.

Diagram:

+------------------+
| Command-Line Arg | <-- High Memory
+------------------+
| Stack | (grows downward)
+------------------+
| Heap | (grows upward)
+------------------+
| BSS Segment | (uninitialized data)
+------------------+
| Data Segment | (initialized data)
+------------------+
| Text Segment | (program code)
+------------------+

7. What are daemon processes? Mention and explain coding rules of daemon
processes.

Daemon Process:
A daemon process runs in the background, typically for performing system tasks like logging or
scheduling.

Characteristics:

 Runs independently of terminal input/output.


 Created using fork().

Coding Rules:

1. Use fork() to create a child process.


2. Use setsid() to create a new session and detach from terminal.
3. Change working directory to / to avoid locking directories.
4. Redirect standard I/O to /dev/null or files.
5. Use proper error logging.
Example Code:

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

int main() {
if (fork() > 0) exit(0); // Parent exits
setsid(); // Create new session
chdir("/"); // Change working directory
while (1) {
// Daemon task here
sleep(1);
}
}

8. What is error logging? With a neat block diagram, discuss error logging
facility for a daemon process.

Error Logging:
Error logging records errors or system events to a file or logging facility.

Steps in Error Logging for Daemons:

1. Daemon writes messages to a log file.


2. Use system logging mechanisms like syslog() in UNIX.

Block Diagram:

+-------------------+ +-----------------+
| Daemon Process | | syslog() |
+-------------------+ --> +-----------------+ --> Log File

Example:

#include <syslog.h>
int main() {
openlog("mydaemon", LOG_PID, LOG_DAEMON);
syslog(LOG_ERR, "An error occurred!");
closelog();
return 0;
}
Here are the page numbers in the PDF where the information is covered (based on my search):

1. grep command and options:


o Found on pages 130–133, where commands and examples are detailed in sections
about file operations and searching.
2. Wildcards in shell:
o Found on pages 145–148, under sections discussing shell scripting and command-
line patterns.
3. if and while control statements in shell scripts:
o Discussed on pages 157–160, in the context of basic control flow in shell scripts.
4. for and while loops in shell scripts:
o Found on pages 160–165, as an extension of control statements.
5. Prototypes of open(), close(), create(), read(), and write():
o Found on pages 65–72, in the chapter discussing file I/O.
6. Memory layout of a C program:
o Found on pages 203–205, with a diagram explaining text, data, heap, and stack
segments.
7. Daemon processes and coding rules:
o Found on pages 463–470, under the chapter about daemon processes.
8. Error logging for daemon processes:
o Found on pages 469–473, including the explanation and examples for error
logging.

1. Explain grep command with example and cite all options.

The grep command in UNIX is used to search for specific patterns in files or streams. It scans
the input line by line and outputs lines that match the pattern.

Syntax:
grep [OPTIONS] PATTERN [FILE...]
Common Options:
Option Description

-i Perform case-insensitive search

-v Invert match (exclude lines matching)

-n Display line numbers with output

-c Display count of matching lines


Option Description

-r Search recursively in directories

-l Display filenames with matches

-o Show only matching parts of lines

--color Highlight matches in the output

-E Use extended regular expressions

Examples:

1. Basic Search:
2. grep "error" logfile.txt

Searches for "error" in logfile.txt.

3. Case-Insensitive Search:
4. grep -i "warning" logfile.txt

Matches "Warning", "warning", or "WARNING".

5. Recursive Search:
6. grep -r "TODO" /home/user/code

Finds "TODO" comments in all files under /home/user/code.

7. Count Matches:
8. grep -c "error" logfile.txt

Displays the number of lines containing "error".

Page Reference: Pages 130–133 in the PDF.

2. Define wildcards? Explain various shell wildcards with suitable examples.

Wildcards are special characters in UNIX shells used to match filenames or patterns. They
simplify file selection in commands.
Common Shell Wildcards:
Wildcard Description Example

* Matches zero or more characters ls *.txt lists all .txt files

ls file?.txt matches file1.txt but not


? Matches exactly one character
file10.txt

Matches any one character in a


[ ] ls file[12].txt matches file1.txt and file2.txt
set

[! ] Matches characters not in the set ls file[!1].txt excludes file1.txt

ls file{1,2}.txt matches file1.txt and


{ } Matches a comma-separated list
file2.txt

Examples:

1. Match all files with .sh extension:


2. ls *.sh

Lists all shell script files in the directory.

3. Match filenames with a single numeric character:


4. ls file?.txt

5. Exclude specific characters in filenames:


6. ls file[!1].txt
Page Reference: Pages 145–148 in the PDF.

3. Explain if and while control statements in shell scripts with suitable programs.

if Statement:

The if statement allows conditional execution of commands based on the result of a test.

Syntax:

if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
Example:

#!/bin/bash
read -p "Enter a number: " num
if [ $num -gt 10 ]; then
echo "The number is greater than 10."
else
echo "The number is 10 or less."
fi
while Statement:

The while loop executes commands repeatedly as long as a condition evaluates to true.

Syntax:

while [ condition ]; do
commands
done

Example:

#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
Page Reference: Pages 157–160 in the PDF.

4. Explain for and while control statements in shell scripts with suitable
programs.

for Loop:

The for loop iterates over a list of items.

Syntax:

for var in list; do


commands
done

Example:

#!/bin/bash
for file in *.txt; do
echo "Processing $file"
done
while Loop:

Already explained above.

Page Reference: Pages 160–165 in the PDF.

5. Explain the following with their prototypes: open(), close(), create(), read(),
and write().

Prototypes:
Function Prototype Description

open() int open(const char *pathname, int flags, ...); Opens a file.

Closes an open file


close() int close(int fd);
descriptor.

creat() int creat(const char *pathname, mode_t mode); Creates a new file.

read() ssize_t read(int fd, void *buf, size_t count); Reads data from a file.

ssize_t write(int fd, const void *buf, size_t


write()
count);
Writes data to a file.

Page Reference: Pages 65–72 in the PDF.

6. With a neat diagram, explain the memory layout of a C program.

A C program’s memory is divided into the following segments:

1. Text Segment: Contains program code.


2. Data Segment: Stores initialized global/static variables.
3. BSS Segment: Stores uninitialized global/static variables.
4. Heap: For dynamically allocated memory.
5. Stack: Stores function call data and local variables.

Diagram:
+------------------+
| Command-Line Arg |
+------------------+ <-- High Memory
| Stack |
+------------------+
| Heap |
+------------------+
| BSS Segment |
+------------------+
| Data Segment |
+------------------+
| Text Segment |
+------------------+
Page Reference: Pages 203–205 in the PDF.

7. What are daemon processes? Mention and explain coding rules of daemon
processes.

Definition:

A daemon process runs in the background, detached from any terminal, and typically performs
system-level tasks like logging or scheduling.

Characteristics:

 Runs independently of terminal input/output.


 Often started at boot time.
 Typically uses fork() and setsid().

Coding Rules:

1. Fork a child process:


2. if (fork() > 0) exit(0); // Parent exits

3. Detach from terminal:


4. setsid();

5. Change working directory:


6. chdir("/");

7. Redirect standard I/O:


8. freopen("/dev/null", "r", stdin);
9. freopen("/dev/null", "w", stdout);
10. freopen("/dev/null", "w", stderr);
Page Reference: Pages 463–470 in the PDF.

8. What is error logging? With a neat block diagram, discuss error logging
facility for a daemon process.

Definition:

Error logging is a mechanism for recording system errors or application messages for debugging
or monitoring purposes.
Steps in Error Logging for Daemons:

1. Use the syslog() facility for structured logging.


2. Redirect error messages to log files.

Block Diagram:
+-------------------+ +-----------------+
| Daemon Process | | syslog() |
+-------------------+ --> +-----------------+ --> Log File
Example:
#include <syslog.h>
int main() {
openlog("mydaemon", LOG_PID, LOG_DAEMON);
syslog(LOG_ERR, "An error occurred!");
closelog();
return 0;
}
Page Reference: Pages 469–473 in the PDF.

You might also like