OS - Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 98

OPERATING SYSTEMS

LABORATORY MANUAL
R20A0584

B.TECH (II YEAR – I SEM)


(2022-23)

DEPARTMENT OF COMPUTATIONAL INTELLIGENCE


(CSE- AIML,AIML,AI&DS)
MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY
(Autonomous Institution – UGC, Govt. of India)
Recognized under 2(f) and 12 (B) of UGC ACT 1956

Affiliated to JNTUH, Hyderabad, Approved by AICTE ‐ Accredited by NBA Tier 1 & NAAC – ‘A’ Grade ‐ ISO 9001:2015Certified)
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, India
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING – AI & ML

VISION

 To achieve high quality in technical education that provides the skills and
attitude to adapt to the global needs of the Information Technology sector,
through academic and research excellence.

MISSION

 To equip the students with the cognizance for problem solving and to
improve the teaching pedagogy by using innovative techniques.

 To strengthen the knowledge base of the faculty and students with motivation
towards possession of effective academic skills and relevant research
experience

 To promote the necessary moral and ethical values among the engineers, for
the betterment of the society
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO1: PROFESSIONALISM & CITIZENSHIP


To create and sustain a community of learning in which students acquire knowledge
and learn to apply it professionally with due consideration for ethical, ecological and
economic issues.
PEO2: TECHNICAL ACCOMPLISHMENTS
To provide knowledge based services to satisfy the needs of society and the industry
byproviding hands on experience in various technologies in core field.
PEO3: INVENTION, INNOVATION AND CREATIVITY
To make the students to design, experiment, analyze, interpret in the core field
withthe help of other multi disciplinary concepts wherever applicable.
PEO4: PROFESSIONAL DEVELOPMENT
To educate the students to disseminate research findings with good soft skills and
become a successful entrepreneur.
PEO5: HUMAN RESOURCE DEVELOPMENT
To graduate the students in building national capabilities in technology, education and
research.
PROGRAM SPECIFIC OUTCOMES (PSOs)

After the completion of the course, B. Tech Information Technology, the


graduates will havethe following Program Specific Outcomes:

1. Fundamentals and critical knowledge of the Computer System:- Able


to Understand the working principles of the computer System and its
components , Apply the knowledge to build, asses, and analyze the software
and hardware aspects of it .

2. The comprehensive and Applicative knowledge of Software


Development: Comprehensive skills of Programming Languages, Software
process models, methodologies, and able to plan, develop, test, analyze, and
manage the software and hardware intensive systems in heterogeneous
platforms individually or working in teams.

Applications of Computing Domain & Research: Able to use the professional,


managerial, interdisciplinary skill set, and domain specific tools in development
processes, identify the research gaps, and provide innovative solutions to them.
PROGRAM OUTCOMES (POs)

Engineering Graduates should possess the following:


1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex
engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of
data, and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilitiesrelevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multi disciplinary
environments.
12. Life- long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
Maisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING – AI & ML

GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory atleast 5 minutes before (to the starting
time), those who come after 5minutes will not be allowed into the lab.

2. Plan your task properly much before to the commencement, come prepared to the lab
with the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a) Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.

b) Laboratory Record updated upto the last session experiments and other utensils (if
any)needed in the lab.

c) Proper Dress code and Identity card.

4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Executeyourtaskinthelaboratory,andrecordtheresults/outputinthelabobservationnotebook,a
nd get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
7. Computerlabsareestablishedwithsophisticatedandhighendbrandedsystems, which should
be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the
lab sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if any
body found loitering outside the lab / class without permission during working hours will be
treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system / seat is
kept properly.

HEAD OF THE DEPARTMENT PRINCIPAL


INDEX

S.NO LIST OF PROGRAMS PAGE NO.


To Install Ubuntu Linux and practice LINUX Commands

WEEK-1 Practice File handling utilities, Process utilities, Disk utilities, Networking
commands, Filters, Test processing utilities and Backup utilities.
WEEK-2 Simulate the following CPU scheduling algorithms.
a)FCFS b) SJF c) Round Robin d) Priority.
WEEK-3 Simulate Bankers Algorithm for Dead Lock Avoidance; Simulate Bankers
Algorithm for Dead Lock Prevention
WEEK-4 Write a C program to simulate the concept of Dining-philosophers
problem.
Write a C program to simulate producer-consumer problem using
WEEK-5 Semaphores
a)Write a C program to implement kill(), raise() and sleep(),functions.
WEEK-6 b)Write a C program to implement alarm(), pause() and abort() functions
a) Write a program that illustrates communication between two process
WEEK-7 using named pipes or FIFO.
b) Write a C program that illustrates two processes communicating
using Shared memory

WEEK-8 Simulate all page replacement algorithms


a) FIFO b) LRU c) OPTIMAL
WEEK-9 Write a C program that takes one or more file/directory names as
command line input and reports following information
A) File Type B) Number Of Links C) Time of last Access D) Read, write
and execute permissions
WEEK-10 Implement in c language the following UNIX commands using system
calls
i) cat ii) ls iii) Scanning Directories (Ex: opendir(),readdir(),etc.)
Write a C program to create child process and allow parent process to
WEEK-11 display “parent” and the child to display “child” on the screen

WEEK-12 Write a C program to simulate disk scheduling algorithms.


a) FCFS b) SCAN c) C-SCAN
To Install Ubuntu Linux – Complete Step by Step
Now again select free space from the table and click add option. Now select size to be around twice the size of
your ram that is around 1000 mb if your ram size is 512mb and select use as swap area and clickok.
Step 6 : Click Install now button and then the wizardwill ask you location. Select your location and click
forward.
A-Z Index of the Bash command line for Linux
a

alias Create an alias •

apropos Search Help manual pages (man -k)

apt-get Search for and install software packages (Debian/Ubuntu)

aptitude Search for and install software packages (Debian/Ubuntu)

aspell Spell Checker

awk Find and Replace text, database sort/validate/index

basename Strip directory and suffix fromfilenames

bash GNU Bourne-Again SHell

bc Arbitrary precision calculatorlanguage

bg Send to background

bind Set or display readline key and function bindings•

break Exit from a loop •

builtin Run a shell builtin

bzip2 Compress or decompress named file(s)

cal Display a calendar

case Conditionally perform a command

cat Concatenate and print (display) the content offiles

cd Change Directory

cfdisk Partition table manipulator for Linux

chattr Change file attributes on a Linux filesystem


chgrp Change group ownership

chmod Change access permissions

chown Change file owner andgroup

chroot Run a command with a different rootdirectory

chkconfig System services (runlevel)

cksum Print CRC checksum and bytecounts

clear Clear terminal screen

cmp Compare two files

comm Compare two sorted files line by line

command Run a command - ignoring shell functions

continue Resume the next iteration of a loop

cp Copy one or more files to another location

cron Daemon to execute scheduled commands

crontab Schedule a command to run at a later time

csplit Split a file into context-determined pieces

curl Transfer data from or to a server

cut Divide a file into several parts

date Display or change the date &time

dc Desk Calculator

dd Convert and copy a file, write disk headers, bootrecords

ddrescue Data recovery tool

declare Declare variables and give them attributes•

df Display free disk space

diff Display the differences between twofiles

diff3 Show differences among three files

dig DNS lookup


dir Briefly list directorycontents

