Operating System Practical

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 74

16CE068 CE221.

01 Operating Systems JAINIL PATEL

Sr.
No Aim Of the Practical
.

1 Study Practical:
A. UNIX Architecture
B. Types of OS
C. Flavors of LINUX

1. Unix Architecture

Here is a basic block diagram of a Unix system −

 Kernel − The kernel is the heart of the operating system. It interacts with the
hardware and most of the tasks like memory management, task scheduling and file
management.
 Shell − The shell is the utility that processes your requests. When you type in a
command at your terminal, the shell interprets the command and calls the program
that you want. The shell uses standard syntax for all commands. C Shell, Bourne
Shell and Korn Shell are the most famous shells which are available with most of
the Unix variants.
 Commands and Utilities − There are various commands and utilities which you
can make use of in your day to day activities. cp, mv, catand grep, etc. are few
examples of commands and utilities. There are over 250 standard commands plus
numerous others provided through 3 rd party software. All the commands come along
with various options.
 Files and Directories − All the data of Unix is organized into files. All files are then
organized into directories. These directories are further organized into a tree-like
structure called the filesystem.

16CE068 Page 1
16CE068 CE221.01 Operating Systems JAINIL PATEL

B. Types of OS

Single- and multi-tasking


A single-tasking system can only run one program at a time, while a multi-tasking operating system
allows more than one program to be running in concurrency. This is achieved by time-sharing, dividing
the available processor time between multiple processes that are each interrupted repeatedly in time
slices by a task-scheduling subsystem of the operating system. Multi-tasking may be characterized in
preemptive and co-operative types. In preemptive multitasking, the operating system slices the CPU time
and dedicates a slot to each of the programs. Unix-like operating systems, e.g., Solaris, Linux, as well
as AmigaOSsupport preemptive multitasking. Cooperative multitasking is achieved by relying on each
process to provide time to the other processes in a defined manner. 16-bit versions of Microsoft Windows
used cooperative multi-tasking. 32-bit versions of both Windows NT and Win9x, used preemptive multi-
tasking.

Single- and multi-user


Single-user operating systems have no facilities to distinguish users, but may allow multiple programs to
run in tandem.[6] A multi-user operating system extends the basic concept of multi-tasking with facilities
that identify processes and resources, such as disk space, belonging to multiple users, and the system
permits multiple users to interact with the system at the same time. Time-sharing operating systems
schedule tasks for efficient use of the system and may also include accounting software for cost
allocation of processor time, mass storage, printing, and other resources to multiple users.

Distributed
A distributed operating system manages a group of distinct computers and makes them appear to be a
single computer. The development of networked computers that could be linked and communicate with
each other gave rise to distributed computing. Distributed computations are carried out on more than one
machine. When computers in a group work in cooperation, they form a distributed system. [7]

Templated
In an OS, distributed and cloud computing context, templating refers to creating a single virtual machine
image as a guest operating system, then saving it as a tool for multiple running virtual machines. The
technique is used both in virtualization and cloud computing management, and is common in large server
warehouses.[8]

Embedded
Embedded operating systems are designed to be used in embedded computer systems. They are
designed to operate on small machines like PDAs with less autonomy. They are able to operate with a
limited number of resources. They are very compact and extremely efficient by design. Windows CE and
Minix 3 are some examples of embedded operating systems.

Real-time
A real-time operating system is an operating system that guarantees to process events or data by a
specific moment in time. A real-time operating system may be single- or multi-tasking, but when
multitasking, it uses specialized scheduling algorithms so that a deterministic nature of behavior is
achieved. An event-driven system switches between tasks based on their priorities or external events
while time-sharing operating systems switch tasks based on clock interrupts

16CE068 Page 2
16CE068 CE221.01 Operating Systems JAINIL PATEL

C. Flavors of LINUX:

Widely used distributions

 Debian, a non-commercial distribution and one of the earliest, maintained by a volunteer


developer community with a strong commitment to free software principles and democratic project
management
 Knoppix, the first Live CD distribution to run completely from removable media without
installation to a hard disk, derived from Debian
 Linux Mint Debian Edition (LMDE) uses Debian packages directly (rather than Ubuntu's)
 Ubuntu, a desktop and server distribution derived from Debian, maintained by British
company Canonical Ltd.
 Kubuntu, the KDE version of Ubuntu
 Linux Mint, a distribution based on and compatible with Ubuntu. Supports multiple
desktop environments, among others GNOME Shell forkCinnamon and GNOME 2
fork MATE.
 Trisquel, an Ubuntu-based distribution based on Linux-libre kernel composed
entirely of free software
 Elementary OS, an Ubuntu-based distribution with strong focus on the visual
experience without sacrificing performance.
 Fedora, a community distribution sponsored by American company Red Hat and the successor to
the company's previous offering, Red Hat Linux. It aims to be a technology testbed for Red Hat's
commercial Linux offering, where new open source software is prototyped, developed, and tested in
a communal setting before maturing into Red Hat Enterprise Linux.
 Red Hat Enterprise Linux (RHEL), a derivative of Fedora, maintained and commercially
supported by Red Hat. It seeks to provide tested, secure, and stable Linux server and
workstation support to businesses.
 CentOS, a distribution derived from the same sources used by Red Hat,
maintained by a dedicated volunteer community of developers with both 100% Red Hat-
compatible versions and an upgraded version that is not always 100% upstream compatible.
 Oracle Linux, which is a derivative of Red Hat Enterprise Linux, maintained and
commercially supported by Oracle
 Scientific Linux, a distribution derived from the same sources used by Red Hat,
maintained by Fermilab
 Mandriva Linux was a Red Hat derivative popular in several European countries and Brazil,
backed by the French company of the same name. After the company went bankrupt, it was
superseded by OpenMandriva Lx, although a number of derivatives now have a larger user base.
 Mageia, a community fork of Mandriva Linux created in 2010.
 PCLinuxOS, a derivative of Mandriva, which grew from a group of packages into a
community-spawned desktop distribution
 ROSA Linux, another former derivative of Mandriva, now developed independently
 openSUSE, a community distribution mainly sponsored by German company SUSE.
 SUSE Linux Enterprise, derived from openSUSE, maintained and commercially
supported by SUSE
 Arch Linux, a rolling release distribution targeted at experienced Linux users and maintained by a
volunteer community, offers official binary packages and a wide range of unofficial user-submitted

16CE068 Page 3
16CE068 CE221.01 Operating Systems JAINIL PATEL

source packages. Packages are usually defined by a single PKGBUILD text file.


 Manjaro Linux, a derivative of Arch Linux that includes a graphical installer and other
ease-of-use features for less experienced Linux users. Rolling release packages from Arch
repositories are held for further testing to achieve increased stability, and packages identified as
addressing security issues of critical or high severity are "fast-tracked" to the stable branch.
 Gentoo, a distribution targeted at power users, known for its FreeBSD Ports-like automated
system for compiling applications from source code
 Chrome OS, Google's commercial operating system (using Gentoo and its Portage) that
primarily runs web applications
 Chromium OS, the fully open-source version of Chrome OS
 Slackware, created in 1993, one of the first Linux distributions and among the earliest still
maintained, committed to remain highly Unix-like and easily modifiable by end users

Other distributions target specific niches, such as:

 Routers – for example, targeted by the tiny embedded router distribution OpenWrt


 Internet of things – for example, targeted by Ubuntu Core
 Home theater PCs – for example, targeted by KnoppMyth, Kodi (former XBMC) and Mythbuntu
 Specific platforms – for example, Raspbian targets the Raspberry Pi platform
 Education – examples are Edubuntu and Karoshi, server systems based on PCLinuxOS
 Scientific computer servers and workstations – for example, targeted by Scientific Linux
 Digital audio workstations for music production – for example, targeted by Ubuntu Studio
 Computer Security, digital forensics and penetration testing – examples are Kali Linux and Parrot
Security OS
 Privacy and anonymity – for example, targeted by Tails
 Offline use – for example, Endless OS

CONCLUSION:

Here we studied about the structure of linux and also some examples

16CE068 Page 4
16CE068 CE221.01 Operating Systems JAINIL PATEL

2 Study of Unix Architecture and the following Unix commands with option:
User Access: login, logout, passwd, exit

Help: man, help

Directory: mkdir, rmdir, cd, pwd, ls, mv

Editor: vi, gedit, ed, sed

File Handling / Text Processing: cp, mv, rm, sort, cat, pg, lp, pr, file, find, more, cmp,
diff, comm, head, tail, cut, grep, touch, tr, uniq

Security and Protection: chmod, chown, chgrp, newgrp

Information: learn, man, who, date, cal, tty, calendar, time, bc,
whoami, which, hostname, history, wc

System Administrator: su or root, date, fsck, init 2, wall, shut down, mkfs,
mount, unmount, dump, restor, tar, adduser, rmuser

Terminal: echo, printf, clear

Process: ps, kill, exec

I/O Redirection (<, >, >>), Pipe ( | ), *, gcc

1.
2. User Access
//Here Sudo is for superuser access
1)sudo login-----login to a different user in the terminal

