LAB MANUAL Course: CSC2205-Operating Systems Department of Computer Science Learning Procedure J (Journey inside-out the concept) Stage a1 (Apply the learned) Stage v (Verify the accuracy) Stage a2 (Assess your work) 1) Stage 2) 3) 4) 1 Table of Contents Lab # Lab # 01 Topics Covered Page # 03 Lab # 02 Operating systems overview Introduction to Linux (Ubuntu Installation) Introduction to Basic Shell commands Lab # 03 Implementation of Linux commands 19 Lab # 04 Inter process communication and implementation through pipes 25 Lab # 05 Multi threading 30 Lab # 06 13 Lab Sessional 1 Lab # 07 Implement Shortest Job First (Non-Preemptive) CPU Scheduling Algorithm 36 Lab # 08 Implement Round Robin CPU Scheduling Algorithm 39 Lab # 09 Simulating Banker’s Algorithm for Deadlock Avoidance 41 Lab # 10 Paging and memory management 44 Lab # 11 Page replacement algorithms FIFO algorithm and its implementation LRU algorithm and its implementation LFU algorithm and its implementation 47 Lab # 12 Lab Sessional 2 Lab # 13 File allocation strategy Sequential 61 Lab # 14 File allocation strategy 65 Lab # 15 Indexed 69 File allocation strategy Linked Terminal Examination 2 LAB # 01 Statement Purpose: This lab will give you the overview of Operating system and introduction to Linux. Activity Outcomes: This lab teaches you the following topics: Operating system overview Introduction to Linux Ubuntu Installation Instructor Note: Lecture 1,2,3,5 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 3 1) Stage J (Journey) Introduction Operating System Operating System is a type of System Software and is a collection (set) of programs, which performs two specific functions. First, it provides a user interface so that human user can interact with the machine. Second, the operating system manages computer resources. Computer Resources Computer resources are physical devices, which an operating system accesses, and manages. Printers, memories, input/output devices, files, etc., are examples of computer resources. So why an operating is called a resource manager. Some of important tasks, which a typical modern operating system has to perform, are given below: Processes Scheduling Inter-process Communication Synchronization Memory Management (physical memory allocation, virtual memory etc.) Resource Management Directory and File Management Communication Usage share of Operating Systems Windows, Unix, Linux, DOS are popular operating systems. There usage for personal computer is given below. Server Operating Systems Server-oriented operating systems tend to have certain features in common that make them more suitable for the server environment, such as GUI not available or optional 4 ability to reconfigure and update both hardware and software to some extent without restart, advanced backup facilities to permit regular and frequent online backups of critical data... etc. (you may cover it later in the course) Linux Linux is an operating system, which is a flavor of Unix. Linux is a multi-user and multitasking operating system. It is a leading operating system on servers and other big iron systems such as mainframe computers and supercomputers. more than 90% of today's 500 fastest supercomputers run some variant of Linux, Including the 10 fastest. The Android system in wide use on mobile devices is built on the Linux kernel. Since with the likeness with UNIX, all the programs written for UNIX can be compiled and run under Linux. Linux operating system runes on verity of machines like 486/Pentium, Sun Sparces, PowerPC, etc. Linus Torvalds, principal author, at the University of Helsinki, Finland, wrote Linux Kernel. UNIX programmers around the world in the development of Linux assisted him. Popular Linux distributions include: Debian (Knoppix, Ubuntu) , Fedora, Gentoo, openSUSE etc. Linux System Linux System can be split into two parts. i) ii) Shell Kernel Formally, a Shell is interface between a user and a Linux operating system, i.e. user interacts with the Linux operating system through the shell. There may be two tasks to be performed by a shell. First, accepts commands from a user and second, interprets those commands. Two shells, which are commonly used, are Bourne shell and C shell. One other shell, which is rather complex, is Korn shell. Kernel is the core of Linux Operating System, while the system is operational, it keeps on running. The kernel is the part of the Linux Operating system which consist of routines, which interact with underlying hardware, and routines which include system call handling, process management, scheduling, pipes, signals, paging, swapping, the file system, and highlevel part of the I/O system. So shell accepts commands from user interpret them and deliver these interpreted commands to kernel for execution. After execution, the shell displays result of executed commands. Shell Kernel 5 Files File is a mechanism through which we store information. Normally, there are two modes of storing information. i) ii) File Directories i) File A simple file stores some type of information. The information it has may be in text format, or in binary format. ii) Directories Directories are special types of files owned the operating system, which contains information about files, and may contain other directories (called Subdirectories). So directories are also files, which contains some vital information about the files, and other directories. There’s a file (management) system in operating system, which manipulates file and directories. The major operations, which can be performed on files and directories, are given below: Create Delete Open Close Read Write Append Seek Rename Get Attributes Set Attributes 2) Stage a1 (apply) Lab Activities: Intalling/setting up Ubuntu: Standard installation If you are looking to install Ubuntu on your personal desktop/laptop, this is probably what you are going for, and it has never been easier! The standard Ubuntu desktop installation uses a Graphical Install, which is meant to cruise you through the installation process in a very small number of easy steps. To get the installer up and running, you will need to do the following: 6 Obtain an installation LiveCD. The LiveCD is a fully functional Ubuntu environment, and it allows you to get a taste of Ubuntu on your machine by using a 'Live' session! If you downloaded a CD image (.iso file), you can burn it to a standard CD. All that remains now is to install Ubuntu by booting from the installation CD. Alternate Installation You may not wish to always use the standard LiveCD, because it may so happen occasionally that your computer is not able to run the standard Desktop installation CD because it does not meet the hardware requirements, or the required drivers are missing from the standard LiveCD. The LiveCD is designed to keep most basic hardware in mind, but there are a few that are bound to be absent from it. Or, you may simply prefer to install a more customized version of Ubuntu different from the standard install depending on your taste. The Alternate CD allows more advanced installation options which are not available with the Standard LiveCD. Other ways to get Ubuntu Direct download and install if you are connected with the Internet. Download link: http://cdimage.ubuntu.com/releases/12.04/release/ Hardware virtualization [Source: Wikipedia] Computer hardware virtualization (or hardware virtualisation) is the virtualization of computer or operating systems. It hides the physical characteristics of a computing platform from users, instead showing another abstract computing platform. At its origins, the software that controlled virtualization was called a "control program", but nowadays the terms “hypervisor” or "virtual machine monitor" are preferred. 7 VMware VMware, Inc. is a company providing virtualization software, founded in 1998 and based in Palo Alto, California, USA. VMware's desktop software runs on Microsoft Windows, Linux, and Mac OS X, while Vmware's enterprise software hypervisors for servers, VMware ESX and VMware ESXi, are bare-metal embedded hypervisors that run directly on server hardware without requiring an additional underlying operating system. Desktop software iii) VMware Workstation (first product launched by VMware in 1999). This software suite allows users to run multiple instances of x86 or x86-64- compatible operating systems on a single physical PC. iv) VMware Fusion provides similar functionality for users of the Intel Mac platform, along with full compatibility with virtual machines created by other VMware products. v) VMware Player is for users without a license to use VMware Workstation or VMware Fusion. VMware offers this software as a freeware product for personal use. While initially not able to create virtual machines, this limitation was removed in version 3.0.1. VMware Player is a freeware virtualization software package from VMware, Inc.(a company which was formerly a division of and whose majority shareholder remains EMC Corporation). VMware Player can run existing virtual appliances and create its own virtual machines (which require an operating system to be installed to be functional). It uses the same virtualization core as VMware Workstation, a similar program with more features, but not free of charge. VMware Player is available for personal non-commercial use, or for distribution or other use by written agreement. No support is provided by VMWare, but there is an active community website for discussing and resolving issues. 8 Download Link https://my.vmware.com/web/vmware/evalcenter?p=vmware-workstation9 How to Share/Access To Partition From Guest Operating Sys. to Host O.S. Open VMWare, and right click on the Virtual Machine (recently created), and click on “virtual machine settings ...” you will see the following figure. Now click on options --> Shared folders Then click on Always enable --> Add Then Browse to the folder of your choice, click Next, and follow the on screen instructions. Viewing Shared Folders in a Linux Guest In a Linux virtual machine, shared folders appear under /mnt/hgfs. Exercise 1 Install Ubuntu on your system or use 'live' version. You can use any of the methods discussed above according to your own personal needs or discuss it with your lab Instructor. Organization of the Linux File System Unlike DOS, which permits you to organize your disks any way you please. the Linux file system is organized into a standard directory structure. A portion of the Linux directory structure is pictured below: /(Root Directory) etc/ bin/ usr/ bin/ home/ lib/ div/ info/ lib/ sbin/ tmp/ sbin/ Root Directory The top most directory is called root directory. The hierarchical structure of directory begins with a root directory. The name of root directory is /. Directory 9 A file, which holds other files and sub-directories. Subdirectory A directory residing within another directory. Home Directory The directory selected by Linux as the working directory when a user logs on. When a user logs on Linux selects home directory (its name usually matches your login name) as his/her working directory. Current/Working Directory The directory currently being used. Pathname Pathname is a reference to identify a file within the directory structure. For example the following file name indicates the file in the hierarchy of directories: /usr/users/bill/letters/pay The first slash (/) indicates the root directory (start from root directory), move down to usr, then users, then bill, then letters and finally to the file. So this pathname is reference to the file pay with respect to the root directory. A path may be of two types. Absolute Pathname The pathname, which identifies a file or a directory irrespective of the current state of the user. The user's "current directory" is part of the user's state. The absolute pathname always starts from the root directory. For example, to locate file any file in lib directory, the absolute path of the file is: /usr/local/lib/filename Relative pathname The pathname, which identifies a file or a directory in a way that depends on the state of the user i.e. users current directory. Relative pathname identifies files with respect to user current directory. Current Directory (Working Directory) thesis chapter4.tex to refer a file chapter4.tex in the in the subdirectory thesis with respect to the current directory, we use pathname. 10 thesis/chepter4.tex Some standard Linux directories are given below: /home Users’ home directory /etc All system administrator commands, configuration files, and installation control files. /bin The core set of system commands and programs. Most systems cannot boot (initially start) without executing some of the commands in this directory. /dev The device files used to access system peripherals (for example, your terminal can be accessed from /dev/tty). /lib programs. The standard set of programming libraries linked with Linux /tmp Temporary files created and used by many Linux programs. /sbin The system program used to boot the system. /var Log files(Record of Web activity), spool files(temp files) etc. /root The root user’s home directory. /usr/bin Common commands and programs. /usr/doc Documentation /usr/games Games /usr/include Header files /usr/info /usr/lib Online documentation Shared libraries /usr/man Manual pages (help) /usr/sbin All system administration utilities /usr/share Shared information /usr/src Source code Elementary File and Directory Commands The elementary commonly used directory commands are ls, cd, mkdir, pwd and rmdir, and most elementary file commands includes cat, cp, mv, and rm. Exploring the File Hierarchy When you login, there is a special directory associated with your login name called your home directory. Your home directory is actually your initial current working directory. The 11 simplest way to find out where in the directory hierarchy your home directory is located is just to use the command pwd straight after you login. The pwd command tells you your present working directory. $ pwd /home/you Note:- Linux commands are case-sensitive. All standard Linux commands use lower case letters only. In order to move your present working directory away from your home directory to somewhere else in the directory hierarchy, you use the cd (change directory) command. So, to change directory to the directory hierarchy’s root directory you would use the command. (Note: Linux directory tree structure is given at the end of handouts). $ cd / (we will see the cd command in much detail after a few minutes) Directory Commands Command Description ls List the file in the directory, just like dir command in DOS. Option: -a Display all the files, and subdirectories, including hidden files. -l Display detailed information about each file, and directory. -r - Display files in the reverse order. 3) Stage v (verify) Activity 1: Install Linux operating system at your home systems. 4) Stage a2 (assess) Checking the Ubuntu installation. 12 LAB # 02 Statement Purpose: This lab will give you the introduction to shell commands. Activity Outcomes: This lab teaches you the following topics: Overview of shell commands Practical implementation of shell comands Instructor Note: Lecture 4 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 13 1) Stage J (Journey) Introduction What is a shell program? Simply put, a shell program (sometimes called a shell script) is a text file that contains standard UNIX and shell commands. Each line in a shell program contains a single UNIX command exactly as if you had typed them in yourself. The difference is that you can execute all the commands in a shell program simply by running the shell program (rather than typing all the commands within). Shell programs are interpreted and not compiled programs. This means when you run a shell program a child shell is started. This child shell reads each line in the shell program and carries out the command on that line. When it has read all the commands the child shell finishes. Support for programming To be truly useful a programming language must provide the following services comments, variables, conditional commands, and repeated action commands. These extra services are provided by the shell. Different shells use different syntax for these services. This means that a shell program written for the Bourne shell cannot be run by the C shell (though it can be run by the bash shell.) For portability, we will use only the Bourne shell syntax. Creating a shell program To create a shell program you need to complete the following steps: create a text file to hold the shell program decide which shell you will use add the required commands to the file save the file change the permissions on the file so it is executable run the shell program 2) Stage a1 (apply) Lab Activities: Command: cat ―cat" is short for concatenate. This command is used to create, view and concatenate files. 14 Example: o cat>file1 This command creates the file, enter the contents into it and to save the content, press Ctrl+D. o cat file1 This command shows the content of the file. o cat file1 file2 > file3 This command combines the contents of the first two files into the third file. Command: pwd "pwd" stands for print working directory. It displays your current position in the UNIX/LINUX file system. Example: o pwd It is simply used to report your current working directory. Command: ls "ls" stands for list. It is used to list information about files and directories. Example: o ls It provides a very basic listing of the files in your current working directory. Filenames beginning with a decimal are considered hidden files, and they are not shown. o ls -al This command provides a long listing of information about all files in the current directory. This is probably the most used version of the ls command. Command: mv The "mv" command is used to move and rename files. Examples: o mv Lab OSLab This command renames the file "Lab" to the new name "OSLab". o mv Chapter1 garbage This command renames the file "Chapter1" to the new name "garbage". (Notice that if "garbage" is a directory, "Chapter1" would be moved into that directory). rm -r Labs This command deletes the directory named "Labs‖. This directory, and all of its' contents, are erased from the disk, including any sub-directories and files. Command: cp The "cp" command is used to copy files and directories. When using the cp command, you must always specify both the source and destination of the file(s) to be copied. Examples: o cp /home/Lab1 /home/OSLabs This command copies the "Lab1" file in "/home" to the directory named "/home/OSLabs". Command: mkdir The "mkdir" command is used to create new directories (sub-directories). Examples: 15 o mkdir Lab This command creates a new directory named "Lab" in your current directory. (This example assumes that you have the proper permissions to create a new sub-directory in your current working directory.) o mkdir memos letters This command creates two new sub-directories (memos, letters) in the current directory. o mkdir /home/labb This command creates a new directory named "labb" in the directory "/home". Command: rmdir The "rm" command is used to remove files and directories. (Warning - be very careful when removing files and directories!) Examples: o rm Lab This command deletes the file named "Lab" (assuming you have permission to delete this file). o rm Lab1 Lab2 This command deletes the files named "Lab1","Lab2". o rm -i Lab1 Lab2 This command prompt you before deleting any of the three files specified. The -i option stands for inquire. You must answer y (for yes) for each file you really want to delete. This can be a safer way to delete files. Command: rm The "rm" command is used to remove files and directories. Examples: o rm OSLab This command deletes the file named "OSLab" (assuming you have permission to delete this file). o rm Chapter1 Chapter2 This command deletes the files named "Chapter1", "Chapter2" o rm -r OSLab1 This command will delete the OSLab1(Assume that OSLab1 is a directory). o rm in* This command deletes all files in the current directory whose filename begins with the characters "in". o rm *.txt This command deletes all files in the current directory whose filename ends with the characters ".txt". rm *.txt This command deletes all files in the current directory whose filename ends with the characters ".txt". o rm in* 16 This command deletes all files in the current directory whose filename begins with the characters "in". o rm -r labb This command deletes the directory named "labb". This directory, and all of its' contents, are erased from the disk, including any sub-directories and files. Command: cd, chdir "cd" stands for change directory. It is the primary command for moving around the file system. Examples: o cd /home This command moves you to the "/home" directory. "/home" becomes your current working directory. o cd /h* Moves you to the "/home" directory - if this is the only directory matching this wildcard pattern. o cd Issuing the "cd" command without any arguments moves you to your home directory. Command: clear ―Clear‖ is used to clear the full screen of text, perhaps garbage on the terminal. Examples: o clear This command clears all text on the terminal. 3) Stage v (verify) Activity 1: Verify that you are in your home directory. Make the directory lABS using the following command. Activity 2: List the files in the current directory to verify that the directory LABS has been made correctly. Change directories to LABS. Activity 3: Create the file named file1. List the contents of the file file1 to the screen. Make a copy of the file file1 under the name file2. Verify that the files file1 and file2 both exist. Activity 4: List the contents of both file1 and file2 to the monitor screen. Then delete the file file1. Clear the window. Rename file2 to thefile. Activity 5: 17 Copy thefile to your home directory. Activity 6: Remove thefile from the current directory. Activity 7: Copy thefile from your home directory to the current directory. Change directories to your home directory. Remove thefile from your home directory and from directory LABS. Verify thefile is removed from the directory LABS. Remove the directory LABS from your home directory with the following command. Verify that thefile and LABS are gone from your home directory. 4) Stage a2 (assess) Through viva or practical demonstration of running commands 18 LAB # 03 Statement Purpose: This lab will give you the implementation of Linux commands. Activity Outcomes: This lab teaches you the following topics: Login to Linux Implement linux commands Instructor Note: Lecture 6,7,8 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 19 1) Stage J (Journey) Introduction Linux Terminal Now we are going to start Linux. As a first step we will do Linux commands. You must have used DOS commands copy, format, dir etc. Similarly Linux has such type of commands but with different syntax and format. You have to remember these commands because you will be using these commands frequently, and these commands will become base for your next practice. There is syntax for each command, using wrong syntax the command will not execute. As a first step we look how a user log in Linux OS. Then we go to Linux commands, and see their general syntax for all Linux commands. 2) Stage a1 (apply) Lab Activities: Logging In As you must have known that shell is interface between a user and Linux kernel. The first step you must accomplish before you can use Shell is to log in to your machine. This is usually a very straightforward process provided that you have a login ID and a password. If you enters a correct password, the system will return with a prompt inviting you to enter commands. When you login successfully, for an ordinary user account, the system will execute a program called the shell. Any program, while it is executing within the system is called a process. And it is your shell process that is responsible for giving you a command prompt. Logging out Logging out of Linux system is done by pressing control-D (^D). Command A request from a programmer, an operator, or a user to Linux operating system asking that a specific function be performed; for example, a request to list all files in your current directory. Shell commands operate on files, directories, and various devices – disk, printers, etc. Command mkdir directory-name Description Creates a new directory. Directory-name specifies the name of the new directory. If the name doesn’t begin with a slash, the new directory is created as a subdirectory of the current working directory. If the name begins with a slash, the name 20 defines the path from the root directory to the new directory. Example Try to use the following command first because this will bring you back to your home directory. $ cd (this command will bring you to the home directory) now try mkdir command user@ubuntu:~$ mkdir books This command will create a new directory under the home directory. user@ubuntu books Though you have created a sub-directory books, but you are still in the home (parent directory of books) directory i.e. user@ubuntu:~$ How would you go to the directory books? Command Description cd Change to another directory. For Example: $cd dir-name To change to any sub-directory under the current directory. Example user@ubuntu:~$ cd books (when enter is pressed the prompt becomes) user@ubuntu:~/books $ What are you feeling differences between two prompts? Now you are in books directory, a step down to home. How will you go up? user@ubuntu:~/books $ cd .. (there’s space between cd and ..) Now you will again in your parent directory. And the prompt becomes: user@ubuntu:~ $ Example Create other directory chemistry under books, and move to chemistry directory. user@ubuntu:~/books $ mkdir chemistry user@ubuntu:~/books $ cd chemistry user@ubuntu:~/chemistry $ Now you are quite away from your home directory. How would you go to your home directory? Your current location is user@ubuntu:~$ books chemistry To go to your home directory: user@ubuntu:~/chemistry $ cd (enter) The prompt will become: user@ubuntu:~ $ 21 Example Now you are in your home directory. How will you go directly to chemistry directory? user@ubuntu:~$ cd books/chemistry (enter) 3) Stage v (verify) What do you think books/chemistry is relative or absolute path? Activity 1: Make the following directory hierarchy: math books physics trigonometry calculus quantum computer classical nuclear Example If I’m in directory classical, how would I find where I am? The command used for the purpose is pwd (covered in previous lab). When I entered this command when I was in directory classical the following information was printed on my screen. The path printed was absolute path. So when you lost in directory structure you could find the way to your current directory by command pwd. For Example: user@ubuntu:~/classical $ pwd /home/staff/uzair/books/physics/classical (for example) Activity 2: How will you add a directory graphics under the directory computer while you are in physics’ sub-directory classical? Now you can create directories. What is the way removing them? Command Description rmdir (‘remove directory”) Deletes a directory. For example $rmdir dirname Note:rmdir will only work if the directory you are trying to remove does not contain any file. So first remove all files from the directory. Activity 3: (Note: First complete part a from this exercise and then move activity. 4) 22 a) You are in books directory, from here try to remove sub-directory quantum under the directory physics. Now move to directory computer, from here remove sub-directory calculus under the directory math. Now create again both removed directories. You can, remove directories, now look at how to create and delete files. Creating file through pico editor There are number of editors (e.g. Gedit-GUI based) through which files can be created, but easiest way to use is through pico editor in shell. Example $ pico notes With this command an editor will be opened. Enter text into the file. Press Ctrl-O to save the file, and Ctrl-X to exit from the editor. In order to view an existing file use cat command. Activity 4: Create a file using “pico” editor and save it with your name. Removing/Deleting files Command Description rm (‘remove’) Removes a file permanently. For example, $rm filename Options -r -i Deletes an entire directory, and all the files it contains. This option puts the rm command into interactive mode and prompts you before it removes it Activity 5: Try to remove a directory having some files in it, and observe the response of system. $rm directoryname Note:- To remove all files from a directory use $ rm dirname/* 23 Command Description date The date command displays the current date and time on the screen. The system administrator sets the date users cannot change them. Example $date Wed Feb 7 10:35:41 PKT 2006 There are number of options in which date can be displayed. If you want to see only date, you can do this like this: $ date +”%d” 07 for time only $date +”%r” 10:38:11 AM %Y = Year. %H = Hour(00..23), %I = Hour (01..12), %m = Month Command Description clear Clears the screen. Command Description echo Echoes back whatever you type on the command line after echo. Options -n information. doesn’t begin a new line after echoing the Example echo Hello there Example echo -n 4) Hello Stage a2 (assess) Through viva or practical demonstration 24 LAB # 04 Statement Purpose: This lab will give you the overview of Inter-process Communication and Implement the Inter-process Communication using pipes Activity Outcomes: This lab teaches you the following topics: Inter process communication Its implementation through pipes Instructor Note: Lecture 9 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 25 1) Stage J (Journey) Introduction Interprocess communication (IPC) is a mechanism for processes to communicate and to synchronize their actions. It is a set of programming interfaces that allows a programmer to coordinate activities among different program processes that can run concurrently in an operating system. This allows a program to handle many user requests at the same time. Since even a single user request may result in multiple processes running in the operating system on the user's behalf, the processes need to communicate with each other. The IPC interfaces make this possible. Each IPC method has its own advantages and limitations so it is not unusual for a single program to use all of the IPC methods. Pipes: A pipe is a communication channel between two ends. It is mostly used to communicate between processes running within a computer. It is a communication device that permits unidirectional communication. Data written to the ―write end‖ of the pipe is read back from the ―read end‖. Pipes are serial devices; the data is always read from the pipe in the same order it was written. A pipe‘s data capacity is limited. If the writer process writes faster than the reader process consumes the data, and if the pipe cannot store more data, the writer process blocks until more capacity becomes available. If the reader tries to read but no data is available, it blocks until data becomes available. Thus, the pipe automatically synchronizes the two processes. 2) Stage a1 (apply) Lab Activities: Creating Pipes: To create a pipe, invoke the pipe command. Supply an integer array of size 2.The call to pipe stores the reading file descriptor in array position 0 and the writing file descriptor in position 1. For example, consider the code: int pipe_fds[2]; int read_fd; int write_fd; pipe (pipe_fds); read_fd = pipe_fds[0]; write_fd = pipe_fds[1]; Data written to the file descriptor read_fd can be read back from write_fd. To create a simple pipe with C, we make use of the pipe () system call. It takes a single argument, which is an array of two integers. If successful, the array will contain two new file descriptors to be used for the pipeline. System call: pipe (); Prototype: int pipe (int fd[2] ); It returns 0 on success, -1 on error. 26 NOTE: o fd[0] is set up for reading o fd[1] is set up for writing The first integer in the array (element 0) is set up and opened for reading, while the second integer (element 1) is set up and opened for writing. Visually speaking, the output of fd1 becomes the input for fd0. 27 printf("End!\n"); } return(0); } 3) Stage v (verify) Activity 1: Compute the Factorial of a number using IPC (PIPE implementation). 28 o Parent creates pipe o Forks a child o Parent writes into pipe (the number whose factorial is to be calculated, take the number from the user) o Child reads from pipe and compute the Factorial of a number written by Parent Activity 2: Using pipes, parent read data from one file, and child write data into another file. 4) Stage a2 (assess) Through viva or practical demonstration 29 LAB # 05 Statement Purpose: This lab will give you the concepts of multi threading. Activity Outcomes: This lab teaches you the following topics: Overview of multithreading Thread programming Instructor Note: Lecture 9 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 30 1) Stage J (Journey) Introduction A thread is a single sequence stream within in a process. Threads have some of the properties of processes; they are sometimes called lightweight processes. In a process, threads allow multiple executions of streams. In many respect, threads are popular way to improve application through parallelism. The CPU switches rapidly back and forth among the threads giving illusion that the threads are running in parallel. Like a traditional process i.e., process with one thread, a thread can be in any of several states (Running, Blocked, Ready or Terminated). Each thread has its own stack. Since thread will generally call different procedures and thus a different execution history. This is why thread needs its own stack. An operating system that has thread facility, the basic unit of CPU utilization is a thread. A thread has or consists of a program counter (PC), a register set, and a stack space. Threads are not independent of one other like processes as a result threads shares with other threads their code section, data section, OS resources also known as task, such as open files and signals. Multithreading is the ability of a program or an operating system process to manage its use by more than one user at a time and to even manage multiple requests by the same user without having to have multiple copies of the programming running in the computer. Each user request for a program or system service (and here a user can also be another program) is kept track of as a thread with a separate identity. As programs work on behalf of the initial request for that thread and are interrupted by other requests, the status of work on behalf of that thread is kept track of until the work is completed. Thread Programming: Some of the basic thread routines are as follows: Creation: int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg); o Analogous to a combined fork and exec routine o Returns a thread id in thread. o When attr is NULL the default thread attributes are used. Pthread_t: It is defining a thread pointer. When a thread is created identifier is written into the variable to which the pointer points. This identifier helps to refer to thread. Pthread_attr_t: It is used to set the thread attributes. If attr is NULL, the default attributes are used. Name of function: The name of the function to be started by the thread for execution. Arguments to be passed to the function: When a new thread is created it executes the function pointed by the function variable name. On success, pthread_create ( ) returns 0, and on error, it returns an error number. Termination void pthread_exit(void * return_value); 31 o o o o o Analogous to exit The exit routine kills all threads and exits the process If the current thread is the last thread then the process terminates Returning from the start_routine is equivalent to calling pthread_exit Returning from the initial thread main is the equivalent to calling exit Detach and Join int pthread_detach(pthread_t thread); int pthread_join(pthread_t thread, void ** status); o Analogous to wait o Must specify thread. There is no wait any. o Current thread blocks until thread terminates o The return value of thread is returned in status o All threads must be detached or joined with. pthread_join: It is used to wait for the thread represented in the thread_join call. It waits for the thread represented in the call to finish executing. It waits for the specified thread to complete, and gathers information about the thread's exit status. Self and Equal pthread_t pthread_self(void); int pthread_equal(pthread_1 t1, pthread_t t2); 2) Stage a1 (apply) Lab Activities: 32 33 /* sleep() causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. */ sleep(1); }} 34 3) Stage v (verify) Activity 1: Write a program for matrix addition, subtraction and multiplication using multithreading. 4) Stage a2 (assess) Through viva or practical demonstration 35 LAB # 07 Statement Purpose: This lab will give you the concept of implementing Shortest Job First (Non-Preemptive) CPU Scheduling Algorithm Activity Outcomes: This lab teaches you the following topics: CPU scheduling algorithm Implementation of shortest job first algorithm Instructor Note: Lecture 15 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 36 1) Stage J (Journey) Introduction Associate with each process the length of its next CPU burst. Use these lengths to schedule the process with the shortest time. Two schemes: Non preemptive: Once CPU given to the process it cannot be preempted until completes its CPU burst Preemptive: If a new process arrives with CPU burst length less than remaining time of current executing process, preempt. This scheme is known as the Shortest-Remaining-Time-First (SRTF) SJF is optimal gives minimum average waiting time for a given set of processes Suppose that there are four processes P1, P2, P3, P4 The Gantt chart for the Schedule is: Average waiting time: (0+6+3+7)/4=4 2) Stage a1 (apply) Algorithm: 1) 2) 3) 4) Take total no. of processes from user. Take Name, Arrival Time and Burst Time for each process. Select the process which have shortest burst will execute first. If all processes arrive at 0 time interval than process with the smallest CPU Burst will execute first. 37 5) If processes arrive at different time intervals than CPU will be given to the process that will arrive first and let the other processes to be in queue. 6) If two processes have same burst length then FCFS scheduling algorithm will be used. 7) Sort the processes in ascending order of their CPU Burst. 8) Compute Waiting Time & Turnaround Time for each process. 9) Compute Average Waiting Time & Turnaround Time of processes. 10) Display Average Waiting and Turnaround Time of processes. 11) Display the Gantt chart. 3) Stage v (verify) Activity 1: Implement Shortest Job First (Non-Preemptive) CPU Scheduling Algorithm. Output: 4) Stage a2 (assess) Through viva or practical demonstration 38 LAB # 08 Statement Purpose: This lab will give you the concept of implementing Round Robin CPU Scheduling Algorithm Activity Outcomes: This lab teaches you the following topics: CPU scheduling algorithm Implementation of Round Robin algorithm Instructor Note: Lecture 15 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 39 1) Stage J (Journey) Introduction The round-robin (RR) scheduling algorithm is designed especially for time-sharing systems. It is similar to FCFS scheduling, but pre-emption is added to switch between processes. A small unit of time called time slice or quantum is defined. All runable processes are kept in a circular queue. The CPU scheduler goes around this queue, allocating the CPU to each process for a time interval of one quantum. New processes are added to the tail of the queue. Every time a process is granted the CPU, a context switch occurs, which adds overhead to the process execution time. 2) Stage a1 (apply) Algorithm for Round Robin: Get total no. of processes from user. Get Name, Arrival Time and Burst Time for each process. Get the Quantum/Time Slice. Maintain a circular ready queue. Make the CPU scheduler goes around the ready queue allocating CPU to each process for the time slice specified. Make the CPU scheduler picks the first process and after quantum expired, dispatches the process. If the process have burst less than the time quantum then: The process releases the CPU. The scheduler will then proceed to the next process in the ready queue. If the CPU burst of the currently running process is longer than 1 time quantum then: The process will be executed for quantum time and then the process will be put at the tail of the ready queue. The CPU scheduler will then select the next process in the ready queue. Compute Waiting Time & Turnaround Time for each process. Calculate Average Waiting Time & Average Turnaround Time of processes. 3) Stage v (verify) Activity 1: Implement Round Robin CPU Scheduling Algorithm.(Time quantum should be entered by user) 4) Stage a2 (assess) Through viva or practical demonstration 40 LAB # 09 Statement Purpose: This lab will give you the concept of Simulating Banker’s Algorithm for Deadlock Avoidance. Activity Outcomes: This lab teaches you the following topics: Deadlock Avoidance Simulating Banker’s algorithm Instructor Note: Lecture 17, 18, 19 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 41 1) Stage J (Journey) Introduction The Banker‘s Algorithm is a resource allocation that tests the safety by simulating the allocation of predetermined maximum possible amounts of all resources, and then makes "s-state" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue. When a new process enters the system, it declares the maximum number of instances that are needed. This number cannot exceed the total number of resources in the system. If the process can be accommodated based upon the needs of the system, then resources are allocated, otherwise the process must wait. The algorithm is actually made up of two separate algorithms: the safety algorithm and the resource allocation algorithm. Data Structures for the Banker’s Algorithm o p = number of processes o r = number of resource types o Available: Vector of length r. If available[j] = k, there are k instances of resource type R j available. o Max: p x r matrix. If Max [i,j] = k, then process Pi may request at most k instances of resource type Rj. o Allocation: p x r matrix. If Allocation [i,j] = k then Pi is currently allocated k instances of Rj. o Need: p x r matrix. If Need [i,j] = k, then Pi may need k more instances of Rj to complete its task. Need [i,j] = Max[i,j] – Allocation [i,j] 2) Stage a1 (apply) Steps for Banker’s (Safety) Algorithm: 1) 2) 3) 4) 5) 6) 7) Get total no. of processes from user. Get total no. of resources. Get the values for Max Matrix. Get the values for Allocation Matrix. Get maximum instances of each resource type. Find Need Matrix. Find Available Vector. 1. Let Finish be vector of length p. Initially Finish[i] = false; i = 1, 2, …, p. 2. Find and i such that both: a. Finish[i] = false b. Needi ≤ Availbale If no such i exists, go to step 4. 3. Available = Available + Allocationi 8) Finish[i] = true 9) Go to step 2. a) If Finish [i] == true for all i, then the system is in a safe state. 10) Display the result. 42 3) Stage v (verify) Activity 1: Implement Banker‘s Algorithm. 4) Stage a2 (assess) Through viva or practical demonstration 43 LAB # 10 Statement Purpose: This lab will give you the concept of paging and memory management. Activity Outcomes: This lab teaches you the following topics: Paging technique Memory management Instructor Note: Lecture 22, 23 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 44 1) Stage J (Journey) Introduction Logical address space of a process can be noncontiguous; process is allocated physical memory whenever the latter is available Divide physical memory into fixed-sized blocks called frames (size is power of 2, between 512 bytes and 8,192 bytes) Divide logical memory into blocks of same size called pages Keep track of all free frames To run a program of size n pages, need to find n free frames and load program ALGORITHM: 1. Start 2. Read the number of pages 3. Read the page size 4. Allocate the memory to the pages dynamically in non contiguous locations. 5. Display the pages and their addresses. 6. Stop 2) Stage a1 (apply) 45 3) Stage v (verify) Activity 1: Implement paging having the number of pages =10, and page size =4. 4) Stage a2 (assess) Through viva or practical demonstration 46 LAB # 11 Statement Purpose: This lab will give you the concept of page replacement algorithms Activity Outcomes: This lab teaches you the following topics: Page replacement algorithms FIFO LRU LFU Instructor Note: Lecture 25 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 47 1) Stage J (Journey) Introduction 1) FIFO: 2) Stage a1 (apply) Code: 48 49 Output: 3) Stage v (verify) Activity 1: Implement the FIFO algorithm. 4) Stage a2 (assess) Through viva or practical demonstration 50 1) Stage J (Journey) Introduction b) LRU: 2) Stage a1 (apply) Code: 51 52 53 Output: 54 3) Stage v (verify) Activity 1: Implement LRU algorithm. 4) Stage a2 (assess) Through viva or practical demonstration 55 1) Stage J (Journey) Introduction c) LFU: 2) Stage a1 (apply) Code: 56 57 58 Output: enter the number of frames:5 enter the page size2 59 3) Stage v (verify) Activity 1: Implement LFU algorithm. 4) Stage a2 (assess) Through viva or practical demonstration 60 LAB # 13 Statement Purpose: This lab will give you the concept of file allocation strategy through sequential method. Activity Outcomes: This lab teaches you the following topics: File allocation strategy Sequential Instructor Note: Lecture 26, 28, 29 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 61 1) Stage J (Journey) Introduction 2) Stage a1 (apply) Code: 62 Output: 63 3) Stage v (verify) Activity 1: Implement file allocation algorithm through sequential method. 4) Stage a2 (assess) Through viva or practical demonstration 64 LAB # 14 Statement Purpose: This lab will give you the concept of file allocation strategy through Indexed method. Activity Outcomes: This lab teaches you the following topics: File allocation strategy Indexed Instructor Note: Lecture 26, 28, 29 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 65 1) Stage J (Journey) Introduction 2) Stage a1 (apply) Code: 66 Output: 67 3) Stage v (verify) Activity 1: Implement File allocation algorithm through Indexed method. 4) Stage a2 (assess) Through viva or practical demonstration 68 LAB # 15 Statement Purpose: This lab will give you the concept of file allocation strategy through Linked method. Activity Outcomes: This lab teaches you the following topics: File allocation strategy Linked Instructor Note: Lecture 26, 28, 29 Text book: Galvin, Peter B., Greg Gagne, and Abraham Silberschatz. Operating system concepts. John Wiley & Sons, Inc., 2016. 69 1) Stage J (Journey) Introduction 2) Stage a1 (apply) Code: 70 } 71 Output: 3) Stage v (verify) Activity 1: Implement File allocation algorithm through Linked method. 4) Stage a2 (assess) Through viva or practical demonstration 72