dircolors Colour setup for `ls'

dirname Convert a full pathname to just a path

dirs Display list of remembered directories

dmesg Print kernel & driver messages

du Estimate file space usage

echo Display message on screen

egrep Search file(s) for lines that match an extendedexpression

eject Eject removable media

enable Enable and disable builtin shell commands

env Environment variables

eval Evaluate severalcommands/arguments

exec Execute a command

exit Exit the shell

expect Automate arbitrary applications accessed over aterminal

expand Convert tabs to spaces

export Set an environment variable

expr Evaluate expressions

false Do nothing, unsuccessfully

fdformat Low-level format a floppydisk

fdisk Partition table manipulator forLinux

fg Send job to foreground

fgrep Search file(s) for lines that match a fixedstring

file Determine file type

find Search for files that meet a desiredcriteria


fmt Reformat paragraph text

fold Wrap text to fit a specified width.

for Expand words, and execute commands

format Format disks or tapes

free Display memory usage

fsck File system consistency check andrepair

ftp File Transfer Protocol

function Define FunctionMacros

fuser Identify/kill the process that is accessing a file

gawk Find and Replace text withinfile(s)

getopts Parse positional parameters

grep Search file(s) for lines that match a givenpattern

groupadd Add a user security group

groupdel Delete a group

groupmod Modify a group

groups Print group names a user is in

gzip Compress or decompress named file(s)

hash Remember the full pathname of a nameargument

head Output the first part of file(s)

help Display help for a built-in command

history Command History

hostname Print or set system name

iconv Convert the character set of afile


id Print user and group id's
if Conditionally perform acommand

ifconfig Configure a network interface

install Copy files and set attributes

ip Routing, devices and tunnels

jobs List active jobs

join Join lines on a common field

kill Kill a process by specifying its PID

killall Kill processes by name

let Perform arithmetic on shell variables

link Create a link to a file

ln Create a symbolic link to afile

local Create a function variable

locate Find files

logname Print current loginname

logout Exit a login shell

look Display lines beginning with a givenstring

lpc Line printer control program

lpr Off line print

lprint Print a file

lprintd Abort a print job

lprintq List the print queue

ls List information aboutfile(s)\


lsof List open files
m
make Recompile a group ofprograms

man Help manual

mkdir Create new folder(s)

mkfifo Make FIFOs (namedpipes)

mkfile Make a file

mktemp Make a temporary file

more Display output one screen at atime

most Browse or page through a textfile


mount Mount a file system
mtools Manipulate MS-DOS files

mtr Network diagnostics(traceroute/ping)


mv Move or rename files or directories
mmv Mass Move and rename (files)

nc Netcat, read and write data acrossnetworks

netstat Networking connections/stats

nice Set the priority of a command or job

nl Number lines and write files

nohup Run a command immune tohangups

notify-send Send desktopnotifications

nslookup Query Internet name servers interactively

open Open a file in its defaultapplication

op Operator access

passwd Modify a user password

paste Merge lines of files


ping Test a networkconnection

pgrep List processes by name

pkill Kill processes by name

popd Restore the previous value of the currentdirectory

pr Prepare files for printing

printcap Printer capability database

printenv Print environment variables

printf Format and print data

ps Process status

pushd Save and then change the current directory

pv Monitor the progress of data through apipe

pwd Print Working Directory

quota Display disk usage and limits

quotacheck Scan a file system for diskusage

ram ram disk device

rar Archive files with compression

rcp Copy files between two machines

read Read a line from standard input

readarray Read from stdin into an array variable

readonly Mark variables/functions as readonly

reboot Reboot the system

rename Rename files

renice Alter priority of running processes

remsync Synchronize remote files via email

return Exit a shell function


rev Reverse lines of a file

rm Remove files

rmdir Remove folder(s)

screen Multiplex terminal, run remote shells viassh

scp Secure copy (remote file copy)

sdiff Merge two files interactively

sed Stream Editor

select Accept keyboard input

seq Print numericsequences

set Manipulate shell variables andfunctions

sftp Secure File Transfer Program

shift Shift positional parameters


shopt Shell Options

shutdown Shutdown or restart linux

sleep Delay for a specifiedtime

slocate Find files

sort Sort text files

source Run commands from a file '.'

split Split a file into fixed-size pieces

ss Socket Statistics

ssh Secure Shell client (remote loginprogram)

su Substitute user identity

sudo Execute a command as anotheruser

sum Print a checksum for a file

suspend Suspend execution of this shell


t

tail Output the last part of file

tar Store, list or extract files in anarchive

tee Redirect output to multiple files

test Evaluate a conditionalexpression

time Measure Program running time

timeout Run a command with a time limit

times User and system times

touch Change file timestamps

top List processes running on the system

tput Set terminal-dependent capabilities, color,position

traceroute Trace Route to Host

trap Execute a command when the shell receives a signal•

tr Translate, squeeze, and/or delete characters

true Do nothing, successfully

tsort Topological sort

tty Print filename of terminal onstdin

type Describe a command

ulimit Limit user resources

umask Users file creation mask

umount Unmount a device

Unalias Remove an alias

uniq Uniquify files

units Convert units from one scale to another

until Execute commands (until error)

uptime Show uptime


useradd Create new user account

userdel Delete a user account

usermod Modify user account

users List users currently logged in

v Verbosely list directory contents (`ls -l -b')