2) logout -----used to logout of user in terminal just like exit


gnome-session-quit -----logout the user

16CE068 Page 5
16CE068 CE221.01 Operating Systems JAINIL PATEL

3) passwd-----used to change password of the user which is currently active

exit ------logout the user in the terminal which is logged in by login command same as logout

2.Help
man-----gives the manual page of command that is typed after it
Eg. man login

help-----when written in the form help (command) it gives info about the specific command

Eg. help logout

16CE068 Page 6
16CE068 CE221.01 Operating Systems JAINIL PATEL

3. Directory
mkdir-----used to create a folder
Eg. mkdir samplefolder

rmdir-----used to delete a folder


Eg. rmdir samplefolder

cd-----changes the present working directory

pwd-----displays the present working directory

ls-----displays the list of files in current directory

mv ------ move (rename) files

4. Editor
vi----- a programmer’s text editor

16CE068 Page 7
16CE068 CE221.01 Operating Systems JAINIL PATEL

gedit------ opens a new gedit file(text file)

16CE068 Page 8
16CE068 CE221.01 Operating Systems JAINIL PATEL

ed----- open a line oriented text editor in terminal

sed-----stream editor for transforming text

16CE068 Page 9
16CE068 CE221.01 Operating Systems JAINIL PATEL

16CE068 Page 10
16CE068 CE221.01 Operating Systems JAINIL PATEL

5.
File Handling and Text Processing
cp-----it is used to copy a file or a folder

cp source_filename destination_directory

mv----- used to move a file or folder


mv source_filename destination_directory
eg. mv sample tutorial

16CE068 Page 11
16CE068 CE221.01 Operating Systems JAINIL PATEL

rm------used to delete a file


Eg. rm sample

Sort-----used to sort lines in a file

*original file

*sort sample

Cat------Used to concat data of multiple files


*sample file

*sample1 file

*cat sample sample1

16CE068 Page 12
16CE068 CE221.01 Operating Systems JAINIL PATEL

pg ----- browse pagewise through text files

lp-----used to print files

*lp sample

Didn’t printed as no printer available

Pr-----Convert text files for printing

*pr sample

File-----Determine file type

*file sample

Find-----Searches for file in the directory

*find sample

More----- file perusal filter for crt viewing

*more sample

cmp ----- compare two files byte by byte

16CE068 Page 13
16CE068 CE221.01 Operating Systems JAINIL PATEL

*cmp sample sample1

diff ------ compare files line by line

*diff sample sample1

comm ----- compare two sorted files line by line

head ----- output the first part of files

tail ----- output the last part of files

cut----- displays the bytes at specific positions from every line in a file

*cut -b 1 sample

the reason on this output is that h is first byte in first line , m is first byte in second line, I is first byte in third
line

Grep -----print lines that contains a specific pattern of text

16CE068 Page 14
16CE068 CE221.01 Operating Systems JAINIL PATEL

*grep is sample

touch ----- change file timestamps

tr ----- translate or delete characters or modify them

uniq ------ report or omit repeated lines

6.Security and Protection

Chmod-----used to change read and write permissions of a file

*chmod u=r sample


//this command makes the file only readable i.e user=read in command,,,,, group=g, others=o, w=write,
x=xecute

chmod u=r sample

16CE068 Page 15
16CE068 CE221.01 Operating Systems JAINIL PATEL

chown ----- change file owner

Eg. sudo chown root sample

Here root is name of user


Sample is name of file
Sudo is for superuser access

The file is now under root owner

Chgrp-----Used the changed the group of file


Newgrp-----Used to login to a new group
8.Information

16CE068 Page 16
16CE068 CE221.01 Operating Systems JAINIL PATEL

who ----- show who is logged on


*who

Date-----gives the current date and time

Cal-----gives the calendar

tty ----- print the file name of the terminal connected to standard input

Calendar ----- reminder service

16CE068 Page 17
16CE068 CE221.01 Operating Systems JAINIL PATEL

time ------ run programs and summarize system resource usage

bc ----- An arbitrary precision calculator language

Whoami-----gives the name of user which is logged in

Which-----locates the location of a command

Hostname-----shows the name of the host

16CE068 Page 18
16CE068 CE221.01 Operating Systems JAINIL PATEL

History-----gives the history of all commands you typed

wc ----- print newline, word, and byte counts for each file
*wc sample

16CE068 Page 19
16CE068 CE221.01 Operating Systems JAINIL PATEL

9.System Administrator (need to write sudo su before using all commands)


Su or root----- gives you superuser or root rights for commands

fsck ----- check and repair a Linux filesystem

init-----init basically defines how the system has to boot up


how to write:- init 1 , init 2 ,init 3

Run Name Description


level

0 Halt Shuts down the system

1 Single-user mode Mode for administrative tasks.

