37
OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT

OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Embed Size (px)

Citation preview

Page 1: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

OPERATING SYSTEM LABCS693

MANUAL & ASSIGNMENT

Page 2: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Manual and Assignment for Operating System Lab (CS693)

Lab # 1:

Objectives Introduction to UNIX:

The Unix operating system is a set of programs that act as a link between the computer and the user.The computer programs that allocate the system resources and coordinate all the details of thecomputer's internals is called the operating system or the kernel.

Users communicate with the kernel through a program known as the shell. The shell is a commandline interpreter; it translates commands entered by the user and converts them into a language that isunderstood by the kernel.

➢ Unix was originally developed in 1969 by a group of AT&T employees Ken Thompson,

Dennis Ritchie, Douglas McIlroy, and Joe Ossanna at Bell Labs.

➢ There are various Unix variants available in the market. Solaris Unix, AIX, HP Unix and

BSD are a few examples. Linux is also a flavor of Unix which is freely available.

➢ Several people can use a Unix computer at the same time; hence Unix is called a multiuser

system.

➢ A user can also run multiple programs at the same time; hence Unix is a multitasking

environment.

Introduction to UNIX architecture:

The main concept that unites all the versions of Unix is the following four basics −➢ Kernel − The kernel is the heart of the operating system. It interacts with the hardware and

most of the tasks like memory management, task scheduling and file management.

➢ Shell − The shell is the utility that processes your requests. When you type in a command at

your terminal, the shell interprets the command and calls the program that you want. Theshell uses standard syntax for all commands. C Shell, Bourne Shell and Korn Shell are themost famous shells which are available with most of the Unix variants.

➢ Commands and Utilities − There are various commands and utilities which you can make

use of in your day to day activities. cp, mv, cat and grep, etc. are few examples ofcommands and utilities. There are over 250 standard commands plus numerous others

provided through 3rd party software. All the commands come along with various options.

➢ Files and Directories − All the data of Unix is organized into files. All files are then

organized into directories. These directories are further organized into a tree-like structurecalled the filesystem.

Introduction to basic UNIX commands:

man: To display the manual page for a given command.

who: To display all the users who are currently using the system.

Page 3: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

whoami: Displays only your details.

pwd: Shows current working directory.

ls: Shows all the files in the current directory. ls can be used with several options. To

learn more type $man ls cd: To change directory.

rm: Removes files. By default it does not remove directory.

cp: Makes copies of files and directories.

mv: Moves files to other directory.

mkdir: Creates directory under the current working directory.

rmdir: Removes directory under the current working directory.

echo: Displays a text or message on the screen.

cat: Universal file viewer. Displays the content of a file.

wc: Count lines, words and characters of a file.

Assignment

0. For each command mentioed above, give a brief description of what it does and how it can be

used

Command Description Syntax Sample Output

Example:cat

Displays the content of the file note1

$cat note1 Hello Java

The screenshots should be pasted for sample output.

1. Provide a short write-up (1 or 2 paragraphs) on the following:

History of Unix and Linux

Kernel of an Operating System

Multi-Tasking OS

Multi-User OS

2. List all the files and directories of ‘/bin’ with detail information from your current directory.

3. List all the files including hidden files in your parent directory.

4. List only the directory files in your current directory.

5. Create a file ‘text 1’ by taking input from the keyboard.

6. Copy the contents of file’ text1’ to another file ‘text2’.

7. Append the contents of file ‘text2 ‘to file ‘text1’.

8. Count the number of lines in the file ‘text1’.

Page 4: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Manual and Assignment for Operating System Lab (CS693)

Lab # 2:

Objectives Meta Characters :

* wildcard: The * (asterisk) metacharacter is used to match any and all characters.

Typing the following command will list all files in the working directory that beginwith the letter l regardless of what characters come after it:

$ ls l*

The * (asterisk) metacharacter can be used anywhere in the filename. It does notnecessarily have to be the last character.

? question mark: The ? (question mark) metacharacter is used to match a single

character in a filename. Typing the following will list all of the files that start with"not" and end with a single character:

$ ls not?

Like the asterisk, the ? (question mark) metacharacter can be used as a substitutionfor any character in the filename.

[ ] brackets: Brackets ([…]) are used to match a set of specified characters. A

comma separates each character within the set. Typing the following will list all filesbeginning with "a", "b", or "c":

$ ls [a,b,c]*

- hyphen: Using the - (hyphen) metacharacter within [] (brackets) is used to match a

specified range of characters. Typing the following will list all files beginning with alowercase letter of the alphabet:

$ ls [a-z]*

> redirection: Redirect the standard output to replace the current content. Typing the

following command will replace the content of the file note1 by the output of thewho command.

$who > note.lst

< redirection: Redirect the standard input to a particular command. Typing the

following command will redirect the content of note.lst to the command wc -l. $wc -l < note.lst

| pipe: Pipe | seperates commands to form a pipe. Typing the following command

will display the same output which can be obtained by executing previous twocommands in sequence.

$who | wc -l

Page 5: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

$ (system) variable: Indicates that the following text is the name of a shell

(environment) variable whose value is to be used. Typing the following commandswill display the value of a which is 4.

$a=4 $echo $a

UNIX commands (cont'd) :

cal: Shows the current calender in the terminal. It can be used with several options.

To learn more type $man cal.

date: Shows the date and time to the nearest second.

cmp: It compares two files of any type and writes the results to the standard output.

By default, cmp is silent if the files are the same; if they differ, the byte and linenumber at which the first difference occurred is reported.

comm: The comm command compares two sorted files line by line. With no options,

comm produces three-column output. Column one contains lines unique to FILE1,column two contains lines unique to FILE2, and column three contains lines commonto both files.

diff: It tells which lines of one file have to be changed to make two files identical.

head: head by default, prints the first 10 lines of each FILE to standard output. With

more than one FILE, it precedes each set of output with a header identifying the filename. If no FILE is specified, or when FILE is specified as a dash ("-"), head readsfrom standard input.

tail: Print the last 10 lines of each FILE to standard output. With more than one

FILE, precede each with a header giving the file name. With no FILE, or when FILEis -, read standard input.

sort: sort is a simple and very useful command which will rearrange the lines in a

text file so that they are sorted, numerically and alphabetically. By default, the rulesfor sorting are:

lines starting with a number will appear before lines starting with a letter;

lines starting with a letter that appears earlier in the alphabet will appear

before lines starting with a letter that appears later in the alphabet;

lines starting with a lowercase letter will appear before lines starting with the

same letter in uppercase.

Sorting can be done in reverse(descending) order with an option -r.

bc

expr

grep

Assignment

0. For each command, give a brief description of what it does and two examples of how it can be used

Page 6: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Command Description Syntax Sample Output

1.

a. Display the current time in 12-hour format.b. With a user-specified date, display only the day of the week (e.g. Tuesday).

2. Write the command to find the square root of 4.3. Show how we can calculate the following expression in the terminal of UNIXA=5, b=6,z=15

Total = (A*b) + (z/A)

Display the Total.

4. How can we sort a list of numbers in a file (both ascending and descending order)?5. Create the file student.dat as follows:Roll | Name | Dept | Year105 | Anik | CSE | 1st 101 | Debesh | CSE | 2nd108 | Aniket | IT | 1st200 | Mainak | ECE | 2nd105 | Anik | CSE | 1sta. Sort the data according to Roll.b. Sort the data according to Dept.c. Show only the records of students from the CSE Dept.

6. Show the last 2 lines of the file animals.txt.7. Show the first 3 lines of the file animals.txt.8. (Re-Visit) List only the directory files in your current directory.9. Count the number of directories in your current directory.10.Dog is a domestic animalDog hates catCat drinks milkDog is bigger than CatCat is also a domestic animala. Find the total number of lines contains the word ‘Dog’ in animals.txt.b. Also find the total number of lines does not contain the word ‘Dog’ in animals.txt.c. Display the lines in animals.txt that end with the word 'cat'.

Page 7: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Manual and Assignment for Operating System Lab (CS693)

Lab # 3:

ObjectivesEssentials of shell programming

1. vi editor: There are many ways to edit files in Unix. Editing files using the screen-orientedtext editor vi is one of the best ways. This editor enables you to edit lines in context withother lines in the file.

The following table lists out the basic commands to use the vi editor −

S.No. Command & Description

1

vi filename

Creates a new file if it already does not exist, otherwise opens an existing file.

2

vi -R filename

Opens an existing file in the read-only mode.

3

view filename

Opens an existing file in the read-only mode.

On opening a file you will notice a tilde (~) on each line following the cursor. A tilderepresents an unused line. If a line does not begin with a tilde and appears to be blank, thereis a space, tab, newline, or some other non-viewable character present.

Operation Modes

While working with the vi editor, we usually come across the following two modes −

• Command mode − This mode enables you to perform administrative tasks such as saving

the files, executing the commands, moving the cursor, cutting (yanking) and pasting thelines or words, as well as finding and replacing. In this mode, whatever you type isinterpreted as a command.

• Insert mode − This mode enables you to insert text into the file. Everything that's typed in

this mode is interpreted as input and placed in the file.

vi always starts in the command mode. To enter text, you must be in the insert mode forwhich simply type i. To come out of the insert mode, press the Esc key, which will take youback to the command mode.

Page 8: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Moving within a File

S.No. Command & Description

1

k

Moves the cursor up one line

2

j

Moves the cursor down one line

3

h

Moves the cursor to the left one character position

4

l

Moves the cursor to the right one character position

Editing Files

S.No. Command & Description

1

i

Inserts text before the current cursor location

2

I

Inserts text at the beginning of the current line

3

a

Inserts text after the current cursor location

4

A

Inserts text at the end of the current line

5

o

Creates a new line for text entry below the cursor location

6

O

Creates a new line for text entry above the cursor location

Page 9: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Deleting Characters

S.No. Command & Description

1

x

Deletes the character under the cursor location

2

X

Deletes the character before the cursor location

3

dw

Deletes from the current cursor location to the next word

4

d^

Deletes from the current cursor position to the beginning of the line

5

d$

Deletes from the current cursor position to the end of the line

6

D

Deletes from the cursor position to the end of the current line

7

dd

Deletes the line the cursor is on

2. Shell basics: A UNIX shell script is a human-readable text file containing a group ofcommands that could also be manually executed one-by-one at the UNIX operating systemcommand prompt. They are often kept in a file (script) because they are too numerous totype in at the command prompt each time you want to perform a specific task, or becausetogether they form a complex computer program.

The vi program, or any one of the many UNIX text editors out there, can be used to create ashell script and save it to disk for subsequent execution. Unlike other high-levelprogramming languages, such as C or C++, shell scripts do not need to be compiled into abinary format for execution. Because of this, programming syntax errors are not revealeduntil the script is executed.

Steps in creating a Shell Script

Page 10: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Create a file using a vi editor(or any other editor). Name script file with extension .sh

Start the script with #! /bin/sh

Write some code.

Save the script file as filename.sh

For executing the script type bash filename.sh

"#!" is an operator called shebang which directs the script to the interpreter location. So, ifwe use"#! /bin/sh" the script gets directed to the bourne-shell.

Let create a small script -

#!/bin/sh

ls

To create the script:

1.$vi demo.sh2. #!/bin/sh ls ~3.bash demo.sh

3. Command line arguments: The command-line arguments $1, $2, $3, ...$9 are positionalparameters, with $0 pointing to the actual command, program, shell script, or function and$1, $2, $3, ...$9 as the arguments to the command.

$0: The filename of the current script.

$#: The number of arguments supplied to a script.

$*: All the arguments are double quoted. If a script receives two arguments, $* is equivalentto $1 $2.

$@: All the arguments are individually double quoted. If a script receives two arguments,$@ is equivalent to $1 $2.

Example1: demo.sh

#!/bin/sh

echo "First Parameter : $1"echo "Second Parameter : $2"echo "Quoted Values: $@"echo "Quoted Values: $*"echo "Total Number of Parameters : $#"

execute: $sh demo.sh darothi sarkar

Page 11: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

First Parameter : darothiSecond Parameter : sarkarQuoted Values: darothi sarkarQuoted Values: darothi sarkarTotal Number of Parameters : 2

Example2: demo1.sh

#!/bin/bash

# Call this script with at least 3 parameters, for example# sh scriptname 1 2 3echo "first parameter is $1"echo "Second parameter is $2"echo "Third parameter is $3"exit 0

execute: $sh demo1.sh 10 20 30

first parameter is 10

Second parameter is 20Third parameter is 30

4. Shell variables: A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data.

For example, first we set a variable TEST and then we access its value using the echo command −

$TEST="Unix Programming"

$echo $TEST

It produces the following result.

Unix Programming

The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _).