vdir Verbosely list directory contents (`ls -l -b')

vi Text Editor

vmstat Report virtual memory statistics

w Show who is logged on and what they are doing

wait Wait for a process to complete

watch Execute/display a program periodically

wc Print byte, word, and line counts

whereis Search the user's $path, man pages and source files

for a program
which Search the user's $path for a program file

while Execute commands


who Print all usernames currently logged in
whoami Print the current user id and name (`id -un')
wget Retrieve web pages or files via HTTP, HTTPS or FTP
write Send a message to another user

xargs Execute utility, passing constructed argument list(s)


xdg-open Open a file or URL in the user's preferred application

xz Compress or decompress .xz and .lzma files

yes Print a string until interrupted


zip Package and compress (archive) files.
. Run a command script in the current shell

!! Run the last command again

### Comment / Remark


Procedure to connect to LINUX(putty)
Step 1:click on putty icon available on desk top. A window is opened

Step 2:fill in ip address of linux server and click open

Step 3: provide login and password (nothing is displayed on screen while typing password)

Step 4: change the default password at your first login


WEEK : 1

Practice File handling utilities, Process utilities, Disk utilities, Networking


commands, Filters, Text processing utilities and Backup utilities.

Aim: Practice basic commands of Linux

File handling utilities


Cat Command: cat linux command concatenates files and print it on the standard output.
To Create a new file:
cat > file1.txt
This command creates a new file file1.txt. After typing into the file press control+d
(^d) simultaneously to end the file.

To Append data into the file: To append data into the same file use append operator >> to write into
thefile, else the file will be overwritten (i.e., all of its contents will be erased).
cat >> file1.txt

To display a file: This command displays the data in the


file.cat file1.txt

To concatenate several files and display:


cat file1.txt file2.txt

The above cat command will concatenate the two files (file1.txt and file2.txt) and it will display the
output in the screen. Some times the output may not fit the monitor screen. In such situation you can
print those files in a new file or display the file using less command.
cat file1.txt file2.txt | less

To concatenate several files and to transfer the output to anotherfile.


cat file1.txt file2.txt > file3.txt

In the above example the output is redirected to new file file3.txt.


rm COMMAND:
rm linux command is used to remove/delete the file from the directory.
To Remove / Delete a file: Here rm command will remove/delete the file
file1.txt.rm file1.txt

To delete a directory tree:


rm -ir tmp
This rm command recursively removes the contents of all subdirectories of the tmp
directory,prompting you regarding the removal of each file, and then removes the
tmpdirectory itself.

To remove more files at once: rm command removes file1.txt and file2.txt files at the
same time.rm file1.txt file2.txt

cd COMMAND: cd command is used to change the directory.

cd linux-command
This command will take you to the sub-directory(linux-command) from its parent directory.

Ex:

cd ..
This will change to the parent-directory from the current working directory/sub-directory.
cd ~
This command will move to the user's home directory which is "/home/username".
cp COMMAND:
cp command copy files from one location to another. If the destination is an existing file, then
the file is overwritten; if the destination is an existing directory, the file is copied into the
directory (thedirectory is not overwritten).

Copy two files:


cp file1.txt file2.txt
The above cp command copies the content of file1.txt to file2.txt

Ex:

ls COMMAND:
ls command lists the files and directories under current working directory. Display root
directorycontents:

ls /
lists the contents of root directory.
Display hidden files and directories:
ls -a
lists all entries including hidden files and directories.
Display inode information:
ls –i
ln COMMAND:
ln command is used to create link to a file (or) directory. It helps to provide soft link for desired files.
Inode will be different for source and destination.
ln -s file1.txt file2.txt
Creates a symbolic link to 'file1.txt' with the name of 'file2.txt'. Here inode for 'file1.txt' and
'file2.txt'will be different.

mkdir command:

rmdir command:

mv command:

diff command:

comm command:

wc command:
Process utilities:
ps Command:
ps command is used to report the process status. ps is the short name for Process Status.
1. ps: List the current running processes.
Output:
PID TTY TIME CMD
2540 pts/1 00:00:00 bash
2. ps –f : Displays full information about currently running processes.
Output:
UID PID PPID C STIME TTY TIME CMD
nirmala 2540 2536 0 15:31 pts/1 00:00:00 bash
3. kill COMMAND: kill command is used to kill the background process.
Step by Step process:
• Open a process music player or any file.
xmms
press ctrl+z to stop the process.
• To know group id or job id of the background task.
jobs -l
It will list the background jobs with its job id as,
• xmms 3956
• kmail 3467
To kill a job or process.
• kill 3956
kill command kills or terminates the background process xmms.

Disk utilities:
du (abbreviated from disk usage) is a standard Unix program used to estimate file space
usage—space used under a particular directory or files on a file system.

$du kt.txt pt.txt /* the first column displayed the file's disk usage */
8 kt.txt
4 pt.txt
Using -h option: As mentioned above, -h option is used to produce the output in human
readable format.
$du -h kt.txt pt.txt
8.0K kt.txt
4.0K pt.txt
/*now the output is in human readable format i.e in Kilobytes */
Using -a option

$du -a kartik
8 kartik/kt.txt 4 kartik/thakral.png
4 kartik/pt.txt 4 kartik/thakral
4 kartik/pranjal.png 24 kartik
/*so with -a option used all the files (under directory kartik) disk usage info is displayed along
with the thakral sub-directory */

df command : Report file system disk space usage

$df kt.txt
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/the2 1957124 1512 1955612 1% /snap/core
/* the df only showed the disk usage details of the file system that contains file kt.txt */
//using df without any filename //

$df
/* in this case df displayed the disk usage details of all mounted file systems */
Using -h : This is used to make df command display the output in human-readable format.
//using -h with df//

$df -h kt.txt
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/the2 1.9G 1.5M 1.9G 1% /snap/core
/*this output is easily understandable by the user and all cause of -h option */
Networking commands
ping
The ping command sends an echo request to a host available on the network. Using this
command, you can check if your remote host is responding well or not.
Syntax: $ping hostname or ip-address
The above command starts printing a response after every second. To come out of the
command, you can terminate it by pressing CNTRL + C keys.
$ping google.com
PING google.com (74.125.67.100) 56(84) bytes of data.
64 bytes from 74.125.67.100: icmp_seq=1 ttl=54 time=39.4 ms
ftp: ftp stands for File Transfer Protocol. This utility helps you upload and download your file
from one computer to another computer.
Syntax $ftp hostname or ip-address
$ftp amrood.com
Connected to amrood.com.
220 amrood.com FTP server (Ver 4.9 Thu Sep 2 20:35:07 CDT 2009)
Name (amrood.com:amrood): amrood
331 Password required for amrood.
Password:
230 User amrood logged in.
ftp> dir
200 PORT command successful.
….
ftp> quit
221 Goodbye.
telnet:
Telnet is a utility that allows a computer user at one site to make a connection, login and then
conduct work on a computer at another site. Once you login using Telnet, you can perform all
the activities on your remotely connected machine.

C:>telnet amrood.com
Trying...
Connected to amrood.com.
Escape character is '^]'.
login: amrood
amrood's Password:
******************************************************
WELCOME TO AMROOD.COM *
***************************************************** $ logout
Connection closed.
C:>
Finger:

The finger command displays information about users on a given host. The host can be either
local or remote.
Check all the logged-in users on the local machine −
$ finger
Login Name Tty Idle Login Time Office
amrood pts/0 Jun 25 08:03 (62.61.164.115)
Check all the logged-in users on the remote machine –
$ finger @avtar.com
Login Name Tty Idle Login Time Office
amrood pts/0 Jun 25 08:03 (62.61.164.115)
Get the information about a specific user available on the remote machine −
$ finger [email protected]
Ifconfig: Ifconfig is used to configure the network interfaces.

Filters

more COMMAND:
more command is used to display text in the terminal screen. It allows only backward
movement.
1. more -c index.txt
Clears the screen before printing the file .
2. more -3 index.txt
Prints first three lines of the given file. Press Enter to display the file line by line.
head COMMAND:
head command is used to display the first ten lines of a file, and also specifies how many lines
to display.
1. head index.php
This command prints the first 10 lines of 'index.php'.
2. head -5 index.php
The head command displays the first 5 lines of 'index.php'.
3. head -c 5 index.php
The above command displays the first 5 characters of 'index.php'.

tail COMMAND:
tail command is used to display the last or bottom part of the file. By default it displays last
10 lines of a file.
1. tail index.php
It displays the last 10 lines of 'index.php'.
2. tail -2 index.php
It displays the last 2 lines of 'index.php'.
3. tail -n 5 index.php
It displays the last 5 lines of 'index.php'.

4. tail -c 5 index.php
It displays the last 5 characters of 'index.php'.
cut COMMAND:
cut command is used to cut out selected fields of each line of a file. The cut command uses
delimiters to determine where to split fields.
cut -c1-3 text.txt
Output:
Thi
Cut the first three letters from the above line.
paste COMMAND:
paste command is used to paste the content from one file to another file. It is also used to set
column format for each line.
paste test.txt>test1.txt
Paste the content from 'test.txt' file to 'test1.txt' file.
sort COMMAND:
sort command is used to sort the lines in a text file.
1. sort test.txt
Sorts the 'test.txt'file and prints result in the screen.
2. sort -r test.txt
Sorts the 'test.txt' file in reverse order and prints result in the screen.
uniq
Report or filter out repeated lines in a file.
uniq myfile1.txt > myfile2.txt - Removes duplicate lines in the first file1.txt and outputs the
results to the second file.
Text processing utilities

echo: display a line of text or echo command prints the given input string to standard output.
eg. echo I love India
echo $HOME
wc: print the number of newlines, words, and bytes in files
eg. wc file1.txt
nl: which lets you number lines in files.
eg. $ nl file1
1 hi
join- Join command is used for merging the lines of different sorted files based on the
presence of common field into a single line. The second line will be appended at the end of
the first line and cursor is placed at the end of line after joining.

$cat file1.txt $cat file2.txt $join file1.txt file2.txt


1 AAYUSH 1 101
2 APAAR 2 102
3 HEMANT 3 103
4 KARTIK 4 104
Grep (Global Regular Expression Searching for a pattern), fgrep and egrep

$ grep ―sales director‖ emp1 emp2

$fgrep ‗good bad great‘ userfile


$egrep ‗good | bad | great‘ userfile
cat, head, tail, sort, uniq, cut, paste and etc.

Backup utilities
Linux backup and restore can be done using backup commands tar, cpio, dump and restore.
Backup Restore using tar command

tar: tape archive is used for single or multiple files backup and restore on/from a tape or file.
$tar cvf /dev/rmt/0 *
Options: c -> create ; v -> Verbose ; f->file or archive device ; * -> all files and directories .
$tar cvf /home/backup *
Create a tar called backup in home directory, from all file and directories s in the current
directory.
Viewing a tar backup on a tape or file
$tar tvf /dev/rmt/0 ## view files backed up on a tape device.
$tar tvf /home/backup ## view files backed up inside the backup
Note: t option is used to see the table of content in a tar file.
Extracting tar backup from the tape
$tar xvf /home/backup ## extract / restore files in to current directory.
Note : x option is used to extract the files from tar file. Restoration will go to present directory
or original backup path depending on relative or absolute path names used for backup.
Backup restore using cpio command

Using cpio command to backup all the files in current directory to tape.

find . -depth -print | cpio -ovcB > /dev/rmt/0


cpio expects a list of files and find command provides the list, cpio has to put these file on
some destination and a > sign redirect these files to tape. This can be a file as well.

Viewing cpio files on a tape

cpio -ivtB < /dev/rmt/0


## Options i -> input ; v->verbose; t-table of content; B-> set I/O block size to 5120 bytes
Restoring a cpio backup
cpio -ivcB < /dev/rmt/0
## Options i -> input ; v->verbose; t-table of content; B-> set I/O block size to 5120 bytes
WEEK: 2

CPU SCHEDULINGALGORITHMS

A. FIRST COME FIRST SERVE:

AIM: To write a c program to simulate the CPU scheduling algorithm First Come First Serve
(FCFS)

DESCRIPTION:

To calculate the average waiting time using the FCFS algorithm first the waiting time of the first
process is kept zero and the waiting time of the second process is the burst time of the first process
and the waiting time of the third process is the sum of the burst times of the first and the second
process and so on. After calculating all the waiting times the average waiting time is calculated as
the average of all the waiting times. FCFS mainly says first come first serve the algorithm which came
first will be served first.

ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process name and the burst time
Step 4: Set the waiting of the first process as ‗0‘and its burst time as its turnaround
timeStep 5: for each process in the Ready Q calculate a).Waiting
time (n) = waiting time (n-1) + Burst time (n-1)b). Turnaround
time (n)= waiting time(n)+Burst time(n)
Step 6: Calculate
a) Average waiting time = Total waiting Time / Number of process
b) Average Turnaround time = Total Turnaround Time / Number of process
Step 7: Stop the process

SOURCE CODE :

#include<stdio.h>
int main()
{
int bt[20], wt[20], tat[20], i, n;
float wtavg, tatavg;
printf("\n Enter the number of processes -- ");
scanf("%d", &n);

for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\t PROCESS \t BURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i], tat[i]);
printf("\n Average Waiting Time --%f", wtavg/n);
printf("\n Average Turnaround Time -- %f", tatavg/n);
}
INPUT:
Enter the number of processes – 3
Enter Burst Time for Process 0 -- 24
Enter Burst Time for Process 1 -- 3

Enter Burst Time for Process 2 – 3


Expected Output:
PROCESS BURST TIME WAITING TIME TURNAROUND TIME

P0 24 0 24
P1 3 24 27
P2 3 27 30
Average Waiting Time --17.000000
Average Turnaround Time -- 27.000000
OUTPUT:
B. SHORTEST JOB FIRST:

AIM: To write a program to stimulate the CPU scheduling algorithm Shortest job first (Non- Preemption)

DESCRIPTION:

To calculate the average waiting time in the shortest job first algorithm the sorting of the process based
on their burst time in ascending order then calculate the waiting time of each process as the sum of the
bursting times of all the process previous or before to that process.

ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue

Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time

Step 4: Start the Ready Q according the shortest Burst time by sorting according to lowest to
highest burst time.
Step 5: Set the waiting time of the first process as ‗0‘ and its turnaround time as its burst time.
Step 6: Sort the processes names based on their Burt time
Step 7: For each process in the ready queue, calculate
A) Waiting time(n)= waiting time (n-1) + Burst time (n-1)

B) Turnaround time (n)= waiting time(n)+Burst time(n)


Step 8: Calculate
A)Average waiting time = Total waiting Time / Number of process
a) Average Turnaround time = Total Turnaround Time / Number ofprocessStep 9: Stop
the process
SOURCE CODE :

#include<stdio.h>

int main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp;
float wtavg, tatavg;
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
for(i=0;i<n;i++) for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=p[i];
p[i]=p[k];
p[k]=temp;
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);

}
INPUT:
Enter the number of processes --4
Enter Burst Time for Process 0 --6
Enter Burst Time for Process 1 --8
Enter Burst Time for Process 2 --7
Enter Burst Time for Process 3 –3

Expected Output:
PROCESS BURST TIME WAITING TIME TURNAROUND TIME
P0 6 3 9
P1 8 16 24
P2 7 9 16
P3 3 0 3

Average Waiting Time -- 7.000000

Average Turnaround Time -- 13.000000

OUTPUT:
C.ROUND ROBIN:

AIM: To simulate the CPU scheduling algorithm round-robin.

DESCRIPTION:

To aim is to calculate the average waiting time. There will be a time slice, each process should be
executed within that time-slice and if not it will go to the waiting state so first check whether the
burst time is less than the time-slice. If it is less than it assign the waiting time to the sum of the total
times. If it is greater than the burst-time then subtract the time slot from the actual burst time and
increment it by time-slot and the loop continues until all the processes are completed.

ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue and time quantum (or) time slice
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Calculate the no. of time slices for each process where No. of time slice for process (n) = burst
time process (n)/time slice
Step 5: If the burst time is less than the time slice then the no. of time slices =1.
Step 6: Consider the ready queue is a circular Q, calculate
a) Waiting time for process (n) = waiting time of process(n-1)+ burst timeof process(n-1 ) + the
time difference in getting the CPU fromprocess(n-1)
b) Turnaround time for process(n) = waiting time of process(n) + burst time of process(n)+ the time
difference in getting CPU from process(n).
Step 7: Calculate
a)Average waiting time = Total waiting Time / Number of process
a) Average Turnaround time = Total Turnaround Time / Number ofprocessStep 8: Stop the process
SOURCE CODE

#include<stdio.h>

int main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
printf("Enter the no of processes -- ");
scanf("%d",&n);for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i]) max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];
att+=tat[i]; awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is --%f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
}
INPUT:
Enter the no of processes – 3
Enter Burst Time for process 1 – 24
Enter Burst Time for process 2 -- 3
Enter Burst Time for process 3 – 3
Enter the size of time slice – 3
Expected Output:
The Average Turnaround time is -- 15.000000
The Average Waiting time is --5.000000

PROCESS BURST TIME WAITING TIME TURNAROUND TIME


1 24 6 30
2 3 3 6
3 3 6 9
OUTPUT:

D.PRIORITY:
AIM: To write a c program to simulate the CPU scheduling priority algorithm.

DESCRIPTION:

To calculate the average waiting time in the priority algorithm, sort the burst times according to
their priorities and then calculate the average waiting time of the processes. The waiting time of
each process is obtained by summing up the burst times of all the previous processes.

ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst timeStep 4:
Sort the ready queue according to the priority number.
Step 5: Set the waiting of the first process as ‗0‘ and its burst time as its turnaround timeStep 6:
Arrange the processes based on process priority
Step 7: For each process in the Ready Q calculate
a) Waiting time(n)= waiting time (n-1) + Burst time (n-1)
b) Turnaround time (n)= waiting time(n)+Burst time(n)
Step 8: Calculate
a) Average waiting time = Total waiting Time / Number of process
Average Turnaround time = Total Turnaround Time / Number of process Print theresults in an order.
Step9:Stop

SOURCE CODE :

#include<stdio.h>

int main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
printf("Enter the no of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i]) max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];
att+=tat[i];
awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is --%f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
}
INPUT:
Enter the no of processes – 3
Enter Burst Time for process 1 – 24
Enter Burst Time for process 2 -- 3
Enter Burst Time for process 3 – 3
Enter the size of time slice – 3
Expected Output:
The Average Turnaround time is -- 15.000000
The Average Waiting time is --5.000000

PROCESS BURST TIME WAITING TIME TURNAROUND TIME


1 24 6 30
2 3 3 6
3 3 6 9
OUTPUT:
WEEK :3

DEAD LOCK AVOIDANCE

AIM: Simulate bankers algorithm for Dead Lock Avoidance (Banker‘s Algorithm)

DESCRIPTION:
Deadlock is a situation where in two or more competing actions are waiting f or the other to finish, and
thus neither ever does. When a new process enters a system, it must declare the maximum number of
instances of each resource type it needed. This number may exceed the total number of resources in the
system. When the user request a set of resources, the system must determine whether the allocation of
each resources will leave the system in safe state. If it will the resources are allocation; otherwise the
process must wait until some other process release the resources.
Data structures Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj Need: If
Need[I, j]=k, Pi may need k more instances of resource type Rj, Need[I, j]=Max[I, j]- Allocation[I, j];
Safety Algorithm

Work and Finish be the vector of length m and n respectively, Work=Available and Finish[i] =False.

1. Find an i such that both


2. Finish[i] =False Need<=Work If no such I exists go to step 4.
3. work= work + Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state. Resource request algorithm
Let Request i be request vector for the process Pi, If request i=[j]=k, then process Pi wants k
instances of resource type Rj.
1. if Request<=Need I go to step 2. Otherwise raise an error condition.
2. if Request<=Available go to step 3. Otherwise Pi must since the resources are available.

3. Have the system pretend to have allocated the requested resources to process Pi by modifying the
state as follows;
Available=Available-Request I; Allocation I=Allocation +Request I; Need i=Need i- Request I;
If the resulting resource allocation state is safe, the transaction is completed and process Pi is
allocated its resources. However if the state is unsafe, the Pi must wait for Request i and the old
resource-allocation state is restored.

ALGORITHM:
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safestate.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety.
9. or not if we allow the request.
10. stop the program.
11. End.
SOURCE CODE :
#include<stdio.h>
void main()
{
int work[5],avl[5],alloc[10][10],l;
int need[10][10],n,m,I,j,avail[10],max[10][10],k,count,i,fcount=0,pr[10];
char finish[10]={'f','f','f','f','f','f','f','f','f','f'};
printf("\n enter the no of process");
scanf("%d",&n);
printf("\n enter the no of resources");
scanf("%d",&m);
printf("\n enter the total no of resources");
for(i=1;i<=m;i++)
scanf("%d",&avail[i]);
printf("\n enter the max resources req by each pr alloc matrix");
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&max[i][j]);
printf("\n process allocation matrix");
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&alloc[i][j]);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
need[i][j]=max[i][j]-alloc[i][j];
for(i=1;i<=n;i++)
{
k=0;
for(j=1;j<=m;j++)
{
k=k+alloc[i][j];
}
avl[i]=avl[i]-k;
work[i]=avl[i];
}
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
{
count=0;
for(j=1;j<=m;j++)
{
if((finish[i]=='f')&&(need[i][j]<=work[i]))
count++;
}
if(count==m)
{
for(l=1;l<=m;l++)
work[l]=work[l]+alloc[i][l];
finish[i]='t';
pr[k]=i;
break;
}
}
for(i=1;i<=n;i++)
if(finish[i]=='t')
fcount++;
if(fcount==n)
{
}
else

printf("\n the system is in safe state");


for(i=1;i<=n;i++)
printf("\n %d",pr[i]);

printf("\n the system is not in safe state");


}

Expected Output:
Enter the no of process 5
Enter the no of resources 3
Enter the total no of resources10 5 7
Enter the max resource req. by each pr alloc matrix
7 5 3
3 2 2
9 0 2
2 2 2
4 3 3
Process allocation matrix
0 1 0
2 0 0
3 0 2
2 1 1
0 2 2
The system is in safe state1
1
3
4
5
2
OUTPUT:
DEAD LOCKPREVENTION

AIM: To implement deadlock prevention technique