2 Multi-User Mode Does not configure network interfaces and does not
export networks services

3 Multi-User Mode with Starts the system normally


Networking

4 Not used / user For special purposes


definable

5 Start the system Run level 3 + display manager


normally with GUI
display manager

6 Reboot Reboots the system

16CE068 Page 20
16CE068 CE221.01 Operating Systems JAINIL PATEL

s or S Single-user mode Not configure network interface or start daemon

wall ----- write a message to all users

shutdown ----- Halt, power-off or reboot the machine

mkfs ----- build a Linux filesystem

16CE068 Page 21
16CE068 CE221.01 Operating Systems JAINIL PATEL

mount ----- mount a filesystem

adduser-----used to add a new user or group to the os

userdel-----used to delete a user

16CE068 Page 22
16CE068 CE221.01 Operating Systems JAINIL PATEL

10.Terminal
Echo-----used to print a message

Printf----- format and print data (mostly used in scripting with variables)

Clear-----clear the terminal screen


After typing clear

16CE068 Page 23
16CE068 CE221.01 Operating Systems JAINIL PATEL

11.I/O Redirection

command > file Redirection of output


command >> file Appends output to specified file
command < file Redirection of input
command 2 > file Redirection of error messages (stdin, stdout and stderr are
associated with numerical values 0, 1 and 2 - called file descriptors)

Some Examples Using Redirection Commands

To send the output produced by the who command to the file called wholist:

Type: who > wholist

To create a file called demo :

Type: cat > demo

To run the program myprog taking input from the file called data and sending the output to the file
called results :

Type: myprog < data > results

CONCLUSION

Here We studied different commands in linux and executed them.

3 1. Write a shell script which calculates nth Fibonacci number where n will be provided as input when
prompted.
Solution:

echo "Enter the number of terms you want "

16CE068 Page 24
16CE068 CE221.01 Operating Systems JAINIL PATEL

read n

a=0

b=1

echo -n $a $b

for(( i=2;i<$n;i++ ))

do

c=$(( $a + $b ))

a=$b

b=$c

echo -n " " $c

done
echo " "
Output:

2. Write a shell script which takes one number from user and finds factorial of a given number.
Solution:
echo -n "enter number::"
read no1
fact=1
for(( i=1;i<=$no1;i++ ))

16CE068 Page 25
16CE068 CE221.01 Operating Systems JAINIL PATEL

do
fact=$(( $fact * $i ))
done
echo "Factorial is "$fact

Output:

3. Write a shell script to sort the number in ascending order. (Using array).

echo "enter the size of the array"


read n

echo "enter Numbers in array:"


for (( i = 0; i < $n; i++ ))
do
read nos[$i]
done

for (( i = 0; i < $n ; i++ ))


do
for (( j = 0; j < $i; j++ ))
do
if [ ${nos[$i]} -lt ${nos[$j]} ]; then
t=${nos[$i]}
nos[$i]=${nos[$j]}
nos[$j]=$t
fi
done
done

echo -e "\nSorted Numbers "


for (( i=0; i < $n; i++ ))
do

16CE068 Page 26
16CE068 CE221.01 Operating Systems JAINIL PATEL

echo -n ${nos[$i]}" "


done
echo ""

Output:

CONCLUSION

Here we implemented factorial , Fibonacci and Bubble sorting in shell scripting

4 1. Write a shell script which will take a file name from the user and finds that whether the file is there or not
in a current working directory and displays the appropriate message.
Solution:
echo -n "Enter file name "
read filename

f=0

16CE068 Page 27
16CE068 CE221.01 Operating Systems JAINIL PATEL

for i in $(ls)
do
if [ $i = $filename ]
then
f=1
break
fi
done

if [ $f -eq 1 ]
then echo "file found"
else echo "Not Found"
fi

Output:

2. Write a shell script which compares two files given by the user and if both files are same then
delete the second one, if not then merge the two files in a new file.
Solution:

if [ $# -eq 2 ]

then

file1=$1

16CE068 Page 28
16CE068 CE221.01 Operating Systems JAINIL PATEL

file2=$2

else

echo " Enter name of file one : "

read file1

echo " Enter name of file two : "

read file2

fi

f1=0

f2=0

for i in $(ls)

do

if [ $file1 = $i ]

then

f1=1

echo "file 1 found"

fi

if [ $file2 = $i ]

then

f2=1

echo "file 2 found"

fi

done

f3=$(( $f1 + $f2 ));

16CE068 Page 29
16CE068 CE221.01 Operating Systems JAINIL PATEL

if [ $f3 -eq 2 ]

then

cmp $file1 $file2

if [ $? -eq 0 ]

then

rm $file2

else

cat $file1 $file2 > file3.txt

fi

else

echo "File not found"


fi

Output:

Conclusion: we studied file handling in shell script.

PRACTICAL 5
Aim: Write a C program in UNIX to perform Memory allocation algorithms and calculate Internal and
External Fragmentation. (First Fit, Best Fit, Worst Fit)
1)firstfit.cpp
#include<iostream>
using namespace std;
void firstfit(int sizeofmem,int sizeofpro,int mem[],int pro[])
{
int noofmemoryspace=sizeofmem;

16CE068 Page 30
16CE068 CE221.01 Operating Systems JAINIL PATEL

int noofprocess= sizeofpro;

for(int i=0;i<noofprocess;i++)
{

int flag=0;
for(int j=0;j<noofmemoryspace;j++)
{
if(pro[i]<=mem[j])
{
cout<<"process "<<i<<" of size "<<pro[i]<<"in memory location "<<j<<"\n";
mem[j]=mem[j]-pro[i];
flag=1;
goto aa;
}
}
if(flag==0)
{
cout<<"no space found for "<<"process "<<i<<" of size "<<pro[i]<<"\n";
}
aa:
;
}
}
int main()
{
int p,m;
cout<<"enter no of processes:";
cin>>p;
int process[p];
cout<<"enter processes size separated by space:";
for(int i=0;i<p;i++)
{
cin>>process[i];

16CE068 Page 31
16CE068 CE221.01 Operating Systems JAINIL PATEL

}
cout<<"enter no of memory locations:";
cin>>m;
int memory[m];
cout<<"enter memory locations available:";
for(int i=0;i<p;i++)
{
cin>>memory[i];
}
firstfit(m,p,memory,process);

}
OUTPUT:

2)bestfit.cpp
#include<iostream>
using namespace std;

void bestfit(int sizeofmem,int sizeofpro,int mem[],int pro[])


