You are on page 1of 53

UNIVERSITY OF ENGINEERING AND TECHNOLOGY PESHAWAR (MARDAN CAMPUS)

Operating System Lab


Manual
Department of Computer Software Engineering

Prepared by: Engr. Fahim Ullah Khan

Version: 1.0

Date: 17th Nov, 2014


Table of Contents

Lab 01 OS Administration- Installation of Linux Distribution (Ubuntu) ............................... 4


1.1 Objective ........................................................................................................................................... 4
1.2 Equipment/ Tools Requirements ................................................................................................... 4
1.3 System Requirements..................................................................................................................... 4
1.4 Downloading Ubuntu ....................................................................................................................... 4
1.5 Allocate Drive Space ....................................................................................................................... 4
1.6 Creating a bootable USB drive ...................................................................................................... 7
1.7 Installation of Ubuntu (Step by Step) ...................................................................................... 8
1.8 Lab Task .................................................................................................................................... 11
Lab 02 OS Administration-2: Exploring the Linux Environment..........................................12
2.1 Objective ......................................................................................................................................... 12
2.2 Equipment/ Tools Requirements ................................................................................................. 12
2.3 Description ...................................................................................................................................... 12
2.4 Linux File Systems ........................................................................................................................ 12
2.5 File system layout .......................................................................................................................... 13
2.6 Subdirectories of the root directory ............................................................................................. 13
2.7 Using commands to explore Linux directory structure ............................................................. 14
2.8 Lab Task ......................................................................................................................................... 16
Lab 03 OS Administration-3: Essential Linux Commands ...................................................17
3.1 Objective ......................................................................................................................................... 17
3.2 Equipment/ Tools Requirements ................................................................................................. 17
3.3 Adding and Deleting the users .................................................................................................... 17
3.4 Linux Basic Commands..................................................................................................................... 18
3.5 Linux process command............................................................................................................... 19
3.6 File Manipulation Commands ...................................................................................................... 19
3.7 Command Grouping and Filter Commands ............................................................................... 20
3.8 Lab Task ......................................................................................................................................... 20
Lab 04 OS Administration-4: Process States In OS..............................................................21
4.1 Objective ......................................................................................................................................... 21
4.2 Windows Operating System Task Manager ......................................................................... 21
1
4.3 Linux operation system Process state........................................................................................ 22
4.4 Lab Task ......................................................................................................................................... 24
Lab 05 Process Management-1: Process Creation ...............................................................25
5.1 Objective ......................................................................................................................................... 25
5.2 Equipment/ Tools Requirements ................................................................................................. 25
5.2 Process creation ............................................................................................................................ 25
5.3 Process Identification .................................................................................................................... 25
5.4 Process System Calls ................................................................................................................... 25
5.5 System calls fork(), getpid(), getppid() ....................................................................................... 26
5.6 Lab Task ......................................................................................................................................... 27
Lab 06 Process Management-2: Process Exit & Wait System Calls ....................................28
6.1 Objective ......................................................................................................................................... 28
6.2 exit() system call ............................................................................................................................ 28
6.3 wait() system calls ......................................................................................................................... 29
6.4 Lab Task ......................................................................................................................................... 30
Lab 07 Process Management-3: Creating and Managing Multiple/Orphan Processes ......31
7.1 Objective ......................................................................................................................................... 31
7.2 Multiple Fork() Calls ...................................................................................................................... 31
7.3 Orphan processes ......................................................................................................................... 31
7.4 Lab Task ......................................................................................................................................... 32
Lab 08 Process Scheduling-1: First Come First Serve (FCFS) ............................................33
8.1 Objective ......................................................................................................................................... 33
8.2 Multiprogramming .......................................................................................................................... 33
8.3 Scheduling Algorithms .................................................................................................................. 33
8.4 First-come First-served Scheduling (FCFS) .............................................................................. 33
8.4.2 Disadvantages ............................................................................................................................ 34
8.5 Lab Task ......................................................................................................................................... 35
Lab 09 Process Scheduling-2: Shortest Job First ................................................................36
9.1 Objective ......................................................................................................................................... 36
9.2 Multiprogramming .......................................................................................................................... 36
9.3 Scheduling Algorithms .................................................................................................................. 36
9.4 Shortest Job First Scheduling (SJF) ........................................................................................... 36
9.4.1 Advantages ................................................................................................................................ 37
9.4.2 Disadvantages ............................................................................................................................ 37

2
9.5 Lab Task ......................................................................................................................................... 38
Lab 10 Process Scheduling-3: Round Robin ........................................................................39
10.1 Objective ....................................................................................................................................... 39
10.2 Round-Robin Scheduling ........................................................................................................... 39
10.2.1 Advantages .............................................................................................................................. 39
10.2.2 Disadvantages .......................................................................................................................... 39
10.3 Performance of RR Scheduling ................................................................................................. 39
10.4 Lab Task ....................................................................................................................................... 41
Lab 11 Mutual Exclusion using Semaphores ........................................................................42
11.1 Objective ....................................................................................................................................... 42
11.2 Description.................................................................................................................................... 42
11.2.1 ADVANTAGES: .......................................................................................................................... 42
11.2.2 DISADVANTAGES: ..................................................................................................................... 42
11.3 Lab Task ....................................................................................................................................... 44
Lab 12 File I/O: Reading & Writing from/to a File ..................................................................45
12.1 Objective ....................................................................................................................................... 45
12.2 Description.................................................................................................................................... 45
12.3 Lab Task ....................................................................................................................................... 46
Lab 13 Inter-Process Communication Using Pipes ..............................................................47
13.1 Objective ....................................................................................................................................... 47
13.2 Description.................................................................................................................................... 47
13.3 Lab Task ....................................................................................................................................... 49
Lab 14 Memory Management .................................................................................................50
14.1 Objective ....................................................................................................................................... 50
14.2 Description.................................................................................................................................... 50
14.3 Lab Task ....................................................................................................................................... 52

3
Lab 01 OS Administration- Installation of Linux Distribution (Ubuntu)

1.1 Objective
In this lab, students will learn how to:

 Download Ubuntu Version 14.04.1 LTS


 Allocate proper drive space for the installation.
 Create bootable USB drive as a start-up disk.
 Install Ubuntu (Step-by-Step).

1.2 Equipment/ Tools Requirements


 Computer with the system requirements listed in section 1.3.
 Internet connectivity.
 A USB memory stick of at least 2 GB free space.

1.3 System Requirements


The following are the minimum system requirements for Ubuntu installation:

 1 GHz x86 processor (Pentium 4 or better)


 1 GB of system memory
 Disk space (at least 15 GB is recommended)

1.4 Downloading Ubuntu


Step 1: Type http://www.ubuntu.com/download in your internet browser’s address bar and press the
enter button. You will see multiple download options on the retrieved website.

Step 2: Click on the “Ubuntu Desktop” option and the download will start. “Ubuntu Desktop” is the version
of Ubuntu operating system for desktop PCs and laptops.
 The other download options “Ubuntu Server” and “Ubuntu Cloud” are for managing servers and
clouds and are beyond the scope of this lab course.
 The download option “Ubuntu Kylin” is for the specific needs of the Chineese users and is beyond
the scope of this lab course.

Step 3: On the next page, select 64bit or 32 bit depending upon the architecture of your computer system
and click the download button.
 Instructor should guide the students in this step for the proper download.

Step 4: On the next page, you will be asked for payment. Ubuntu is a free to download, use and re-use
Linux Distribution. However, payment is volunteer/optional and can be skipped by sliding all the bars to
the left to make overall $0 contribution.