By convention, Unix shell variables will have their names in UPPERCASE.

The following examples are valid variable names −

_ALI

TOKEN_AVAR_1VAR_2

Following are the examples of invalid variable names −

2_VAR-VARIABLEVAR1-VAR2

Page 12: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

VAR_A!

The reason you cannot use other characters such as !, *, or - is that these characters have a special meaning for the shell.

5. If else block:

Syntax

if [ expression 1 ]then Statement(s) to be executed if expression 1 is trueelif [ expression 2 ]then Statement(s) to be executed if expression 2 is trueelif [ expression 3 ]then Statement(s) to be executed if expression 3 is trueelse Statement(s) to be executed if no expression is truefi

Example

a=10

b=20

if [ $a == $b ]then echo "a is equal to b"elif [ $a -gt $b ]then echo "a is greater than b"elif [ $a -lt $b ]then echo "a is less than b"else echo "None of the condition met"fi

Assignment

1. Write a shell program to display the content of a file after reading the file.

2. Write a shell program to display the first three lines of a file.

3. Write a shell program to perform the swapping between two numbers taken from user during run time.

4. Write a shell program to print the largest among three numbers by passing the numbers through command line arguments.

Page 13: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

5. Write a shell program to display the following mark sheets of students by taking the input marks of student through the terminal Marks range Grade90>=M<=100 A70>=M<=89 B