{

int noofmemoryspace=sizeofmem;
int noofprocess= sizeofpro;

16CE068 Page 32
16CE068 CE221.01 Operating Systems JAINIL PATEL

for(int i=0;i<noofprocess;i++)
{

int flag=0;
int bestindexfound=0;
for(int j=0;j<noofmemoryspace;j++)
{
if((mem[j]-pro[i])<(mem[bestindexfound]-pro[i])&&((mem[j]-pro[i])>=0))
{
bestindexfound=j;
}
}
if(mem[bestindexfound]>=pro[i])
{
cout<<"process "<<i<<" of size "<<pro[i]<<"in memory location "<<bestindexfound<<"\n";
mem[bestindexfound]=mem[bestindexfound]-pro[i];
}
else
{
cout<<"no space found for "<<"process "<<i<<" of size "<<pro[i]<<"\n";
}
}
}
int main()
{
int p,m;
cout<<"enter no of processes:";
cin>>p;
int process[p];
cout<<"enter processes size separated by space:";
for(int i=0;i<p;i++)
{
cin>>process[i];

16CE068 Page 33
16CE068 CE221.01 Operating Systems JAINIL PATEL

}
cout<<"enter no of memory locations:";
cin>>m;
int memory[m];
cout<<"enter memory locations available:";
for(int i=0;i<p;i++)
{
cin>>memory[i];
}
bestfit(m,p,memory,process);

}
OUTPUT:

3)worstfit
#include<iostream>
using namespace std;

void worstfit(int sizeofmem,int sizeofpro,int mem[],int pro[])


{

int noofmemoryspace=sizeofmem;
int noofprocess= sizeofpro;

16CE068 Page 34
16CE068 CE221.01 Operating Systems JAINIL PATEL

for(int i=0;i<noofprocess;i++)
{

int flag=0;
int bestindexfound=0;
for(int j=0;j<noofmemoryspace;j++)
{
if((mem[j]-pro[i])>(mem[bestindexfound]-pro[i])&&((mem[j]-pro[i])>=0))
{
bestindexfound=j;
}
}
if(mem[bestindexfound]>=pro[i])
{
cout<<"process "<<i<<" of size "<<pro[i]<<"in memory location "<<bestindexfound<<"\n";
mem[bestindexfound]=mem[bestindexfound]-pro[i];
}
else
{
cout<<"no space found for "<<"process "<<i<<" of size "<<pro[i]<<"\n";
}
}
}
int main()
{
int p,m;
cout<<"enter no of processes:";
cin>>p;
int process[p];
cout<<"enter processes size separated by space:";
for(int i=0;i<p;i++)
{
cin>>process[i];

16CE068 Page 35
16CE068 CE221.01 Operating Systems JAINIL PATEL

}
cout<<"enter no of memory locations:";
cin>>m;
int memory[m];
cout<<"enter memory locations available:";
for(int i=0;i<p;i++)
{
cin>>memory[i];
}
worstfit(m,p,memory,process);
}
Output:

4)nextfit.cpp
#include<iostream>
using namespace std;

void nextfit(int sizeofmem,int sizeofpro,int mem[],int pro[])


{
int memoryindexgot[sizeofpro];
int noofmemoryspace=sizeofmem;
int noofprocess= sizeofpro;

16CE068 Page 36
16CE068 CE221.01 Operating Systems JAINIL PATEL

for(int i=0;i<noofprocess;i++)
{

int flag=0;
for(int j=0;j<noofmemoryspace;j++)
{
if(pro[i]<=mem[j])
{
cout<<"process "<<i<<" of size "<<pro[i]<<"in memory location "<<j<<"\n";
mem[j]=mem[j]-pro[i];
flag=1;
memoryindexgot[i]=j;
goto aa;
}
}
if(flag==0)
{
cout<<"no space found for "<<"process "<<i<<" of size "<<pro[i]<<"\n";
}
aa:
;
}
}
int main()
{
int p,m;
cout<<"enter no of processes:";
cin>>p;
int process[p];
cout<<"enter processes size separated by space:";
for(int i=0;i<p;i++)
{
cin>>process[i];

16CE068 Page 37
16CE068 CE221.01 Operating Systems JAINIL PATEL

}
cout<<"enter no of memory locations:";
cin>>m;
int memory[m];
cout<<"enter memory locations available:";
for(int i=0;i<p;i++)
{
cin>>memory[i];
}
nextfit(m,p,memory,process);

PRACTICAL 6
Aim: Write a C program in UNIX to implement Process scheduling algorithms and compare.
A. First Come First Serve (FCFS) Scheduling
B. Shortest-Job-First (SJF) Scheduling
C. Priority Scheduling (Non-preemption) after completion extend on Preemption.
D. Round Robin(RR) Scheduling

A)fcfs.java

16CE068 Page 38
16CE068 CE221.01 Operating Systems JAINIL PATEL

package fcfs;

import java.util.Scanner;

/**
*
* @author jainil
*/
class process
{
public int processid;
public int arrivaltime;
public int bursttime;
public int completiontime;
public int turnaroundtime;
public int waitingtime;
public process(int processid, int arrivaltime, int bursttime) {
this.processid = processid;
this.arrivaltime = arrivaltime;
this.bursttime = bursttime;
}
public process() {
}
}
public class Fcfs {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("enter no of process");
int n;
Scanner sc=new Scanner(System.in);

16CE068 Page 39
16CE068 CE221.01 Operating Systems JAINIL PATEL

n=sc.nextInt();
process p[]=new process[n];

System.out.println("enter details of process");


for(int i=0;i<n;i++)
{
int processid=i;
int arrivaltime;
int bursttime;
System.out.println("enter arrival time of process "+i);
arrivaltime=sc.nextInt();
System.out.println("enter bursttime of process "+i);
bursttime=sc.nextInt();
p[i]=new process(processid,arrivaltime,bursttime);
}
int currenttime=0;
for(int i=0;i<n;i++)
{
while(p[i].arrivaltime>currenttime)
{
currenttime++;
}
currenttime=currenttime+p[i].bursttime;
System.out.println("process "+i+" completed after "+currenttime+" ms ");
}

}
OUTPUT:
enter no of process
5
enter details of process
enter arrival time of process 0

16CE068 Page 40
16CE068 CE221.01 Operating Systems JAINIL PATEL

0
enter bursttime of process 0
5
enter arrival time of process 1
1
enter bursttime of process 1
4
enter arrival time of process 2
2
enter bursttime of process 2
3
enter arrival time of process 3
3
enter bursttime of process 3
2
enter arrival time of process 4
4
enter bursttime of process 4
1
process 0 completed after 5 ms
process 1 completed after 9 ms
process 2 completed after 12 ms
process 3 completed after 14 ms
process 4 completed after 15 ms

B)shortest job first non preemptive


package sjf;
import java.util.Scanner;

/**
*
* @author jainil
*/

16CE068 Page 41
16CE068 CE221.01 Operating Systems JAINIL PATEL