Step 5: On the bottom of the page, click on the “Download” button. The ISO image of Ubuntu Desktop
will be downloaded to the specified location on the hard drive for further installation.

1.5 Allocate Drive Space

To prepare your hard disk to store the Ubuntu system and your files, hard disk is divided into partitions.
Each partition reserves a specific portion of the hard disk for use by a particular operating system. As an
example, you may use the entire hard disk for your new Ubuntu system or you may share the disk so that
both Windows and Ubuntu are installed. This shared scenario is known as dual-booting. In a dual-booting
situation, your hard disk typically has Windows partitions as well as Linux partitions where it gives you a
4
menu at start up so that you can select whether to boot Windows or Linux. Follow the following steps to
shrink a windows partition and make un-allocated space for Ubuntu installation.

Step 1: Right click on “My Computer” icon and click on the “Manage” from the drop down menu.
 Note: This partition facility is only available in Microsoft Windows 7 and onward releases. For the
previous windows releases, use a third party utility (e.g., Partition Magic).

Step 2: A window will open as shown in Figure 1.1. Double click on the “Disk Management” under the
“Storage” on the left hand side (as highlighted in the figure).

Figure 1.1: Disk Management Utility in Win 7 & 8

Step 3: You will see the screen, as shown in Figure 1.2, showing the entire hard drive partitions. Right
click on the drive which you want to shrink to make un-allocated space. Click on the “Shrink” option.

 Note: The drive shrink facility is only available for the NTFS file system. If your drive is
formatted using FAT32 file system, use alternative methods.

5
Figure 1.2: Disk Management Utility in Win 7 & 8.

Step 4: If you need a capacity of 15 GB free space, enter 15360MB as shown in the Figure 1.3.

Figure 1.3: Allocating free space

Step 5: You will see 15GB “unallocated” space on your hard drive shown in Figure 1.4.

6
Figure 1.4: Unallocated space

1.6 Creating a bootable USB drive


You will need a bootable media to boot the system for your Linux distribution installation. In this session, we will use
USB memory stick as the bootable media. You need to make your USB memory stick bootable for the installation
start up by using a certain tool. To make a bootable USB memory stick, perform the following steps:

Step1: Type http://www.softpedia.com/get/System/OS-Enhancements/Universal-USB-Installer.shtml#download in


your internet browser’s address bar and press the enter button and download the installer tool. Alternatively, search
for “USB universal installer” on the Internet.

 Note: The Universal USB installer has been placed on the Windows desktop for your convenience.

Step2: Insert the USB stick in the port and double click the installer icon (.exe). Click on “I Agree” button.

Step3: On the next screen, select “OpenSuse 64 bit” or “Ubuntu 64 bit” from the Linux distribution drop down menu.
Click on the “Browse” button and locate the OpenSuse or Ubuntu image on the disk. Select USB from the last drop
down menu on the dialogue box. Finally, click on the “Create” button. The process is shown in Figure 1.5.
 Note: The OpenSuse or Ubuntu image has been placed on your windows desktop for your convenience.
Alternatively, you can download the image directly from the opensuse or Ubuntu official websites.

Figure 1.5: Universal USB Installer setup

7
Step 4: Insert the USB memory stick in the USB port of your computer. Select “Disk Image” radio option
on the left bottom of Figure 1.5. Select ISO from the drop down menu against the Diskimage and click the
button to load the Ubuntu ISO image (already saved to the specified location on hard disk in section 1.4
Step 5).

Step 5: Select USB Drive from the drop down menu in front of Type label. Select the USB memory stick
from the Drive drop down menu. Click OK to continue.

Step 6: At the end, the system will ask for reboot. Press the “Reboot” button.

1.7 Installation of Ubuntu (Step by Step)


Step 1: Make sure that you have created 15 GB (recommended) unallocated space on the storage media
in Section 1.5 and a bootable USB memory stick as given in Section 1.6. Make sure that you have
changed the BIOS setup to make USB as the first boot device.

Step 2: Insert the bootable USB Memory stick in the computer USB port and restart the computer. The
welcome window shown in Figure 1.6 will allow you to select language and start installation. Click on the
“Install Ubuntu” button.

Figure 1.6: Ubuntu Installation Welcome Screen

Step 3: The installer will ask you to connect to the existing internet connection. It is recommending
because the installer will update the required software online as shown in Figure 1.7. Configure the
wireless/wired network connection. Click on “Connect”.

8
Figure 1.7: Network Connection

Step 4: The next screen will ask to enter your location. As shown in Figure 1.8, select your region and
click the continue button. Ubuntu will automatically adjust/configure the time zone.

Figure 1.8: Location and Time Zone

