TY_OS_Lab_Manual
TY_OS_Lab_Manual
TY_OS_Lab_Manual
Objectives:
Description:
To execute a command, type its name, options and arguments at the shell prompt.
ls -l /etc
Objectives:
Simple Filters
1. pr <file> :Paginating the file
Ex pr –h “test” –d –n fname
2. head <file>:Display first 10 lines of file
Ex head –n -3 fname
3. tail <file> :To display last 10 lines of file
Ex tail -3 fname ; tail –c 100 fname
4. cut <file> :Splitting file vertically
Ex cut –c 2-10,12-14 fname
a. cut –d “|” –f 2,4 fname
5. paste <file1> <file2> :To combine two file vertically rather than horizontally
Ex paste –d “|” fname1 fname2
6. sort <file>:To sort file in order by field wise
Ex sort –t”|” –k 2 fname
sort –r fname
7. uniq <file> :Locate repeated & nonrepeated lines
Ex uniq fname; uniq –d fname
8. tr ch1 ch2 < <file1>:To translate occurrence of ch1 by ch2
Ex tr ‘|’ ‘+’ < fname1
9. tee: read from standard input and write to standard output and files
Ex. ls *.txt | wc -l | tee count.txt
Pipe :Connects commands so the output of previous command becomes input for the second.
Vertical bar(|) is the pipe operator.
Ex. ls -l | more
cat file1 file2 | sort > file3
Concatenates file1 and file2
Sends the result to the sort command
Store the alphabetized, concatenate result as a new file called file3
Grep: Global Regular Expression Print
Searching and pattern matching tools
Searches files for one or more pattern arguments. It does plain string, basic regular
expression, and extended regular expression searching
Following are some of the options for grep
-i ignore case for matching
-v doesn’t display lines matching expression
-n display line numbers along of occurrences
-c counting number of occurrences
-l display list of file names
-e exp for matching
1. What is a pipe?
2. What is a filter?
5. What is an alias?
OBJECTIVES:
Description:
Shell
● Interface to the user
● Command interpreter
● Programming features
Shell Scripting
● Automating command execution
● Batch processing of commands
● Repetitive tasks
Shells in Linux
● Many shells available
● Examples -sh, ksh, csh, bash
● Bash is most popular
The Bourne Again Shell
● Abbreviated bash
● Default in most Linux distributions
● Most widely used on all UNIX platforms
● Derives features from ksh, csh, sh, etc.
● Support for many programming features variables, arrays, loops, decision
operators, functions, positional parameters
● Pipes, I/O re-direction
Shell variables:
1) System variables - Created and maintained by Linux itself. This type of variable
defined in CAPITAL LETTERS
BASH=/bin/bash Our shell name
HOME=/home/vivek Our home directory
LOGNAME=studentsstudents Our logging name
PATH=/usr/bin:/sbin:/bin:/usr/sbin Our path settings
PS1=[\u@\h \W]\$ Our prompt settings
PWD=/home/students/Common Our current working directory
SHELL=/bin/bash Our shell name
USERNAME=vivek User name who is currently login to this PC
2) User defined variables (UDV) - Created and maintained by user. This type of
variable defined in lower letters.
To define UDV use following syntax
Syntax: variable name=value
'value' is assigned to given 'variable name' and Value must be on right side = sign.
Example:
$ no=10# this is ok
$ 10=no# Error, NOT Ok, Value must be on right side of = sign.
To define variable called 'vech' having value Bus
$ vech=Bus
To define variable called n having value 10
$ n=10
The read Statement: Use to get input (data from user) from keyboard and store (data) to
variable.
Syntax: read variable1, variable2,...variableN
Ex. echo "Your first name please:"
read fname
Command line arguments:
$1,$2...$9 –positional parameter representing cnd line args
$# -total no. of args
$0 –name of executed cmd
$* -complete set of positional parameters
Using functions to perform repetitive tasks is an excellent way to create code reuse. Code
reuse is an important part of modern object-oriented programming principles. Shell
functions are similar to subroutines, procedures, and functions in other programming
languages.
function_name () {
list of commands
The name of your function is function_name, and that's what you will use to call it from
elsewhere in your scripts. The function name must be followed by parentheses, which are
followed by a list of commands enclosed within braces.
Example:
#!/bin/sh
Hello () {
Hello
When you would execute above script it would produce following result:
Hello World
$./test.sh
Hello World Zara Ali
$
Thus if your function will use three arguments you can just use $1, $2 and $3 in your code.
You may want to use $# which gives you number of arguments passed to the function if
you want to implement a function with variable arguments.
If you execute an exit command from inside a function, its effect is not only to terminate
execution of the function but also of the shell program that called the function.
If you instead want to just terminate execution of the function, then there is way to come
out of a defined function. Based on the situation you can return any value from your
function using the return command whose syntax is as follows:
Here code can be anything you choose here, but obviously you should choose something
that is meaningful or useful in the context of your script as a whole.
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World $1 $2"
return 10
}
# Invoke your function
Hello Zara Ali
# Capture value returned by last command
ret=$?
echo "Return value is $ret"
$./test.sh
Hello World Zara Ali
Return value is 10
Nested Functions:
One of the more interesting features of functions is that they can call themselves as well as
call other functions. A function that calls itself is known as a recursive function.
#!/bin/sh
# Calling one function from another
number_one () {
echo "This is the first function speaking..."
ALGORITHMS
1. Start.
2. Accept the string from user.
3. Find the actual length of string as len.
4. Initialize a pointer to character in string to 1 and also flag to true.
5. Take the character pointed to by the pointer and the character pointed to by len
6. If the characters are not found, make the flag as false and go to step 9.
7. Decrement variable len by 1 and increment pointer by 1.
8. If the value of len is less than or equal to 1 then repeat from step 5.
9. If the flag is true, display the message that ‘String is a palindrome’ else display ‘String is
not palindrome.’
10. Stop.
Test Condition:
• String should not be NULL.
1. Start.
2. Accept how many numbers to be sort say n .
3. Accept the numbers in array say num [].
4. Initialize i and j to 0.
5. While i<n .
6. do
assign j=0
while j<n
do
j=i
if num[j]<num[i] then
swap num[i] and num[j]
end if
j=j+1
done
i=i+1
done
7. Display the sorted list.
8. Stop.
Test Conditions:
• A certain maximum number of elements can be entered.
• Negative numbers are allowed.
1. Start.
2. Accept the two strings.
3. Compare two strings character by character.
4. If match is found then store the pointer of first string in an array.
5. Bring counter for second string to the first position.
6. Repeat the steps 3 to 5 until first string gets over.
7. Display the position array if substring exists else display substring does not exist.
8. Stop.
Test condition:
• First string should not be NULL.
Conclusion: Thus we have studies how to use shell script. It is Useful for integrating our
existing applications. And useful for System Administrator.
FAQs:
OBJECTIVES:
DESCRIPTION: The problem consists of readers and writers that share a data resource. The
readers only want to read from the resource, the writers want to write to it. Obviously, there is no
problem if two or more readers access the resource simultaneously. However, if a writer and a
reader or two writers access the resource simultaneously, the result becomes indeterminable.
Therefore the writers must have exclusive access to the resource.
A data object is to be shared among several concurrent processes. Some of these
processes may only want to read content of the shared object, whereas others may want to update
the shared object.
We distinguish between these two types of processes by referring to those processes that are
interested in only reading as readers and to rest as writers. Obviously, if two readers access the
shared data object simultaneously, no adverse effect will result.
1. The first readers-writers problem: Requires that no reader will be kept waiting unless a
writer has already obtained permission to use the shared object.
2. The second readers – writers problem: Requires that, once a writer is ready, that writer
performs its write as soon as possible. At given time, there is only one writer and any
number of readers. When a writer is writing, the readers cannot enter into the database
.The readers need to wait until the writer finishes to write to the database. Once a reader
succeeds in reading the database, subsequent readers can enter into the critical section
without waiting for the precedent reader finish to read. On the other hand, a writer who
MUTEX:
A mutex is mutual exclusion lock. Only one thread can hold the lock. Mutexes are used
to protect data or other resources from concurrent access. A mutex has attributes, which
specify the characteristics of the mutex.
ALGORITHM:
1. Start.
2. Create two threads associated with processes update and display.
3. Declare mutex variable timer_lock and initialize to 0 using pthread_mutex_init function.
4. Join two threads. Initiate processes update and display.
Update ( )
1. Lock access to critical sections using mutex timer_lock.
2. Update the values of variables seconds, minutes, and hours.
3. Unlock the access to critical sections using mutex.
Display( )
1. Lock the access to critical sections using mutex timer_lock.
2. Display the values of variables hours, minutes, seconds.
3. Unlock the access to critical sections using mutex timer_lock.
FAQS:
OBJECTIVES:
1. To understand problems of mutual exclusion and Producer Consumer Problem.
2. To grasp techniques and to develop the skills in the use of the tools: semaphores,
threads, and mutex in concurrent programming.
THEORY: The producer-consumer problem illustrates the need for synchronization in systems
where many processes share a resource. In this problem, two processes share a fixed size buffer.
One process produces information and puts it in the buffer, while the other process consumes
information from the buffer. These processes do not take turns accessing the buffer, they both
work concurrently.
SEMAPHORE:
• It can be used to restrict access to the database under certain conditions.
• Semaphore allows a sleep and wakeup mutual exclusion policy to be implemented.
• Basically, a semaphore is a new type of variable. A semaphore can have a value of
0(meaning no wakeups are saved) or a positive integer value, indicating the number
of sleeping processes.
• Two different operations can be performed on a semaphore, down and up,
corresponding to Sleep and Wakeup.
ALGORITHM
Using semaphore and thread:
1. Declare two thread variables of pthread_t structure.
2. Create two threads associated with producer and consumer processes using
pthread_create function.
3. Declare two semaphore variables of sem_t structure bfull and bempty.
PROBLEM STATEMENT: Write a program to compute the finish time, turnaround time and
waiting time by using different CPU scheduling algorithms
OBJECTIVES:
THEORY:
Scheduling decisions may take place when a process switches from:
1.Running to waiting.
2.Running to ready.
3.Waiting to ready.
4.Running to terminate.
Non-preemptive scheduling:
The current process keeps the CPU until it releases the CPU by either terminating or by
switching to a waiting state.
Non-preemptive scheduling occurs only under situations 1 and 4, it does not require special
hardware (timer).
Preemptive scheduling:
The currently running process may be interrupted and moved to the ready state by the operating
system. It requires special hardware (timer), mechanisms to coordinate access to shared data.
Definitions:
• Throughput Number of processes/time unit.
• Turnaround Time it take to execute a process from start to finish.
• Waiting Time Total time spent in the ready queue.
• Response time Amount of time it takes to start responding (average, variance).
1. Accept burst time and arrival time for every process entered by user.
2. Compare the arrival time of all processes.
3. Sort processes in ascending order with respect to their arrival time.
4. Execute all processes in sorted order.
5. Calculate the finish time of each process using the formula.
FT = start time + burst time.
6. Calculate the turnaround and waiting time for all processes.
7. Display finish time, turnaround time, waiting time, Gantt chart.
8. Stop.
Round Robin:
1. Accept the number of processes from the user.
2. Accept arrival time and burst times for each process.
3. Start with arrival time
4. Execute all processes present at arrival time for one time slot.
5. Increment arrival time.
Preemptive SJF:
1. Accept the number of processes from the user.
2. Accept arrival time and burst times for each process.
3. Sort all the processes according to the arrival time.
4. Start with the first process
5. After the first time slice of the process, if any other process has less arrival time then
execute that.
6. Continue this process till all the processes are completed.
7. Display finish time, turnaround time, waiting time with Gantt chart.
8. Stop.
FAQS:
1. Why is scheduling used?
2. What is the difference between preemptive & non- preemptive scheduling?
3. Which algorithm is more useful & why?
4. What do you mean by time quantum?
PROBLEM STATEMENT: Write a program to check whether given system is in safe state or
not using Banker’s Deadlock Avoidance algorithm
OBJECTIVES:
THEORY:
Deadlock: In operating systems or databases, a situation in which two or more processes are
prevented from continuing while each waits for resources to be freed by the continuation of the
other.
Deadlock Characterization: Deadlock can arise if four conditions hold simultaneously. (All
four must hold)
1. Mutual exclusion: Only one process at a time can use a resource
2. Hold and Wait: A process holding at least one resource is waiting to acquire
additional resources held by other processes.
3. No preemption: A resource can be released only voluntarily by the process holding
it, after that process has completed its task.
4. Circular Wait: There exists a set {P0, P1,….Pn} of waiting processes such that P0 is
waiting for a resource that is held by P1,P1 is waiting for a resource that is held by
P2..Pn-1 is waiting for a resource that is held by Pn ,and Pn is waiting for a resource
that is held by P0.
Deadlock Prevention: Restrain the ways that processes can make resource requests:
Mutual Exclusion- not required for sharable resources; must hold for non-sharable
resources
Deadlock Avoidance:
Requires that the system has additional information in advance.
• Simplest and most useful model requires that each process declare the maximum
number of resources of each type that it may need
• The deadlock –avoidance algorithm dynamically examines the resource allocation
state to ensure that there can never be a circular-wait condition.
• Resource-allocation state is defined by the number of available and allocated
resources, and the maximum demands of the processes.
ALGORITHMS
1. Start.
2. Calculate the current need for each process, for each resource from the data entered
by user.
3. For a process, check if current available resources satisfy all current needs.
Test Condition: Safe sequence is not unique. A different safe sequence may also be possible.
APPLICATIONS
Can be used in a system where prior information regarding usage of resources for
different processes is known in advance.
FAQS:
1. What do you mean by deadlock?
2. What are 4 conditions necessary for deadlock existence?
3. What are time complexities of deadlock avoidance and deadlock detection algorithm?
OBJECTIVES:
THEORY:
Page: One of numerous equally sized chunks of memory.
Page Replacement: This policy determines which page should be removed from main memory
so that page from secondary memory replaces it.
ALGORITHMS
Optimal:
1. Start.
2. Accept the sequence of requirement of pages.
3. Initialize a count for each page in main memory to zero.
4. Check if the page is already present in the main memory.
5. If the page is not present, find the page which will not be used for longest
period.
FAQS:
1. What do you mean by virtual memory?
2. What is segmentation?
3. What is a translation look aside buffer?
4. What is thrashing?
5. What is Belady’s anomaly?
OBJECTIVES:
THEORY:
In multiprogramming systems several different processes may want to use the system's resources
simultaneously. For example, processes will contend to access an auxiliary storage device
such as a disk. The disk drive needs some mechanism to resolve this contention, sharing
the resource between the processes fairly and efficiently.
First Come First Serve (FCFS)
The disk controller processes the I/O requests in the order in which they arrive, thus moving
backwards and forwards across the surface of the disk to get to the next requested
location each time. Since no reordering of request takes place the head may move almost
randomly across the surface of the disk. This policy aims to minimize response time with
little regard for throughput.
Shortest Seek Time First (SSTF)
Each time an I/O request has been completed the disk controller selects the waiting request
whose sector location is closest to the current position of the head. The movement across
the surface of the disk is still apparently random but the time spent in movement is
minimized. This policy will have better throughput than FCFS but a request may be
delayed for a long period if many closely located requests arrive just after it.
SCAN
The drive head sweeps across the entire surface of the disk, visiting the outermost cylinders
before changing direction and sweeping back to the innermost cylinders. It selects the
next waiting requests whose location it will reach on its path backwards and forwards
across the disk. Thus, the movement time should be less than FCFS but the policy is
clearly fairer than SSTF.
Circular SCAN (C-SCAN)
C-SCAN is similar to SCAN but I/O requests are only satisfied when the drive head is traveling
in one direction across the surface of the disk. The head sweeps from the innermost
cylinder to the outermost cylinder satisfying the waiting requests in order of their
locations. When it reaches the outermost cylinder, it sweeps back to the innermost
cylinder without satisfying any requests and then starts again
1. Start.
2. Accept the number of tracks n.
3. Accept the requested tracks and store it in the track [ ].
4. Consider the first value of track[ ] as starting track.
5. Process the track values in given order to calculate difference as
trackdiff [i] = track[i] - track[i+1] .
6. Calculate totaldiff = totaldiff + trackdiff[i].
7. Calculate average seek time.
8. Display the value of average seek time.
9. Stop.
1. Start.
2. Accept the number of tracks n.
3. Accept the requested tracks and store it in track[ ].
4. Consider the first value of track[ ] as starting track .
5. First process all the tracks which are having value less than starting track in decreasing
order of tracks as trackdiff[i] = track[i]-track[i+1] .
6. Then process all the tracks which are having value greater than starting in increasing
order of track as trackdiff[i] = track[i] - track[i+1].
7. Calculate totaldiff = totaldiff + trackdiff[i]
8. Calculate average seek time.
9. Display the value of average seeks time.
10. Stop.
1. Start.
2. Accept the number of tracks n.
3. Accept the requested tracks and store it in track[ ]
4. Consider the first value of track[ ] as starting track .
5. First process all the tracks which are having value greater than starting track in
increasing order of track as trackdiff[i] = track[i] - track[i+1]
6. then process all the tracks which are having value less than starting track in
decreasing order of track as trackdiff[i] = track[i] - track[i+1]
7. Calculate totaldiff = totaldiff + trackdiff[i]
8. Calculate average seek time.
9. Display the value of average seek time.
10. Stop
C-SCAN:
1. Start.
2. Accept the number of tracks n.
3. Accept the requested tracks and store it in track[ ]
4. Consider the first value of track[ ] as starting track .
5. First process all the tracks which are having value greater than starting track in
increasing order of track as trackdiff[i]= track[i] - track[i+1]
6. Then process all the tracks which are having value less than starting track in
increasing order of track(Wrap around to starting track) as trackdiff[i] = track[i] -
track[i+1]
7. Calculate totaldiff = totaldiff + trackdiff[i]
8. Calculate average seek time.
9. Display the value of average seek time.
10. Stop
R 00
0
01
03
C IC
MAIN
CPU STORAGE
CARD LINE
READER PRINTER 98
99
A storage word may be interpreted as an instruction or data word. The operation code of an
instruction occupies the two high-order bytes of the word, and the operand address appears in the
two low-order bytes. Table A-I gives the format and interpretation of each instruction. Note that
the input instruction (GD) reads only the first 40 columns of a card and that the output
instruction (PD) prints a new line of 40 characters. The first instruction of a program must
always appeal in location 00. With this simple machine, a batch of compute-bound, IO-bound,
and balanced programs can be quickly written. The usual kinds of programming errors are also
almost guaranteed to be made. (Both these characteristics are desirable, since the MOS should be
able to handle a variety of jobs and user errors.)
Timer
Supervisor
Storage User
Registers
Storage
CPU
Notation:
M: memory; IR: Instruction Register (4 bytes)
IR [1, 2]: Bytes 1, 2 of IR/Operation Code
IR [3, 4]: Bytes 3, 4 of IR/Operand Address
M[&]: Content of memory location &
IC: Instruction Counter Register (2 bytes)
R: General Purpose Register (4 bytes)
C: Toggle (1 byte)
: Loaded/stored/placed into
READ:
IR [4] 0
Read next (data) card from input file in memory locations IR [3,4] through IR [3,4] +9
If M [IR [3,4]] = $END, abort (out-of-data)
EXECUTEUSERPROGRAM
WRITE:
TERMINATE:
Write 2 blank lines in output file
MOS/LOAD
LOAD:
m0
While not e-o-f
Read next (program or control) card from input file in a buffer
Control card: $AMJ, end-while
$DTA, MOS/STARTEXECUTION
$END, end-while
Program Card: If m = 100, abort (memory exceeded)
Store buffer in memory locations m through m + 9
m m + 10
End-While
STOP
MOS/STARTEXECUTION
IC 00
EXECUTEUSERPROGRAM
Project
BEGIN
INITIALIZATION
SI = 3, TI = 0
Case TI and PI of
TI PI Action
0 1 TERMINATE (4)
0 2 TERMINATE (5)
0 3 If Page Fault Valid, ALLOCATE, update page Table, Adjust IC if
necessary, EXECUTE USER PROGRAM Otherwise
TERMINATE (6)
2 1 TERMINATE (3,4)
2 2 TERMINATE (3,5)
2 3 TERMINATE (3)
READ:
If next data card is $END, TERMINATE (1)
Read next (data) card from input file in memory locations RA through RA + 9
WRITE:
LLC LLC + 1
If LLC > TLL, TERMINATE (2)
Write one block of memory from locations RA through RA + 9 to output file
EXECUTEUSERPROGRAM
TERMINATE (EM):
Write 2 blank lines in output file
Write 2 lines of appropriate Terminating Message as indicated by EM
LOAD
LOAD:
While not e-o-f
Read next (program or control) card from input file in a buffer
Control card: $AMJ, create and initialize PCB
ALLOCATE (Get Frame for Page Table)
Initialize Page Table and PTR
Endwhile
$DTA, STARTEXECUTION
$END, end-while
Program Card: ALLOCATE (Get Frame for Program Page)
Update Page Table
Load Program Page in Allocated Frame
End-While
End-While
STOP
STARTEXECUTION:
IC 00
EXECUTEUSERPROGRAM
END (MOS)
SIMULATION:
Increment TTC
If TTC = TTL then TI 2
Question Bank:
1. What is significance of PI?
2. What is use of PTR?
3. What PCB contains?
4. What different errors may occur in a job?
5. When TI would set to 1 / 2?
6. What is a difference between relative ,absolute and logical address?