Laboratory Manual Operating System Design Lab Third Year - IT Teaching Scheme Examination Scheme Theory : —— Term Work: 25 Marks Practical : 4 Hrs/Week/batch Practical : 50 Marks Oral : —— Prepared By Prof. Dinesh A. Zende Department of Information Technology Vidya Pratishthan’s College of Engineering Baramati – 413133, Dist- Pune (M.S.) INDIA June 2013 Contents 1 Shell Programming (Handling Student Database) 1.1 Problem Statement . . . . . . . . . . . . . . . . . . . . 1.2 Pre Lab . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2.1 Basic UNIX commands . . . . . . . . . . . . . 1.2.2 Loop and conditional statements in Shell Script 1.3 Procedure . . . . . . . . . . . . . . . . . . . . . . . . . 1.3.1 Algorithm . . . . . . . . . . . . . . . . . . . . . 1.4 Post Lab . . . . . . . . . . . . . . . . . . . . . . . . . . 1.5 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 1 1 3 5 5 7 7 2 Shell Programming (Mathematical Operations) 2.1 Problem Statement . . . . . . . . . . . . . . . . . 2.2 Pre Lab . . . . . . . . . . . . . . . . . . . . . . . 2.3 Procedure . . . . . . . . . . . . . . . . . . . . . . 2.3.1 Algorithms . . . . . . . . . . . . . . . . . 2.4 Post Lab . . . . . . . . . . . . . . . . . . . . . . . 2.5 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 8 8 9 9 12 12 3 Shell Programming (Command Line Parameters) 3.1 Problem Statement . . . . . . . . . . . . . . . . . . 3.2 Theory . . . . . . . . . . . . . . . . . . . . . . . . . 3.3 Pre Lab . . . . . . . . . . . . . . . . . . . . . . . . 3.4 Procedure . . . . . . . . . . . . . . . . . . . . . . . 3.4.1 Algorithms . . . . . . . . . . . . . . . . . . 3.5 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 13 13 14 14 14 15 4 AWK Programming(Handling Student Database) 4.1 Problem Statement . . . . . . . . . . . . . . . . . . . 4.2 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3 Pre Lab . . . . . . . . . . . . . . . . . . . . . . . . . 4.3.1 Examples of AWK one-liners . . . . . . . . . 4.3.2 Pattern Matching . . . . . . . . . . . . . . . . 4.3.3 Matching against the particular field . . . . . 4.3.4 Control and Loop Statements . . . . . . . . . 4.4 Procedure . . . . . . . . . . . . . . . . . . . . . . . . 4.4.1 Algorithms . . . . . . . . . . . . . . . . . . . 4.5 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 16 16 17 17 17 17 18 21 21 21 i CONTENTS CONTENTS 5 AWK Programming (Mathematical 5.1 Problem Statement . . . . . . . . . 5.2 Pre Lab . . . . . . . . . . . . . . . 5.3 Procedure . . . . . . . . . . . . . . 5.3.1 Algorithm . . . . . . . . . . 5.4 Viva Questions . . . . . . . . . . . Operations) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 22 22 22 22 23 6 UNIX Process control 6.1 Problem Statement . . . . . . . . . . . . . 6.2 Theory . . . . . . . . . . . . . . . . . . . . 6.2.1 Process Creation . . . . . . . . . . 6.2.2 Orphan and Zombie Process State 6.3 Pre Lab . . . . . . . . . . . . . . . . . . . 6.4 Procedure . . . . . . . . . . . . . . . . . . 6.4.1 Algorithms . . . . . . . . . . . . . 6.5 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 24 24 24 27 31 31 31 33 7 CPU scheduling Algorithms 7.1 Problem Statement . . . . . . . . 7.2 Theory: . . . . . . . . . . . . . . 7.2.1 First-Come, First-Served. 7.2.2 Shortest-Job-First (SJF) 7.2.3 Priority Scheduling. . . . 7.2.4 Round-robin (RR):- . . . 7.3 Post Lab: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 34 34 35 38 40 41 42 8 Memory allocation algorithms 8.1 Problem Statement: . . . . . 8.2 Theory: . . . . . . . . . . . . 8.2.1 Best Fit . . . . . . . 8.2.2 Worst Fit . . . . . . . 8.2.3 First Fit . . . . . . . 8.2.4 Next Fit . . . . . . . 8.3 Post Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 43 43 44 45 45 46 46 9 Page Replacement Algorithms 9.1 Problem Statement . . . . . . 9.2 Pre Lab: . . . . . . . . . . . . 9.3 Theory . . . . . . . . . . . . . 9.4 Post Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 47 47 47 50 10 Bankers Algorithm 10.1 Problem Statement . . . . . . . . . . . . 10.2 Pre Lab: . . . . . . . . . . . . . . . . . . 10.3 Theory . . . . . . . . . . . . . . . . . . . 10.3.1 Resources . . . . . . . . . . . . . 10.3.2 Example . . . . . . . . . . . . . . 10.3.3 Safe and Unsafe States . . . . . . 10.3.4 Pseudocode (Bankers Algorithm) 10.3.5 Example . . . . . . . . . . . . . . 10.3.6 Requests . . . . . . . . . . . . . . 10.4 Post Lab: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 51 51 51 51 52 53 53 54 54 55 ii CONTENTS CONTENTS 11 Dining Philosophers Problem 11.1 Problem Statement . . . . . . . . . . . . 11.2 Prelab: . . . . . . . . . . . . . . . . . . . . 11.3 Theory . . . . . . . . . . . . . . . . . . . . 11.3.1 Functions used with their syntax : 11.4 Post Lab: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 56 56 56 57 58 12 Inter Process Communication 12.1 Problem Statement . . . . . . . . . . 12.2 Pre Lab: . . . . . . . . . . . . . . . . 12.3 Theory . . . . . . . . . . . . . . . . . 12.3.1 Process . . . . . . . . . . . . 12.3.2 Process States: . . . . . . . . 12.3.3 Inter-process Communication: 12.3.4 Messages: . . . . . . . . . . . 12.4 Post Lab: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 59 59 59 59 60 61 61 62 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Linux kernel 2.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 63 63 63 63 64 66 13 Linux Kernel compilation 13.1 Problem Statement . . . 13.2 Prelab . . . . . . . . . . 13.3 Theory . . . . . . . . . . 13.3.1 How to: Compile 13.3.2 Commands . . . 13.4 PostLab . . . . . . . . . . . . . . . . . . . . . . . . . iii Assignment 1 Shell Programming (Handling Student Database) 1.1 Problem Statement Write a program to handle student data base with options given below, 1. Create data base. 2. View Data Base. 3. Insert a record. 4. Delete a record. 5. Modify a record. 6. Result of a particular student. 7. Exit. 1.2 1.2.1 Pre Lab Basic UNIX commands • ls Command 1 1.2. PRE LAB Shell Programming (Handling Student Database) -a list hidden files -d list the name of the current directory -F show directories with a trailing ’/’ executable files with a trailing ’*’ -g show group ownership of file in long listing -i print the inode number of each file -l long listing giving details about files and directories -R list all subdirectories encountered -t sort by time modified instead of name • more Command - shows the first part of a file, just as much as will fit on one screen. Just hit the space bar to see more or q to quit. You can use /pattern to search for a pattern. • mv Command Syntax mv [-f] [-i] oldname newname Renames a file or moves it from one directory to another directory. -f mv will move the file(s) without prompting even if it is writing over an existing target. Note that this is the default if the standard input is not a terminal. -i Prompts before overwriting another file. oldname The oldname of the file renaming. newname The newname of the file renaming. filename The name of the file you want to move directory e.g. $ mv file1 file2 - Renames file file1 with file2 $ mv \dir1\file1 \dir2\file1 - Moves file file1 from dir1 to dir2 • cp command - Copies a file into another one. Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 2 VPCOE, Baramati 1.2. PRE LAB Shell Programming (Handling Student Database) • rm filename - removes a file. It is wise to use the option rm -i, which will ask you for confirmation before actually deleting anything. You can make this your default by making an alias in your .cshrc file. • diff filename1 filename2 - compares files, and shows where they differ • wc filename - tells you how many lines, words, and characters there are in a file • chmod options filename- lets you change the read, write, and execute permissions on your files. The default is that only you can look at them and change them, but you may sometimes want to change these permissions. For example, chmod o+r filename will make the file readable for everyone, and chmod o-r filename will make it unreadable for others again. Note that for someone to be able to actually look at the file the directories it is in need to be at least executable. • mkdir dirname- make a new directory. • cd dirname - change directory. • pwd- tells you where you currently are. 1.2.2 Loop and conditional statements in Shell Script • if- Used to execute one or more statements on a condition. A Syntax: if [ $expr <RO> Value ] then <if body> else <else body> fi The Relational Operators are as follows -gt Is Greater than Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 3 VPCOE, Baramati 1.2. PRE LAB Shell Programming (Handling Student Database) -ge Is Greater than or equal to -lt Is Less than -le Is less than or equal to -ne Is not equal to -eq Is equal to • case - Used to execute specific commands based on the value of a variable. A Syntax: case $EXPR in 1) <expr1 body> ;; 2) <expr2 body> ;; *) <default body> ;; esac • for - Used to loop for all cases of a condition. for word in myfile echo $word done The above will print all of the words in file myfile on a new line. • until - Cycles through a loop until some condition is met. The syntax for the command is shown below: until [$expression ] do Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 4 VPCOE, Baramati 1.3. PROCEDURE Shell Programming (Handling Student Database) statements<body> done • while - Cycles through a loop while some condition is met. The below example will cycle through a loop forever: while [ $expression ] do statement(s) done 1.3 Procedure 1.3.1 Algorithm 1. Display menu in one of the function. 2. Ask user to enter choice. 3. Depending on the choice of the user perform the required action by calling a userdefined function. (Note- make use of case-esac statement) 4. Choice-1: Create Database (a) Ask user to enter name of the database. (b) Check if it is available in the current working directory. (c) If yes then prompt the user about it and exit. (d) If not then create database using touch command. 5. Choice-2: View Database (a) Ask user to enter name of the database. (b) Check if it is available in the current working directory. (c) If yes then display the contents using cat command. (d) If not then prompt the user about it and exit. Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 5 VPCOE, Baramati 1.3. PROCEDURE Shell Programming (Handling Student Database) 6. Choice-3: Insert Record (a) Ask user to enter name of the database. (b) Check if it is available in the current working directory. (c) If yes then, i. Ask the user to enter a roll number. ii. Check if roll number is present in the file. iii. If yes then prompt the user and exit. iv. If no then ask the other details and insert the record by using cat command. (d) If not then prompt the user about it and exit. 7. Choice-4: Delete Record (a) Ask user to enter name of the database (b) Check if it is available in the current working directory (c) If yes then, i. Ask the user to enter a roll number ii. Check if roll number is present in the file iii. If yes then delete record using sed command iv. If not then prompt the user about it and exit (d) If not then prompt the user about it and exit 8. Choice-5: Modify a Record (a) Ask user to enter name of the database (b) Check if it is available in the current working directory (c) If yes then i. Ask the user to enter a roll number ii. Check if roll number is present in the file iii. If yes then display the contents of the record iv. Ask user about the modified values of the record Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 6 VPCOE, Baramati 1.4. POST LAB Shell Programming (Handling Student Database) v. Replace the existing record with the modified value using sed command. vi. If not then prompt the user about it and exit (d) If not then prompt the user about it and exit 9. Choice-6: View result of a particular record (a) Ask user to enter name of the database (b) Check if it is available in the current working directory (c) If yes then i. Ask the user to enter a roll number ii. Check if roll number is present in the file iii. If yes then display the contents of the record iv. If not then prompt the user about it and exit (d) If not then prompt the user about it and exit 1.4 Post Lab Assume Employee database with following attributes Employee(EmpNo,Name,Age,Sex,Dept,Salary). You can implement the same problem statement for Employee database. 1.5 Viva Questions • Understanding of UNIX Operating System Structure. • Understanding of Shell Programming Concepts. • Understanding of File handling operations and commands. Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 7 VPCOE, Baramati Assignment 2 Shell Programming (Mathematical Operations) 2.1 Problem Statement Write a menu driven program for 1. Find factorial of a no. 2. Find greatest of three numbers 3. Find a prime no 4. Find whether a number is palindrome 5. Find whether a string is palindrome 2.2 Pre Lab Basic linux commands studied in Assignment no. 01 8 2.3. PROCEDURE 2.3 Procedure 2.3.1 Algorithms Shell Programming (Mathematical Operations) Factorial of a number 1: procedure Factorial(n) 2: f act ← 1 3: while n ≥ 1 do 4: f act ← f act ∗ n 5: n←n−1 6: end while 7: return f act 8: end procedure Input: num=5 Output: 120 Input: num=6 Output: 720 Input: num=1 Output: 1 . Returns Factorial of a number Greatest Among Three 1: 2: procedure Greatest(a, b, c) if (a > b( then 3: if (a > c) then 4: return a 5: else return c 6: 7: 8: end if else 9: if (b > c) then 10: return b 11: 12: 13: . Returns Greatest among a,b,c else return c end if Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 9 VPCOE, Baramati 2.3. PROCEDURE 14: 15: Shell Programming (Mathematical Operations) end if end procedure Sample Inputs and outputs Input: a=2 b=4 c=6 Output: 6 Input: a=2 b=8 c=6 Output: 8 Input: a=9 b=4 c=6 Output: 9 Number Palindrome 1: procedure NumberPalindrome(n) 2: tnum ← n 3: while n ≥ 0 do . Returns True or False 4: reminder ← n mod 10 5: reverse ← reverse ∗ 10 + reminder 6: n ← n/10 7: end while 8: if (reverse = tnum) then 9: 10: 11: 12: 13: return T rue else return F alse end if end procedure Sample Inputs and outputs Input: num=123 Output: False Input: num=313 Output: True Input: num=54345 Output: True Prime Number 1: 2: procedure Prime Number(n) . Returns True or False F lag ← T rue Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 10 VPCOE, Baramati 2.3. PROCEDURE 3: Divisor ← 2 4: while 2 ≤ n do Shell Programming (Mathematical Operations) 5: reminder ← n mod Divisor 6: if (reminder = 0) then 7: F lag ← F alse 8: Break 9: 10: end if Divisor ← Divisor + 1 11: end while 12: if (F lag = T rue) then 13: 14: 15: 16: 17: return T rue . Prime Number else return F alse . Not a Prime end if end procedure Sample Inputs and outputs Input: num=15 Output: False Input: num=7 Output: True Input: num=31 Output: True String Palindrome 1: procedure StringPalindrome(str) 2: length1 ← Length(str) 3: while n ≥ 1 do 4: ch ← substr(str, ch, 1) 5: str2 ← Concate(str2, ch) 6: length1 ← lengh1 − 1 7: end while 8: if (str1 = str2) then 9: return T rue Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course . Returns True or False 11 VPCOE, Baramati 2.4. POST LAB else 10: return F alse 11: end if 12: 13: Shell Programming (Mathematical Operations) end procedure Sample Inputs and outputs Input: num="vpcoe" Output: False Input: num="NITIN" Output: True Input: num="MADAM" Output: True 2.4 Post Lab Write a program to print all prime numbers up to a limit. For Example if limit is given as 20 then it should print 2,3,5,7,11,13,17,19 2.5 Viva Questions • Understanding of UNIX Operating System Structure. • Understanding of Shell Programming Concepts. • Understanding of various mathematical operations. Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 12 VPCOE, Baramati Assignment 3 Shell Programming (Command Line Parameters) 3.1 Problem Statement Write shell program using command-line argument for following menu 1. Finding biggest of three numbers 2. Reversing a number 3. Accept a number N and a word and print the word N times, one word per line 4. Sum of individual digits of a 4-digit number (1234 -¿ 1+2+3+4=10) 3.2 Theory Command line is one more way where scripts interact with their environment. Just as we can pass command-line options and arguments to commands, you can also pass these to shell scripts. Shell places the command-line arguments in special variables that we can access within our script. For example, the variable $1 holds the first item on the command line for our script. For example $ sh myShellScript one two three 13 3.3. PRE LAB Shell Programming (Command Line Parameters) Here, myShellScript is the name of the script whereas, one, two, three are the three arguments passed on the command line. Following table will give you an idea about special variable set Special Variable Description $0 Name of the script from the command line $1 First command-line argument $2 Second command-line argument Upto $9 upto ninth command line argument $# Number of command-line arguments $* All command-line arguments, separated with spaces 3.3 Pre Lab Basic linux commands studied in Assignment no. 01 3.4 Procedure 3.4.1 Algorithms Print a word n-times 1: procedure PrintWord(word, n) 2: while n ≥ 0 do 3: P rint W ord 4: n←n−1 5: 6: end while end procedure Sample Inputs on command line and outputs Input: N=3 WORD=VPCOE Output: VPCOE VPCOE Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 14 VPCOE, Baramati 3.5. VIVA QUESTIONS Shell Programming (Command Line Parameters) VPCOE Sum of Digits 1: procedure SumofDigits(n) 2: Sum ← 0 3: while n ≥ 0 do 4: reminder ← n mod 10 5: Sum ← Sum + reminder 6: n ← n/10 7: end while 8: return Sum 9: end procedure Sample Inputs on command line and outputs Input: num=1234 Output: 10 Input: num=1000 Output: 1 Input: num=5555 Output: 20 3.5 Viva Questions • Understanding of UNIX Operating System Structure. • Understanding of Shell Programming Concepts. • Understanding of Command Line parameter passing and its usage. Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 15 VPCOE, Baramati Assignment 4 AWK Programming(Handling Student Database) 4.1 Problem Statement Write a program to handle student data base with options given below, 1. Create data base. 2. View Data Base. 3. Insert a record. 4. Delete a record. 5. Modify a record. 6. Result of a particular student. 7. Exit. 4.2 Theory The name awk comes from the initials of its designers: Alfred V. Aho, Peter J. Weinberger, and Brian W. Kernighan. The original version of awk was written in 1977 at “AT&T Bell” Laboratories. In 1985 a new version made the programming language more 16 4.3. PRE LAB AWK Programming(Handling Student Database) powerful, introducing user-defined functions, multiple input streams, and computed regular expressions. This new version became generally available with Unix System V Release 3.1. The version in System V Release 4 added some new features and also cleaned up the behavior in some of the dark corners of the language. 4.3 4.3.1 Pre Lab Examples of AWK one-liners $ cat db01 11 zdinesh 92.2 12 ganesh 78.5 13 sameer 85.5 $ awk {print} db01 11 zdinesh 92.2 12 ganesh 78.5 13 sameer 85.5 $ awk {print $1} db01 11 12 13 4.3.2 Pattern Matching $awk /zdinesh/ {print} db01 11 zdinesh 92.2 4.3.3 Matching against the particular field $awk $1~/12/ { print } db01 12 ganesh 78.5 Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 17 VPCOE, Baramati 4.3. PRE LAB 4.3.4 AWK Programming(Handling Student Database) Control and Loop Statements • If-Then-Else if (condition) then body [else else-body] Example if (x % 2 == 0) print "x is even" else print "x is odd" OR if (x % 2 == 0) print "x is even"; else print "x is odd" • The while Statement while (condition) body Example awk ’{ i = 1 while (i <= 3) { print $i i++ } }’ student_db Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 18 VPCOE, Baramati 4.3. PRE LAB AWK Programming(Handling Student Database) • The do-while Statement do body while (condition) Examples: awk ’{ i = 1 do { print $0 i++ } while (i <= 10) }’ • The for Statement for (initialization; condition; increment) body Examples: awk ’{ for (i = 1; i <= 3; i++) print $i }’student_db • The break Statement Examples: awk ’# find smallest divisor of num { num = $1 for (div = 2; div*div <= num; div++) Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 19 VPCOE, Baramati 4.3. PRE LAB AWK Programming(Handling Student Database) if (num % div == 0) break if (num % div == 0) printf "Smallest divisor of %d is %d\n", num, div else printf "%d is prime\n", num }’ • The continue Statement Examples: BEGIN { while (getline > 0) { if (/^@ignore/) ignoring = 1 else if (/^@end[ \t]+ignore/) { ignoring = 0 continue } if (ignoring) continue print } } • Built-in Variables that Control awk FS Field Separator ---------------------------RS Record Separator Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 20 VPCOE, Baramati 4.4. PROCEDURE AWK Programming(Handling Student Database) NF Number of fields NR Number of records OFS Output Field Separator ORS Output Record Separator ARGC Argument Count ARGV Argument Value ( List of arguments) FILENAME name of the input file 4.4 Procedure 4.4.1 Algorithms Refer Section - Algorithm in Assignment No. 01 4.5 Viva Questions • Understanding of UNIX Operating System Structure. • Understanding of AWK Programming Concepts. • Understanding of File handling operations and commands in AWK Programming. Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 21 VPCOE, Baramati Assignment 5 AWK Programming (Mathematical Operations) 5.1 Problem Statement Write a menu driven program for 1. Find factorial of a no. 2. Find greatest of three numbers 3. Find a prime no 4. Find whether a number is palindrome 5. Find whether a string is palindrome 5.2 Pre Lab Refer Pre Lab Section of Assignment No -04 5.3 Procedure 5.3.1 Algorithm Refer Algorithm Section of Assignment No -02 22 5.4. VIVA QUESTIONS 5.4 AWK Programming (Mathematical Operations) Viva Questions • Understanding of UNIX Operating System Structure. • Understanding of AWK Programming Concepts. • Understanding of various mathematical operations in AWK Programming. Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 23 VPCOE, Baramati Assignment 6 UNIX Process control 6.1 Problem Statement Part-A Write a Program where parent process sorts array elements in descending order and child process sorts array elements in ascending order. Part-B Write a Program where parent process count number of vowels in given sentence and child process counts no of words in same sentence. It should use UNIX calls like fork, exec and wait. And also show the orphan and zombie states 6.2 6.2.1 Theory Process Creation A “parent process” is a process that has created one or more child processes.In UNIX, every process except process 0 (the swapper) is created when another process executes the fork system call. The process that invoked fork is the parent process and the newlycreated process is the “child process”. Every process (except process 0) has one parent process, but can have many child processes. The kernel identifies each process by its process identifier (PID). Process 0 is a special process that is created when the system boots; after forking a child process (process 1), process 0 becomes the swapper process. Process 1, known as init, is the ancestor of every 24 6.2. THEORY UNIX Process control other process in the system. When a child process terminates execution, either by calling the exit system call, causing a fatal execution error, or receiving a terminating signal, an exit status is returned to the operating system. The parent process is informed of its child’s termination through a SIGCHLD signal. A parent will typically retrieve its child’s exit status by calling the wait system call. However, if a parent does not do so, the child process becomes a “zombie process.” Following table illustrates various process system calls. General Class Specific Class System Call Process Related Calls Process Creation and Termination exec() fork() wait() exit() Process Owner and Group getuid() geteuid() getgid() getegid() Process Identity getpid() getppid() Process Control signal() kill() alarm() Change Working Directory chdir() The fork() System Call fork - create a child process Synopsis: #include <unistd.h> pid_t fork(void); Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 25 VPCOE, Baramati 6.2. THEORY UNIX Process control Retrun Value: On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately. Description: fork() creates a new process by duplicating the calling process. The new process, referred to as the child, is an exact duplicate of the calling process, referred to as the parent, except for the following points: • The child has its own unique process ID, and this PID does not match the ID of any existing process group. • The child’s parent process ID is the same as the parent’s process ID. • The termination signal of the child is always SIGCHLD. • The child does not inherit timers from its parent. • The child does not inherit semaphore adjustments from its parent. • The child’s set of pending signals is initially empty. Example: #include <stdio.h> #include <string.h> #include <sys/types.h> void main(void) { int retPID; retPID = fork() if(retPID == -1) /*Error*/ { Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 26 VPCOE, Baramati 6.2. THEORY UNIX Process control printf("\n Can not create processes"); exit(0); } /*Process is created*/ else if(retPID == 0) { printf("\n I am in Parent Process"); } else if(retPID == 1) { printf("\n I am in Child Process"); } } 6.2.2 Orphan and Zombie Process State Zombie Processes On Unix and Unix-like computer operating systems, a “zombie process” or defunct process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the parent process to read its child’s exit status. The term zombie process derives from the common definition of zombie an undead person. When a process ends, all of the memory and resources associated with it are deallocated so they can be used by other processes. However, the process’s entry in the process table remains. The parent can read the child’s exit status by executing the wait system call, whereupon the zombie is removed. Demonstration of Zombie State /* Program zombie.c */ #include <stdio.h> #include <stdlib.h> Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 27 VPCOE, Baramati 6.2. THEORY UNIX Process control #include <sys/types.h> int main() { int childpid; /* Create a child process */ childpid = fork(); if(childpid > 0 ) { /* Parent Process */ /* Sleep Process for 60 Seconds */ /* Parent is not waiting for child to terminate */ sleep(60); } else { /*childpid==0*/ /* Child Process */ exit(0); } return 0; } Compile and Run C program $ cc zombie.c $ ./a.out & List the processes $ ps - l OR $ ps -o stat,pid,ppid,cmd Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 28 VPCOE, Baramati 6.2. THEORY PPID UNIX Process control PID STAT CMD -------------------------------------------------------3434 3478 S -bash 3478 3974 S ./a.out 3974 3975 Z [a.out] <defunct> 3478 3982 R+ ps -o ppid,pid,stat,cmd Note:- The Process with status as Z or marked as ¡defunct¿ i.e., de-functioning is ZOMBIE Process. Orphan Processes An “orphan process” is a computer process whose parent process has finished or terminated, though it remains running itself. In a Unix-like operating system any orphaned process will be immediately adopted by the special init system process. This operation is called re-parenting and occurs automatically. Even though technically the process has the “init” process as its parent, it is still called an orphan process since the process that originally created it no longer exists. A process can be orphaned unintentionally, such as when the parent process terminates or crashes. DEMONSTRATION OF ORPHAN PROCESSES /* Program orphan.c */ #include<stdio.h> #include<stdlib.h> #include<sys/types.h> int main(){ int child_pid; child_pid = fork(); if(child_pid>0){ /* Parent Process waiting for child to terminate */ Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 29 VPCOE, Baramati 6.2. THEORY UNIX Process control wait(NULL); while(1); } else { /* Child Process, executing forever */ while(1); } return 0; } Compile and Run C program $ cc orphan.c $ ./a.out & List the processes $ ps -o stat,pid,ppid,cmd PPID PID STAT CMD -------------------------------------------------------2681 2677 S -bash 2754 2681 S ./a.out <---PARENT PROCESS 2755 2754 R ./a.out <---CHILD PROCESS 2756 2681 R+ ps -o pid,ppid,stat,cmd Find the Parent and Child Process (For this look at the PPID Column) Kill the Parent Process, but the child is still executing, as parent had been killed the child process becomes the ORPHAN Process. You can see this by again listing out the processes. $ ps o stat,pid,ppid,cmd Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 30 VPCOE, Baramati 6.3. PRE LAB PID UNIX Process control PPID STAT CMD -------------------------------------------------------2681 2677 S -bash 2755 1 R ./a.out 2767 2681 R+ ps -o pid,ppid,stat,cmd <--Child Process(Orphaned) Note:-Look at the PPID of child. It is 1 means; it is the Process ID of the Kernel. The child is get adopted by the kernel. 6.3 Pre Lab • Basic UNIX Commands • C - Programming • Commands like fork(), exec() and wait() 6.4 Procedure 6.4.1 Algorithms Sorting of Arrays 1: procedure ArraySort(A[1..n]) 2: pid ← f ork() 3: if (pid == -1) then 4: 5: 6: Print failed to create processes else if (pid == 0) then 7: Print : In Child Process 8: Sort array in descending order 9: Display Array 10: 11: else Print : In Parent Process Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 31 VPCOE, Baramati 6.4. PROCEDURE UNIX Process control 12: Sort array in ascending order 13: Display Array 14: 15: 16: end if end if end procedure Sample input: Array: [ 1 4 5 2 3 6 9 7 8 0 ] Sample output: In child process Sorted array by child is: 0 1 2 3 4 5 6 7 8 9 In Parent process Sorted array by parent is: 9 8 7 6 5 4 3 2 1 0 Counting of Vowels and words 1: procedure VowelCount(Sentence) 2: pid ← f ork() 3: if (pid == -1) then 4: 5: 6: Print failed to create processes else if (pid == 0) then 7: Print : In Child Process 8: Count Words from the sentence. 9: Display Count 10: else 11: Print : In Parent Process 12: Count Vowels from the sentence. 13: Display Count 14: 15: end if end if Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 32 VPCOE, Baramati 6.5. VIVA QUESTIONS 16: UNIX Process control end procedure Sample input: I am studying in VPCOE Baramati. Sample output: In child process No of words=6 In Parent Process:: No of Vowels = 10 6.5 Viva Questions • Understanding of UNIX Operating System Structure. • Understanding of C Programming Concepts. • Understanding of Processes and Process Creation. • Knowledge of fork(), exec() and wait() System Calls. Lab Manual-Operating System Design Lab (T.E. - IT) 2008 Course 33 VPCOE, Baramati Assignment 7 CPU scheduling Algorithms 7.1 Problem Statement Write a program to implement Simulation of following CPU scheduling algorithms: 1. FCFS 2. SJF (preemptive and non-preemptive) 3. Priority Scheduling (preemptive and non-preemptive) 4. Round Robin Scheduling 7.2 Theory: What is CPU scheduling? Determining which processes run when there are multiple run able processes. It can have a big effect on resource utilization and the overall performance of the system. Basic assumptions behind most scheduling algorithms: • There is a pool of runnable processes contending for the CPU. • The processes are independent and compete for resources. • The job of the scheduler is to distribute the scarce resource of the CPU to the different processes ”fairly” According to some definition of fairness) and in a way that optimizes some performance criteria. In general, these assumptions are starting to break down. First of all, CPUs are not really that scarce 34 35 - almost everybody has several, and pretty soon people will be able to afford lots. Second, many applications are starting to be structured as multiple cooperating processes. So, a view of the scheduler as mediating between competing entities may be partially obsolete. How to evaluate scheduling algorithm? There are many possible criteria: • CPU Utilization: Keep CPU utilization as high as possible. (What is utilization, by the way?). • Throughput: number of processes completed per unit time. • Turnaround Time: mean time from submission to completion of process. • Waiting Time: Amount of time spent ready to run but not running. • Response Time: Time between submission of requests and first response to the request. • Scheduler Efficiency: The scheduler doesn’t perform any useful work, so any time it takes is pure overhead. So, need to make the scheduler very efficient 7.2.1 First-Come, First-Served. One ready queue, OS runs the process at head of queue; new processes come in at the end of the queue. A process does not give up CPU until it either terminates or performs IO. ” Consider performance of FCFS algorithm for three compute-bound processes. What if have 4 processes P1 (takes 24 seconds), P2 (takes 3 seconds) and P3 (takes 3 seconds). If arrive in order P1, P2, P3, what is • Waiting Time= (24 + 27) / 3 = 17 • Turnaround Time= (24 + 27 + 30) = 27. • Throughput= 30 / 3 = 10. What about if processes come in order P2, P3, P1, then • Waiting Time= (3 + 3) / 2 = 6 • Turnaround Time= (3 + 6 + 30) = 13. • Throughput= 30 / 3 = 10. 36 Algorithm Data: Processes 1 read no of processes n 2 Read process name and burst time for each process 3 calculate waiting time and turn around time for each process 4 waiting time[0]=0 5 turn arround time[0]=burst time[0] 6 while i< n do 7 waiting time[i]=waiting time[i-1] + burst time[i-1] 8 turn arround time[i]=waiting time[i]+burst time[i] 9 end 10 Calculate average waiting time and average turnaround time 11 Display output 12 Display Gantt chart 13 End Algorithm 1: First fit Sample input:- Enter no of processes=3 Enter process name and burst time for process 1:: A 3 Enter process name and burst time for process 2:: B 2 Enter process name and burst time for process 3:: C 4 Sample output:: Process Name A B C Burst time 3 2 4 Average waiting time=2.66 Average turnaround time=5.66 Gant Chart for process A: A A A Gant Chart for process B: - - - B B Gant Chart for process C: - - - - - C C C C waiting time 0 3 5 Turn around time 3 5 9 37 7.2.2 Shortest-Job-First (SJF) • It can eliminate some of the variance in Waiting and Turnaround time. In fact, it is optimal with respect to average waiting time. Big problem: how does scheduler figure out how long will it take the process to run? • Preemptive vs. Non-preemptive SJF scheduler. Preemptive scheduler reruns scheduling decision when process becomes ready. If the new process has priority over running process, the CPU preempts the running process and executes the new process. Non-preemptive scheduler only does scheduling decision when running process voluntarily gives up CPU. In effect, it allows every running process to finish its CPU burst. • Consider 4 processes P1 (burst time 8), P2 (burst time 4), P3 (burst time 9) P4 (burst time 5) that arrive one time unit apart in order P1, P2, P3, P4. Assume that after burst happens, process is not reenabled for a long time (at least 100, for example). What does a preemptive SJF scheduler do? What about a non-preemptive scheduler? Algoritham:Data: Processes 1 read no of processes n 2 Read process name and burst time for each process 3 sort the processes according to its burst time 4 calculate waiting time and turn around time for each process 5 waiting time[0]=0 6 turn arround time[0]=burst time[0] 7 while i<n do 8 waiting time[i]=waiting time[i-1] + burst time[i-1] 9 turn arround time[i]=waiting time[i]+burst time[i] 10 11 end Calculate average waiting time and average turnaround time 12 Display output display gantt chart 13 End Algorithm 2: Shortest Job First Sample input:- Enter no of processes=3 Enter process name and burst time for process 1:: A 3 Enter process name and burst time for process 2:: B 2 Enter process name and burst time for process 3:: C 4 38 Sample output:: Average waiting time=2.66 Process Name B A C Burst time 2 3 4 waiting time 0 2 5 Turn around time 2 5 9 Average turnaround time=5.66 Gant Chart for process A: B B Gant Chart for process B:- - A A Gant Chart for process C:- - - - - C C C C 7.2.3 Priority Scheduling. Each process is given a priority, and then CPU executes process with highest priority. If multiple processes with same priority are runnable, use some other criteria - typically FCFS. SJF is an example of a priority-based scheduling algorithm. With the exponential decay algorithm above, the priorities of a given process change over time. • Assume we have 5 processes P1 (burst time 10, priority 3), P2 (burst time 1, priority 1), P3 (burst time 2, priority 3), P4 (burst time 1, priority 4), P5 (burst time 5, priority 2). Lower numbers represent higher priorities. What would a standard priority scheduler do? • Big problem with priority scheduling algorithms: starvation or blocking of low-priority processes. Can use aging to prevent this - make the priority of a process go up the longer it stays runnable but doesn’t run. Algoritham:- 39 Data: Processes 1 read no of processes n 2 Read process name , burst time and priority for each process 3 sort the processes according to its priority 4 calculate waiting time and turn around time for each process 5 waiting time[0]=0 6 turn arround time[0]=burst time[0] 7 while i<n do 8 waiting time[i]=waiting time[i-1] + burst time[i-1] 9 turn arround time[i]=waiting time[i]+burst time[i] 10 11 end Calculate average waiting time and average turnaround time 12 Display output display gantt chart 13 End Algorithm 3: Priority Sheduling Sample input:Enter no of processes=3 Enter process name, burst time and priority for process 1:: A 3 1 Enter process name, burst time and priority for process 2:: A 2 0 Enter process name, burst time and priority for process 3:: C 4 2 Sample output:- Process Name B A C Burst time 2 3 4 Average waiting time=2.66 Average turnaround time=5.66 Gant Chart for process A: B B Gant Chart for process B:- - A A Gant Chart for process C:- - - - - C C C C Priority 0 1 2 waiting time 0 2 5 Turn around time 2 5 9 40 7.2.4 Round-robin (RR):- is one of the simplest scheduling algorithms for processes in an operating system, which assigns time slices to each process in equal portions and in circular order, handling all processes without priority. Roundrobin scheduling is both simple and easy to implement, and starvation-free. Round-robin scheduling can also be applied to other scheduling problems, such as data packet scheduling in computer networks. The name of the algorithm comes from the round-robin principle known from other fields, where each person takes an equal share of something in turn. Algorithm:- 41 1 read no of processes n, process name , burst time and priority and time quantum, calculate total burst time 2 while i¡totalbt do 3 while j<n do if bt[j]<tq && bt[j]>0 then 4 while k<bt[j] do 5 strcpy(p[i].gc,p[j].name); i++; 6 7 end 8 bt[j]=0; 9 else 10 end 11 if bt[j]>=tq && bt[j]>0 then bt[j]=bt[j]-tq; while k<tq do 12 strcpy(p[i].gc,p[j].name); l++; i++; 13 end 14 15 else 16 end 17 end 18 calculate waiting time(wt=waiting time gc=GantChart array bt=burst time) 19 while i<totalbt do while j<n do 20 21 f=strcmp(p[i].gc,p[j].name); 22 if f==0&&bt[j]>0 then bt[j]–; 23 else 24 p[j].wt++; 25 end 26 end 27 28 end 29 calculate turn around time 30 calculate average waiting time average turn around time 31 display result 32 display gantt chart 33 end Algorithm 4: Priority Sheduling 42 Sample input: Enter no of processes=3 Enter process name and burst time for process 1:: A 9 Enter process name and burst time for process 2:: B 8 Enter process name and burst time for process 3:: C 3 Enter Time Quantum: 4 Sample output:: Process Name A B C Burst time 9 8 3 waiting time 11 11 8 Turn around time 20 19 11 Average waiting time=10 Average turnaround time=16.66 Gant Chart for process A: A A A A - - - - - - - A A A A - - - - A Gant Chart for process B: - - - - B B B B - - - - - - - B B B B Gant Chart for process C: - - - - - - - - C C C C 7.3 Post Lab: 1. Simulation of scheduling algorithms. 2. Performance analysis of various algorithms Assignment 8 Memory allocation algorithms 8.1 Problem Statement: Simulation of Memory allocation algorithms 1. First Fit 2. Best Fit 3. Next Fit 8.2 Theory: Memory Management Algorithms In an environment that supports dynamic memory allocation, the memory manager must keep a record of the usage of each allocatable block of memory. This record could be kept by using almost any data structure that implements linked lists. An obvious implementation is to define a free list of block descriptors, with each descriptor containing a pointer to the next descriptor, a pointer to the block, and the length of the block. The memory manager keeps a free list pointer and inserts entries into the list in some order conducive to its allocation strategy. A number of strategies are used to allocate space to the processes that are competing for memory. 8.2.1 Best Fit The allocator places a process in the smallest block of unallocated memory in which it will fit. Problems: • It requires an expensive search of the entire free list to find the best hole. • More importantly, it leads to the creation of lots of little holes that are not big enough to satisfy any requests. 43 44 This situation is called fragmentation, and is a problem for all memory-management strategies, although it is particularly bad for best-fit. Solution: One way to avoid making little holes is to give the client a bigger block than it asked for. For example, we might round all requests up to the next larger multiple of 64 bytes. That doesn’t make the fragmentation go away, it just hides it. • Unusable space in the form of holes is called external fragmentation • Unusable space in the form of holes is called external fragmentation Sample input:: ::Block No:: 1 2 3 4 5 ::Block Size:: 10 20 25 15 40 ::process Name:: A B C D E ::Process size 5 30 15 8 25 Sample output:: ::Process name:: A B C D E 8.2.2 ::Process size:: 5 30 15 8 25 ::Block allocated:: 1 5 4 2 3 ::Block Size:: 10 40 15 20 25 Worst Fit The memory manager places process in the largest block of unallocated memory available. The ides is that this placement will create the largest hole after the allocations, thus increasing the possibility that, compared to best fit, another process can use the hole created as a result of external fragmentation. Sample input:: Sample output:: 45 ::Block No:: 1 2 3 4 5 ::Block Size:: 10 20 25 15 40 ::Process name:: A B C D E 8.2.3 ::process Name:: A B C D E ::Process size:: 5 30 15 8 25 ::Process size 5 30 15 8 25 ::Block allocated:: 5 3 2 - ::Block Size:: 40 25 20 - First Fit Another strategy is first fit, which simply scans the free list until a large enough hole is found. Despite the name, first-fit is generally better than best-fit because it leads to less fragmentation. Problems: • Small holes tend to accumulate near the beginning of the free list, making the memory alligator search farther and farther each time. Solution: 8.2.4 Next Fit The first fit approach tends to fragment the blocks near the beginning of the list without considering blocks further down the list. Next fit is a variant of the first-fit strategy. The problem of small holes accumulating is solved with next fit algorithm, which starts each search where the last one left off, wrapping around to the beginning when the end of the list is reached (a form of one-way elevator) Sample input:: ::Block No:: 1 2 3 4 5 ::Block Size:: 10 20 25 15 40 Sample output:: ::process Name:: A B C D E ::Process size 5 30 15 8 25 46 ::Process name:: A B C D E 8.3 ::Process size:: 5 30 15 8 25 ::Block allocated:: 1 5 2 3 - Post Lab 1. Simulation of various memory management techniques 2. Performance analysis of First, Best and next fit. ::Block Size:: 10 40 20 25 - Assignment 9 Page Replacement Algorithms 9.1 Problem Statement Write a program to simulate following page replacement algorithms in c 1. FIFO 2. LRU 3. Optimal 9.2 Pre Lab: • Concepts of paging. • concepts of memory. 9.3 Theory When a page fault occurs, the operating system has to choose a page to remove from memory to make room for the page that has to be brought in. If the page to be removed has been modified while in memory, it must be rewritten to the disk to bring the disk copy up to date. If, however, the page has not been changed (e.g., it contains program text), the disk copy is already up to date, so no rewrite is needed. The page to be read in just overwrites the page being evicted. While it would be possible to pick a random page to evict at each page fault, system performance is much better if a page that is not heavily used is chosen. If a heavily used page is removed, it will probably have to be brought back in quickly, resulting in extra overhead. Much work has been done on the subject of page replacement 47 48 algorithms, both theoretical and experimental. Below we will describe some of the most important algorithms. For example, most computers have one or more memory caches consisting of recently used 32-byte or 64-byte memory blocks. When the cache is full, some block has to be chosen for removal. This problem is precisely the same as page replacement except on a shorter time scale (it has to be done in a few nanoseconds, not milliseconds as with page replacement). The reason for the shorter time scale is that cache block misses are satisfied from main Memory, which has no seek time and no rotational latency. A second example is in a Web server. The server can keep a certain number of heavily used Web pages in its memory cache. However, when the memory cache is full and a new page is referenced, a decision has to be made which Web page to evict. The considerations are similar to pages of virtual memory, except for the fact that the Web pages are never modified in the cache, so there is always a fresh copy on disk. In a virtual memory system, pages in main memory may be either clean or dirty. 1. The First-In, First-Out (FIFO) Page Replacement Algorithm: Another low-overhead paging algorithm is the FIFO (First-In, First-Out) algorithm. The operating system maintains a list of all pages currently in memory, with the page at the head of the list the oldest one and the page at the tail the most recent arrival. On a page fault, the page at the head is removed and the new page added to the tail of the list. When applied to stores, FIFO might remove mustache wax, but it might also remove flour, salt, or butter. When applied to computers the same problem arises. For this reason, FIFO in its pure form is rarely used. 2. The Least Recently Used (LRU) Page Replacement Algorithm A good approximation to the optimal algorithm is based on the observation that pages that have been heavily used in the last few instructions will probably be heavily used again in the next few. Conversely, pages that have not been used for ages will probably remain unused for a long time. This idea suggests a realizable algorithm: when a page fault occurs, throw out the page that has been unused for the longest time. This strategy is called LRU (Least Recently Used) paging. The workings of this algorithm are given in Fig. 4-3 for four page frames and page references in the order 0 1 2 3 2 1 0 3 2 3 After page 0 is referenced, we have the situation of Fig. 4-3(a). After page 1 is reference, we have the situation of Fig. 4-3(b), and so forth. 3. The Optimal Page Replacement Algorithm: The best possible page replacement algorithm is easy to describe but impossible to implement.At the moment that a page fault occurs, some set of pages is in memory. One of these pages will be 49 referenced on the very next instruction (the page containing that instruction). Other pages may not be referenced until 10, 100, or perhaps 1000 instructions later. Each page can be labeled with the number of instructions that will be executed before that page is first referenced. The optimal page algorithm simply says that the page with the highest label should be removed. If one page will not be used for 8 million instructions and another page will not be used for 6 million instructions, removing the former pushes the page fault that will fetch it back as far into the future as possible. The only problem with this algorithm is that it is unrealizable. At the time of the page fault, the operating system has no way of knowing when each of the pages will be referenced next. (We saw a similar situation earlier with the shortest job first scheduling algorithm-how can the system tell which job is shortest?) Still, by running a program on a simulator and keeping track of all page references, it is possible to implement optimal page replacement on the second run by using the page reference information collected during the first run. In this way it is possible to compare the performance of realizable algorithms with the best possible one. If an operating system achieves a performance of, say, only 1 percent worse than the optimal algorithm, effort spent in looking for a better algorithm will yield at most a 1 percent improvement. To avoid any possible confusion, it should be made clear that this log of page references refers only to the one program just measured and then with only one specific input. The page replacement algorithm derived from it is thus specific to that one program and input data. Although this method is useful for evaluating page replacement algorithms, it is of no use in practical systems. Below we will study algorithms that 50 are useful on real systems 9.4 Post Lab • Simulation of Page Replacement algorithms • Performance evaluation and analysis of the same. Assignment 10 Bankers Algorithm 10.1 Problem Statement Write a program in c to implement Bankers Algorithm 10.2 Pre Lab: • Concepts of process scheduling • C Programming. 10.3 Theory The Banker’s algorithm is run by the operating system whenever a process requests resources.[2] The algorithm prevents deadlock by denying or postponing the request if it determines that accepting the request could put the system in an unsafe state (one where deadlock could occur). When a new process enters a system, it must declare the maximum number of instances of each resource type that may not exceed the total number of resources in the system. Also, when a process gets all its requested resources it must return them in a finite amount of time. 10.3.1 Resources For the Banker’s algorithm to work, it needs to know three things: • How much of each resource each process could possibly request • How much of each resource each process is currently holding 51 52 • How much of each resource the system has available Resources may be allocated to a process only if it satisfies the following conditions: 1. request ¡= max, else set error condition as process has crossed maximum claim made by it. 2. request ¡= available, else process waits until resources are available. Some of the resources that are tracked in real systems are memory, semaphores and interface access. 10.3.2 Example Assuming that the system distinguishes between four types of resources, (A, B, C and D), the following is an example of how those resources could be distributed. Note that this example shows the system at an instant before a new request for resources arrives. Also, the types and number of resources are abstracted. Real systems, for example, would deal with much larger quantities of each resource. Available system resources are: A 3 B 1 C 1 D 2 Processes (currently allocated resources): P1 P2 P3 A 1 1 1 B 2 0 1 C 2 3 1 D 1 3 0 Processes (maximum resources): P1 P2 P3 A 3 1 1 B 3 2 1 C 2 3 5 D 2 4 0 53 10.3.3 Safe and Unsafe States A state (as in the above example) is considered safe if it is possible for all processes to finish executing (terminate). Since the system cannot know when a process will terminate, or how many resources it will have requested by then, the system assumes that all processes will eventually attempt to acquire their stated maximum resources and terminate soon afterward. This is a reasonable assumption in most cases since the system is not particularly concerned with how long each process runs (at least not from a deadlock avoidance perspective). Also, if a process terminates without acquiring its maximum resources, it only makes it easier on the system. Given that assumption, the algorithm determines if a state is safe by trying to find a hypothetical set of requests by the processes that would allow each to acquire its maximum resources and then terminate (returning its resources to the system). Any state where no such set exists is an unsafe state. 10.3.4 Pseudocode (Bankers Algorithm) function: bankers algorithm(set of processes P, currently available resources A) 54 Data: Processes 1 while P not empty do 2 boolean found = false 3 while All processes do 4 Cp = current resource allocation for process(p) 5 Mp = maximum resource requirement for process(p) 6 if Mp - Cp ≤ A then 7 // p can obtain all it needs. 8 // Assume it does so, terminates, and releases what it already has. 9 A = A + Cp 10 remove element from set(p, P) 11 found = true else 12 continue 13 end 14 15 end 16 if not found then return UNSAFE 17 18 else return SAFE 19 20 21 end end Algorithm 5: Safety Algorithm 10.3.5 Example We can show that the state given in the previous example is a safe state by showing that it is possible for each process to acquire its maximum resources and then terminate. 1. P1 acquires 2 A, 1 B and 1 D more resources, achieving its maximum. The system now still has 1 A, no B, 1 C and 1 D resource available 2. P1 terminates, returning 3 A, 3 B, 2 C and 2 D resources to the system The system now has 4 A, 3 B, 3 C and 3 D resources available 3. P2 acquires 2 B and 1 D extra resources, then terminates, returning all its resources The system now has 5 A, 3 B, 6 C and 6 D resources 55 4. P3 acquires 4 C resources and terminates The system now has all resources: 6 A, 4 B, 7 C and 6 D 5. Because all processes were able to terminate, this state is safe Note that these requests and acquisitions are hypothetical. The algorithm generates them to check the safety of the state, but no resources are actually given and no processes actually terminate. Also note that the order in which these requests are generated - if several can be fulfilled - doesn’t matter, because all hypothetical requests let a process terminate, thereby increasing the system’s free resources. For an example of an unsafe state, consider what would happen if process 2 were holding 1 more unit of resource B at the beginning. 10.3.6 Requests When the system receives a request for resources, it runs the Banker’s algorithm to determine if it is safe to grant the request. The algorithm is fairly straight forward once the distinction between safe and unsafe states is understood. 1. Can the request be granted • If not, the request is impossible and must either be denied or put on a waiting list 2. Assume that the request is granted 3. Is the new state safe? • If so grant the request • If not, either deny the request or put it on a waiting list 10.4 Post Lab: Whether the system denies or postpones an impossible or unsafe request is a decision specific to the operating system. Simulation of Bankers Algorithm and check it for deadlock avoidance. Assignment 11 Dining Philosophers Problem 11.1 Problem Statement Write a program in c to implement Dining Philosophers problem by using Mutex or Semaphore 11.2 Prelab: • Multithreading concepts • Mutex functions or Semaphore functions. 11.3 Theory In this problem, there are 5 philosophers present who spend their life in eating and thinking. Philosophers share a common circular table surrounded by 5 chairs, each belonging to 1 philosopher .In the center of the table. A bowl of rice is present and across each philosopher a pair of chopstick is present. When a philosopher thinks, he does not interact with his colleague. Whenever a philosopher gets hungry, he tries to pick up 2 chopsticks that are close to him. Philosopher may pick up one chopstick at a time. He cannot pick up a chopstick that is already in the hand of neighbor. When a hungry philosopher has both chopsticks at the same time, he start eating without releasing his chopstick and starts thinking again .The problem could be raised when all the philosopher try to keep the chopstick at the same time. This may lead to deadlock situations. To synchronize all philosophers, semaphore chopsticks [5] is used as a variable where all the elements are first initialized to 1.The structure of philosopher is shown 56 57 below; Figure 11.1: Dining Philosophers problem Data: Philosopher Number 1 i = 0; 2 while true do 3 wait(chopstick[i]); 4 wait(chopstick[(i+1)%5]); 5 ——– 6 eat 7 signal(chopstick[i]); 8 signal(chopstick[(i+1)%5]); 9 ——– 10 think 11 ——– 12 end Algorithm 6: Dining Philosophers Problem 11.3.1 Functions used with their syntax : 1. The following three functions lock and unlock a mutex: # include<pthread.h> int pthread_mutex_lock(pthread_mutex_t * mptr); int pthread_mutex_trylock(pthread_mutex_t * mptr); int pthread_mutex_unlock(pthread_mutex_t * mptr); 58 2. The mutex or condition variable is initialized or destroyed with the following functions. # include<pthread.h> int pthread_mutex_init(pthread_mutex_t * mptr,const pthread_mutexattr_t * attr); int pthread_mutex_destroy(pthread_mutex_t * mptr); 3. When a program is started by exec, a single thread is created , called the initial thread or main thread . Additional threads are by pthread create. # include<pthraed.h> int pthread_create(pthread_t * tid,constpthread_attr_t * attr, void * (* func)void *),void* arg); 11.4 Post Lab: Implementation of Dining Philosopher Problem for Process synchronization and understanding and using different functions available for mutual exclusion. Assignment 12 Inter Process Communication 12.1 Problem Statement Write a program in unix to exhibit Inter-process Communication for Producer-Consumer problem by using Pipes or Shared Memory 12.2 Pre Lab: • Pipe Concept • Shared Memory concepts • Multithreading of Fork system calls. 12.3 Theory 12.3.1 Process A process is the execution of a program and consists of a pattern of bytes that the CPU interprets as machine instructions, data and stack. Many processes appear to execute simultaneously as the Kernel Schedules them for execution and several processes may be instances of one program. A process executes by following a strict sequence of instructions that is self-contained. 59 60 In practical terms, a process on a UNIX system is the entity that is created by the fork system call. Every process except process O is created when another process executes the fork system call. The process that invoked the fork system call is the parent, process and the newly created one is the child process. The Kernel identifies each process by its process number called the Process ID (PID). Context of a Process: The context of a process is its state as defined by its text, the values of its global user variables and data structures, the values of machine registers it uses, the values stored in its process table slot and the contents of its user and Kernel stacks. When executing a process the system is said to be executing in the context of its process. When the Kernel decides that it should execute another process, it does a context switch so that the system executes in the context of the other process. When doing a context of the other process. When doing a context switch the Kernel saves back to the first process and resume its execution. 12.3.2 Process States: The lifetime of a process can be divided into a set of states, each with certain characteristic that describe the process. 1. The process is currently executing in user mode. 2. The process is currently executing in Kernel mode. 3. The process is not executing, but is it ready to run as soon as the scheduler chooses it. 4. The process is sleeping. A process puts itself to sleep when it can no longer continue executing, such as when it is waiting for I/O complete. Because a process can execute only one process at a time, at most one process may be in states 1 and 2. The two states correspond to the two modes of execution uses and kernel. 61 12.3.3 Inter-process Communication: Inter-process communication mechanisms allow arbitrary process to exchange data and synchronize execution. Arbitrary process communication by sending signals, but the ”message” consists only of the signals number. Messages allow process to send formatted data streams to arbitrary process, shared m/m allow process to share parts of their virtual address space and semaphores allow process to synchronize execution. 12.3.4 Messages: There are 4 system calls for messages. • –msgget returns (and possibly creates) a msg description that designates a msg queue for use in other system calls. • –msgctl has options to set and return parameters associated with a message description and an option to remove descriptions. • –msgsnd sends a message. • –msgrcv receives a message. The syntax for msg get system call is msgqid= msgget(key,flag) Where, msgquid is the description returned by the call and key and flag have the semantics for the general get calls. The kernel stores messages on a linked and uses msgid as an index into an array of message queue headers. The kernel checks that the sending process has write permission for the message description. The message length does not exceed the system limit, the message queue does not contain too many bytes and that the message type is a positive integer. If all the tests succeed, the kernel allocates space for the message and copies the data from the user space. A process receives message by, Count= msgrcv(id,msg,maxcount,type,flag) Where id is the message description. Msg is the addresss of the user structure to contain the received message. maxcount is the size of the data array in msg. Type specifies the 62 message type the user wants to read. And the flag specifies what the kernel should do, if no messages are on the queue. The return value count is the number of bytes returned to the user. In this way, communication between processes is achieved in UNIX operating system. 12.4 Post Lab: • Inter-Processes communication between processes in UNIX operating system can be achieved using Pipes or shared memory. • Understanding and using pipes/Shared memory for IPC Assignment 13 Linux Kernel compilation 13.1 Problem Statement Download Raw unix kernel and compile it on your system 13.2 Prelab 1. Linux kernel fundamentals 2. Unix commands 13.3 Theory 13.3.1 How to: Compile Linux kernel 2.6 Compiling custom kernel has its own advantages and disadvantages. However, new Linux user / admin find it difficult to compile Linux kernel. Compiling kernel needs to understand few things and then just type couple of commands. This step by step how to covers compiling Linux kernel version 2.6.xx under Debian GNU Linux. However, instructions remains the same for any other distribution except for apt-get command. 63 64 13.3.2 Commands Step # 1 Get Latest Linux kernel code Visit http://kernel.org/ and download the latest source code. File name would be linux-x.y.z.tar.bz2, where x.y.z is actual version number. For example file inux-2.6.25.tar.bz2 represents 2.6.25 kernel version. Use wget command to download kernel source code: $ cd /tmp $ wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-x.y.z.tar.bz2 Note: Replace x.y.z with actual version number. Step # 2 Extract tar (.tar.bz3) file Type the following command: # tar -xjvf linux-2.6.25.tar.bz2 -C /usr/src # cd /usr/src Step # 3 Configure kernel Before you configure kernel make sure you have development tools (gcc compilers and related tools) are installed on your system. If gcc compiler and tools are not installed then use apt-get command under Debian Linux to install development tools. # apt-get install gcc Now you can start kernel configuration by typing any one of the command: • $ make menuconfig - Text based color menus, radiolists & dialogs. This option also useful on remote server if you wanna compile kernel remotely. • $ make xconfig - X windows (Qt) based configuration tool, works best under KDE desktop • $ make gconfig - X windows (Gtk) based 65 configuration tool, works best under Gnome Dekstop. For example make menuconfig command launches following screen: $ make menuconfig You have to select different options as per your need. Each configuration option has HELP button associated with it so select help button to get help. Step # 4 Compile kernel Start compiling to create a compressed kernel image, enter: $ make Start compiling to kernel modules: \$ make modules Install kernel modules (become a root user, use su command): $ su # make modules\_install Step # 5 Install kernel So far we have compiled kernel and installed kernel modules. It is time to install kernel itself. \# make install It will install three files into /boot directory as well as modification to your kernel grub configuration file: System.map-2.6.25 config-2.6.25 vmlinuz-2.6.25 Step # 6: Create an initrd image Type the following command at a shell prompt: 66 # cd /boot # mkinitrd -o initrd.img-2.6.25 2.6.25 initrd images contains device driver which needed to load rest of the operating system later on. Not all computer requires initrd, but it is safe to create one. Step # 7 Modify Grub configuration file - /boot/grub/menu.lst Open file using vi: # vi /boot/grub/menu.lst title Debian GNU/Linux, kernel 2.6.25 Default root (hd0,0) kernel /boot/vmlinuz root=/dev/hdb1 ro initrd /boot/initrd.img-2.6.25 savedefault boot Remember to setup correct root=/dev/hdXX device. Save and close the file. If you think editing and writing all lines by hand is too much for you, try out update-grub command to update the lines for each kernel in /boot/grub/menu.lst file. Just type the command: # update-grub Step # 8 : Reboot computer and boot into your new kernel Just issue reboot command: # reboot 13.4 PostLab • Downloading a raw kernel from www.kernel.org . • Compiling the raw kernel. • Booting your system with newly compiled kernel.