Step 5: The next screen will ask you to configure/select the keyboard layout. Select the appropriate
keyboard layout (e.g., English(US) and click on the continue button as shown in Figure 1.9.

9
Figure 1.9: Selecting Keyboard Layout

Step 6: Next, the Ubuntu installer will ask you to give information, i.e. computer name, your desired
name and password as shown in Figure 1.10. Enter your desired user name and secure/strong password.
Click continue button to proceed.

Figure 1.10: Entering User Name and Password

Step 7: After providing the required information the installer will finish installation and Ubuntu is ready
work.

10
1.8 Lab Task
 The students are required to install Ubuntu/OpenSuse or any other Linux distribution on their PCs
individually.
 Students are required to document all the steps (write on a sheet) and report it to the instructor.
 Explore the GUI of the Linux distribution.
 Start the Shell (Terminal).

11
Lab 02 OS Administration-2: Exploring the Linux Environment

2.1 Objective
The purpose of this lab session is:

 Description of Unix/Linux Systems


 To get familiar with Linux file system
 Using Command to Explore Linux Directory Structure

2.2 Equipment/ Tools Requirements


 Computer System with Linux installed
 Shell

2.3 Description

A simple description of the UNIX system, also applicable to Linux, is this:

 "On a UNIX system, everything is a file; if something is not a file, it is a process”. This statement
is true because there are special files that are more than just files (named pipes and sockets, for
instance), but to keep things simple, saying that everything is a file is an acceptable generalization.
 A Linux system, just like UNIX, makes no difference between a file and a directory, since a
directory is just a file containing names of other files.
 Programs, services, texts, images, are all files.
 Input and output devices, and generally all devices, are considered to be files, according to the
system.
 In order to manage all those files in an orderly fashion, we like to think of them in an ordered tree-
like structure on the hard disk, as we know from MS-DOS (Disk Operating System) for instance.
 The large branches contain more branches, and the branches at the end contain the tree's leaves or
normal files.

2.4 Linux File Systems

Most files are just files, called regular files; they contain normal data, for example text files, executable
files or programs, input for or output from a program and so on.

While it is reasonably safe to suppose that everything you encounter on a Linux system is a file, there are
some exceptions.

 Directories: files that are lists of other files.


 Special files: the mechanism used for input and output. Most special files are in /dev, we will
discuss them later.
 Links: a system to make a file or directory visible in multiple parts of the system's file tree. We
will talk about links in detail.

12
2.5 File system layout
For convenience, the Linux file system is usually thought of in a tree structure. On a standard Linux
system you will find the layout generally follows the scheme presented in Figure 2.1.

Figure 2.1: Linux Directory System

Depending on the system admin, the operating system and the mission of the UNIX machine, the structure
may vary, and directories may be left out or added at will. The names are not even required; they are only
a convention.

The tree of the file system starts at the trunk or slash, indicated by a forward slash (/). This directory,
containing all underlying directories and files, is also called the root directory or "the root" of the file
system.

Directories that are only one level below the root directory are often preceded by a slash, to indicate their
position and prevent confusion with other directories that could have the same name. When starting with
a new system, it is always a good idea to take a look in the root directory. Let's see what you could run
into:

cselab:~> cd /
cselab:/> ls
bin/ dev/ home/ lib/ misc/ opt/ root/ tmp/ var/
boot/ etc/ initrd/ lost+found/ mnt/ proc/ sbin/ usr/

2.6 Subdirectories of the root directory


 To view the directory structure and their purpose issue the command heir on the command
shell and press enter key.

Note: Instructor is directed to explain the purpose of these directories to the students.

Directory Content
/bin Common programs, shared by the system, the system administrator and the users.

13
Directory Content
The startup files and the kernel, vmlinuz. In some recent distributions also grub data.
/boot Grub is the GRand Unified Boot loader and is an attempt to get rid of the many different
boot-loaders we know today.
Contains references to all the CPU peripheral hardware, which are represented as files with
/dev
special properties.
Most important system configuration files are in /etc, this directory contains data similar
/etc
to those in the Control Panel in Windows
/home Home directories of the common users.
/initrd (on some distributions) Information for booting. Do not remove!
/lib Lcsey files, includes files for all kinds of programs needed by the system and the users.
Every partition has a lost+found in its upper directory. Files that were saved during
/lost+found
failures are here.
/misc For miscellaneous purposes.
/mnt Standard mount point for external file systems, e.g. a CD-ROM or a digital camera.
/net Standard mount point for entire remote file systems
/opt Typically contains extra and third party software.
A virtual file system containing information about system resources. More information
/proc about the meaning of the files in proc is obtained by entering the command man proc in
a terminal window. The file proc.txt discusses the virtual file system in detail.
The administrative user's home directory. Mind the difference between /, the root directory
/root
and /root, the home directory of the root user.
/sbin Programs for use by the system and the system administrator.
Temporary space for use by the system, cleaned upon reboot, so don't use this for saving
/tmp
any work!
/usr Programs, lcseies, documentation etc. for all user-related programs.
Storage for all variable files and temporary files created by users, such as log files, the mail
/var queue, the print spooler area, space for temporary storage of files downloaded from the
Internet, or to keep an image of a CD before burning it.

2.7 Using commands to explore Linux directory structure


● To check your current working directory, use pwd command
– cse@linux-8f49:~> pwd //press enter
– /home/cse //output on the screen
● The cd command changes the current directory to the target directory
– cse@linux-8f49:~> cd /home // changes the current directory from /home/cse to /home
– cse@linux-8f49:/home> pwd //check it
– /home //report it
● The cd command without argument (target) will place you in your home directory
– cse@linux-8f49:/home> pwd //test where you are currently
– /home //at /home
– cse@linux-8f49:/home> cd // change to your home directory
– cse@linux-8f49:~> pwd
– /home/cse // here it is
● The cd.. will switch you to your parent directory one above your current directory

14
– cse@linux-8f49:~> pwd //check your current home directory
– /home/cse //printed
– cse@linux-8f49:~> cd.. //this will lift you one step above
– cse@linux-8f49:/home> pwd //check it
– /home //the parent directory above cse is the home directory
– cse@linux-8f49:/home> cd.. // again lifted one step above
– cse@linux-8f49:/> pwd //the parent directory of home is /
– /
– Try cd ../.. assuming that you are in your home directory
● The cd - (space between cd & -) command will place you in your previous directory
– cse@linux-8f49:~> pwd // check your current directory
– /home/cse // your current directory
– cse@linux-8f49:~> cd /etc //change it to something else
– cse@linux-8f49:/etc> pwd // check it
– /etc
– cse@linux-8f49:/etc> cd - //go to the previous directory directly
– /home/cse //your previous directory was this one
– cse@linux-8f49:~> pwd //check it
– /home/cse //here it is

● The ls command displays the contents of a directory

– Go to the / directory (type command cd /)

– cse@linux-8f49:/> pwd

– /

– cse@linux-8f49:/> ls

– bin boot dev etc home lib lib64 lost+found media mnt opt proc root run sbin selinux srv
sys tmp usr var

– Navigation to all the directories and seeing their contents

● Recognizing the contents of a directory by color

– Blue color - Directory

– Green color - Executable or recognized data file

– Sky Blue Color - Linked file

– yellow with black background - device

– Pink colour - graphic image file

– Red - Archive file

● The ls -a command shows all files of the current directory including hidden files
– Hidden files/directories start with a dot (.)
● The ls -l command shows the files and directories in a long list
● The ls -l -h (ls -lh or ls -hl) command shows the files and directories in more human readable format

15
2.8 Lab Task
 Switch to the sbin directory and report your current working directory.
 List the contents of etc directory directly from your current directory assuming that you are not at the “/”
directory.
 List the contents of etc directory by navigation from /var directory.
 List and identify the contents of /bin and /sbin.
 From the /bin directory, write the name of any entry and press enter. Report the output of the action taken.
 List the contents of /dev directory.
 List the contents of the root directory.
 List a long listing of the root directory
 Save your lab activity after executing each command along with the output in a text file.
 Save the text file with your RegistrationNuber_Name.

16
Lab 03 OS Administration-3: Essential Linux Commands

3.1 Objective
In this lab, the students will get familiar with the basic Linux shell Commands. The objectives of the lab
session are:

 To create users using command line.


 To execute the Linux basic commands and know their purpose.
 To explore the commands used for process state information on a Linux machine.

3.2 Equipment/ Tools Requirements


 Computer with Linux Operating System Installed
 Shell

3.3 Adding and Deleting the users


You must be the root/super user to create and delete users’ accounts. To switch to the super user, if you
are not already, type the following commands in the shell:

– cse@linux-8f49:~> su // this is a common user


– Password: **** // here provide the password
– linux-8f49:/home/cse # // root (super) user interface
To create a user account with the name 'aslam'

– linux-8f49:/home/cse # useradd aslam


– linux-8f49:/home/cse # passwd aslam
– New password: //Type the password for the new user
– BAD PASSWORD: it is WAY too short
– BAD PASSWORD: is too simple
– Retype new password: //Re-type the password for the new user
– passwd: password updated successfully
To create another user account with the name 'fahad'

– linux-8f49:/home/cse # useradd fahad


– linux-8f49:/home/cse # passwd aslam
– New password: //Type the password for the new user
– BAD PASSWORD: it is WAY too short
– BAD PASSWORD: is too simple
– Retype new password: //Re-type the password for the new user
– passwd: password updated successfully
To remove the user account from the system
17
– linux-8f49:/home/cse # userdel fahad

– linux-8f49:/home/cse # usedel aslam

Note: Instructor is advised to give practice to students using on a set of commands the following
commands from various domains.

3.4 Linux Basic Commands


Command Syntax Purpose

$ date Date To See date

$ who Who To see who is using the system

$ pwd Pwd Print working directory

$ ls Ls List the name of files in current directory

$ cat > myfile cat > {filename} To create text file

Note: when file created press ctrl+d to finish

$ cat myfile cat {filename} To see the text of file

$ mv cse cse01 mv {filename1} To move or rename file/directory


{filename2}

$ rm myfile Rm {file1} To remove the file

$ rm -rf oldfiles Rm -rf {dirname} Remove all files in given Directory/subdirectory.

Use it very carefully.

$ chmod Chmod {r|w|x} To change file access


u+x,g+wx,o+x {u|g|o|a}
permissions
Myscript {filename} {+|-}
r - Read permission

w - Write permission

x - Execute permission

u - User who owns the file

g – group file owner

o – other user(classified)

a – all other users

+ set permission

18
- remove permission

3.5 Linux process command


Command Syntax Purpose

$ ps Ps To see currently running process

$ kill 1372 Kill {PID} To stop any process

$ ps -ag Ps -ag To get information about all running process

$ kill 0 Kill 0 To stop all process except your shell

: It is used to display the process number of the current shell.


echo $$ echo $$

: nohup <command> : It permits the execution of the process even after the user has logged
nohup out.

: $! is the system variable which stores the process id of the last


kill $! kill $! background
job. The command kill $! is used to kill the last process

3.6 File Manipulation Commands


Command Syntax Purpose

cat <file name > : It is used to display the contents of the file as well as used to create a
$ cat new

more <file name > It is used to display the contents of the file on the screen at a time.
$more

wc [options] <file name > It is used to count the number of lines ,words and characters in a file or
$ wc group of files.

file <file name > : It is used to determine the type of the file.
$File

: cat <source file name > : It is used to copy one or more files.
<destination file name>
$cp

19
split –size <file name > < It is used to split the given file into smaller pieces of given size.
$split splitted file name >

mv <source file name > It is used to move a file within a directory with different names and also
$mv <destination file name> used to move a file to different directory with its original name.

rm <file name > It is used to remove a file from the disk.


$rm

3.7 Command Grouping and Filter Commands


head [options] <file name> It is used to display the top portion of the file.
$head

tail [options] <file name > It is used to display the bottom portion of the file.
$tail

It is used to display the contents of the file by separating


$pr pr [options] <file name > them into pages and each page begins with the header
information.
It is used to extract selected fields or columns from each
$cut cut [options] <file name > line of one or more files and display them on the
standard output device.
It concatenates the line from each input file column by
$paste paste [options] <file name > column with tab characters in between them.

It is used to extracts common lines from two sorted


$join join [options] <file name1 > <file name 2> files and there should be the common field in both file.

It compares adjacent lines in the file and displays the


Uniq uniq [options] <file name > output by eliminating duplicate adjacent lines in it.

3.8 Lab Task


 Making directory with the name 'UET'

 Removing the directory 'UET'

 Creating and removing directory with absolute path

 Create three users with the names CSE, TE & EE and provide the passwords you can remember

 Switch to CSE user account

 Switch to TE user account from CSE

 Switch to EE user account from TE

 Document all your lab tasks in this session and save it in a text file with your registration
number_name.

20
Lab 04 OS Administration-4: Process States In OS

4.1 Objective
This lab is to demonstrate information about the processes running on different operating systems i.e.
windows and Linux. At the end of this lab, students will learn the following:

 To view process states using Windows task manager.


 To use the “ps lax” command on Linux machine.
 To know the use of “ps aux” command on Linux machine.
 To know the use of “ps top” command on Linux machine.

4.2 Windows Operating System Task Manager


Step1: To open the task manager in windows operating you have to press Alt+Ctlr+Del at the same time.

Step2: The tab shows Processes, Performance, App history, Start up, User detail and services. Figure 4.1
demonstrates task manager of windows operating system.

Figure 4.1: Windows Task Manager

21
 The processes tab in Figure 4.1 shows different processes (Apps, Background Processes, and
Windows Processes) currently running and their usage of resources.
 The performance tab in Figure 4.1 graphically represents the usage of resources by presently
running task.
 The next tab on Task Manager is App history. It shows the history of resource usage by different
process which are currently stopped.
 Startup tab shows all the processes which have to start when the windows boots.
 User tab gives information about the currently logged in users and all applications which are opened
by the user.
 The detailed menu shows the information about all currently running processes in detail i.e. process
name, PID(process identification number) CPU usage, memory usage, process type and process
description. Service tab gives information about the system process their PID and it also shows the
status of the running process.

4.3 Linux operation system Process state

Step1: Start the Shell (Terminal).

Step2: Enter the Command ps aux as shown in Figure 4.2. The output shows the states of various process
on the system.

Figure 4.2: Process States in Linux

Step3: Type ps aux command in the terminal and press enter key. The “ps aux” command shows the
currently running processes states.

Setp4: Type ps lax command in the terminal and press enter key. “ps lax” command shows more technical
information.

Step5: ps lax shows the detailed information about the process. The fields such as the parent process
ID(PPID), nice value (NI), and resource the process is waiting for (WCHAN) are displayed shown in
Figure 4.3.

22
Figure 4.3: Linux process states using Command ps lax

Step6: Execute the “ top” command from the terminal. “top” command provides the big picture and
regularly updated summery of the active processes and their uses of resources shown in Figure 4.4.

Figure 4.4: Linux process states(Using Command Top)

Description of the output of “top” command shown in Figure 4.4 is given below:
 PID -- Process Id
It is the task’s unique process ID, which periodically wraps, though never restarting at zero.

 USER -- User Name


User is the effective user name of the task’s owner.

 TTY -- Controlling Tty


TTY is the name of the controlling terminal. This is usually the device (serial port, pty, etc.) from which the
process was started, and which it uses for input or output. However, a task need not be associated with a terminal, in
which case you’ll see ’?’ Displayed.

 PR -- Priority
PR is the priority of the task.

 NI -- Nice value
23
NI is the nice value of the task. A negative nice value means higher priority, whereas a positive nice value means
lower priority. Zero in this field simply means priority will not be adjusted in determining a task’s dispatch
ability.

 %CPU -- CPU usage


The task’s share of the elapsed CPU time since the last screen update, expressed as a percentage of total CPU
time.

 TIME+ -- CPU Time, hundredths


It shows the time in hundredths

 %MEM -- Memory usage (RES)


A task’s currently used share of available physical memory.

 VIRT -- Virtual Image (kb)


It is the total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages
that have been swapped out. VIRT = SWAP + RES.

 SWAP -- Swapped size (kb)


It is the swapped out portion of a task’s total virtual memory image.

 RES -- Resident size (kb)


The non-swapped physical memory a task has used.

 SHR -- Shared Mem size (kb)


The amount of shared memory used by a task is SHR. It simply reflects memory that could be potentially shared
with other processes.
 S -- Process Status
The status of the task which can be one of:
’D’ = uninterruptible sleep
’R’ = running
’S’ = sleeping
’T’ = traced or stopped
’Z’ = zombie

4.4 Lab Task


 Students are required to use different process states commands and observe the difference
between them. Check the process ID of different running processes, their priority value, nice value
and shared values located to the running process.
 Report the output in a document.

24
Lab 05 Process Management-1: Process Creation

5.1 Objective

The students will learn how:


 To create a new process by using the fork() system call.
 To know the process ID of a process by using the getpid() system call.
 To know the process’s parent ID of a process by using the getppid() system call.

This lab describes how a new process is created/spawned by the existing process.

5.2 Equipment/ Tools Requirements


 A Linux/Unix machine having the following installed:
 Shell environment
 vi/vim/emac/kwrite editor
 gcc compiler

5.2 Process creation

 A process is a program in execution; you can have multiple processes executing the same
program, but each process has its own copy of the program within its own address space and
executes it independently of the other copies.
 In Linux, processes are organized hierarchically in a parent-child relationship. The processes
created by a given parent are called its child processes.
 Processes are created with the fork() system call (so the operation of creating a new process is
sometimes called forking or spawning a process).
 The child process created by fork() system call is the exact copy(clone) of the original parent
process, except that it has its own/different process ID.

5.3 Process Identification


 The pid_t data type represents process IDs which is basically a signed integer type (int).

 You can get the process ID of a process by calling getpid() system call.

 The getppid system call returns the process ID of the parent of the current process (this is also
known as the parent process ID).

 Your program should include the header files ‘unistd.h’ and ‘sys/types.h’ to use these functions.

5.4 Process System Calls


We will use the following system calls in the experiment:

 fork()

o system call which is used to duplicate the current process and its data. The duplicated
process is called the child process.

o fork() returns twice; it returns “0” in the child process and the process id of the child
process in the parent.

 getpid()

25
o sytyem call which shows the value of process id for the process in which it is called.

 getppid()

o System call which shows the value of parent id of the child process.

In the next experiment, fork(), getpid() and getppid() system calls have been demonstrated in C on a
Linux platform. Follow the following steps for successful program execution:

Step1: Start the terminal (command shell).

Step2: Change directory (cd) to the directory where you want to save your programs.

Step3: Write the command kwrite process_creation.c and enter. process_creation.c is the name of your
program.

Step4: Write the program given in the next example, save and close the kwrite editor.

Step5: Compile and run your program as follows:

 cse@linux-8f49:~/oslab> gcc process_creation.c -o process_creation

 cse@linux-8f49:~/oslab> ./process_creation

5.5 System calls fork(), getpid(), getppid()


#include<stdio.h>

int main()

/* Declare the return type of fork() as integer*/

int p;

/* This print message be executed by the parent process only*/

printf("This is before creating the process-executed by parent only\n");

/* fork() will create a new process and returns "0" in child and the pid of
child in parent. Parent and child will execute independently after this call.
It means that anything written after this call will be executed twice, once
by the parent and once by the child*/

p = fork();

/* This will decide between the child and parent, if return value is "0",
you are in child process*/

if (p ==0)

printf("I am the Child Process and my ID is:%d\n", getpid());

printf("My Parent Process ID is:%d\n", getppid());

26
}

