0% found this document useful (0 votes)
15 views34 pages

Unix QB Solutions

The document explains the relationship between the kernel and shell in the Unix operating system, highlighting that the kernel interacts with hardware while the shell serves as the user interface. It outlines key features of Unix, including its multi-user and multi-tasking capabilities, and provides examples of various commands such as 'cat', 'printf', and 'who'. Additionally, it discusses file permissions and the use of the 'chmod' command to change them using both absolute and relative methods.

Uploaded by

anshara418
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views34 pages

Unix QB Solutions

The document explains the relationship between the kernel and shell in the Unix operating system, highlighting that the kernel interacts with hardware while the shell serves as the user interface. It outlines key features of Unix, including its multi-user and multi-tasking capabilities, and provides examples of various commands such as 'cat', 'printf', and 'who'. Additionally, it discusses file permissions and the use of the 'chmod' command to change them using both absolute and relative methods.

Uploaded by

anshara418
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Module-1

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:

Eg: $echo Sun solaris


yo

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

2.List and explain the salient features of Unix operating system


y

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:

Multiple user can run separate jobs.

A single user can also run multiple jobs.


Multi-tasking system:

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.

Building block approach:

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.

Unix tool kit:

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.

3.Explain the following commands with example: i)cat ii)printf iii)who

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:

`$ printf "Hello %s\n" World` Output: `Hello World`

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.

4.Differentiate between Internal and External commands in UNIX operating system

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

echo [options] [string...]

```

- **Options**:

- `-n`: Do not output a trailing newline.

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 `.`).

- `-R`: List subdirectories recursively.


- **Example**:

```bash

$ ls -l

drwxr-xr-x 2 user user 4096 Jan 1 12:00 directory

-rw-r--r-- 1 user user 1024 Jan 1 12:00 file.txt

```

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

user1 tty1 Jan 1 12:00


ud

user2 tty2 Jan 1 12:05


St

```

### 4. **passwd**

The `passwd` command allows a user to change their password or an administrator to


change a user’s password.

- **Syntax**:

```bash
passwd [username]

```

- **Options**:

- `--help`: Display help information.

- `-n DAYS`: Set the minimum number of days between password changes.

- **Example**:

k
```bash

ris
$ passwd

Changing password for user.

n
Current password:

ow
New password:

Retype new password:

```
ur
### 5. **date**
yo

The `date` command displays the current date and time.

- **Syntax**:
at

```bash

date [options] [format]


y

```
ud

- **Options**:
St

- `+%Y`: Display only the year.

- `+%m`: Display only the month.

- `+%d`: Display only the day.

- **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.

### 2. **Relative Pathname**

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

```

This relative path only works if the current directory is `/home/user/`.

- **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

- Starts from the root directory `/`.

- Always provides the full path to a file or directory.


at

- Works from any location in the filesystem.

- **Relative Pathname**:
y
ud

- Starts from the current directory (does not start with `/`).

- Shorter and context-specific; depends on the user’s current directory.


St

- Only works correctly if the current directory aligns with the given path.

### Example Comparison:

Suppose you have a file `file.txt` located in `/home/user/docs/`.

- **Absolute Path**:

```bash

/home/user/docs/file.txt
```

- **Relative Path** (if you are in `/home/user`):

```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.

All files in unix are related to one another.

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.

Top is represented by a /(front slash).


ur
Root directory(/) has several sub directories under it.
yo

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

of home and the grand parent of mthomas.

In the parent-child relationship, the parent is always a directory.


St

o Ex: login.sql is an ordinary file, it cannot have a directory under it.

11.Explain any five file related commands with an example.

five essential file-related commands in UNIX, along with examples and explanations of their
usage:

cat (concatenate):

Displays file contents or combines multiple files.


Example: $ cat file1 file2 displays the contents of file1 followed by file2.

Options:

-n: Adds line numbers to the output.

-v: Displays non-printing characters.

Can also create files by redirecting input ($ cat > newfile).

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.

Can use wildcard * to copy multiple files ($ cp ch* destination).

rm (remove):
ur
Deletes files or directories.
yo

Example: $ rm file1 file2 deletes file1 and file2.

Options:
at

-i: Prompts for confirmation before deletion.

-r: Recursively deletes directories and contents.


y

-f: Forces deletion without prompts.


ud

mv (move/rename):
St

Moves or renames files and directories.

Example: $ mv oldname newname renames oldname to newname.

Can move multiple files to a directory ($ mv file1 file2 dir).

wc (word count):

Counts lines, words, and characters in files.

Example: $ wc file outputs line, word, and character counts for file.
Options:

-l: Counts only lines.

-w: Counts only words.