Banker‘s Algorithm:
When a new process enters a system, it must declare the maximum number of instances of each resource
type it needed. This number may exceed the total number of resources in the system. When the user
request a set of resources, the system must determine whether the allocation of each resources will leave
the system in safe state. If it will the resources are allocation; otherwise the process must wait until
some other process release the resources.

DESCRIPTION

Data structures n-Number of process, m-number of resource types.Available: Available[j]=k, k –


instance of resource type Rj is available. Max: If max[i, j]=k, Pi may request at most k instances resource
Rj. Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj Need: If Need[I, j]=k, Pi
may need k more instances of resource type Rj, Need[I, j]=Max[I, j]-Allocation[I, j];Safety Algorithm
Work and Finish be the vector of length m and n respectively, Work=Available and Finish[i] =False.
Find an i such that both Finish[i] =False Need<=Work If no such I exists go to step
4.work=work+Allocation, Finish[i] =True; if Finish[1]=True for all I, then the system is in safe state

ALGORITHM:

1. Start the program.

2. Get the values of resources and processes.


3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safestate.
7. Else system is not in safety state

8. Stop the process


.

SOURCE CODE :

#include<stdio.h>
void main()
{
char job[10][10];
int time[10],avail,tem[10],temp[10];
int safe[10];
int ind=1,i,j,q,n,t;
printf("Enter no of jobs: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter name and time: ");
scanf("%s%d",&job[i],&time[i]);
}
printf("Enter the available resources:");
scanf("%d",&avail);
for(i=0;i<n;i++)
{
temp[i]=time[i];
tem[i]=i;
}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(temp[i]>temp[j])
{
t=temp[i];
temp[i]=temp[j];
temp[j]=t;
t=tem[i];
tem[i]=tem[j];
tem[j]=t;
}
}
for(i=0;i<n;i++)
{
q=tem[i];
if(time[q]<=avail)
{
safe[ind]=tem[i];
avail=avail-tem[q];
printf("%s",job[safe[ind]]);
ind++;
}
else
{
printf("No safe sequence\n");
}
}
printf("Safe sequence is:");
for(i=1;i<ind; i++)
printf(" %s %d\n",job[safe[i]],
time[safe[i]]);

Expected Output:
Enter no of jobs: 4
Enter name and time: A 1
Enter name and time: B 4
Enter name and time: C 2
Enter name and time: D 3
Enter the available resources:20
Safe sequence is: A 1
C2
D3
B4

OUTPUT:
WEEK : 4

AIM: To Write a C program to simulate the concept of Dining-Philosophers problem.

DESCRIPTION
The dining-philosophers problem is considered a classic synchronization problem because it is an
example of a large class of concurrency-control problems. It is a simple representation of the need to
allocate several resources among several processes in a deadlock-free and starvation-free manner.
Consider five philosophers who spend their lives thinking and eating. The philosophers share a circular
table surrounded by five chairs, each belonging to one philosopher. In the center of the table is a bowl of
rice, and the table is laid with five single chopsticks. When a philosopher thinks, she does not interact
with her colleagues. From time to time, a philosopher gets hungry and tries to pick up the two chopsticks
that are closest to her (the chopsticks that are between her and her left and right neighbors). A
philosopher may pick up only one chopstick at a time. Obviously, she cam1ot pick up a chopstick that is
already in the hand of a neighbor. When a hungry philosopher has both her chopsticks at the same time,
she eats without releasing her chopsticks. When she is finished eating, she puts down both of her
chopsticks and starts thinking again. The dining-philosophers problem may lead to a deadlock situation
and hence some rules have to be framed to avoid the occurrence of deadlock.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int tph, philname[20], status[20], howhung, hu[20], cho;
main()
{
int i;
printf("\n\nDINING PHILOSOPHER PROBLEM");
printf("\nEnter the total no. of philosophers: ");
scanf("%d",&tph);
for(i=0;i<tph;i++)
{
philname[i]=(i+1);
status[i]=1;
}
printf("How many are hungry : ");
scanf("%d", &howhung);
if(howhung==tph)
{
printf("\n All are hungry..\nDead lock stage will occur");
printf("\nExiting\n");
}
else
{
for(i=0;i<howhung;i++)
{
printf("Enterphilosopher%dposition:",(i+1));
scanf("%d",&hu[i]);
status[hu[i]]=2;
}
do
{
printf("1.One can eat at a time\t2.Two can eat at a time\t3.Exit\nEnter your choice:");
scanf("%d", &cho);
switch(cho)
{
case 1:one();

break;
case
2:two();
break;
case 3: exit(0);
default: printf("\nInvalid option..");
}
}while(1);
}
}
one()
{
int pos=0, x, i;
printf("\nAllow one philosopher to eat at any time\n");
for(i=0;i<howhung; i++, pos++)
{
printf("\nP %d is granted to eat", philname[hu[pos]]);
for(x=pos;x<howhung;x++)
printf("\nP %d is waiting", philname[hu[x]]);
}
}
two()
{
int i, j, s=0, t, r, x;
printf("\n Allow two philosophers to eat at same time\n");
for(i=0;i<howhung;i++)
{
for(j=i+1;j<howhung;j++)
{
if(abs(hu[i]-hu[j])>=1&& abs(hu[i]-hu[j])!=4)
{
printf("\n\ncombination %d \n", (s+1));
t=hu[i];
r=hu[j];
s++;
printf("\nP %d and P %d are granted to eat", philname[hu[i]], philname[hu[j]]);
for(x=0;x<howhung;x++)
{
if((hu[x]!=t)&&(hu[x]!=r))
printf("\nP %d is waiting", philname[hu[x]]);
}
}
}
}
}
.

INPUT:

DINING PHILOSOPHER PROBLEM


Enter the total no. of philosophers: 5

How many are hungry : 3

Enter philosopher 1 position: 2

Enter philosopher 2 position: 4

Enter philosopher 3 position: 5

Expected Output:

1. One can eat at a time 2.Two can eat at a time 3.Exit


Enter your choice:1

Allow one philosopher to eat at any time

P 3 is granted to eat

P 3 is waiting

P 5 is waiting

P 0 is waiting

P 5 is granted to eat

P 5 is waiting

P 0 is waiting

P 0 is granted to eat

P 0 is waiting1.One can eat at a time 2.Two can eat at a time 3.Exit

Enter your choice:2

Allow two philosophers to eat at same time

combination 1

P 3 and P 5 are granted to eat

P 0 is waiting

combination 2

P 3 and P 0 are granted to eat

P 5 is waiting

combination 3

P 5 and P 0 are granted to eat

P 3 is waiting1.One can eat at a time 2.Two can eat at a time 3.Exit


Enter your choice:3

OUTPUT:
WEEK : 5

AIM: To Write a C program to simulate producer-consumer problem using semaphores.

DESCRIPTION
Producer consumer problem is a synchronization problem. There is a fixed size buffer where the
producer produces items and that is consumed by a consumer process. One solution to the producer-
consumer problem uses shared memory. To allow producer and consumer processes to run
concurrently, there must be available a buffer of items that can be filled by the producer and emptied by
the consumer. This buffer will reside in a region of memory that is shared by the producer and
consumer processes. The producer and consumer must be synchronized, so that the consumer does not
try to consume an item that has not yet been produced.

PROGRAM
#include<stdio.h>
int main()
{
int buffer[10], bufsize, in, out, produce, consume,choice=0;
in = 0;
out = 0;
bufsize = 10;
while(choice !=3)
{
printf("\n1.Produce\t 2.Consume\t 3.Exit");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: if((in+1)%bufsize==out)
printf("\nBuffer is Full");
else
{
printf("\nEnter the value:"); scanf("%d", &produce); buffer[in] = produce;
in = (in+1)%bufsize;
}
break;
case 2:
if(in == out) printf("\nBuffer is Empty"); else
{
consume = buffer[out];
printf("\nThe consumed value is %d", consume);
out = (out+1)%bufsize;
}break;

}
}
}
Expected Output:

1. Produce 2. Consume 3. Exit


Enter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. Exit
Enter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. Exit
Enter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. Exit
Enter your choice: 3

OUTPUT:
WEEK : 6

A. Write a C program to implement kill(), raise() and sleep() functions.

Aim: Implement kill(), raise() and sleep() functions using a C program.

kill( ) and sleep( ):

Program file name: kill.c

#include <signal.h>

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <unistd.h>

// function declarationvoid
sighup();

void sigint(); void


sigquit();

// driver codevoid main()


{
int pid;

/* get child process */


if ((pid = fork()) < 0) {
perror("fork");
exit(1);
}

if (pid == 0)
{ /* child */ signal(SIGHUP, sighup);
signal(SIGINT, sigint);
signal(SIGQUIT, sigquit);
for (;;)
; /* loop for ever */
}
else /* parent */
{ /* pid hold id of child */
printf("\nPARENT: sending SIGHUP\n\n");
kill(pid, SIGHUP);
sleep(3); /* pause for 3 secs */
printf("\nPARENT: sending SIGINT\n\n");
kill(pid, SIGINT);
sleep(3); /* pause for 3 secs */
printf("\nPARENT: sending SIGQUIT\n\n");
kill(pid, SIGQUIT);
sleep(3);
}
}
// sighup() function definition