/* Else you are in parent process */

else

printf("I am the Parent Process and my ID is:%d\n", getpid());

printf("My Child Process ID is:%d\n",p);

Output:

This is before creating the process

I am the Parent Process and my ID is:2011

My Child Process ID is:2012

I am the Child Process and my ID is:2012

My Parent Process ID is:2011

System call getpid() returns the ID of the process. It is clear from the output that the process ID of parent
process is 2011 and the child process has a process ID 2012.

Note: You may get different process IDs as these are allocated dynamically.

5.6 Lab Task


 Write a program in C which uses fork() call inside a fork()

 Print child process ID of each child process inside the parent process.

 Print parent process ID in each child process

27
Lab 06 Process Management-2: Process Exit & Wait System Calls

6.1 Objective
To write and execute programs with Exit() and Wait() system calls.

The students will learn function of the following system calls.

 To use the exit() system call.


 To use the wait() system call.

wait() system call prevents the termination of parent process till the child process is not terminated first.
wait() will force a parent process to wait for a child process to stop or terminate. wait() return the pid
of the child or -1 for an error.

exit() System call is used to terminate the currently running process. exit() terminates the process
which calls this function and returns the exit status value. Both UNIX and C (forked) programs can
read the status value.

6.2 exit() system call


The exit() system call is used to terminate the current process. Now consider the following program. So
End will not be printed for the child process. To use this system call we will use stdlib header.