40>=M<=69 C

M<40 F

Page 14: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Manual and Assignment for Operating System Lab (CS693)

Lab #4

Objectives

Essentials of shell programming:

1. Use of arithmetic expression.

Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example+ (Addition)

Adds values on either side of the operator`expr $a + $b` will give 30

- (Subtraction)

Subtracts right hand operand from left hand operand

`expr $a - $b` will give -10

* (Multiplication)

Multiplies values on either side of the operator`expr $a \* $b` will give 200

/ (Division)

Divides left hand operand by right hand operand`expr $b / $a` will give 2

% (Modulus)

Divides left hand operand by right hand operand and returns remainder

`expr $b % $a` will give 0

= (Assignment)

Assigns right operand in left operanda = $b would assign value of binto a

== (Equality)

Compares two numbers, if both are same then returns true.

[ $a == $b ] would return false.

!= (Not Equality)

Compares two numbers, if both are different then returns true.

[ $a != $b ] would return true.

It is very important to understand that all the conditional expressions should be insidesquare braces with spaces around them, for example [ $a == $b ] is correct whereas,[$a==$b] is incorrect.

Example:

a=10

b=20

val=`expr $a + $b`

Page 15: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

echo "a + b : $val"

val=`expr $a - $b`echo "a - b : $val"

val=`expr $a \* $b`echo "a * b : $val"

val=`expr $b / $a`echo "b / a : $val"

val=`expr $b % $a`echo "b % a : $val"

if [ $a == $b ]then echo "a is equal to b"fi

if [ $a != $b ]then echo "a is not equal to b”

fi

Output:

a + b : 30

a - b : -10a * b : 200b / a : 2b % a : 0a is not equal to b

2. Relational Operators.

The following operators do not work for string values unless their value is numeric.

For example, following operators will work to check a relation between 10 and 20 as well asin between "10" and "20" but not in between "ten" and "twenty".

Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example

-eqChecks if the value of two operands are equal or not; if yes, then the condition becomes true.

[ $a -eq $b ] is not true.

-neChecks if the value of two operands are equal or not; if valuesare not equal, then the condition becomes true.

[ $a -ne $b ] is true.

-gtChecks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true.

[ $a -gt $b ] is not true.

-lt Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true.

[ $a -lt $b ] is true.

Page 16: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

-geChecks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true.

[ $a -ge $b ] is not true.

-leChecks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true.

[ $a -le $b ] is true.

Example

a=10

b=20

if [ $a -eq $b ]then echo "$a -eq $b : a is equal to b"else echo "$a -eq $b: a is not equal to b"fi

if [ $a -ne $b ]then echo "$a -ne $b: a is not equal to b"else echo "$a -ne $b : a is equal to b"fi

if [ $a -gt $b ]then echo "$a -gt $b: a is greater than b"else echo "$a -gt $b: a is not greater than b"fi

if [ $a -lt $b ]then echo "$a -lt $b: a is less than b"else echo "$a -lt $b: a is not less than b"fi

if [ $a -ge $b ]then echo "$a -ge $b: a is greater or equal to b"else echo "$a -ge $b: a is not greater or equal to b"fi

if [ $a -le $b ]then echo "$a -le $b: a is less or equal to b"else echo "$a -le $b: a is not less or equal to b"fi

Output

10 -eq 20: a is not equal to b

10 -ne 20: a is not equal to b

Page 17: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

10 -gt 20: a is not greater than b10 -lt 20: a is less than b10 -ge 20: a is not greater or equal to b10 -le 20: a is less or equal to b

3. Boolean Operators

The following Boolean operators are supported by the Bourne Shell.

Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example

!This is logical negation. This inverts a true condition into false and vice versa.

[ ! false ] is true.