void sighup()
{
signal(SIGHUP, sighup); /* reset signal */
printf("CHILD: I have received a SIGHUP\n");
}

// sigint() function definitionvoid


sigint()
{
signal(SIGINT, sigint); /* reset signal */
printf("CHILD: I have received a SIGINT\n");
}
// sigquit() function definition
void sigquit()
{
printf("My DADDY has Killed me!!!\n");
exit(0);
}

Expected Output:$ ./a.out

OUTPUT:
raise( ):

Program file name: raise.c

#include <stdio.h>

#include <stdlib.h>

#include <signal.h>
void signal_handler(int signal)
{
/* Display a message indicating we have received a signal */
if (signal == SIGUSR1) printf("Received a SIGUSR1 signal\n");

/* Exit the application


*/exit(0);
}
int main(int argc, const char * argv[])
{
/* Display a message indicating we are registering the signal handler */
printf("Registering the signal handler\n");

/* Register the signal handler */


signal(SIGUSR1, signal_handler);

/* Display a message indicating we are raising a signal */


printf("Raising a SIGUSR1 signal\n");

/* Raise the SIGUSR1 signal */


raise(SIGUSR1);

/* Display a message indicating we are leaving main */


printf("Finished main\n");

return 0;
}

Expected Output:

Registering the signal handlerRaising a SIGUSR1 signal Received a SIGUSR1 signal

OUTPUT:
B. Write a C program to implement alarm(), pause() and abort() functions.

Aim: Implement alarm(), pause() and abort() functions using a C program

Program file name: alarmpause.c

#define _POSIX_SOURCE

#include <unistd.h>
#include
<signal.h>
#include
<stdio.h>
#include
<time.h>
void catcher(int signum) {puts("inside catcher. ");
}
void
timestamp()
{time_t t;
time(&t);
printf("the time is %s", ctime(&t));
}
main() {
struct sigaction sigact;
sigemptyset(&sigact.sa_mask
);sigact.sa_flags = 0;
sigact.sa_handler = catcher;
sigaction(SIGALRM, &sigact, NULL);
alarm(10);
printf("before
pause... ");
timestamp();
pause();
printf("after
pause... ");
timestamp();
}
Expected Output:
before pause... the time is Fri Jun 16
09:42:29 2001inside catcher...

after pause... the time is Fri Jun 16 09:42:39 2001

OUTPUT:
abort():

/* abort.c -- terminates execution abnormally */


#include <stdio.h>
#include <stdlib.h>
int main(void)
{
abort();
printf("\"abort() called prior to printf()\"\n");
return 0;
}

OUTPUT:
WEEK :7

A. Aim:- Write a C program that illustrate communication between two process usingnamed
pipes or FIFO

Algorithm:
Create two processes, one is fifoserver_twoway and another one is fifoclient_twoway.
Algorithm for fifoserver_twoway :
step 1:Start
step 2: Creates a named pipe (using library function mkfifo())
with name ―fifo_twoway‖ in /tmp directory, if not created.
step 3: Opens the named pipe for read and write purposes.
step 4: Here, created FIFO with permissions of read and write for Owner. Read for Group and no
permissions for Others.
step 5: Waits infinitely for a message from the client.
step 6: If the message received from the client is not ―end‖, prints the message and
reverses the string. The reversed string is sent back to the client. If the message is ―end‖,
closes the fifo and ends the process.
step 7:stop.

Algorithm for client :


Step 1: start
Step 2: Opens the named pipe for read and write purposes.
Step 3: Accepts string from the user.
Step 4: Checks, if the user enters ―end‖ or other than ―end‖. Either way, it
sends a message to the server. However, if the string is ―end‖, this closes
the FIFO and also ends the process.
Step 5: If the message is sent as not ―end‖, it waits for the message
(reversed string) from the client and prints the reversed string.
Step 6: Repeats infinitely until the user enters the string ―end‖.
Step 7: stop

Program:

/* Filename: fifoserver_twoway.c */
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define FIFO_FILE "/tmp/fifo_twoway"


void reverse_string(char *);
int main() {

int fd;

char readbuf[80];
char end[10]; int
to_end;
int read_bytes;

/* Create the FIFO if it does not exist */

mkfifo(FIFO_FILE, S_IFIFO|0640);
strcpy(end, "end");
fd = open(FIFO_FILE, O_RDWR);
while(1) {
read_bytes = read(fd, readbuf, sizeof(readbuf));
readbuf[read_bytes] = '\0';
printf("FIFOSERVER: Received string: \"%s\" and length is %d\n", readbuf,
(int)strlen(readbuf));
to_end = strcmp(readbuf, end);

if (to_end == 0) {
close(fd); break;
}
reverse_string(readbuf);
printf("FIFOSERVER: Sending Reversed String: \"%s\" and length is %d\n", readbuf, (int)
strlen(readbuf));
write(fd, readbuf, strlen(readbuf));
/*
sleep - This is to make sure other process reads this, otherwise this
process would retrieve the message
*/ sleep(2);
}
return 0;
}

void reverse_string(char *str)


{
int last, limit, first;
char temp;
last = strlen(str) - 1;
limit = last/2;
first = 0;

while (first < last) {


temp = str[first];
str[first] = str[last];
str[last] = temp; first++;
last--; }
return;
}

Expected Output:
FIFOSERVER: Received string: "LINUX IPCs" and length is 10
FIFOSERVER: Sending Reversed String: "sCPI XUNIL" and length is 10
FIFOSERVER: Received string: "Inter Process Communication" and length is 27
FIFOSERVER: Sending Reversed String: "noitacinummoC ssecorP retnI" and length is 27
FIFOSERVER: Received string: "end" and length is 3
/* Filename: fifoclient_twoway.c */

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define FIFO_FILE "/tmp/fifo_twoway"
int main() {
int fd;
int end_process;
int stringlen;
int read_bytes;
char readbuf[80];
char end_str[5];
printf("FIFO_CLIENT: Send messages, infinitely, to end enter \"end\"\n");
fd = open(FIFO_FILE, O_CREAT|O_RDWR);
strcpy(end_str, "end");
while (1) {
printf("Enter string: ");
fgets(readbuf, sizeof(readbuf), stdin);
stringlen = strlen(readbuf);
readbuf[stringlen - 1] = '\0';
end_process = strcmp(readbuf, end_str);
//printf("end_process is %d\n", end_process);
if (end_process != 0) {
write(fd, readbuf, strlen(readbuf));
printf("FIFOCLIENT: Sent string: \"%s\" and string length is %d\n", readbuf,(int)strlen(readbuf));
read_bytes = read(fd, readbuf, sizeof(readbuf));
readbuf[read_bytes] = '\0';
printf("FIFOCLIENT: Received string: \"%s\" and length is %d\n", readbuf,(int)strlen(readbuf));
} else {
write(fd, readbuf, strlen(readbuf));
printf("FIFOCLIENT: Sent string: \"%s\" and string length is %d\n", readbuf,(int)strlen(readbuf));
close(fd);
break;
}
}
return 0;
}

Expected Output:
FIFO_CLIENT: Send messages, infinitely, to end enter "end" Enter string: LINUX IPCs
FIFOCLIENT: Sent string: "LINUX IPCs" and string length is 10
FIFOCLIENT: Received string: "sCPI XUNIL" and length is 10 Enter string: Inter Process Communication
FIFOCLIENT: Sent string: "Inter Process Communication" and string length is 27
FIFOCLIENT: Received string: "noitacinummoC ssecorP retnI" and length is 27 Enter string: end
FIFOCLIENT: Sent string: "end" and string length is 3
OUTPUT:
B.Aim:-Write a C program that illustrates two processes communicating using Shared

memoryAlgorithm:-
step1.Start
step 2.Include header files required for the
program are
#include <sys/types.h>
#include<sys/ipc.>
#include<sys/shm.>
#include <unistd.h>
#include <string.h>
#include <errno.h>
step 3.Declare the variable which are required aspid_t pidint *shared /* pointer to the shm */int shmid
step 4. Use shmget function to create shared
memory#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg)
The shmget() function shall return the shared memory identifier associated with key The
argumentkey is equal to IPC_PRIVATE. so that the operating system selects the next
Available key for a newly created shared block of memory. Size
represents size of shared memory block Shmflg shared memory permissions which are
represented by octalinteger shmid = shmget (IPC_PRIVATE, sizeof(int), IPC_CREAT |
0666);
print the shared memory id
step 5.if fork()==0
Then begin
shared = shmat(shmid, (void *) 0, 0)
print the shared variable(shared) *shared=2print
*shared sleep(2)
print *shared
end

step 6.else

begin

shared = shmat(shmid, (void *) 0, 0)print the shared variable(shared) print *shared sleep(1)
*shared=30

printf("Parent value=%d\n", *shared);sleep(5)


shmctl(shmid, IPC_RMID, 0)
end

step 7.stop

Sha.c
#include<sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <errno.h>
int main(void)
{
pid_t pid;
int *shared; /* pointer to the shm */ int shmid;
shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
printf("Shared MemoryID=%u",shmid);
if (fork() == 0) { /* Child */
/* Attach to shared memory and print the pointer */ shared = shmat(shmid, (void *) 0,
0);printf("Child pointer %u\n", shared);
*shared=1;
printf("Child value=%d\n", *shared);
sleep(2); printf("Child value=%d\n", *shared);
}
else { /* Parent */
/* Attach to shared memory and print the pointer */ shared = shmat(shmid, (void *) 0,
0);printf("Parent pointer %u\n", shared); printf("Parent value=%d\n", *shared); sleep(1);
*shared=42;
printf("Parent value=%d\n", *shared);
sleep(5);shmctl(shmid, IPC_RMID, 0);
}

Expected Output: $ ./a.out


Shared Memory ID=65537Child pointer 3086680064 Child value=1
Shared Memory ID=65537Parent pointer 3086680064 Parent value=1
Parent value=42 Child value=42
OUTPUT:
WEEK : 8

PAGE REPLACEMENT ALGORITHMS

AIM: To implement FIFO page replacement technique.


a) FIFO b) LRU c) OPTIMAL