#include<stdio.h>
#include<stdlib.h>

int main()
{
int p;
p = fork();
if (p ==0)
{
printf(“\n Hi I am a Child Process with an ID %d”, getpid());
printf(“\n My Parent Process with an ID %d”, getppid());
exit(0);
}
else
{
printf(“\n I am the Parent Process with an ID %d”, getpid());
}
puts(“\n End \n”);
}
OUTPUT
I am the Parent Process with an ID 2270

End

28
Hi I am a Child Process with an ID 2271

My Parent Process with an ID 2270

6.3 wait() system calls


#include<stdio.h>
#include<stdlib.h>
int main()
{
int p;
p = fork();
if (p ==0)
{
printf(“\n Hi I am a Child Process with an ID %d”, getpid());
sleep(5);
printf(“\n My Parent Process with an ID %d”, getppid());
exit(0);
}
else
{
printf(“\n I am the Parent Process with an ID %d”, getpid());
}
puts(“\n End \n”);
}
OUTPUT

I am the Parent Process with an ID 2270

End

root@ubuntu:~/Desktop$

Hi I am a Child Process with an ID 2271

My Parent Process with an ID 1

Note: Here the prompt is returned to the user after the completion of parent process. It is not waiting for
the completion of child process. This is because the parent process in this case is already terminated and
returns 1.

By using wait() system call the parent process wait for the child process and terminate at the same time as
shown in the next program.
#include<stdio.h>
#include<stdlib.h>
int main()
{

29
int p;
p = fork();
if (p ==0)
{
printf(“\n Hi I am a Child Process with an ID %d”, getpid());
sleep(3);
printf(“\n My Parent Process with an ID %d”, getppid());
exit(0);
}
else
{
wait(0);
printf(“\n I am the Parent Process with an ID %d”, getpid());
}
puts(“\n End \n”);
}
OUTPUT

I am the Parent Process with an ID 2270

End

Hi I am a Child Process with an ID 2271

My Parent Process with an ID 2270

End

6.4 Lab Task

Write a program in C which execute $date command when fork() system call is initiated.

30
Lab 07 Process Management-3: Creating and Managing Multiple/Orphan
Processes

7.1 Objective
The aim of this Lab is:

 To learn how to create multiple processes.


 To learn Multiple fork() calls
 To learn about the Orphan process

A parent process can be distinguished from the child process by examining the return value of the fork
call. The fork() system call returns a zero to the child process and the process id of the child process to the
parent. A process can execute as many forks as desired.

7.2 Multiple Fork() Calls

#include <stdio.h>

#include <unistd.h> /* contains fork prototype */

main(void)
{
printf("Here I am just before first forking statement\n");
fork();
printf("Here I am just after first forking statement\n");
fork();
printf("Here I am just after second forking statement\n");

printf("\t\tHello World from process %d!\n", getpid());


}

7.3 Orphan processes


When a parent dies before its child, the child is automatically adopted by the original “init” process
whose PID is 1. To, illustrate this insert a sleep statement into the child’s code. This ensured that the
parent process terminated before its child.

#include <stdio.h>
main()
{
int pid ;
printf("I'am the original process with PID %d and PPID %d.\n",
getpid(), getppid()) ;
pid = fork ( ) ; /* Duplicate. Child and parent continue from here */
if ( pid != 0 ) /* pid is non-zero,so I must be the parent*/
{
printf("I'am the parent with PID %d and PPID %d.\n",
getpid(), getppid()) ;
printf("My child's PID is %d\n", pid ) ;
}
else /* pid is zero, so I must be the child */
{
sleep(4); /* make sure that the parent terminates first */
printf("I'm the child with PID %d and PPID %d.\n",

31
getpid(), getppid()) ;
}
printf ("PID %d terminates.\n", getpid()) ;
}
The output is:
I'am the original process with PID 5100 and PPID 5011.
I'am the parent process with PID 5100 and PPID 5011.
My child's PID is 5101
PID 5100 terminates. /* Parent dies */
I'am the child process with PID 5101 and PPID 1.
/* Orphaned, whose parent process is “init” with pid 1 */
PID 5101 terminates.

7.4 Lab Task


 Students are required to execute C program and observe the significance of wait() and sleep()
system call in parent and child processes.
 Document your programs and their output in a text file with name: RegNo_Name.

32
Lab 08 Process Scheduling-1: First Come First Serve (FCFS)

8.1 Objective
The objective of this lab is to familiar students with the scheduling in Operating System. To write the
program to implement CPU & scheduling algorithm for first come first serve scheduling.

8.2 Multiprogramming
The objective of multiprogramming is to have some process running at all times, to maximize CPU
utilization. The objective of time sharing is to switch the CPU among processes so frequently. In
uniprocessor only one process is running. A process migrates between various scheduling queues
throughout its life time .The process of selecting processes from among these queues is carried out by a
scheduler. The aim of processor scheduling is to assign processes to be executed by the processor.
Scheduling affects the performance of the system, because it determines which process will wait and which
will progress.