class process
{

public int processid;


public int arrivaltime;
public int bursttime;
public int completiontime;
public int turnaroundtime;
public int waitingtime;
public process(int processid, int arrivaltime, int bursttime) {
this.processid = processid;
this.arrivaltime = arrivaltime;
this.bursttime = bursttime;
} public process() {
}

public class Sjf {


public static void main(String[] args) {
// TODO code application logic here
System.out.println("enter no of process");
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
process p[]=new process[n];

System.out.println("enter details of process");


for(int i=0;i<n;i++)
{
int processid=i;
int arrivaltime;

16CE068 Page 42
16CE068 CE221.01 Operating Systems JAINIL PATEL

int bursttime;
System.out.println("enter arrival time of process "+i);
arrivaltime=sc.nextInt();
System.out.println("enter bursttime of process "+i);
bursttime=sc.nextInt();
p[i]=new process(processid,arrivaltime,bursttime);
}
int currenttime=0;
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if((p[i].arrivaltime<=currenttime)&&(p[j].bursttime<p[i].bursttime))
{
process temp=new process();
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}

while(p[i].arrivaltime>currenttime)
{
currenttime++;
}
currenttime=currenttime+p[i].bursttime;
System.out.println("process "+p[i].processid+" completed at "+currenttime);
}
}
}
OUTPUT:
enter no of process
5
enter details of process

16CE068 Page 43
16CE068 CE221.01 Operating Systems JAINIL PATEL

enter arrival time of process 0


0
enter bursttime of process 0
1
enter arrival time of process 1
1
enter bursttime of process 1
5
enter arrival time of process 2
2
enter bursttime of process 2
8
enter arrival time of process 3
3
enter bursttime of process 3
4
enter arrival time of process 4
5
enter bursttime of process 4
9
process 0 completed at 1
process 3 completed at 7
process 1 completed at 12
process 2 completed at 20
process 4 completed at 29
B)shortest remaining time first
import java.io.*;
public class SRTF {
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
System.out.println("Please enter the number of Processes: ");
n = Integer.parseInt(br.readLine());

16CE068 Page 44
16CE068 CE221.01 Operating Systems JAINIL PATEL

int proc[][] = new int[n + 1][4];//proc[][0] is the AT array,[][1] - RT,[][2] - WT,[][3] - TT


for(int i = 1; i <= n; i++)
{
System.out.println("Please enter the Arrival Time for Process " + i + ": ");
proc[i][0] = Integer.parseInt(br.readLine());
System.out.println("Please enter the Burst Time for Process " + i + ": ");
proc[i][1] = Integer.parseInt(br.readLine());
}
System.out.println();

//Calculation of Total Time and Initialization of Time Chart array


int total_time = 0;
for(int i = 1; i <= n; i++)
{
total_time += proc[i][1];
}
int time_chart[] = new int[total_time];

for(int i = 0; i < total_time; i++)


{
//Selection of shortest process which has arrived
int sel_proc = 0;
int min = 99999;
for(int j = 1; j <= n; j++)
{
if(proc[j][0] <= i)//Condition to check if Process has arrived
{
if(proc[j][1] < min && proc[j][1] != 0)
{
min = proc[j][1];
sel_proc = j;
}
}
}

16CE068 Page 45
16CE068 CE221.01 Operating Systems JAINIL PATEL

//Assign selected process to current time in the Chart


time_chart[i] = sel_proc;

//Decrement Remaining Time of selected process by 1 since it has been assigned the CPU for 1 unit of
time
proc[sel_proc][1]--;

//WT and TT Calculation


for(int j = 1; j <= n; j++)
{
if(proc[j][0] <= i)
{
if(proc[j][1] != 0)
{
proc[j][3]++;//If process has arrived and it has not already completed execution its TT is
incremented by 1
if(j != sel_proc)//If the process has not been currently assigned the CPU and has arrived its WT is
incremented by 1
proc[j][2]++;
}
else if(j == sel_proc)//This is a special case in which the process has been assigned CPU and has
completed its execution
proc[j][3]++;
}
}

//Printing the Time Chart


if(i != 0)
{
if(sel_proc != time_chart[i - 1])
//If the CPU has been assigned to a different Process we need to print the current value of time and
the name of
//the new Process

16CE068 Page 46
16CE068 CE221.01 Operating Systems JAINIL PATEL

{
System.out.print("--" + i + "--P" + sel_proc);
}
}
else//If the current time is 0 i.e the printing has just started we need to print the name of the First
selected Process
System.out.print(i + "--P" + sel_proc);
if(i == total_time - 1)//All the process names have been printed now we have to print the time at
which execution ends
System.out.print("--" + (i + 1));

}
System.out.println();
System.out.println();

//Printing the WT and TT for each Process


System.out.println("P\t WT \t TT ");
for(int i = 1; i <= n; i++)
{
System.out.printf("%d\t%2dms\t%2dms",i,proc[i][2],proc[i][3]);
System.out.println();
}

System.out.println();

//Printing the average WT & TT


float WT = 0,TT = 0;
for(int i = 1; i <= n; i++)
{
WT += proc[i][2];
TT += proc[i][3];
}
WT /= n;
TT /= n;

16CE068 Page 47
16CE068 CE221.01 Operating Systems JAINIL PATEL

System.out.println("The Average WT is: " + WT + "ms");


System.out.println("The Average TT is: " + TT + "ms");
}
}

OUTPUT:
Please enter the number of Processes:
5
Please enter the Arrival Time for Process 1:
0
Please enter the Burst Time for Process 1:
2
Please enter the Arrival Time for Process 2:
1
Please enter the Burst Time for Process 2:
5
Please enter the Arrival Time for Process 3:
2
Please enter the Burst Time for Process 3:
6
Please enter the Arrival Time for Process 4:
3
Please enter the Burst Time for Process 4:
7
Please enter the Arrival Time for Process 5:
4
Please enter the Burst Time for Process 5:
8

0--P1--2--P2--7--P3--13--P4--20--P5--28

P WT TT
1 0ms 2ms

16CE068 Page 48
16CE068 CE221.01 Operating Systems JAINIL PATEL

2 1ms 6ms
3 5ms 11ms
4 10ms 17ms
5 16ms 24ms

The Average WT is: 6.4ms


The Average TT is: 12.0ms

C)PRIORITY non preemptive


/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package p;

import java.util.Scanner;

16CE068 Page 49
16CE068 CE221.01 Operating Systems JAINIL PATEL

/**
*
* @author jainil
*/