-oThis is logical OR. If one of the operands is true, then the condition becomes true.

[ $a -lt 20 -o $b -gt 100 ] is true.

-aThis is logical AND. If both the operands are true, then the condition becomes true otherwise false.

[ $a -lt 20 -a $b -gt 100 ] is false.

Example

a=10

b=20

if [ $a != $b ]then echo "$a != $b : a is not equal to b"else echo "$a != $b: a is equal to b"fi

if [ $a -lt 100 -a $b -gt 15 ]then echo "$a -lt 100 -a $b -gt 15 : returns true"else echo "$a -lt 100 -a $b -gt 15 : returns false"fi

if [ $a -lt 100 -o $b -gt 100 ]then echo "$a -lt 100 -o $b -gt 100 : returns true"else echo "$a -lt 100 -o $b -gt 100 : returns false"fi

if [ $a -lt 5 -o $b -gt 100 ]then echo "$a -lt 100 -o $b -gt 100 : returns true"else echo "$a -lt 100 -o $b -gt 100 : returns false"

fi

Page 18: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Output

10 != 20 : a is not equal to b

10 -lt 100 -a 20 -gt 15 : returns true10 -lt 100 -o 20 -gt 100 : returns true10 -lt 5 -o 20 -gt 100 : returns false

4. Use of for loop.

The for loop operates on lists of items. It repeats a set of commands for every item in a list.

Syntax:

for var in 0 1 2 3 4 5

do echo $vardone

Output:

0

1

2

3

4

5

The above code can be written like this-

for var in `seq 0 5`

do echo $var

done

The above code can also be written like this-

j=”0 1 2 3 4 5”

for var in $j

do echo $var

done

5. Use of while loop.

Page 19: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

The while loop enables you to execute a set of commands repeatedly until some condition occurs. Each while loop consists of a set of commands and a condition. The general syntax as follows for bash while loop:

Syntax

while [ condition ]

do command1 command2 commandN

done

Example

a=0

while [ $a -lt 5 ]do echo $a a=`expr $a + 1`done

Output:

0

1

2

3

4

5

6. Use of switch case.

The case statement is good alternative to multilevel if-then-else-fi statement. It enable you tomatch several values against one variable. It is easier to read and write.

Syntax

case $variable-name in

pattern1) command1 ... .... commandN ;; pattern2)

Page 20: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

command1 ... .... commandN ;; patternN) command1 ... .... commandN ;; *) esac

Or

case $variable-name in

pattern1|pattern2|pattern3) command1 ... .... commandN ;; pattern4|pattern5|pattern6) command1 ... .... commandN ;; pattern7|pattern8|patternN) command1 ... .... commandN ;; *) esac

Example

FRUIT="kiwi"

case "$FRUIT" in "apple") echo "Apple pie is quite tasty." ;; "banana") echo "I like banana nut bread." ;; "kiwi") echo "New Zealand is famous for kiwi." ;;esac

Output

New Zealand is famous for kiwi.

Page 21: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Example

echo "Please talk to me ..."

while :do read INPUT_STRING case $INPUT_STRING in hello) echo "Hello yourself!" ;; bye) echo "See you again!" break ;; *) echo "Sorry, I don't understand" ;; esacdoneecho echo "That's all folks!"

Execution

Please talk to me ...

helloHello yourself!What do you think of politics?Sorry, I don't understandbyeSee you again!

That's all folks!

Assignment

1. Write a shell program to calculate the factorial of a number.

2. Write a shell menu driven program to do the following:

a. Display the current working directory.

b. Check whether an input number is even or odd.

c. Display the number of counts of all the files in the directory.

d. Print the long listing of all the files.

Page 22: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

3. Write a shell program to display all the prime numbers between 1 to 100 using while loop.

4. Write a menu program to find out whether a given letter is vowel or not.

5. Write a shell script which will generate the output as follows:

*

* *

* * *

* * * *

Page 23: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Manual and Assignment for Operating System Lab (CS693)

Lab #5

Objectives

Unix command (contd.)

$ls -l gives a long listing of file attributes. For example,

drwxr-xr-x 12 admin123 admin123 4096 Jun 15 2016 PacketTracer70x64

drwxr-xr-x 13 admin123 admin123 4096 Jun 15 2016 PacketTracer70x86

drwxr-xr-x 2 admin123 admin123 4096 Jan 7 00:16 Pictures

-rw-rw-r-- 1 admin123 admin123 18944 Feb 6 10:39 progression.xls

drwxrwxr-x 6 admin123 admin123 4096 Mar 11 16:51 pt