8.3 Scheduling Algorithms


Scheduling algorithms or scheduling policies are mainly used for short-term scheduling. The main
objective of short-term scheduling is to allocate processor time in such a way as to optimize one or more
aspects of system behavior.
For these scheduling algorithms assume only a single processor is present. Scheduling algorithms decide
which of the processes in the ready queue is to be allocated to the CPU is basis on the type of scheduling
policy and whether that policy is either preemptive or non-preemptive. For scheduling arrival time and
service time are also will play a role.
List of scheduling algorithms are as follows:

 First-come, first-served scheduling (FCFS) algorithm


 Shortest Job First Scheduling (SJF) algorithm
 Shortest Remaining time (SRT) algorithm
 Non-preemptive priority Scheduling algorithm
 Preemptive priority Scheduling algorithm
 Round-Robin Scheduling algorithm
 Highest Response Ratio Next (HRRN) algorithm
 Multilevel Feedback Queue Scheduling algorithm
 Multilevel Queue Scheduling algorithm

8.4 First-come First-served Scheduling (FCFS)

First-come First-served Scheduling follow first in first out method. As each process becomes ready, it
joins the ready queue. When the current running process ceases to execute, the oldest process in the
Ready queue is selected for running. That is first entered process among the available processes in the
ready queue. The average waiting time for FCFS is often quite long. It is non-preemptive.

8.4.1 Advantages

 Better for long processes


 Simple method (i.e., minimum overhead on processor)
 No starvation

33
8.4.2 Disadvantages

 Convoy effect occurs. Even very small process should wait for its turn to come to utilize the
CPU. Short process behind long process results in lower CPU utilization.
 Throughput is not emphasized.

Detail steps of program

Get the number of processes and their burst time.


Initialize the waiting time for process 1 and 0.
The waiting time for the other processes are calculated as follows:
For (i=2;i<=n;i++), wt.p[i] = p[i-1]+bt.p[i-1].
The waiting time of all the processes is summed then average value time is calculated.
The waiting time of each process and average times are displayed.
Stop the program.

#include<stdio.h>
struct process
{
int pid; int bt; int wt,tt;
}
p[10];
int main(){
int i,n,totwt,tottt,avg1,avg2;
printf("enter the no of process \n");
scanf("%d",&n);
for(i=1;i<=n;i++){
p[i].pid=i;
printf("enter the burst time \n");
scanf("%d",&p[i].bt);
}
p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n){
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;

i++;
}
i=1;
totwt=tottt=0;
printf("\n processid \t bt\t wt\t tt\n");
while(i<=n){
printf("\n\t%d \t%d \t%d \t%d",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}
avg1=totwt/n; avg2=tottt/n;
printf("\navg1=%d \t avg2=%d \t",avg1,avg2);
return 0;
}
Output:

34
enter the no of process 3
enter the burst time 2
enter the burst time 4
enter the burst time 6

Process sid bt wt tt
1 2 0 2
2 4 2 6
3 6 6 12
avg1=2 avg2=6

8.5 Lab Task


Write a program that ask the user to enter number of process, Process Name in integer, arrival time, burst
time and shows the start time, turnaround time and finish time at the output. Which also calculate the
average wait time of the processes?

35
Lab 09 Process Scheduling-2: Shortest Job First

9.1 Objective
The objective of this lab is:
 To familiarize the students with the scheduling in Operating System
 To implement the Shortest Job First Scheduling algorithm using C on a Linux machine

9.2 Multiprogramming
The objective of multiprogramming is to have some process running at all times, to maximize CPU
utilization. The objective of time sharing is to switch the CPU among processes so frequently. In
uniprocessor only one process is running. A process migrates between various scheduling queues
throughout its life time .The process of selecting processes from among these queues is carried out by a
scheduler. The aim of processor scheduling is to assign processes to be executed by the processor.
Scheduling affects the performance of the system, because it determines which process will wait and
which will progress.

9.3 Scheduling Algorithms

Scheduling algorithms or scheduling policies are mainly used for short-term scheduling. The main
objective of short-term scheduling is to allocate processor time in such a way as to optimize one or more
aspects of system behavior.
For these scheduling algorithms assume only a single processor is present. Scheduling algorithms decide
which of the processes in the ready queue is to be allocated to the CPU is basis on the type of scheduling
policy and whether that policy is either preemptive or non-preemptive. For scheduling arrival time and
service time are also will play a role.
List of scheduling algorithms are as follows:

 First-come, first-served scheduling (FCFS) algorithm


 Shortest Job First Scheduling (SJF) algorithm
 Shortest Remaining time (SRT) algorithm
 Non-preemptive priority Scheduling algorithm
 Preemptive priority Scheduling algorithm
 Round-Robin Scheduling algorithm
 Highest Response Ratio Next (HRRN) algorithm
 Multilevel Feedback Queue Scheduling algorithm
 Multilevel Queue Scheduling algorithm

9.4 Shortest Job First Scheduling (SJF)

This algorithm associates with each process the length of the next CPU burst. Shortest-job-first scheduling
is also called as shortest process next (SPN). The process with the shortest expected processing time is
selected for execution, among the available processes in the ready queue. Thus, a short process will jump
to the head of the queue over long jobs. If the next CPU bursts of two processes are the same then FCFS
scheduling is used to break the tie. SJF scheduling algorithm is probably optimal. It gives the minimum
average time for a given set of processes. It cannot be implemented at the level of short term CPU
scheduling. There is no way of knowing the shortest CPU burst. SJF can be preemptive or non-preemptive.
A preemptive SJF algorithm will preempt the currently executing process if the next CPU burst of newly
arrived process may be shorter than what is left to the currently executing process.
A Non-preemptive SJF algorithm will allow the currently running process to finish. Preemptive SJF
Scheduling is sometimes called Shortest Remaining Time First algorithm.
36
9.4.1 Advantages

 It gives superior turnaround time performance to shortest process next because a short job is
given immediate preference to a running longer job.
 Throughput is high.

9.4.2 Disadvantages

 Elapsed time (i.e., execution-completed-time) must be recorded, it results an additional overhead


on the processor.
 Starvation may be possible for the longer processes.

To write a program in C to implement “CPU scheduling algorithm” for shortest job first
scheduling.

Details of the steps

Get the number of processes and their burst time.


Initialize the waiting time for process 1 as 0.
The processes are stored according to their burst time.
The waiting times for the processes are calculated as follows:
for(i=2;i<=n;i++).wt.p[i]=p[i=1]+bt.p[i-1].
The waiting time of all the processes summed and then the average time is calculated.
The waiting time of each processes and average time are displayed.

#include<stdio.h>
#include<conio.h>
struct process{
int pid;
int bt;
int wt;
int tt;
}
p[10],temp;
int main()
{
int i,j,n,totwt,tottt;
float avg1,avg2;
printf("\nEnter the number of process:\t");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("\nEnter the burst time:\t");
scanf("%d",&p[i].bt);
}
for(i=1;i<n;i++)
{
for(j=i+1;j<=n;j++)
{
if(p[i].bt>p[j].bt)
{
temp.pid=p[i].pid; p[i].pid=p[j].pid;
p[j].pid=temp.pid; temp.bt=p[i].bt;

37
p[i].bt=p[j].bt; p[j].bt=temp.bt;

}
}
}
p[1].wt=0; p[1].tt=p[1].bt+p[1].wt;
i=2;