class process
{

public int processid;


public int arrivaltime;
public int bursttime;
public int completiontime;
public int turnaroundtime;
public int waitingtime;
public int priority;

public process(int processid, int arrivaltime, int bursttime,int priority) {


this.processid = processid;
this.arrivaltime = arrivaltime;
this.bursttime = bursttime;
this.priority=priority;
}

public process() {
}

public class priorityqueue {

/**

16CE068 Page 50
16CE068 CE221.01 Operating Systems JAINIL PATEL

* @param args the command line arguments


*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("enter no of process");
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
process p[]=new process[n];

System.out.println("enter details of process");


for(int i=0;i<n;i++)
{
int processid=i;
int arrivaltime;
int bursttime;
int priority;
System.out.println("enter arrival time of process "+i);
arrivaltime=sc.nextInt();
System.out.println("enter bursttime of process "+i);
bursttime=sc.nextInt();
System.out.println("enter priority of process "+i);
priority=sc.nextInt();

p[i]=new process(processid,arrivaltime,bursttime,priority);
}
int currenttime=0;
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if((p[i].arrivaltime<=currenttime)&&(p[j].priority>p[i].priority))
{
process temp=new process();

16CE068 Page 51
16CE068 CE221.01 Operating Systems JAINIL PATEL

temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}

while(p[i].arrivaltime>currenttime)
{
currenttime++;
}
currenttime=currenttime+p[i].bursttime;
System.out.println("process "+p[i].processid+" of priority "+p[i].priority+" completed at
"+currenttime);

}
OUTPUT:
enter no of process
5
enter details of process
enter arrival time of process 0
0
enter bursttime of process 0
5
enter priority of process 0
1
enter arrival time of process 1
1
enter bursttime of process 1
6

16CE068 Page 52
16CE068 CE221.01 Operating Systems JAINIL PATEL

enter priority of process 1


2
enter arrival time of process 2
2
enter bursttime of process 2
6
enter priority of process 2
3
enter arrival time of process 3
3
enter bursttime of process 3
4
enter priority of process 3
5
enter arrival time of process 4
4
enter bursttime of process 4
5
enter priority of process 4
4
process 1 of priority 2 completed at 7
process 3 of priority 5 completed at 11
process 4 of priority 4 completed at 16
process 2 of priority 3 completed at 22
process 0 of priority 1 completed at 27
D)round robin:
import java.io.*;
import java.util.Scanner;

public class round


{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(System.in);

16CE068 Page 53
16CE068 CE221.01 Operating Systems JAINIL PATEL

int i,j,k,q,sum=0;
System.out.println("Enter number of process:");
int n=sc.nextInt();
int bt[]=new int[n];
int wt[]=new int[n];
int tat[]=new int[n];
int a[]=new int[n];
System.out.println("Enter brust Time:");
for(i=0;i<n;i++)
{
System.out.println("Enter brust Time for "+(i+1));
bt[i]=sc.nextInt();
}
System.out.println("Enter Time quantum:");
q=sc.nextInt();
for(i=0;i<n;i++)
a[i]=bt[i];
for(i=0;i<n;i++)
wt[i]=0;
do
{
for(i=0;i<n;i++)
{
if(bt[i]>q)
{
bt[i]-=q;
for(j=0;j<n;j++)
{
if((j!=i)&&(bt[j]!=0))
wt[j]+=q;
}
}
else
{

16CE068 Page 54
16CE068 CE221.01 Operating Systems JAINIL PATEL

for(j=0;j<n;j++)
{
if((j!=i)&&(bt[j]!=0))
wt[j]+=bt[i];
}
bt[i]=0;
}
}
sum=0;
for(k=0;k<n;k++)
sum=sum+bt[k];
}
while(sum!=0);
for(i=0;i<n;i++)
tat[i]=wt[i]+a[i];
System.out.println("process\t\tBT\tCT\tWT\tTAT");
for(i=0;i<n;i++)
{
System.out.println("process"+(i+1)+"\t"+a[i]+"\t"+(wt[i]+a[i])+"\t"+wt[i]+"\t"+tat[i]);
}
float avg_wt=0;
float avg_tat=0;
for(j=0;j<n;j++)
{
avg_wt+=wt[j];
}
for(j=0;j<n;j++)
{
avg_tat+=tat[j];
}
System.out.println("average waiting time "+(avg_wt/n)+"n Average turn around time"+(avg_tat/n));
}
}
OUTPUT:

16CE068 Page 55
16CE068 CE221.01 Operating Systems JAINIL PATEL

Enter number of process:


5
Enter brust Time:
Enter brust Time for 1
5
Enter brust Time for 2
4
Enter brust Time for 3
2
Enter brust Time for 4
3
Enter brust Time for 5
1
Enter Time quantum:
2
process BT CT WT TAT
process1 5 15 10 15
process2 4 13 9 13
process3 2 6 4 6
process4 3 14 11 14
process5 1 9 8 9
average waiting time 8.4n Average turn around time11.4

PRACTICAL 7:
Aim: Process control system calls:
A. The demonstration of fork()
B. execve() and wait() system calls along with zombie and orphan states.

A) . The demonstration of fork()

#include <stdio.h>

16CE068 Page 56
16CE068 CE221.01 Operating Systems JAINIL PATEL

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

#define MAX_COUNT 20

void ChildProcess(void); /* child process prototype */

void ParentProcess(void); /* parent process prototype */

void main(void)

pid_t pid;

pid = fork();

if (pid == 0)

ChildProcess();

else

ParentProcess();

16CE068 Page 57
16CE068 CE221.01 Operating Systems JAINIL PATEL

void ChildProcess(void)

int i;

for (i = 1; i <= MAX_COUNT; i++)

printf(" This line is from child, value = %d\n", i);

printf(" *** Child process is done ***\n");

void ParentProcess(void)

int i;

for (i = 1; i <= MAX_COUNT; i++)

printf("This line is from parent, value = %d\n", i);

printf("*** Parent is done ***\n");

16CE068 Page 58
16CE068 CE221.01 Operating Systems JAINIL PATEL

}
OUTPUT:

B) execve() and wait() system calls along with zombie and orphan states.
At which condition Process becomes Zombie Process? How process is removed from
Zombie state?

 Whenever a child process dies, its parent process recieves the signal SIGCHLD. Suppose
a parent spawned the child process and forgot to handle the SIGCHLD signal or ignored
the signal (which is the default scenario when signal is not handled), then the child
process becomes the Zombie process. Whenever a parent waits for its child process and
reads its exit status, the child process is removed from the process structure table before
the parent.

 Suppose the child  has become a zombie, it remains zombie only for the time interval for
which its parent is alive. Once the parent of a zombie process is dead, it is adopted by

16CE068 Page 59
16CE068 CE221.01 Operating Systems JAINIL PATEL

the init process of the unix which then acts as the father of the process. Init continously
runs wait system call to remove zombies from the system. Zombie processes are a big
problem when their parent processes run for a long time. In this case Zombies will
persist in the process structure table for a lot of time.

Command to see Zombie Process:ps -le|grep 'Z'

Program:

#include<stdio.h>
int main()
{
int pid;
pid=fork();
if(pid>0)
{
sleep(30);
printf("parent process id %d",getpid());
printf("in parent process");
}
else if(pid==0)
{
printf("child process id %d",getpid());
printf("in child process");
}
return 1;
}

PRACTICAL 8:
AIM: Thread management using pthread library. Write a simple program to understand it.

// A normal C function that is executed as a thread

// when its name is specified in pthread_create()

void *myThreadFun(void *vargp)

16CE068 Page 60
16CE068 CE221.01 Operating Systems JAINIL PATEL

printf("Printing from Thread \n");

return NULL;

int main()

pthread_t tid;