drwxr-xr-x 2 admin123 admin123 4096 Jan 7 00:16 Public

-rw-rw-r-- 1 admin123 admin123 123 Feb 28 15:21 swap1.sh

-rw-rw-r-- 1 admin123 admin123 156 Feb 28 15:34 swap2.sh

-rw-rw-r-- 1 admin123 admin123 144 Feb 28 14:35 swap.sh

drwxr-xr-x 2 admin123 admin123 4096 Jan 7 00:16 Templates

drwxr-xr-x 2 admin123 admin123 4096 Jan 7 00:16 Videos

drwxrwxr-x 3 admin123 admin123 4096 Jan 25 15:07 wx

The first column shows the permission given to different category of users. The first group is owner,the second group is group owner and the third group is others. The row started with – (hyphen) is anordinary file and the row started with d is a directory.

r- read permission

w- write permission

x- execution permission

Absence of any of these three means that particular permission is not given to that user.

chmod command:

This command is used to set the permission of one or more files for all these three categories of users. It can run only by the user and superuser.

Page 24: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Relative permission:

Using chmod in Symbolic Mode

S.No. Chmod operator & Description

1

+

Adds the designated permission(s) to a file or directory.

2

-

Removes the designated permission(s) from a file or directory.

3

=

Sets the designated permission(s).

Here's an example using testfile. Running ls -1 on the testfile shows that the file's permissions are asfollows −

$ls -l testfile-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile

Then each example chmod command from the preceding table is run on the testfile, followed by

ls –l, so you can see the permission changes −

1. $chmod o+wx testfile

2. $ls -l testfile

-rwxrwxrwx 1 amrood users 1024 Nov 2 00:10 testfile

3. $chmod u-x testfile

4. $ls -l testfile

-rw-rwxrwx 1 amrood users 1024 Nov 2 00:10 testfile

5. $chmod g = rx testfile

6. $ls -l testfile

-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile

Here's how you can combine these commands on a single line −

$chmod o+wx,u-x,g = rx testfile

$ls -l testfile

-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile

Page 25: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Absolute permission:

The second way to modify permissions with the chmod command is to use a number to specify eachset of permissions for the file.

Number Octal Permission Representation Ref0 No permission ---1 Execute permission --x2 Write permission -w-3 Execute and write permission: 1 (execute) + 2 (write) = 3 -wx4 Read permission r--5 Read and execute permission: 4 (read) + 1 (execute) = 5 r-x6 Read and write permission: 4 (read) + 2 (write) = 6 rw-7 All permissions: 4 (read) + 2 (write) + 1 (execute) = 7 rwx

Here's an example using the testfile. Running ls -1 on the testfile shows that the file's permissions are as follows −

$ls -l testfile

-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile

Then each example chmod command from the preceding table is run on the testfile, followed by

ls –l, so you can see the permission changes −

1. $ chmod 755 testfile

2. $ls -l testfile

-rwxr-xr-x 1 amrood users 1024 Nov 2 00:10 testfile

3. $chmod 743 testfile

$ls -l testfile

-rwxr---wx 1 amrood users 1024 Nov 2 00:10 testfile

$chmod 043 testfile

$ls -l testfile

----r---wx 1 amrood users 1024 Nov 2 00:10 testfile

Assignment:

1. Determine if a file exists or not using and without using test command.

[Hint: The test command is used to evaluate a condition, commonly called an expression, todetermine whether it is true or false and then will exit with a status (return code) indicating the

Page 26: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

same. If the outcome of the expression is true, a zero ("0") is returned. When the expression is false,the exit status will be one ("1"). ]

2. Compare two strings using test command.

3. Write a shell script to find out the sum of the digits of a number.

4. Write a shell script to print the reverse of a given number.

5. Write a shell script that accepts two integers as its arguments and computers the value of first number raised to the power of the second number.

6. Write a shell script that computes the gross salary of a employee according to the following rules:

i)If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the basic.ii)If basic salary is >=1500 then HRA =Rs500and DA=98% of the basicThe basic salary is entered interactively through the key board.

Page 27: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Manual and Assignment for Operating System Lab (CS693)

Lab #6

Objectives

1. Process Creation- System call fork() is used to create processes. It takes no arguments andreturns a process ID. The purpose of fork() is to create a new process, which becomes the childprocess of the caller. After a new child process is created, both processes will execute the nextinstruction following the fork() system call. Therefore, we have to distinguish the parent from thechild. This can be done by testing the returned value of fork():