while(i<=n)
{
p[i].wt=p[i-1].bt+p[i-1].wt; p[i].tt=p[i].bt+p[i].wt;
i++;
}
i=1;
totwt=tottt=0;
printf("\nProcess id \tbt \twt \ttt");
while(i<=n)
{
printf("\n\t%d \t%d \t%d \t%d\n",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}
avg1=totwt/n; avg2=tottt/n;
printf("\nAVG1=%f\t AVG2=%f",avg1,avg2);
return 0;
}
Output:
enter the number of process 3
enter the burst time: 2
enter the burst time: 4
enter the burst time: 6

process id bt wt tt
1 2 0 2
2 4 2 6
3 6 6 12
AVG1=2.000000 AVG2=6.000000

9.5 Lab Task


Write a program which implements Shortest Job First with a six number of processes.

38
Lab 10 Process Scheduling-3: Round Robin

10.1 Objective
In this lab we have to write a program to implement CPU scheduling for Round Robin Scheduling .

10.2 Round-Robin Scheduling

This type of scheduling algorithm is basically designed for time sharing system. It is similar to FCFS with
preemption added. Round-Robin Scheduling is also called as time-slicing scheduling and it is a
preemptive version based on a clock. That is a clock interrupt is generated at periodic intervals usually
10-100ms. When the interrupt occurs, the currently running process is placed in the ready queue and the
next ready job is selected on a First-come, First-serve basis. This process is known as time-slicing,
because each process is given a slice of time before being preempted.
One of the following happens:

 The process may have a CPU burst of less than the time quantum or
 CPU burst of currently executing process be longer than the time quantum. In this case the context
switch occurs the process is put at the tail of the ready queue.

In round-robin scheduling, the principal design issue is the length of the time quantum or time-slice to be
used. If the quantum is very short, then short processes will move quickly.

10.2.1 Advantages

 Round-robin is effective in a general-purpose, times-sharing system or transaction-processing


system.
 Fair treatment for all the processes.
 Overhead on processor is low.
 Overhead on processor is low.
 Good response time for short processes.

10.2.2 Disadvantages

 Care must be taken in choosing quantum value.


 Processing overhead is there in handling clock interrupt.
 Throughput is low if time quantum is too small .

10.3 Performance of RR Scheduling

 If there are n processes in the ready queue and time quantum is q, then each process gets 1/n of
the CPU time in chunks of at most q time units at once.
 No process waits for more than (n-1)*q time units until the next time quantum.
 The performance of RR depends on time slice. If it is large then it is the same as FCFS. If q is
small then overhead is too high.

39
To write a program to implement CPU scheduling for Round Robin Scheduling.

Details of the steps

Get the number of process and their burst time.


Initialize the array for Round Robin circular queue as ‘0’.
The burst time of each process is divided and the quotients are stored on the round robin array.
According to the array value the waiting time for each process and the average time are calculated
as line the other scheduling.
The waiting time for each process and average times are displayed.
Stop the program.

#include<stdio.h>
#include<conio.h>
struct process
{
int pid,bt,tt,wt;
};
int main()
{
struct process x[10],p[30];
int i,j,k,tot=0,m,n;
float wttime=0.0,tottime=0.0,a1,a2;
printf("\nEnter the number of process:\t");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
x[i].pid=i;
printf("\nEnter the Burst Time:\t");
scanf("%d",&x[i].bt);
tot=tot+x[i].bt;
}
printf("\nTotal Burst Time:\t%d",tot);
p[0].tt=0;
k=1;
printf("\nEnter the Time Slice:\t");
scanf("%d",&m);
for(j=1;j<=tot;j++)
{
for(i=1;i<=n;i++)
{
if(x[i].bt!=0)
{
p[k].pid=i;
if(x[i].bt-m<0)
{
p[k].wt=p[k-1].tt;
p[k].bt=x[i].bt;
p[k].tt=p[k].wt+x[i].bt;
x[i].bt=0;
k++;
}
else
{
p[k].wt=p[k-1].tt;
p[k].tt=p[k].wt+m;
x[i].bt=x[i].bt-m;
k++;
40
}
}
}
}
printf("\nProcess id \twt \ttt");
for(i=1;i<k;i++)
{
printf("\n\t%d \t%d \t%d",p[i].pid,p[i].wt,p[i].tt);
wttime=wttime+p[i].wt;
tottime=tottime+p[i].tt;
a1=wttime/n;
a2=tottime/n;
}
printf("\n\nAverage Waiting Time:\t%f",a1);
printf("\n\nAverage TurnAround Time:\t%f",a2);
return 0;
}
Output:
enter the no of process 3
enter the burst time 3
enter the burst time 5
enter the burst time 7
total burst time : 15
enter the time slice: 2
process id wt tt
1 0 2
2 2 4
3 4 6
1 6 7
2 7 9
3 9 11
2 11 12
3 12 14
3 14 15
avg waiting time: 21.666666

avg turnaround time: 26.666666

Conclusion

The result shows that process 1,2 and 3 is executing in a round robin fashion taking each one its
time of execution.

10.4 Lab Task


Write a program which implements Round Robin scheduling of 6 processes with a slice time 3.

41
Lab 11 Mutual Exclusion using Semaphores

11.1 Objective
This is an illustration of a solution to the classic producer-consumer (bounded-buffer) problem using
semaphores to ensure mutual exlusion.

11.2 Description
Concept Producers produce items to be stored in the buffer. Consumers remove and consume items which
have been stored. Mutual exclusion must be enforced on the buffer itself. Moreover, producers can store
only when there is an empty slot, and consumers can remove only when there is a full slot. Three
semaphores are used. The binary semaphore mutex controls access to the buffer itself. The counting
semaphore empty keeps track of empty slots, and the counting semaphore full keeps track of full slots. In
this example, the buffer is implemented as an array of size MAX treated as a circular (ring) buffer. Variables
in and out give the index of the next position for putting in and taking out (if any). Variable count gives the
number of items in the buffer.

11.2.1 ADVANTAGES:
Effective resource utilization

11.2.2 DISADVANTAGES:
A semaphore does not keep track of which of the resources are free.
This includes:
Requesting a resource and forgetting to release it releasing a resource that was never requested holding a
resource for a long time without needing it using a resource without requesting it first (or after releasing
it).

Detail Steps

Declare the variables in the type of pthread_t as tid_produce tid_consume.


Declare a structure for semaphore variables.
During run time read the number of items to be produced and consumed.
Declare and define semaphore function for creation and destroy.
Define producer function.
Define consumer function.
Call producer and consumer function.

#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#define NBUFF 10
int nitems; struct
{
int buff[NBUFF];
sem_t mutex, nempty, nstored;
}
shared;
void *produce (void *);
void *consume (void *);
int main(int argc, char **argv)
{
pthread_t tid_produce, tid_consume; if(argc !=2)

42
{
printf("Useage: filename <nitems> ");
return 0;
}
printf ("\n\n Producer - Consumer Problem using Semaphore\n");
printf (" -------------------------------------------\n\n");
nitems=atoi(argv[1]);
sem_init(&shared.mutex,0,1);
sem_init(&shared.nempty,0,NBUFF);
sem_init(&shared.nstored,0,0);
pthread_setconcurrency(2);
pthread_create(&tid_produce,NULL,produce,NULL);
pthread_create(&tid_consume,NULL,consume,NULL);
pthread_join(tid_produce,NULL);
pthread_join(tid_consume,NULL);
sem_destroy(&shared.mutex);
sem_destroy(&shared.nempty);
sem_destroy(&shared.nstored);
}
void *produce (void *arg)
{
int i; for(i=0;i<nitems;i++)
{
sem_wait(&shared.nempty);
sem_wait(&shared.mutex);
shared.buff[i % NBUFF]=i;
printf ("\tProducer.....");
printf ("buff[%d] = %d\n\n",i,shared.buff[i % NBUFF]);
sem_post(&shared.mutex);
sem_post(&shared.nstored); sleep(3);
}
return NULL;
}
void *consume (void *arg)
{
int i; for(i=0;i<nitems;i++)
{
sem_wait(&shared.nstored);
sem_wait(&shared.mutex);
printf("\tConsumer.....");
printf("buff[%d] = %d\n\n\n",i,shared.buff[i%NBUFF]);
sem_post(&shared.mutex);
sem_post(&shared.nempty);
sleep(3);
}
return NULL;
}
OUTPUT:
[root@NS2-05 root]# cc -pthread prod_cons.c
[root@NS2-05 root]# ./a.out 4
Producer - Consumer Problem using Semaphore
Producer.....buff[1] = 1
Consumer.....buff[1] = 1
Producer.....buff[2] = 2
Consumer.....buff[2] = 2
Producer.....buff[3] = 3
Consumer.....buff[3] = 3