DESCRIPTION:

Page replacement algorithms are an important part of virtual memory management and it helps the OS to
decide which memory page can be moved out making space for the currently needed page. However, the
ultimate objective of all page replacement algorithms is to reduce the number of page faults.
FIFO-This is the simplest page replacement algorithm. In this algorithm, the operating system keeps
track of all pages in the memory in a queue, the oldest page is in the front of the queue. When a page
needs to bereplaced page in the front of the queue is selected for removal.
LRU-In this algorithm page will be replaced which is least recently used
OPTIMAL- In this algorithm, pages are replaced which would not be used for the longest duration of
time in the future. This algorithm will give us less page fault when compared to other page replacement
algorithms.

ALGORITHM:
1. Start the process

2. Read number of pages n

3. Read number of pages no

4. Read page numbers into an array a[i]

5. Initialize avail[i]=0 .to check page hit

6. Replace the page with circular queue, while re-placing check page availability in the frame Place

avail[i]=1 if page is placed in theframe Count page faults

7. Print the results.

8. Stop the process

A.FIRST IN FIRST OUTSOURCE CODE :

#include<stdio.h>
int fr[3];
void main()
{
void display();
int i,j,page[12]={2,3,2,1,5,2,4,5,3,2,5,2};
int flag1=0,flag2=0,pf=0,frsize=3,top=0;
for(i=0;i<3;i++)
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0;
flag2=0;
for(i=0;i<12;i++)
{
if(fr[i]==page[j])
{
flag1=1;
flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<frsize;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];
flag2=1;
break;
}
}
}
if(flag2==0)
{
fr[top]=page[j];
top++;
pf++;
if(top>=frsize)
top=0;
}
display();
}

printf("\n Number of page faults : %d ",pf+frsize);


}
void display()
{
int
i
;
printf("\n");
for(i=0;i<3;i++)
printf("%d\t",fr[i]);
}
Expected Output:
2 -1 -1
2 3 -1
2 3 -1
2 3 1
5 3 1
5 2 1
5 2 4
5 2 4
3 2 4
3 2 4
3 5 4
3 5 2

Number of page faults: 9

OUTPUT:
B.LEAST RECENTLY USED

AIM: To implement LRU page replacement technique.


ALGORITHM:

1. Start the process

2. Declare the size

3. Get the number of pages to be inserted

4. Get the value

5. Declare counter and stack

6. Select the least recently used page by counter value

7. Stack them according the selection.

8. Display the values

9. Stop the process.

SOURCE CODE :

#include<stdio.h>

#include<conio.h>

int fr[3];

void main()

void display();

int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];

int index,k,l,flag1=0,flag2=0,pf=0,frsize=3;

for(i=0;i<3;i++)

fr[i]=-1;

for(j=0;j<12;j++)

flag1=0,

flag2=0;
for(i=0;i<3;i++)

if(fr[i]==p[j])

flag1=1;

flag2=1;

break;

if(flag1==0)

for(i=0;i<3;i++)

if(fr[i]==-1)

fr[i]=p[j];

flag2=1;

break;

if(flag2==0)

for(i=0;i<3;i++)

fs[i]=0;

for(k=j-1,l=1;l<=frsize-1;l++,k--)

for(i=0;i<3;i++)
{

if(fr[i]==p[k])

fs[i]=1;

}}

for(i=0;i<3;i++)

if(fs[i]==0)

index=i;

fr[index]=p[j];

pf++;

display();

printf("\n no of page faults :%d",pf+frsize);

void display()

int i;

printf("\n");

for(i=0;i<3;i++)

printf("\t%d",fr[i]);
}

Expected Output:
2 -1 -1
2 3 -1

2 3 -1
2 3 1
2 5 1
2 5 1
2 5 4

2 5 4

3 5 4
3 5 2
3 5 2
3 5 2
no of page faults :7

OUTPUT:
C. OPTIMAL

AIM: To implement optimal page replacement technique.

ALGORTHIM:

1. Start Program

2 Read Number Of Pages And Frames

3. Read Each Page Value

4. Search For Page In The Frames

5. If Not Available Allocate Free Frame

6. If No Frames Is Free Repalce The Page With The Page That Is Leastly Used

7. Print Page Number Of Page Faults

8. Stop process.

SOURCE CODE:

/*Program to simulate optimal page replacement */


#include<stdio.h>
int fr[3], n, m;
void display(); void main()
{
int i,j,page[20],fs[10]; int
max,found=0,lg[3],index,k,l,flag1=0,flag2=0,pf=0;
float pr;
//clrscr();
printf("Enter length of the reference string:");
scanf("%d",&n);
printf("Enter the reference string: ");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter no of frames:");
scanf("%d",&m);
for(i=0;i<m;i++)
fr[i]=-1;
pf=m;
for(j=0;j<n;j++)
{
flag1=0; flag2=0;
for(i=0;i<m;i++)
{
if(fr[i]==page[j])
{
flag1=1; flag2=1; break;
}
}
if(flag1==0)
{
for(i=0;i<m;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j]; flag2=1;break;
}
}
}
if(flag2==0)
{
for(i=0;i<m;i++) lg[i]=0; for(i=0;i<m;i++)
{
for(k=j+1;k<=n;k++)
{
if(fr[i]==page[k])
{
lg[i]=k-j; break;
}
}
}
found=0;
for(i=0;i<m;i++)
{
if(lg[i]==0)
{
index
=i;
found =1;
break;
}
}
if(found==0)
{
max=lg[0]; index=0; for(i=0;i<m;i++)
{
if(max<lg[i])
{
max=lg[i]; index=i;
}
}
}
fr[index]=page [j];
pf++;
}
display();
}
printf("Number of page faults :
%d\n",pf);
pr=(float)pf/n*100;
printf("Page fault rate = %f \n", pr);
//getch();
}
void display()
{
int i;
for(i=0;i<m;i++)
printf("%d\t",fr[i]);
printf("\n");
}
Expected Output:
Enter length of the reference string: 12
Enter the reference string: 1 2 3 4 1 2 5 1 2 3 4 5
Enter no of frames: 3
1 -1 -1
1 2 -1
123
124
124
124
125
125
125
325
425
425
Number of page faults : 7 Page fault rate = 58.333332

OUTPUT:
WEEK : 9

Aim: Write a C program that takes one or more file/directory names as command
lineinput and reports following information
A) File Type B)Number Of Links
C) Time of last Access D) Read, write and execute permissions

Algorithm:
Step 1:start

Step 2:Declare struct stat a

Step 3:read arguments at command line

Step 4: set the status of the argument using stat(argv[i],&a);

Step 5:Check whether the given file is Directory file by using S_ISDIR(a.st_mode) if it is a directory
file

print Directory file Else print is Regular file

Step6: print number of links

Step 7:print last time access

Step 8:Print Read,write and execute permissions

Step 9:stop

Program:

#include<stdio.h>
#include<sys/stat.h>
#include<time.h>
int main(int argc,char *argv[])
{
int i,j; struct
stat a;
for (i=1;i<argc;i++)
{
printf("%s : ",argv[i]); stat(argv[i],&a);
if(S_ISDIR(a.st_mode))
{
printf("is a Directory file\n");
}
else
{
printf("is Regular file\n");
}
printf("Inode Number:%d\n",a.st_ino);
printf("UID:%o\n",a.st_uid);
printf("GID:%o\n",a.st_gid);
printf("No of Links:%d\n",a.st_nlink);
printf("Last Access time:%s",asctime(localtime(&a.st_atime)));

OUTPUT:
WEEK : 10

Aim: Implement in c language the following Unix commands usingsystem


callsa)cat b)ls c) Scanning Directories (Ex: opendir(),
readdir(),etc.)