• If fork() returns a negative value, the creation of a child process was unsuccessful.

• fork() returns a zero to the newly created child process.

• fork() returns a positive value, the process ID of the child process, to the parent. The

returned process ID is of type pid_t defined in sys/types.h. Normally, the process ID is an

integer. Moreover, a process can use function getpid() to retrieve the process ID assigned tothis process.

#include <stdio.h>

#include <string.h>#include <sys/types.h>

void main(void)

{ pid_t pid;

pid = fork(); if (pid == 0) ChildProcess(); else ParentProcess();}

2. CPU Scheduling

• FCFS: First-Come-First-Served algorithm is the simplest scheduling algorithm. Processes

are dispatched according to their arrival time on the ready queue. Being a nonpreemptivediscipline, once a process has a CPU, it runs to completion.

Process Burst Time

P1 24

P2 3

P3 3

Page 28: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

P1 P2 P30 24 27 30

Waiting time for P1=0, P2= 24, P3=27

Turnaround time for P1=24, P2= 27, P3=30

• SJF: Ready queue is treated as a priority queue based on smallest CPU time requirement

Priorities are assigned in inverse order of time needed for completion of the entire job If equal time of completion, then FCFS is used for assigning priority. Arriving jobs inserted at proper position in queue Dispatcher selects shortest job (1st in queue) and runs to completion

Gives minimum average waiting time for a given set of processes. Minimizes average turnaround time.

Process Burst Time

P1 24

P2 3

P3 3

P2 P3 P1 0 3 6 30

Waiting time for P1=6, P2= 0, P3=3

Turnaround time for P1=30, P2= 3, P3=6

Assignment:

1. Create a process and distinguish the parent from child.

[Hint: In this program, both processes will print lines that indicate (1) whether the line is printedby the child or by the parent process ]

void ParentProcess(void)

{ int i;

for (i = 1; i <= MAX_COUNT; i++) printf("This line is from parent, value = %d\n", i); printf("*** Parent is done ***\n");}

2. Write a program to implement the FCFS scheduling algorithm.

Page 29: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Algorithm:

• Start the process

• Declare the array size

• Get the number of processes to be inserted

• Get the value

• Start with the first process from it’s initial position let other process to be in queue

• Calculate the total number of burst time

• Display the values

• Stop the process

Test case:Input:No of processes: 4Burst time: 4 9 8 3Arrival Time: 0 2 4 3

Output:

process waiting time turn arround time

p0 0 4

p1 2 11

p2 9 17

p3 18 21

the average waiting time is 7.250000

the average turn around time is 13.250000

3. Write a program to implement the SJF scheduling algorithm.

Test case:

Input

No of processes: 4

Burst time: 4 9 8 3

Page 30: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Output:

process waiting time turn arround time

p0 3 7

p1 15 24

p2 7 15

p3 0 3

the average waiting time is 6.250000

the average turn around time is 12.250000

Page 31: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Manual and Assignment for Operating System Lab (CS693)

Lab #7

Objectives

CPU Scheduling (contd..)

Priority Scheduling: Each process is assigned a priority. Process with highest priority is to

be executed first and so on. Processes with same priority are executed on first come firstserved basis. Priority can be decided based on memory requirements, time requirements orany other resource requirement.

Process Burst Time Priority

P1 10 3

P2 1 1

P3 2 4

P4 1 5

P5 5 2

P2 P5 P1 P3 P4

0 1 6 16 18 19

Waiting time for P1=6, P2= 0, P3=16, P4=18, P5=1

Turnaround time for P1=16, P2= 1, P3=18, P4=19, P5=6

Round Robin Scheduling: Round Robin is the preemptive process scheduling algorithm.

Each process is provided a fix time to execute, it is called a quantum. Once a process isexecuted for a given time period, it is preempted and other process executes for a given timeperiod. Context switching is used to save states of preempted processes.

Process Burst Time

P1 24

P2 3

P3 3

Quantum: 4ms

P1 P2 P3 P1 P1 P1 P1 P10 4 7 10 14 18 22 26 30

Page 32: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Waiting time for P1=0+(10-4)=6, P2= 4, P3=7

Turnaround time for P1=30, P2= 7, P3=10

Assignment:

1. Write a program to implement the Priority Scheduling scheduling algorithm. Use the example given in the manual as your test case.

2. Write a program to implement the Round robin scheduling algorithm. Use the example given in the manual as your test case.

Page 33: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Manual and Assignment for Operating System Lab (CS693)

Lab #8

Objectives

Creation of Process