Conclusion

43
The program to implement producer and consumer problem using semaphores has been executed and
shown the results as above.

11.3 Lab Task


Implement the producer and consumer problem using semaphores with a buffer size 5.

44
Lab 12 File I/O: Reading & Writing from/to a File

12.1 Objective
In this lab the student will learn

 How to read from a file


 How to write into a file

12.2 Description
For files you want to read or write, you need a file pointer, e.g. FILE *fp; What is this type "FILE *"?
Realistically, you don't need to know. Just think of it as some abstract data structure, whose details are
hidden from you. In other words, the only way you can use a FILE * is via the functions that C gives you.
Reading from or writing to a file in C requires 3 basic steps:

1. Open the file.


2. Do all the reading or writing.
3. Close the file.

Steps
Get the data from the user.
Open a file.
Read from the file.
Close the file.

Write a program to create the file, read data from the file and update the file.

#include<stdio.h>
int main()
{
char str[100];
FILE *fp;
fp=fopen("file1.dat","r");
while(!feof(fp))
{
fscanf(fp,"%s",str);
printf(" %s ",str);
}
fclose(fp);
}
OUTPUT:
$ vi read1.c
$gcc read1.c
$ ./a.out
Hi this is a program to read the content of the file.

Conclusion

Thus C program to write data into a file was executed successfully.

45
To write a C program to write the data into a file.

Steps

Get the data from the user.


Open a file.
Write the data from the file.
Get the data and update the file.

#include<stdio.h>
int main()
{
char str[100];
FILE *fp;
printf("Enter the string");
gets(str);
fp=fopen("file1.dat","w+");
while(!feof(fp))
{
fscanf(fp,"%s",str);
}
fprintf(fp,"%s",str);
}
OUTPUT:
$ gcc write.c
$ ./a.out
Enter the string: os lab
$vi file1.dat

Conclusion

Thus C program to write data into a file was executed successfully.

12.3 Lab Task


Write a program which execute the following

 Open a file
 Write into a file
 Close a file
 Append a file

46
Lab 13 Inter-Process Communication Using Pipes

13.1 Objective
In this lab we will learn how to create pipes and how processes communicate by reading or writing to the
pipe.

13.2 Description
Linux provides many ways for processes to communicate with each other. One of them is using pipes.
Like a pipe that carries water in which water enters from one end and exits from the other, in Linux pipes
data enters from one end and exits from the other. Pipes are created using the system call pipe() and the
system calls read() and write() are used to read and write from the pipe. The clcsey in Linux provides
wrappers around these system calls which make their use much easier. The function popen() is a wrapper
for pipe, which allows us to create a pipe and read or write from it using c fuctions like fprintf, fscanf etc
popen() :
Command that will be executed by the child process. The type of communication by the parent, i.e.
whether the parent is going to read from the pipe or write into the pipe. Return : It returns a file descriptor
that gets created as a result of th call to the pipe

Write a program for pipe processing.

Steps

Declare the file pointer fp, f1, f2.


Read the choice.
In case ‘1’ open a file and display the list of files and directories.
In case ‘2’ open a file and ptr bin\pwd for read mode it displays the personnel working directory.
In case ‘3’ open a file in write mode.
In case ‘4’ Exit command is execute.

#include<stdio.h>
#include<sys/stat.h>
#include<string.h>
int main()
{
FILE *fp,*f1,*f2;
int opt;
char line[100];
printf("enter ur choice\n");
scanf("%d",&opt);
switch(opt){
case 1:
if((fp=popen("/bin/ls","r"))==NULL)
{
printf("pipeline error");

}
printf("list command\n");
printf("*************\n");
while(fgets(line,80,fp))
{
printf("%s",line);
}
47
break;
case 2:
printf("PWD comman\n");
printf("**********\n");
if((f1=popen("/bin/pwd","r"))==NULL)
{
printf("PWD function error\n");
}
while(fgets(line,80,f1)){
printf("%s",line);
}
break;
case 3:
printf("cat commond\n");
printf("***********\n");
if((f2=fopen("ch.c","w"))==NULL)
{
printf("Cat function error\n");
}
while(fgets(line,80,f2))
{
printf("%s",line);
}
break;
case 4:
printf("exit\n");
printf("****\n");
exit(0);
break;
}
}
Output:
enter the choice
1
list command
*********************
a.out
ch.c
come.c
data
file1.c
file2.c
enter the choice
2
PWD command
**********************
enter the choice
3
CAT command
***********************
enter the choice
4
exit
***********************

48
13.3 Lab Task
Implement a half-duplex inter process communication.

49
Lab 14 Memory Management

14.1 Objective
The purpose of this lab is to study

 Memory layout of a process


 Memory allocation strategies
 Memory placement algorithms

14.2 Description

Linux is a particularly good environment to show you memory management, as there are often
hundreds of running processes (started by dozens of people) that each require memory in order to
work. Linux must distribute the pages of available memory fairly and equitably.

The function malloc() is used to allocate a certain amount of memory during the execution of a program.
The malloc() function will request a block of memory from the heap. If the request is granted, the
operating system will reserve the requested amount of memory.

To write a C program to Search a String using Dynamic Memory Allocation Concept.

Detail Steps

Declare an array of pointer variables one containing strings and the other containing the string to be
searched.
Get the value for both the variables.
Compare the string to be searched in the array of strings.
If found Print the result.

#include<string.h>
#include<stdio.h>
main( )
{
char *t=(char*)malloc(10);
char *s[5]={ “PASCAL”,”COBOL”,”BASIC”,”LISP”,”FORTRAN”};
printf(“Enter the String to be Searched\n”);
scanf(“%s”,&t);
search(s,t,5);
}
search(char *s[5],char *t,int n);
{
int i;
for(i=0;i<n;i++)
{
if(!strcmp(*s+i),t))
{
printf(”String %s is successfully searched \n”,t);
break;
}
else if(i==n-1)
printf(“Not found \n”);

50
}
}

OUTPUT
Enter the String to be searched
PASCAL

Implement FIFO page replacement algorithm.

Detail Steps
Obtain the number of sequences, number of frames and sequence string from the user
Now when a page is not in the frame comes, increment the number of page fault and remove the page that
come in the first in FIFO algorithm.

#include<#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("ENTER THE NUMBER OF PAGES:");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);
getch();
return 0;
}
OUTPUT
51
14.3 Lab Task
 Implement First Fit and Best Fit Algorithms using C language on a Linux plateform.
 Document your program and its output in a text file and save it under the name
YourRegistrationNUM_Name.
 Report it to the instructor.

52

You might also like