a) AIM:-Write a c program to implement cat command using system calls


Description:
cat COMMAND:cat linux command concatenates files and print it on the standard output.
SYNTAX:
cat [OPTIONS] [FILE]...

OPTIONS:
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to a new line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
-s If the output has multiple empty lines it replaces it with one empty line.
-T Displays the tab characters in the output.
-v Non-rinting characters (with the exception of tabs, new-lines & form-feeds) are printed visibly.
Operations With cat Command:

1. To Create a new file:

$cat > file1.txt


This command creates a new file file1.txt. After typing into the file press control+d (^d)
simultaneously toend the file.

2. To Append data into the file:


$cat >> file1.txt
To append data into the same file use append operator >> to write into the file, else
the file will beoverwritten (i.e., all of its contents will be erased).
3. To display a file:
$cat file1.txt

This command displays the data in the file.

4. To concatenate several files and display:

$cat file1.txt file2.txt


The above cat command will concatenate the two files (file1.txt and file2.txt) and it will
display the output in the screen. Some times the output may not fit the monitor screen. In
such situation you can print those files in a new file or display the file using less command.
cat file1.txt file2.txt | less
5. To concatenate several files and to transfer the output to another file.
$cat file1.txt file2.txt > file3.txt
In the above example the output is redirected to new file file3.txt. The cat command will create new
filefile3.txt and store the concatenated output into file3.txt
Algorithm:
Step 1: Start
Step 2 : read arguments from keyboard at command line
Step 3: if no of arguments are less than two print ENTER CORRECT ARGUMENTS else go to step 4

Step 4: read the date from specified file and write it to destination file

Step 5 : stop

Program :

#include<stdio.h>

#include<sys/types.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>

int main(int argc,char *argv[])

{
int fd,n;
char buff[512];
if(argc!=2)
printf("ENTER CORRECT ARGUMENTS :");

if((fd=open(argv[1],4))<0)
{
printf("ERROR");
return 0;
}
while(n=read(fd,buff,sizeof(buff))>0)
write(1,buff,n);
}

OUTPUT:
II. AIM:-Write a c program to implement ls command using system calls

Description: ls command is used to list the files present in a directory

Algorithm:
Step 1: Start.
Step 2: open directory using opendir( ) system call.
Step 3: read the directory using readdir( ) system call.
Step 4: print dp.name and dp.inode.
Step 5: repeat above step until end of directory.
Step 6: Stop.

Program name: Ls.c


#include<stdio.h>
#include<dirent.h>
void quit(char*,int);
int main(int argc,char **argv )
{
DIR *dirop;
struct dirent *dired;
if(argc!=2)
{
printf("Invalid number of arguments\n");
}
if((dirop=opendir(argv[1]))==NULL)
printf("Cannot open directory\n");
while((dired=readdir(dirop))!=NULL)
printf("%10d %s\n",dired>d_ino,dired>d_name);
closedir(dirop);
}

OUTPUT:
III. Aim :write a c program that simulates Scanning directories (using system calls)

Description:
Scanning directories is used to opendir(), readdir(), rewinddir(), closedir(), etc.)
Week:11

Aim: Write a C program to create child process and allow parent process to display “parent” andthe
child to display “child” on the screen

Algorithm:
Step 1: start
Step2: call the fork() function to create a childprocess fork function returns 2 values
step 3: which returns 0 to child process
step 4:which returns process id to the parent process
step 5:stop

Program file name:


11b.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
int pid,pid1,pid2;
pid=fork();
if(pid==-1)
{
printf("ERROR IN PROCESS CREATION \n");
exit(0);
}
if(pid!=0)
{
pid1=getpid();
printf("\n the parent process ID is %d", pid1);
}

else
{

pid2=getpid();
printf("\n the child process ID is %d\n", pid2);
}
}
Expected Output:
the child process ID is 4485
the parent process ID is 4484

OUTPUT:
WEEK : 12

AIM: To Write a C program to simulate disk scheduling algorithms


a) FCFS b) SCAN c) C-SCAN
DESCRIPTION:
One of the responsibilities of the operating system is to use the hardware efficiently. For the disk
drives, meeting this responsibility entails having fast access time and large disk bandwidth. Both the
access time and the bandwidth can be improved by managing the order in which disk I/O requests are
serviced which is called as disk scheduling. The simplest form of disk scheduling is, of course, the
first-come, first-served (FCFS) algorithm. This algorithm is intrinsically fair, but it generally does not
provide the fastest service. In the SCAN algorithm, the disk arm starts at one end, and moves towards
the other end, servicing requests as it reaches each cylinder, until it gets to the other end of the disk. At
the other end, the direction of head movement is reversed, and servicing continues. The head
continuously scans back and forth across the disk. C-SCAN is a variant of SCAN designed to provide
a more uniform wait time. Like SCAN, C-SCAN moves the head from one end of the disk to the other,
servicing requests along the way. When the head reaches the other end, however, it immediately
returns to the beginning of the disk without servicing any requests on the return trip.

PROGRAM:

A) FCFS DISK SCHEDULING ALGORITHM

#include<stdio.h>

#include<stdlib.h>

int main()

int RQ[100],i,n,TotalHeadMoment=0,initial;

printf("Enter the number of Requests\n");

scanf("%d",&n);

printf("Enter the Requests sequence\n");

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

scanf("%d",&RQ[i]);

printf("Enter initial head position\n");

scanf("%d",&initial);

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

TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);

initial=RQ[i];

printf("Total head moment is %d",TotalHeadMoment);

return 0;

INPUT

Enter the number of Request 8

Enter the Requests Sequence 95 180 34 119 11 123 62 64

Enter initial head position 50

Expected Output:

Total head moment is 644

OUTPUT:
B. SCAN DISK SCHEDULING ALGORITHM

#include<stdio.h>
int main()
{
int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;
clrscr();
printf("enter the no of tracks to be traversed ");
scanf("%d'",&n);
printf("enter the position of head ");
scanf("%d",&h);
t[0]=0;
t[1]=h;
printf("enter the tracks ");
for(i=2;i<n+2;i++)
scanf("%d",&t[i]);
for(i=0;i<n+2;i++)
{
for(j=0;j<(n+2)-i-1;j++)
{
if(t[j]>t[j+1])
{
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp;
}}}
for(i=0;i<n+2;i++)
if(t[i]==h)
j=i;k=i;
p=0;
while(t[j]!=0)
{
atr[p]=t[j];
j--;
p++;
}
atr[p]=t[j];
for(p=k+1;p<n+2;p++,k++)
atr[p]=t[k+1];
for(j=0;j<n+1;j++)
{
if(atr[j]>atr[j+1])
d[j]=atr[j]-atr[j+1];
else
d[j]=atr[j+1]-atr[j];
sum+=d[j];
}
printf("\nAverage header movements:%f",(float)sum/n);
}

INPUT

enter the no of tracks to be traversed 9


enter the position of head 50
enter the tracks
65
78
23
44
65
76
78
89
75

Expected Output:

Average header movements:-116849760.000000

OUTPUT:
C. C-SCAN DISK SCHEDULING ALGORITHM

#include<stdio.h>

int main()

int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;

printf("enter the no of tracks to be traversed ");

scanf("%d",&n);

printf("enter the position of head ”);

scanf("%d",&h);

t[0]=0;

t[1]=h;

printf("enter total tracks ");

scanf("%d",&tot);

t[2]=tot-1;

printf("enter the tracks ");

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

scanf("%d",&t[i]);

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

for(j=0;j<=(n+2)-i-1;j++)

if(t[j]>t[j+1])

temp=t[j];

t[j]=t[j+1];

t[j+1]=temp;

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

{
if(t[i]==h)

j=i;

break;

p=0;

while(t[j]!=tot-1)

atr[p]=t[j];

j++;

p++;

atr[p]=t[j];

p++;

i=0;

while(p!=(n+3) && t[i]!=t[h])

atr[p]=t[i];

i++;

p++;

for(j=0;j<n+2;j++)

if(atr[j]>atr[j+1])

d[j]=atr[j]-atr[j+1];

else

d[j]=atr[j+1]-atr[j];

sum+=d[j];

}
printf("total header movements%d\n",sum);

printf("avg is %f",(float)sum/n);

INPUT:

enter the no of tracks to be traveresed10

enter the position of head100

enter total tracks10

enter the tracks55 58 60 70 18 90 15 01 84 164

Expected Output:

total header movements12590526avg is 1259052.625000

OUTPUT:

You might also like