-c: Counts only characters.

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:

1. In a relative manner by specifying the changes to the current permissions.


ur
2. In an absolute manner by specifying the final permissions.

Relative Permissions:
yo

• chmod only changes the permissions specified in the command line and leaves the
other permissions unchanged.
at

• Its syntax is:

chmod category operation permission filename(s)


y

• chmod takes an expression as its argument which contains:


ud

• user category (user, group, others).

• operation to be performed (assign or remove a permission).


St

• type of permission (read, write, execute).

• Category : u – user g – group o – others a - all (ugo)

• operations : + assign - remove = absolute

• permissions: r – read w – write x - execute

Example:
• Initially,

-rw-r—r-- 1 kumar metal 1906 sep 23:38 xstart

$chmod u+x xstart

-rwxr—r-- 1 kumar metal 1906 sep 23:38 xstart

• The command assigns (+) execute (x) permission to the user (u), other permissions
remain unchanged.

$chmod ugo+x xstart or chmod a+x xstart or chmod +x

k
ris
xstart

$ls –l xstart

-rwxr-xr-x 1 kumar metal 1906 sep 23:38 xstart

n
ow
• chmod accepts multiple file names in command line

$chmod u+x note note1 note3

• Let Initially,
ur
-rwxr-xr-x 1 kumar metal 1906 sep 23:38 xstart
yo

$chmod go-r xstart

Then it becomes
at

$ls –l xstart

-rwx—x--x 1 kumar metal 1906 sep 23:38 xstart


y

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:

$chmod 666 xstart

$chmod 644 xstart

$chmod 761 xstart

• 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

other user‘s file‘s permissions.

• But the system administrator can do anything.


ur
4.Explain grep command? List its options with its significance.
yo

grep: Searching for a pattern

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

2233 | a. k. shukla | g. m. | sales | 12/12/52 | 6000


St

9876 | jai sharma | director | production | 12/03/50 | 7000

5678 | sumit chakrobarty | d. g. m. | marketing | 19/04/43 | 6000

2365 | barun sengupta | director | personnel |11/05/47 | 7800

5423 | n. k. gupta | chairman | admin | 30/08/56 | 5400

1006 | chanchal singhvi | director | sales | 03/09/38 | 6700


6213 | karuna ganguly | g. m. | accounts | 05/06/62 | 6300

1265 | s. n. dasgupta | manager | sales | 12/09/63 | 5600

4290 | jayant choudhury | executive | production | 07/09/50 | 6000

2476 | anil aggarwal | manager | sales | 01/05/59 | 5000

6521 | lalit chowdury | director | marketing | 26/09/45 | 8200

3212 | shyam saksena |d. g. m. | accounts | 12/12/55 | 6000

k
3564 | sudhir Agarwal | executive | personnel | 06/07/47 | 7500

ris
2345 | j. b. saxena | g. m. | marketing | 12/03/45 | 8000

0110 | v. k. agrawal | g. m. | marketing | 31/12/40 | 9000

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 options pattern filename(s)

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

$ grep “sales” emp.lst

2233|a. k. shukla |g. m. |sales |12/12/52|6000


y

1006|chanchal singhvi |director |sales |03/09/38|6700


ud

1265|s. n. dasgupta |manager |sales |12/09/63|5600

2476|anil aggarwal |manager |sales |01/05/59|5000


St

here, grep displays 4 lines containing pattern as “sales” from the file emp.lst.

$ grep president emp.lst #No quoting necessary here

$_ #No pattern (president) found

here, grep silently returns the prompt because no pattern as “president”

found in file emp.lst.


$ grep “director” emp1.lst emp2.lst

emp1.lst: 9876|jai sharma |director |production |12/03/50|7000 emp1.lst: 2365|barun


sengupta |director |personnel |11/05/47|7800 emp1.lst: 1006|chanchal singhvi |director
|sales |03/09/38|6700 emp2.lst: 6521|lalit chowdury |director |marketing |26/09/45|8200

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?

Escaping & Quoting:

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

To list the contents of the file chap0[1-3], use,

$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

special characters are turned off.

Examples:

$rm chap* Removes files chap*

$rm “My Document.doc” Removes file My Document.doc

6.Explain three standard files supported by unix? Explain about special files used for
output redirection?

Redirection: The three standard files


The shell associates three files with the terminal – two for display and one for the keyboard.
These files are streams of characters which many commands see as input and output. When
a user logs in, the shell makes available three files representing three streams. Each stream
is associated with a default device: -

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.

✓ A file using redirection with the < symbol.

n
Unix Programming

ow
✓ Another program using a pipeline.

The standard output can represent three possible destinations:


ur
✓ The terminal, the default destination.

✓ A file using the redirection symbols > and >>.


yo

✓ As input to 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

These descriptors are implicitly prefixed to the redirection symbols. Examples:

Assuming file2 doesn’t exist, the following command redirects the standard

output to file myOutput and the standard error to file myError.

$ls –l file1 file2 1>myOutput 2>myError

Filters: Using both standard input and standard output


UNIX commands can be grouped into four categories viz.,

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`

this will produce following result:


at

2
y

3
ud

5
St

8.What are wild card characters? Explain shell wild card characters with example?

Pattern Matching-Wild Cards:

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

use, $cd /usr?local to change to /usr/local.

9.What is a shell? Briefly give the shell interpretive cycle.


ur
The shell sits between you and the operating system, acting as a command interpreter. It
yo

reads your terminal input and translates the

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

compatible shell available.


ud

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

recreate a simplified command line.

✓ It then passes on the command line to the kernel for execution.

✓ The shell waits for the command to complete and normally can’t do

any work while the command is running.

✓ After the command execution is complete, the prompt reappears and

k
the shell returns to its waiting role to start the next cycle. You are free

ris
to enter another command.

11.What is the output of the following; (i) ls [ijk]*doc (ii) [A-Z]????*

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]

Lists files with an extension of two characters, where:


St

The first character in the extension is not "s."

The second character in the extension is not "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]

Lists files whose names do not end with a digit (0-9).


For example, it might match files like fileA, document.txt, report, but not data1, test123, or
log0.

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

2)Explain about the following functions: chdir, fchdir,getcwd,getrlimit,setrlimit


St
ud
y
at
yo
ur
ow
n
ris
k
St
ud
y
at
yo
ur
ow
n
ris
k
St
ud
y
at
yo
ur
ow
n
ris
k
k
ris
n
ow
ur
yo
at
y
ud

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>

int open(const char *pathname, int flags, mode_t mode);


pathname: The path to the file.

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>

ssize_t read(int fd, void *buf, size_t count);

n
fd: File descriptor returned by open().

buf: Buffer where the read data will be stored.

count: Number of bytes to read. ow


ur
yo

3. write()

#include <unistd.h>

ssize_t write(int fd, const void *buf, size_t count);


at
y

fd: File descriptor returned by open().


ud

buf: Buffer containing the data to be written.

count: Number of bytes to write.


St

4.close()

#include <unistd.h>

int close(int fd);


5.lseek()

#include <unistd.h>

off_t lseek(int fd, off_t offset, int whence);

fd: File descriptor.

offset: Offset in bytes.

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>

int stat(const char *pathname, struct stat *buf);


ur
pathname: Path to the file.
yo

buf: Buffer where file status information is stored.


at

7.fstat()
y

#include <sys/stat.h>
ud

int fstat(int fd, struct stat *buf);


St

fd: File descriptor.

buf: Buffer where file status information is stored.

8.chmod()
#include <sys/stat.h>

int chmod(const char *pathname, mode_t mode);

pathname: Path to the file.

mode: New permissions for the file.

k
ris
9.chown()

n
#include <unistd.h>

ow
int chown(const char *pathname, uid_t owner, gid_t group);

pathname: Path to the file.


ur
owner: New owner’s user ID.
yo

group: New owner’s group ID.


at

10.unlink()

#include <unistd.h>
y

int unlink(const char *pathname);


ud
St

○ pathname: Path to the file to be deleted.

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:

int main(int argc, char *argv[]);

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:

✓ Return from main.


ur
✓ Calling exit.

✓ Calling _exit or _Exit.


yo

✓ Return of the last thread from its start routine.

✓ Calling pthread_exit from the last thread.


at

Abnormal termination occurs in three ways:

✓ Calling abort.
y
ud

✓ Receipt of a signal.

✓ Response of the last thread to a cancellation request.


St

5. Explain with a neat diagram memory layout of a C program and briefly discuss the
different functions used for memory allocation.

Memory layout of C Program:

Historically, a C program has been composed of the following pieces:

➢ 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

int maxcount = 99;

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

➢ Heap: where dynamic memory allocation usually takes place. Historically,

the heap has been located between the uninitialized data and the stack.
y

Memory Allocation:
ud

ISO C specifies three functions for memory allocation:

➢ malloc, which allocates a specified number of bytes of memory. The initial value of the
St

memory is indeterminate.

➢ calloc, which allocates space for a specified number of objects of a

specified size. The space is initialized to all 0 bits.

➢ 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>

void *malloc(size_t size);

void *calloc(size_t nobj, size_t size);

void *realloc(void *ptr, size_t newsize);

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

You might also like