The system( ) function is a library function. It is constructed from the system calls

execl(), fork() and wait().

The entire process life cycle is built around four system calls.

1. execl()

2. fork()

3. wait()

4. exit()

1. execl ()

It is used to run a command within a C program. Syntax : int execl (path, Arg 0, Arg 1, Arg2, ....,0); The path argument is the name of the file holding the command we wish to run. Arg 0 is thename of the command. and Arg1 ,Arg2, Arg3,...are the list of arguments required for thatparticular command. 0 is used to mark the end of the argument list. Example : # include < stdio.h> main() { printf(“ Here comes the data : \n”) execl(“/bin/date” , “date”, 0); printf (“Hello”); } Here execl() overlays the original program with the call ed program, and the called program becomes the program of record. In terms of processes, the summoned command has thesame ID that the calling program has before it was overlaid. In other words, the processremains the same, but the program instructions in the process are replaced.

2. fork ()

fork() is used to create a new process. Syntax: pid_t fork(void); Fork creates an exact replica of parent ( calling )process. After fork returns, the parentprocess and child process now have different PIDs.

Page 34: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Example :

# include <stdio.h> main()

{ int pid; pid = fork(); if ( pid == 0) { // this is the child process; } else { // This is the Parent process.

}}

3. wait()This function blocks the calling process until one of its child processes exits.

Syntax : int wait ( int * status); The function returns the process identification number of the terminated processes. Further

information concerning the terminated process is writte n into the location whose address is supplied as the function parameter. One of the main purposes of wait() is to wait forcompletion of child processes.

4. exit()The system call exit() is used to terminate the current process. The system call wait() is usedwhen a process wishes to wait until a child process terminates and determine the exit code ofthe child process.

• Zombi Process

When a process dies on Linux, it isn’t all removed from memory immediately — its processdescriptor stays in memory (the process descriptor only takes a tiny amount of memory). Theprocess’s status becomes EXIT_ZOMBIE and the process’s parent is notified that its childprocess has died with the SIGCHLD signal. The parent process is then supposed to executethe wait() system call to read the dead process’s exit status and other information. This allowsthe parent process to get information from the dead process. After wait() is called, the zombieprocess is completely removed from memory.

This normally happens very quickly, so you won’t see zombie processes accumulating on yoursystem. However, if a parent process isn’t programmed properly and never calls wait(), itszombie children will stick around in memory until they’re cleaned up.

Run “ps aux” and look for a Z in the STAT column.

• Orphan Process

Page 35: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

A process whose parent process no more exists i.e. either finished or terminated withoutwaiting for its child process to terminate is called an orphan process i.e. the parent finishesexecution and exits while the child process is still executing.

Assignment:

1. Write a C program to create a child process and allow the parent to display “parent” and the childto display “child” on the screen.

2. Write a C program to create a Zombie process.

3. Write a C program that illustrates how an orphan is created.

Page 36: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

Manual and Project Assignment for Operating System Lab (CS693)

Lab #9

Objectives: Banker’s Algorithm

Consider a system consisting 5 processes and 3 resource types R1 (with 15), R2 (with 8) and R3 (with 8 instances).

Process Max Allocation

R1 R2 R3 R1 R2 R3

P0 5 6 3 2 1 0

P1 8 5 6 3 2 3

P2 4 8 2 3 0 2

P3 7 4 3 3 2 0

P4 4 3 3 1 0 1

Find the Available matrix and Need matrix. Whether the system is in safe state or not? If yes, display the safe sequence.

Suppose P4 now requests [2 0 2].Whether the request will be granted or rejected?Your program should respond by granting or rejecting each request. Program output should appear as follows:

Grant request 1 or Deny request 1 Output:Available matrix

Resources

R1 R2 R3

3 3 2

Need MatrixProcess Resources

R1 R2 R3

P0 3 5 3

P1 5 3 3

P2 1 8 0

P3 4 2 3

P4 3 3 2

Page 37: OPERATING SYSTEM LAB CS693 MANUAL & ASSIGNMENT · Manual and Assignment for Operating System Lab (CS693) Lab # 3: Objectives Essentials of shell programming 1.vi editor: There are

The safe sequence <P4 P3 P0 P1 P2>Deny request 1

Implementation:n= Number of processesm= Number of resources

Data Structure:Available[j]: The number of instances currently available for resource type j.Max[i, j]: The maximum number of instances of resource j that process i can request at any

given time.Allocation [i, j]: Process i currently holds the instatnces of resource j.Need [i, j]: Process i may need additional instances of resource j.