printf("Before Thread\n");

int a=pthread_create(&tid, NULL, myThreadFun, NULL);

int b=pthread_join(tid, NULL);

printf("After Thread\n");

exit(0);

PRACTICAL 9:
Aim: Write a C program in UNIX to implement inter process communication (IPC) using Semaphore.
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>

sem_t readCountAccess;
sem_t databaseAccess;
int readCount=0;
int NumberofReaderThread;
int NumberofWriterThread;

16CE068 Page 61
16CE068 CE221.01 Operating Systems JAINIL PATEL

//databaseAccess is rw_mutex
//readCountAccess is mutex

void *Reader(void * arg)


{

int temp=*(int *)arg;


printf("\nReader %d is trying to enter into the Database for reading the data",temp);
sem_wait(&readCountAccess);
readCount++;
if(readCount==1){
sem_wait(&databaseAccess);}
sem_post(&readCountAccess);
printf("\nReader %d is reading the database",temp);

sem_wait(&readCountAccess);
readCount--;
if(readCount==0)
{
printf("\nReader %d is leaving the database",temp);
sem_post(&databaseAccess);
}
sem_post(&readCountAccess);
}
void *Writer(void * arg)
{

int temp=*(int *)arg;


printf("\nWriter %d is trying to enter into database for modifying the data",temp);
sem_wait(&databaseAccess);
printf("\nWriter %d is writting into the database",temp);
printf("\nWriter %d is leaving the database",temp);
sem_post(&databaseAccess);
}

