Professional Documents
Culture Documents
Version: 1.0
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:
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.
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).
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.
Step 5: You will see 15GB “unallocated” space on your hard drive shown in Figure 1.4.
6
Figure 1.4: Unallocated space
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.
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.
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.
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.
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.
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:
2.3 Description
"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.
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.
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.
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/
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.
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
– 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
● 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:
Note: Instructor is advised to give practice to students using on a set of commands the following
commands from various domains.
w - Write permission
x - Execute permission
o – other user(classified)
+ set permission
18
- remove permission
: nohup <command> : It permits the execution of the process even after the user has logged
nohup out.
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.
tail [options] <file name > It is used to display the bottom portion of the file.
$tail
Create three users with the names CSE, TE & EE and provide the passwords you can remember
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:
Step2: The tab shows Processes, Performance, App history, Start up, User detail and services. Figure 4.1
demonstrates task manager of windows operating system.
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.
Step2: Enter the Command ps aux as shown in Figure 4.2. The output shows the states of various process
on the system.
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.
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.
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.
24
Lab 05 Process Management-1: Process Creation
5.1 Objective
This lab describes how a new process is created/spawned by the existing process.
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.
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.
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:
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.
cse@linux-8f49:~/oslab> ./process_creation
int main()
int p;
/* 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)
26
}
else
Output:
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.
Print child process ID of each child process inside the parent 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.
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.
#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
End
root@ubuntu:~/Desktop$
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
End
End
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:
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.
#include <stdio.h>
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");
#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.
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.
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
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.
#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
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.
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:
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
To write a program in C to implement “CPU scheduling algorithm” for shortest job first
scheduling.
#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
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 .
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
10.2.2 Disadvantages
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.
#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
Conclusion
The result shows that process 1,2 and 3 is executing in a round robin fashion taking each one its
time of execution.
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
#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.
44
Lab 12 File I/O: Reading & Writing from/to a File
12.1 Objective
In this lab the student will learn
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:
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
45
To write a C program to write the data into a file.
Steps
#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
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
Steps
#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
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.
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
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