Unix QB Solutions
Unix QB Solutions
1.Explain with a figure ,the kernel and shell relationship in unix operating system
The main concept in the unix architecture is the division of labor between two agencies the
KERNEL and SHELL. The kernel interacts with hardware and shell interacts with user.
The kernel is the core of the operating system- a collection of routines mostly written in C. It
is loaded into memory when the system is booted and communicates directly with the
hardware. User applications (programs) that need to access the hardware, uses the services
of kernel. These programs access the kernel through a set of function called system calls.
k
ris
Apart from providing support to user programs, the kernel also performs other tasks like
managing system’s memory, scheduling processes, decides their priorit ies etc. So the kernel
is often called the operating system- a program’s gateway to the computer’s resource.
n
The shell is the command interpreter, it translates command into action. It is the interface
between user and kernel. System contains only one kernel, but there may be several shells.
ow
When user enters a command through the keyboard the shell thoroughly examines
keyboard input for special characters, if it finds any, it rebuilds simplified command line and
finally communicates with kernel to see that the command is executed.For eg,consider a
ur
echo command which has lots of spaces between the arguments:
In the above example shell first rebuilds the command line i.e. it will compress all extra
spaces, then it will produces output.
at
Sun solaris
Features of UNIX:
ud
Multi-user system:
Unix is a multi-user system i.e. multiple user can use the system at a time, resources are
St
shared between all users. In unix systems, computer breaks up a unit of time into several
segments. So at any point in time, the machine will be doing the job of a single user. The
moment the allocated time expires, the previous job will be preempted and next user’s job is
taken up. This process goes on until clock has turned full circle and the first user’s job is
taken up once again.Unix is a multi-programming system, it permits multiple programs to
run. This can happen in two ways:
A single user can run multiple tasks concurrently, in multitasking environment a user sees
one job running in the foreground, the rest running in the background. It is possible to
switch the job between background and foreground, suspend or even
terminate them.
Unix contains several commands each performs one simple job. It is possible to connect
k
different with the pipe (|) to get different jobs done. The commands that can be connected in
this way are called filters, because they filter or manipulate data in different way.for ex: ls
ris
command lists all files.wc command counts the number of words .They can be combined
using pipes(|) to find the total number of files in the directory.
n
ow
Unix contains set of tools like general purpose tools, text manipulation utilities (called
filters), compilers, interpreters, networked application and system administration tools.
Pattern matching:
ur
Unix contains pattern matching features, using this features it is possible to match the
different strings.
yo
Eg: ‘*’
$ls chap*
at
Here ‘*’ is the special character, which matches the filename, which starts with ‘chap’.
Programming facility:
y
Unix shell is also a programming language. It has control structures, variables, loops that
ud
establish it as a powerful programming language. This features can be used to design a shell
scripts.
St
Documentation:
Unix contains ‘man’ pages for each command, it contains references for commands and their
configuration files.Apart from man page, we can even get the command information in
internet.there are several newsgroups on unix where we can fire our queries to get the
solution to a problem.
i) **cat** The `cat` command is used to display file contents or to concatenate files:
`$ cat file1` This displays the content of `file1`.
ii) **printf** The `printf` command formats and prints text. Unlike `echo`, it provides more
control over output formatting:
iii) **who** The `who` command displays users currently logged into the system:
`$ who` This lists users with login information, such as login time and terminal.
k
with example.
ris
Internal and external commands:
External commands will have independent existence in one of the directories specified in
n
the PATH variable.
ow
Eg: $ls
ls is /bin/ls
‘ls’ command having an independent existence in the /bin directory (or /usr/bin). So
ur
‘ls’ is a external command.
yo
Internal commands doesn’t have independent existence, they are shell built -ins. Eg: $type
echo
echo is a built-in.
at
Shell is an external command with difference, i.e. shell possesses its own set of internal
commands. If a command exists both as an internal command of the shell as well as an
y
external one, the shell will give top priority to its internal command.
ud
Eg: echo command, which is also found in /bin directory but rarely ever executed, because
the shell makes sure that the internal echo command takes precedence over the external.
St
Command arguments can take the form of an expression (in grep), a set of instructions (in
sed), or a program (in awk and perl).
5.Explain the following commands with syntax, option and example Echo, ls, who,
passwd, date.
Here's a detailed explanation of each command along with its syntax, options, and examples.
### 1. **echo**
The `echo` command is used to display a message or the value of a variable on the terminal.
- **Syntax**:
```bash
```
- **Options**:
k
- `-e`: Enable interpretation of backslash escapes (e.g., `\n` for newline, `\t` for tab).
ris
- **Example**:
```bash
n
$ echo "Hello, World!"
ow
Hello, World!
$ echo -e "Hello\nWorld"
Hello
ur
World
yo
```
### 2. **ls**
at
The `ls` command lists files and directories within the current directory or specified
directory.
y
- **Syntax**:
ud
```bash
ls [options] [directory...]
St
```
- **Options**:
- `-l`: Display detailed information about files, such as permissions, owner, size, and
modification date.
- `-a`: Show all files, including hidden files (those starting with `.`).
```bash
$ ls -l
```
k
### 3. **who**
ris
The `who` command displays information about users currently logged into the system.
- **Syntax**:
n
```bash
ow
who [options]
```
- **Options**:
ur
- `-H`: Display a header.
yo
- `-u`: Show detailed information about idle time and process ID.
- **Example**:
at
```bash
$ who
y
```
### 4. **passwd**
- **Syntax**:
```bash
passwd [username]
```
- **Options**:
- `-n DAYS`: Set the minimum number of days between password changes.
- **Example**:
k
```bash
ris
$ passwd
n
Current password:
ow
New password:
```
ur
### 5. **date**
yo
- **Syntax**:
at
```bash
```
ud
- **Options**:
St
- **Example**:
```bash
$ date
Mon Nov 6 10:30:00 UTC 2024
$ date +"%Y-%m-%d"
2024-11-06
```
6.With suitable example bring out the differences between absolute and relative
pathnames
In Unix and Linux, **absolute** and **relative** pathnames are two ways to specify the
k
location of a file or directory.
ris
### 1. **Absolute Pathname**
An absolute pathname specifies the location of a file or directory from the root directory
n
(`/`). It begins with a `/`, which represents the root of the filesystem, and includes the entire
path to reach the target.
ow
- **Example**:
```bash
ur
/home/user/docs/file.txt
```
yo
Here, `/home/user/docs/file.txt` is an absolute path, starting from the root (`/`) and
providing the complete directory structure to reach `file.txt`.
at
- **Usage**:
```bash
y
$ cat /home/user/docs/file.txt
ud
```
St
This command will display the contents of `file.txt`, wherever you are in the directory
structure, because the absolute path starts from the root.
A relative pathname specifies the location of a file or directory from the current directory. It
does not begin with `/` but instead specifies the path relative to where the user is currently
located.
- **Example**:
If the current directory is `/home/user/`, the relative path to `file.txt` in the `docs`
subdirectory would be:
```bash
docs/file.txt
```
- **Usage**:
k
ris
```bash
$ cd /home/user
$ cat docs/file.txt
n
ow
```
This command works because we specify `file.txt` in relation to the current directory
(`/home/user/`).
ur
### Summary of Differences:
- **Absolute Pathname**:
yo
- **Relative Pathname**:
y
ud
- Starts from the current directory (does not start with `/`).
- Only works correctly if the current directory aligns with the given path.
- **Absolute Path**:
```bash
/home/user/docs/file.txt
```
```bash
docs/file.txt
```
By understanding these differences, you can navigate the filesystem more flexibly using
either method as needed.
k
ris
10.What is a parent child relationship? With the help of neat diagram, explain UNIX
file system.
n
The file system is organized in a hierarchical structure.
ow
The implicit feature of unix file system is that there is a top directory which is called as root
which serves as the reference point for all files.
These subdirectories in turn have more sub directories and other files under them.
o Ex: bin and usr are two directories directly under /, while cp and pwd are subdirectories
under bin.
at
Every file must have a parent and it should be possible to trace the ultimate parentage of a
file to root.
y
Thus, the home directory in the above figure is the parent for mthomas, while / is the parent
ud
five essential file-related commands in UNIX, along with examples and explanations of their
usage:
cat (concatenate):
Options:
cp (copy):
k
Copies files or directories.
ris
Example: $ cp file1 file2 copies file1 to file2.
Options:
n
-i: Prompts before overwriting files.
ow
-R: Recursively copies directories.
rm (remove):
ur
Deletes files or directories.
yo
Options:
at
mv (move/rename):
St
wc (word count):
Example: $ wc file outputs line, word, and character counts for file.
Options:
Module-2
3.What are file permissions? Explain the use of chmod to change file permissions
k
using both absolute and relative methods?
ris
Changing File Permission:
A file or a directory is created with a default set of permissions, which can be determined by
umask. Let us assume that the file permission for the created file is -rw-r-- r--. Using chmod
n
command, we can change the file permissions and allow the owner to execute his file.
ow
The command can be used in two ways:
Relative Permissions:
yo
• chmod only changes the permissions specified in the command line and leaves the
other permissions unchanged.
at
Example:
• Initially,
• The command assigns (+) execute (x) permission to the user (u), other permissions
remain unchanged.
k
ris
xstart
$ls –l xstart
n
ow
• chmod accepts multiple file names in command line
• Let Initially,
ur
-rwxr-xr-x 1 kumar metal 1906 sep 23:38 xstart
yo
Then it becomes
at
$ls –l xstart
Absolute Permissions:
ud
• Here, we need not to know the current file permissions. We can set all nine
permissions explicitly. A string of three octal digits is used as an expression. The permission
can be represented by one octal digit for each category. For each category, we add octal
St
digits. If we represent the permissions of each category by one octal digit, this is how the
permission can be represented:
Read permission – 4 (octal 100) Write permission – 2 (octal 010) Execute permission – 1
(octal 001)
• We have three categories and three permissions for each category, so three octal
digits can describe a file‘s permissions completely. The most significant digit represents user
and the least one represents others. chmod can use this three-digit string as the expression.
• Using absolute permission, we have:
• will assign all permissions to the owner, read and write permissions for the
group and only execute permission to the others.
• 777 signify all permissions for all categories, but still we can prevent a file from
k
being deleted.
ris
• 000 signifies absence of all permissions for all categories, but still we can delete a
file.
n
• It is the directory permissions that determine whether a file can be deleted or not.
ow
• Only owner can change the file permissions. User cannot change
You often need to search a file for a pattern, either to see the lines containing ( or not
containing) it or to have it replaced with something else. This chapter discusses two
at
important filters that are specially suited for these tasks- grep and sed. This chapter also
takes up one of the fascinating features of UNIX – regular expressions (RE).
y
To discuss all the examples in this chapter we use following emp.lst as the reference file
ud
$ cat emp.lst
k
3564 | sudhir Agarwal | executive | personnel | 06/07/47 | 7500
ris
2345 | j. b. saxena | g. m. | marketing | 12/03/45 | 8000
n
grep scans its input for a pattern displays lines containing the pattern, the line numbers or
ow
filenames where the pattern occurs. The command uses the following syntax:
grep searches for pattern in one or more filename(s), or the standard input if no filename is
ur
specified.
The first argument (except the options) is the pattern and the remaining arguments are
yo
filenames.
Examples:
at
here, grep displays 4 lines containing pattern as “sales” from the file emp.lst.
Here, first column shows file name. when grep is used with multiple filenames, it
displays the filenames along with the output.
grep options:
k
The below table shows all the options used by grep.
ris
5.Explain the concept of escaping and quoting with suitable example?
n
Escaping is providing a \ (backslash) before the wild-card to remove (escape)
ow
its special meaning.
For instance, if we have a file whose filename is chap* (Remember a file in UNIX can be
names with virtually any character except the / and null), to remove the file, it is dangerous
to give command as rm chap*, as it will remove all files beginning with chap. Hence to
ur
suppress the special meaning of *, use the command rm chap\*.
yo
$cat chap0\[1-3\]
at
A filename can contain a whitespace character also. Hence to remove a file named My
Documend.doc, which has a space embedded, a similar reasoning should be followed:
rm My\ Document.doc
y
ud
Quoting is enclosing the wild-card, or even the entire pattern, within quotes. Anything
within these quotes (barring a few exceptions) are left alone by the shell and not
interpreted. When a command argument is enclosed in quotes, the meanings of all enclosed
St
Examples:
6.Explain three standard files supported by unix? Explain about special files used for
output redirection?
Standard input: The file (stream) representing input, connected to the keyboard.
Standard output: The file (stream) representing output, connected to the display.
Standard error: The file (stream) representing error messages that emanate from the
command or shell, connected to the display.
k
The standard input can represent three input sources:
ris
✓ The keyboard, the default source.
n
Unix Programming
ow
✓ Another program using a pipeline.
A file is opened by referring to its pathname, but subsequent read and write operations
at
identify the file by a unique number called a file descriptor. The kernel maintains a table of
file descriptors for every process running in the system. The first three slots are generally
allocated to the three standard streams as,
y
ud
0 – Standard input
1 – Standard output
St
2 – Standard error
Assuming file2 doesn’t exist, the following command redirects the standard
Directory-oriented commands like mkdir, rmdir and cd, and basic file handling commands
like cp, mv and rm use neither standard input nor standard output.
2. Commands like ls, pwd, who etc. don’t read standard input but they write to standard
output.
3. Commands like lp that read standard input but don’t write to standard
output.
k
4. Commands like cat, wc, cmp etc. that use both standard input and
ris
standard output.
Commands in the fourth category are called filters. Note that filters can also read directly
n
from files whose names are provided as arguments.
ow
Example:
To perform arithmetic calculations that are specified as expressions in input file calc.txt and
redirect the output to a file result.txt, use
ur
$bc < calc.txt > result.txt6.
7.Explain if and While control statements in shell scripts with suitable program
yo
While Looping:
A while loop is different from a for loop in that is uses a test condition to determine whether
at
or not to execute its command block. As long as the condition returns true when tested, the
loops executes the commands.
y
If it returns false, the script skips the loop and proceeds beyond its terminate point.
ud
Consequently, the command set could conceiveably never run. This is further illustrated by
the loop’s syntax:
Unix Programming
St
Syntax:
while condition
do
done
command1
.
. commandn
because the loop starts with the test, if the condition fails, then the program continues at
whatever action immediately follows the loops done statement. If the condition passes then
the script executes the enclosed command block.
After performing the last command in the block, the loop starts tests the condition again &
k
determine whether to proceed beyond the loop or fail through it once more.
ris
Example:
Here is the example that uses while loop to open through the given list of numbers:
n
i=1
ow
while [ $i -le 5 ]
do
done
ur
echo $i
yo
i=`expr $i + 1`
2
y
3
ud
5
St
8.What are wild card characters? Explain shell wild card characters with example?
A pattern is framed using ordinary characters and a meta character (like *) using well-
defined rules. The pattern can then be used as an argument to the command, and the shell
will expand it suitably before the command is executed.
The meta characters that are used to construct the generalized pattern for matching
filenames belong to a category called wild-cards. The following table lists them:
Examples:
To list all files that begin with chap, use, $ls chap*
To list all files whose filenames are six character long and start with chap, use , $ls chap??
Note: Both * and ? operate with some restrictions. for example, the * doesn’t match all files
beginning with a . (dot) or the / of a pathname. If you wish to list all hidden filenames in
k
your directory having at least three characters after the dot, the dot must be matched
explicitly.
ris
$ ls .???*
However, if the filename contains a dot anywhere but at the beginning, it need not be
n
matched explicitly.
ow
Similarly, these characters don’t match the / in a pathname. So, you cannot
commands into actions taken by the system. The shell is analogous to command.com in DOS.
When you log into the system you are given a default shell. When the shell starts up it reads
at
its startup files and may set environment variables, command search paths, and command
aliases, and executes any commands specified in these files. The original shell was the
Bourne shell, sh. Every Unix platform will either have the Bourne shell, or a Bourne
y
Numerous other shells are available. Some of the more well known of these may be on your
Unix system: the Korn shell, ksh, by David Korn, C shell, csh, by Bill Joy and the Bourne Again
SHell, bash, from the Free Software Foundations GNU project, both based on sh, the T-C
St
shell, tcsh, and the extended C shell, cshe, both based on csh.
Even though the shell appears not to be doing anything meaningful when there is no activity
at the terminal, it swings into action the moment you key in something.
The following activities are typically performed by the shell in its interpretive cycle:
✓ The shell issues the prompt and waits for you to enter a command.
✓ After a command is entered, the shell scans the command line for
meta characters and expands abbreviations (like the * in rm *) to
✓ The shell waits for the command to complete and normally can’t do
k
the shell returns to its waiting role to start the next cycle. You are free
ris
to enter another command.
n
(iii) *.[!s][!h] (iv) *[!0-9]
ow
the explanation of each of these command patterns and their expected output in a UNIX-like
system:
ls [ijk]*doc
ur
Lists files that start with either "i," "j," or "k" and end with "doc."
yo
For example, this might match files like idoc, ijournal.doc, kfiledoc, etc.
ls [A-Z]????*
at
Lists files that start with any uppercase letter (A to Z) followed by exactly four characters,
then any additional characters.
For example, it would match files like Test1.txt, File2, or Data3test, but not TEST (since it has
y
fewer than 5 characters) or aFile (since it doesn’t start with an uppercase letter).
ud
ls *.[!s][!h]
For example, this might match files like file.ab, document.tx, data.ci, but not notes.sh (since it
ends in sh), or file.sa (since it starts with s in the extension).
ls *[!0-9]
Module 3
1)Explain mkdir and rmdir with an example
k
ris
n
ow
ur
yo
at
y
ud
St
St
ud
y
at
yo
ur
ow
n
ris
k
k
ris
n
ow
ur
yo
at
y
ud
St
3)Describe general UNIX file API’s with syntax and explain each field in details.
St
The general UNIX file APIs include several functions that allow processes to access and
manage files and file metadata. Here are some of the key functions along with their syntax
and explanations:
1. open()
#include <sys/types.h>
#include <fcntl.h>
flags: Specifies how the file should be opened (e.g., O_RDONLY for read-only, O_WRONLY for
write-only, O_RDWR for read and write).
mode: Specifies the permissions to use in case a new file is created (e.g., S_IRUSR for read
permission for the owner).
k
2.read()
ris
#include <unistd.h>
n
fd: File descriptor returned by open().
3. write()
#include <unistd.h>
4.close()
#include <unistd.h>
#include <unistd.h>
k
whence: Position from where offset is added (e.g., SEEK_SET for beginning of file,
ris
SEEK_CUR for current position, SEEK_END for end of file).
n
6.stat()
ow
#include <sys/stat.h>
7.fstat()
y
#include <sys/stat.h>
ud
8.chmod()
#include <sys/stat.h>
k
ris
9.chown()
n
#include <unistd.h>
ow
int chown(const char *pathname, uid_t owner, gid_t group);
10.unlink()
#include <unistd.h>
y
These functions form the core of file manipulation in UNIX systems, allowing for
comprehensive file operations
4.Describe how a c program is started and various ways it terminates.
A C program starts execution with a function called main. The prototype for the main
function is:
where argc is the number of command-line arguments, and argv is an array of pointers to
the arguments.
When a C program is executed by the kernel by one of the exec functions, a special start-up
k
routine is called before the main function is called. The executable program file specifies this
routine as the starting address for the program; this is set up by the link editor when it is
ris
invoked by the C compiler. This start-up routine takes values from the kernel, the
command-line arguments and the environment and sets things up so that the main function
is called.
n
Process Termination:
ow
There are eight ways for a process to terminate. Normal termination occurs in five ways:
✓ Calling abort.
y
ud
✓ Receipt of a signal.
5. Explain with a neat diagram memory layout of a C program and briefly discuss the
different functions used for memory allocation.
➢ Text segment: the machine instructions that the CPU executes. Usually, the text segment
is sharable so that only a single copy needs to be in memory for frequently executed
programs, such as text editors, the C compiler, the shells, and so on. Also, the text segment is
often read-only, to prevent a program from accidentally modifying its instructions.
➢ Initialized data segment: usually called simply the data segment,
containing variables that are specifically initialized in the program. For example, the C
declaration
appearing outside any function causes this variable to be stored in the initialized data
segment with its initial value.
➢ Uninitialized data segment: often called the "bss" segment, named after an ancient
k
assembler operator that stood for "block started by symbol." Data in this segment is
initialized by the kernel to arithmetic 0 or null pointers before the program starts executing.
ris
The C declaration
long sum[1000];
n
appearing outside any function causes this variable to be stored in the uninitialized data
ow
segment.
➢ Stack: where automatic variables are stored, along with information that
is saved each time a function is called. Each time a function is called, the address of where to
ur
return to and certain information about the caller's environment, such as some of the
machine registers, are saved on the stack. The newly called function then allocates room on
the stack for its automatic and temporary variables. This is how recursive functions in C can
yo
work. Each time a recursive function calls itself, a new stack frame is used, so one set of
variables doesn't interfere with the variables from another instance of the function.
at
the heap has been located between the uninitialized data and the stack.
y
Memory Allocation:
ud
➢ malloc, which allocates a specified number of bytes of memory. The initial value of the
St
memory is indeterminate.
➢ realloc, which increases or decreases the size of a previously allocated area. When the
size increases, it may involve moving the previously
allocated area somewhere else, to provide the additional room at the end. Also, when the
size increases, the initial value of the space between the old
contents and the end of the new area is indeterminate.
#include <stdlib.h>
All three return: non-null pointer if OK, NULL on error. void free(void *ptr);
k
The pointer returned by the three allocation functions is guaranteed to be suitably aligned
ris
so that it can be used for any data object. Because the three alloc functions return a generic
void * pointer, if we #include (to obtain the function prototypes), we do not explicitly have
to cast the pointer returned by these functions when we assign it to a pointer of a different
type.
n
The function free causes the space pointed to by ptr to be deallocated. This freed space is
ow
usually put into a pool of available memory and can be allocated in a later call to one of the
three alloc functions.
The realloc function lets us increase or decrease the size of a previously allocated area. For
ur
example, if we allocate room for 512 elements in an array that we fill in at runtime but find
that we need room for more than 512 elements, we can call realloc. If there is room beyond
the end of the existing region for the requested space, then realloc doesn't have to move
yo
anything; it simply allocates the additional area at the end and returns the same pointer
that we passed it. But if there isn't room at the end of the existing region,
at
realloc allocates another area that is large enough, copies the existing 512- element array to
the new area, frees the old area, and returns the pointer to the new area.
y
The allocation routines are usually implemented with the sbrk(2) system call. Although sbrk
ud
can expand or contract the memory of a process, most versions of malloc and free never
decrease their memory size. The space that we free is available for a later allocation, but the
freed space is not usually returned to the kernel; that space is kept in the malloc pool.
St
It is important to realize that most implementations allocate a little more space than is
requested and use the additional space for record keeping the size of the allocated block, a
pointer to the next allocated block, and the like. This means that writing past the end of an
allocated area could overwrite this record-keeping information in a later block. These types
of errors are often catastrophic, but difficult to find, because the error may not show up until
much later. Also, it is possible to overwrite this record keeping by writing before the start of
the allocated area.
Because memory allocation errors are difficult to track down, some systems provide
versions of these functions that do additional error checking every time one of the three
alloc functions or free is called. These versions of the functions are often specified by
including a special library for the link editor. There are also publicly available sources that
you can compile with special flags to enable additional runtime checking.
k
ris
n
ow
ur
yo
at
y
ud
St