void main()
{
int i=0,NumberofReaderThread=0,NumberofWriterThread;
sem_init(&readCountAccess,0,1);
sem_init(&databaseAccess,0,1);
pthread_t Readers_thr[10],Writer_thr[10];

16CE068 Page 62
16CE068 CE221.01 Operating Systems JAINIL PATEL

printf("\nEnter number of Readers thread(MAX 100)");


scanf("%d",&NumberofReaderThread);
printf("\nEnter number of Writers thread(MAX 100)");
scanf("%d",&NumberofWriterThread);

for(i=0;i<NumberofWriterThread;i++)
{
pthread_create(&Writer_thr[i],NULL,Writer(&i),NULL);
}
for(i=0;i<NumberofReaderThread;i++)
{
pthread_create(&Readers_thr[i],NULL,Reader(&i),NULL);
}
for(i=0;i<NumberofWriterThread;i++)
{
pthread_join(Writer_thr[i],NULL);
}

for(i=0;i<NumberofReaderThread;i++)
{
pthread_join(Readers_thr[i],NULL);
}


PRACTICAL 10
AIM: Thread synchronization using counting semaphores and mutual exclusion using mutex.

#include<stdio.h>
#include<semaphore.h>
#include<sys/types.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>

#define BUFFER_SIZE 10

16CE068 Page 63
16CE068 CE221.01 Operating Systems JAINIL PATEL

pthread_mutex_t mutex;
sem_t empty,full;

int buffer[BUFFER_SIZE];
int counter;

pthread_t tid;

void *producer();
void *consumer();

void insert_item(int);
int remove_item();

void initilize()
{
pthread_mutex_init(&mutex,NULL);
sem_init(&full,0,0);
sem_init(&empty,0,BUFFER_SIZE);
}
int c=0;
void *producer()
{
int item,wait_time;
while(1){
wait_time=rand()%5;
sleep(wait_time);
item=c;
c++;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
printf("Producer produce %d\n\n",item);
insert_item(item);
pthread_mutex_unlock(&mutex);
sem_post(&full);}
}
void *consumer()
{
while(1){
int item,wait_time;
wait_time=rand()%5;
sleep(wait_time);
sem_wait(&full);

16CE068 Page 64
16CE068 CE221.01 Operating Systems JAINIL PATEL

pthread_mutex_lock(&mutex);
item=remove_item();
printf("Consumer consume %d\n\n",item);
pthread_mutex_unlock(&mutex);
sem_post(&empty);}
}
void insert_item(int item)
{ buffer[counter++]=item;}
int remove_item()
{ return buffer[--counter];}

int main()
{
int n1,n2;
int i;
printf("Enter number of Producers");
scanf("%d",&n1);
printf("Enter number of Consumers");
scanf("%d",&n2);
initilize();
for(i=0;i<n1;i++)
pthread_create(&tid,NULL,producer,NULL);
for(i=0;i<n2;i++)
pthread_create(&tid,NULL,consumer,NULL);
int b=pthread_join(tid, NULL);

exit(0);
}

16CE068 Page 65
16CE068 CE221.01 Operating Systems JAINIL PATEL

PRACTICAL 11:

16CE068 Page 66
16CE068 CE221.01 Operating Systems JAINIL PATEL

Aim: Write a C program in UNIX to implement Bankers algorithm for Deadlock Avoidance

#include<stdio.h>
#include<conio.h>
void main()
{int res[10],v[10],c[10][10],a[10][10],ca[10][10],tot[10],p=0;
int r,I,j,n,flag,flag1,flag3[10],pos,count=0,r=0,order[10];
clrscr();
printf(“enter no of processes \n”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{flag3[i]=0;order[i]=0;}
printf(“enter the no.of resources\n”);
scanf(“%d”,&r);
printf(“enter the instances of each resource\n”);
for(i=0;i<r;i++)
{scanf(“%d”,&res[i]);}
printf(“enter the max required from each process from each resorce”);
for(i=0;i<n;i++)
{for(j=0;j<r;j++)
{scanf(“%d”,&c[i][j]);}}
printf(“\n enter the current allocation of resources”);
for(i=0;i<n;i++)
{for(j=0;j<r;j++)
{scanf(“%d”,&a[i][j]);}}
start:for(i=0;i<n;i++){for(j=0;j<r;j++){
ca[i][j]=c[i][j]-a[i][j];}}
for(i=0;i<r;i++)
{for(j=0;j<n;j++)
{tot[i]=tot[i]+a[j][i];}}
for(i=0;i<r;i++){v[i]=res[i]-tot[i];}
for(i=0;i<r;i++){if(res[i]<tot[i])
{flag=0;goto out;}
Else flag=1;}
out:for(i=0;i<r;i++)

16CE068 Page 67
16CE068 CE221.01 Operating Systems JAINIL PATEL

{for(j=0;j<n;j++)
{if(res[j][i]>tot[i])
flag1=0;
goto next;}
else flag1=1;}}
next:if((flag==1)&&(flag1==1)
printf(“the system is in safe state”);
else if((flag==0)||(flag1==0))
{ printf(“the system is in unsafe state”);goto next;}
for(i=0;i<n;i++)
{count=0;for(j=0;j<r;j++)
{if((ca[i][j]<=v[i]&&flag3[i]==0))count++;}
if(count==r){ pos=i;flag3[pos]=1;goto cout;}}cout:order[p]=pos; p++; printf(“process
%dis completed”,pos);
for(i=0;i<r;i++)
{v[i]=v[i]+a[pos][i];}
for(i=0;i<r;i++)
{for(j=0;j<r;j++)
{c[pos][j]=0;ca[pos][j]=0;a[pos][j]=0;}}
printf(“C-A matrix “);for(i=0;i<n;i++)
{ printf(“\n”);
for(j=0;j<r;j++)
{ printf(“%d”,ca[i][j]);}
for(i=0;i<n;i++)
{if(flag3[i]==1)
t++;
if(t==n)
goto exit;
else goto start;}
exit:printf(“order of execution is”);
for(i=0;i<n;i++)
printf(“%d”,order[i]);}
getch();}
Output:
Enter the no of process
16CE068 Page 68
16CE068 CE221.01 Operating Systems JAINIL PATEL

4
Enter the no of resources
3enter the instances of each resource
936
enter the max required from each process for each resourece
322613314422
enter the current allocation of resources
00612211002
The available matrix is 0 1 1
process 1 completed
after completion of the 1 process available vecteor is 6 2 3
The available matrix is 6 2 3
process 0 completed
after completion of the 0 process available vecteor is 7 2 3
The available matrix is 7 2 3
process 2 completed
after completion of the 2 process available vecteor is 9 3 4
The available matrix is 9 3 4
process 3 completed
after completion of the 3 process available vecteor is 9 3 6
Order of execution of process 1 0 2 3

Practical 12
Aim: To perform Kernel Space Programming.

16CE068 Page 69
16CE068 CE221.01 Operating Systems JAINIL PATEL

Problem Statement:
Implement and add a loadable kernel module to Linux kernel, demonstrate using insmod, lsmod and rmmod
commands. A sample kernel space program should print the "Hello World" while loading the kernel module
and "Goodbye World" while unloading the kernel module.

Theory:
What is a loadable kernel module?
To add a new code to a Linux kernel, it is necessary to add some source files to kernel source tree and
recompile the kernel. You can also add code to the Linux kernel while it is running. A chunk of code added in
such way is called a loadable kernel module.

Typical modules:
Device drivers, File system drivers, System calls

Advantages of modules
1. There is no necessity to rebuild the kernel, when a new kernel option is added.
2. Modules help find system problems (if system problem caused a module just don't load it).
3. Modules are much faster to maintain and debug.
4. Modules once loaded are in as much fast as kernel.

Module Implementation
 Modules are stored in the file system as ELF object files.
 The kernel makes sure that the rest of the kernel can reach the module's global symbols.
 Module must know the addresses of symbols (variables and functions) in the kernel and in other
modules (/proc/kallsyms).
 The kernel keeps track of the use of modules, so that no modules is unloaded while another module
or kernel is using it (/proc/modules)
 The kernel considers only modules that have been loaded into RAM by the insmod program and for
each of them allocates memory area containing: a module object
 null terminated string that represents module's name
 the code that implements the functions of the module

Module Object

16CE068 Page 70
16CE068 CE221.01 Operating Systems JAINIL PATEL

Programs for linking and unlinking

1. insmod
 inserts the module into the kernel space.
 Reads from the name of the module to be linked
 Locates the file containing the module's object code
 Computes the size of the memory area needed to store the module code, its name, and the module
object.
 Invokes the create_module( ) system call

2. Insmod
 Invokes the query_module( ) system call Using the kernel symbol table, the module symbol tables,
and the address returned by the create_module( ) system call, relocates the object code included in
the module's file.
 Allocates a memory area in the User Mode address space and loads with a copy of the module
object.
 Invokes the init_module( ) system call, passing to it the address of the User Mode memory area.
 Releases the User Mode memory area and terminates

3. lsmod
 reads /proc/modules and displays on the terminal.
4. Rmmod
 reads the name of the module to be unlinked.

16CE068 Page 71
16CE068 CE221.01 Operating Systems JAINIL PATEL

 Invokes the query_module( )


 Invokes the delete_module( ) system call
5. modprobe
 takes care of possible complications due to module dependencies, uses depmod program and
/etc/modules.conf file

Compiling kernel module

 A kernel module is not an independent executable, but an object file which will be linked into the
kernel in runtime and they should be compiled with
o -c flag
o _KERNEL_ symbol
o CONFIG_MODVERSIONS symbol

Steps for the program compilation, linking, loading and executing

1. Edit a Hello.c program


2. Edit a makefile
3. The program and makefile should be kept in a single folder.
4. Change directory to this folder
5. Execute “ make” on terminal
6. Execute insmodHello.ko from this folder.
7. Execute dmesg from a terminal to see the kernel buffer
8. contents (reads the kernel log file /var/log/syslog)
9. Execute lsmod from this folder.
10. Execute rmmodHello.ko from this folder when done.

Files created after building the module

 Hello.o - Module object file before linking


 Hello.mod.c - Contains module’s information
 Hello.mod.o - After compilation and linking of Hello.mod.c
 Modules.order - The order in which two or three modules get linked..
 Modules.symvers - Symbol versions if any.
 Hello.ko - A module kernel object file after linking Hello.o and
 Hello.mod.o - Hello.mod.c details

Hello.mod.c details

16CE068 Page 72
16CE068 CE221.01 Operating Systems JAINIL PATEL

Include/linux/module.h , include/linux/vermagic.h, include/linux/kernel.h

Step 1 –
 Find all modules from the files listed in $(MODVERDIR)/
 modpost is then used to create one <module>.mod.c file
o Create one Module.symvers file with CRC for all exported symbols
o Compile all <module>.mod.c files
o Final link of the module to a <module.ko> file

Step 2 - is used to place certain information in the module's ELF


• Version magic (see include/linux/vermagic.h for full details)
• Kernel release
• GCC Version

• Module info
• Module version (MODULE_VERSION)
• Module license (MODULE_LICENSE)

Step 3 - is used to allow module versioning in external modules, where the CRC of each module is retrieved
from the Module.symvers file.

Module definition:

struct module __this_module


__attribute__((section(".gnu.linkonce.this_module")
)) = {
.name = KBUILD_MODNAME,
.init = init_module,
#ifdef CONFIG_MODULE_UNLOAD
.exit = cleanup_module,
#endif
.arch = MODULE_ARCH_INIT
}

16CE068 Page 73
16CE068 CE221.01 Operating Systems JAINIL PATEL

The symbol version definitions:


(nm – modules in the object file- nm hello.ko)

static const struct modversion_info ____versions[]


__used
__attribute__((section("__versions"))) =
{
{ 0x4d5503c4, "module_layout" },
{ 0xb4390f9a, "mcount" },
{ 0x50eedeb8, "printk" },
};

• /usr/src/linux-version-headers/Module.symvers
• This file contains the list of symbols that are exported
by kernel to loadable 07/01/15 kernel modules (LKM).

Conclusion:
Loadable kernel module is implemented and added to Linux kernel using insmod, lsmod and rmmod
commands.

16CE068 Page 74

You might also like