- 1. [100] Create a Bash script / Shell script to identify all possible ways in which Date can appear in a document.Here are the requirements:a. Your program will accept and read a given text file.b. It will extract all Dates appearing in the text file using different regular expression patterns.c. The program will display all the extracted Dates and total number of extracted Dates from the given text file.d. Write out all the extracted Dates and total number of extracted Dates in a report file. Each Date extraction will add a new line to the report file.You will submit the following: The Bash script / Shell script program that you develop and a short description of your experiential learning while working on this project. The second part should be about 5-10 sentences (less than 150 words) talking about what you learned and the process you used to find the patterns and extract the patterns.Script = 75 Points, Report = 25 Points
More Bash Commands
Environment Variables
User
Home
Editor
Shell
Logname
Path
Lang
Term
Mail
Commands
Users
Users | wc –w :Logged in user count
wc -w : prints the number of words in a file.
wc -c : Displays the count of bytes in a file.
(wc -c hello.c)
wc -m : prints the count of characters from a file.
wc -l : prints the number of lines from a file.
wc -L : prints only the length of the longest line in
a file.
Commands
Users
who
Who| wc –l :Currently logged in users
who -q : Currently logged in users
Stat file.txt
Commands
Hostname
hostname –d: Displays domain name
hostname –i: Displays IP address
uname –p: Displays processor name
cal : Displays Day in the year
Cal 8 2023
hostname –d: Displays domain name
Combining Commands
Number of files in directory
ls
ls | wc –l :Number of files in current directory
who -q : Currently logged in users
Grep print hello.c
Grep print *.c | wc –l
Grep print *.c | sort
Grep print *.c | wc –l | uniq –c
Grep print file.c | wc –l | uniq –c
Combining Commands
who | cut –f2 –d:
Who | cut –f2 –d/
Grep print file.c | cut –f2 -d: | sort | uniq –c
grep information Logfile.txt | cut -f2 -d- | sort –g
grep information Logfile.txt | cut -f2 -d- | sort –g |
tail -1
Unix Filters
head :top to bottom display (head -3 file.txt)
tail : bottom to top display
cut –f :displays particular column field
paste : combining files
tr : translating uppercase to lowercase
(cat file.txt | tr “[a-z]” “[A-Z]”) or tr ‘{ }’ ‘( )’
Sed : stream editor for text related operation
Grep : search pattern in file (also fgrep, egrep)
Unix Filters
Sed : stream editor for text related
operation
$sed ‘s/unix/linux/’ file.txt
Changes unix word to linux in file
Grep : search pattern in file (also fgrep,
egrep)
$grep print *.c
Unix Change
Chmod 0750 file.txt
Chmod u=rwx,g=rx,o= file.txt
Chmod a-x file.txt
Chmod g-x file.txt
Exam1 Review
Exam 1
Online Exam
3rd Oct. to 5th Oct, at Testing Center
No class on 3rd Oct
Time duration – 2 hours
Prior registration before 72 hours of Exam required
Closed book, closed notes
Topics in Exam 1
Unix Kernel
Regular Expressions
Unix File System
Unix Commands
C programming
Question Types
1 – Fill in the blanks
2 – True/ False
3 – Problems
4 – Comparisons/ Matchings
5 – Multiple choice
6 – Problems
7 – Short answers
Tips to do well
1 – Read the covered sections from book
2 – Solve the exercises for these sections
3 – Solve Quiz 1 – on elearning
4 – Go through lecture videos, slides and
notes, homeworks
5 – Practice
Tips to do well
1 – Find two hour time when you can give
exam uninterrupted
2 – Keep paper, pen/pencil and eraser
3 – Read questions carefully
4 – If you can’t solve then move quickly to
next question as time is limited
Unix
Kernel
File structure
Identify absolute, relative paths
Unix Commands
How different Unix commands work
Usability of commands
Should be able to write commands
Writing commands in command line
Writing in Shell Script
Unix Commands for files
Different Unix commands to manipulate files
Their syntax and usage
Shell Scripting
Unix File Permissions
Different types
How to give permissions to file
C/C++ Constructs in Unix
if, if…else, for
case
Regular Expression
How to write regular expression
Patterns
FSAs
Regular Expression in Unix
grep
Write a regular expression pattern for expressing email address.
Write a regular expression pattern for expressing money up to 1000$.
Write a regular expression pattern for expressing phone number.
What are functionalities of grep?
Bash How to Program
Slides in this presentation contain hyperlinks.
JAWS users should be able to get a list of links by
using INSERT+F7
Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
Vi hello.c
Press i or shift+a for insert mode
Type program
Press escape button
Type :wq! To save and exit
On command prompt,
Compile it with
$ cc hello.c
Now a.out executable file is ready.
Execute it by
$ ./a.out
It will print output as Hello world on the console.
sequence of commands that are
executed by the bash program line by
line.
It allows you to perform a series of
actions, such as navigating to a specific
directory, creating a folder, and
launching a process using the command
line.
By saving these commands in a script,
you can repeat the same sequence of
steps multiple times and execute them
by running the script.
Bash scripting is a powerful and versatile tool
for automating system administration tasks,
managing system resources, and performing
other routine tasks in Unix/Linux systems.
Some advantages of shell scripting are:
• Automation: Shell scripts allow you to
automate repetitive tasks and processes,
saving time and reducing the risk of errors
that can occur with manual execution.
• Portability: Shell scripts can be run on
various platforms and operating systems,
including Unix, Linux, macOS, and even
Windows.
• Flexibility: Shell scripts are highly
customizable and can be easily modified to
suit specific requirements. They can also be
combined with other programming languages
or utilities to create more powerful scripts.
• Accessibility: Shell scripts are easy to write
and don’t require any special tools or
software. They can be edited using any text
editor, and most operating systems have a
built-in shell interpreter.
• Integration: Shell scripts can be integrated
with other tools and applications, such as
databases, web servers, and cloud services,
allowing for more complex automation and
system management tasks.
In Bash, you can use and set the variable values
in the following ways:
1. Assign the value directly:
country=USA
In Bash scripting, the following are the variable naming
conventions:
1.Variable names should start with a letter or an
underscore (_).
2.Variable names can contain letters, numbers, and
underscores (_).
3.Variable names are case-sensitive.
4.Variable names should not contain spaces or special
characters.
5.Use descriptive names that reflect the purpose of the
variable.
6.Avoid using reserved keywords, such
as if, then, else, fi, and so on as variable names.
To access the variable value,
append $ to the variable name.
$country=USA
$echo $country USA
$new_country=$country
$echo $new_country USA
2. Assign the value based on the output obtained from a
program or command,
using command substitution.
Note that $ is required to access an existing variable’s
value.
same_country=$country
This assigns the value of country to the new
variable same_country
3. Reading from a file
This code reads each line from a file
named input.txt and prints it to the terminal.
while read line
do
echo $line
done < input.txt
4. Command line arguments
In a bash script or function,
$1 denotes the initial argument passed,
$2 denotes the second argument passed, and so
forth.
This script takes a name as a command-line
argument and
prints a personalized greeting.
echo "Hello, $1!"
Displaying output
Here we'll discuss some methods
to receive output from the scripts.
1.Printing to the terminal:
echo "Hello, World!"
This prints the text "Hello, World!" to the
terminal.
2. Writing to a file:
echo "This is some text." >
output.txt
This writes the text “This is some
text.”
to a file named output.txt.
Note that the >operator overwrites a
file
if it already has some content.
3. Appending to a file:
echo “More text.” >> output.txt
This appends the text “More text.”
to the end of the file output.txt.
4. Redirecting output:
ls > files.txt
This lists the files in the current directory and writes
the output
to a file named files.txt.
You can redirect output of any command to a file this
way.
Adding the Shebang
Bash scripts start with a shebang.
Shebang is a combination of bash
# and bang ! followed by the bash shell path.
This is the first line of the script.
Shebang tells the shell to execute it via bash shell.
Shebang is simply an absolute path to the bash
interpreter.
Below is an example of the shebang statement.
#!/bin/bash
You can find your bash shell path (which may vary
from the above) using the command:
which bash
$ echo “Hello World”
$ vim hello.sh
#!/bin/bash
echo “Hello World“
Line #1: The shebang (#!/bin/bash) points toward the bash shell
path.
Line #2: This line will print “Hello World” on the console.
Executing the bash script
To make the script executable, assign execution rights to
your user using this command:
Executing bash scripting
chmod u+x hello.sh
Here,
•chmod modifies the ownership of a file for the current user :
•u+x adds the execution rights to the current user. This
means that the user who is the owner can now run the
script.
•hello.sh is the file we wish to run.
$ bash hello.sh
Or,
$ chmod a+x hello.sh
$ ./hello.sh
Vi hello.sh
Press i or shift+a for insert mode
Type program
#! /bin/bash
echo Hello, $LOGNAME
echo -n “age:”
read age
if [ $age -lt 50 ]
then echo “great”
else echo “wise”
fi
Press escape button
Type :wq! To save and exit
On command prompt,
Execute it by
$./hello.sh
It will print output as Hello world on the console.
Compound comparison
-a logical and
Similar to &&
-o logical or
Similar to ||
Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
Integer Comparison
-eq is equal to
if [ “$a” -eq “$b” ]
-ne is not equal to
if [ “$a” -ne “$b” ]
-gt is greater than
if [ “$a” -gt “$b” ]
-ge is greater than or equal to
if [ “$a” -ge “$b” ]
-lt is less than
if [ “$a” -lt “$b” ]
-le is less than or equal to
if [ “$a” -le “$b” ]
Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
Integer Comparison
< is less than
(within double parentheses)
(("$a" < "$b"))
"$b"))
>= is greater than or equal to
(within double parentheses)
((“$a” >= “$b”))
< is less than
(within double parentheses)
(("$a" < "$b"))
ls *.c
Lists all the files with c extension or
> ls ab*
lists all file names that starts with ab in the current directory.
Pattern Matching
> cp *.c /afs/andrew.cmu.edu/course/15/123/handin/Lab6/guna
copies all .c files in the current directory to the given directory
GREP
The grep (Global Regular Expression Print) is a unix command utility that
can be used to find specific patterns described in “regular expressions”,
a notation which we will learn shortly. For example, the “grep”
command can be used to match all lines containing a specific pattern.
For example,
> grep “ output.txt
writes all lines containing the matching substring “grep “foo” filename
it returns all lines of the file given by filename that matches string foo.
GREP
Unix provide the | command (pipe command) to send an
input from one process to another process. Say for
example, we would like to find all files that have the
pattern “guna”. We can do the following to accomplish
that task.
> ls | grep guna
it returns all lines of the file given by filename that
matches string foo.
GREP
If we need to find a pattern a.c in a file name (that is any
file name that has the substring a.c, where dot(.) indicates
that any single character can be substituted) we can give
the command
> ls | grep a.c
So we can find file name that has the substring aac, abc,
a_c etc.
Family Differences
grep – uses regular expressions for pattern matching
fgrep – file grep, does not use regular expressions, only
matches fixed strings but can get search strings from a
file
egrep – extended grep, uses a more powerful set of
regular expressions but does not support
backreferencing, generally the fastest member of the
grep family
agrep – approximate grep; not standard
Syntax
Regular expression concepts we have seen so far are common to grep and
egrep.
grep and egrep have slightly different syntax
◦ grep: BREs
◦ egrep: EREs (enhanced features we will discuss)
Major syntax differences:
◦ grep: \( and \), \{ and \}
◦ egrep: ( and ), { and }
Protecting Regex
Metacharacters
Since many of the special characters used in regexs also have special
meaning to the shell, it’s a good idea to get in the habit of single
quoting your regexs
◦ This will protect any special characters from being operated on by the shell
◦ If you habitually do it, you won’t have to worry about when it is necessary
Escaping Special
Characters
Even though we are single quoting our regexs so the
shell won’t interpret the special characters, some
characters are special to grep (eg * and .)
To get literal characters, we escape the character with a
\ (backslash)
Suppose we want to search for the character sequence
a*b*
◦ Unless we do something special, this will match zero or more
‘a’s followed by zero or more ‘b’s, not what we want
◦ a\*b\* will fix this – now the asterisks are treated as regular
characters
Egrep: Alternation
Regex also provides an alternation character | for
matching one or another subexpression
◦ (T|Fl)an will match ‘Tan’ or ‘Flan’
◦ ^(From|Subject): will match the From and Subject lines
of a typical email message
◦ It matches a beginning of line followed by either the characters ‘From’
or ‘Subject’ followed by a ‘:’
Subexpressions are used to limit the scope of the
alternation
◦ At(ten|nine)tion then matches “Attention” or
“Atninetion”, not “Atten” or “ninetion” as would happen
without the parenthesis – Atten|ninetion
Egrep: Repetition
Shorthands
The * (star) has already been seen to specify zero or
more occurrences of the immediately preceding
character
+ (plus) means “one or more”
abc+d will match ‘abcd’, ‘abccd’, or ‘abccccccd’ but will
not match ‘abd’
Equivalent to {1,}
Egrep: Repetition
Shorthands cont
The ‘?’ (question mark) specifies an optional character, the
single character that immediately precedes it
July? will match ‘Jul’ or ‘July’
Equivalent to {0,1}
Also equivalent to (Jul|July)
The *, ?, and + are known as quantifiers because they specify
the quantity of a match
Quantifiers can also be used with subexpressions
◦ (a*c)+ will match ‘c’, ‘ac’, ‘aac’ or ‘aacaacac’ but will not match ‘a’
or a blank line
Grep: Backreferences
Sometimes it is handy to be able to refer to a match
that was made earlier in a regex
This is done using backreferences
◦ \n is the backreference specifier, where n is a number
Looks for nth subexpression
For example, to find if the first word of a line is the
same as the last:
◦ ^\([[:alpha:]]\{1,\}\) .* \1$
◦ The \([[:alpha:]]\{1,\}\) matches 1 or more letters
Practical Regex
Examples
Variable names in C
◦ [a-zA-Z_][a-zA-Z_0-9]*
Dollar amount with optional cents
◦ \$[0-9]+(\.[0-9][0-9])?
Time of day
◦ (1[012]|[1-9]):[0-5][0-9] (am|pm)
HTML headers …
◦
grep Family
Syntax
grep [-hilnv] [-e expression] [filename]
egrep [-hilnv] [-e expression] [-f filename] [expression]
[filename]
fgrep [-hilnxv] [-e string] [-f filename] [string] [filename]
◦ -h
Do not display filenames
◦ -i
Ignore case
◦ -l
List only filenames containing matching lines
◦ -n
Precede each matching line with its line number
◦ -v
Negate matches
◦ -x
Match whole line only (fgrep only)
◦ -e expression
Specify expression as option
◦ -f filename
Take the regular expression (egrep) or
a list of strings (fgrep) from filename
grep
Examples
grep ‘men’ GrepMe
grep ‘fo*’ GrepMe
egrep ‘fo+’ GrepMe
egrep -n ‘[Tt]he’ GrepMe
fgrep ‘The’ GrepMe
egrep ‘NC+[0-9]*A?’ GrepMe
fgrep -f expfile GrepMe
• Find all lines with signed numbers
$ egrep ’[-+][0-9]+\.?[0-9]*’ *.c
bsearch. c: return -1;
compile. c: strchr(“+1-2*3”, t-> op)[1] – ’0’, dst,
convert. c: Print integers in a given base 2-16 (default 10)
convert. c: sscanf( argv[ i+1], “% d”, &base);
strcmp. c: return -1;
strcmp. c: return +1;
• egrep has its limits: For example, it cannot match all lines that
contain a number divisible by 7.
Examples
•Match all lines that start with ‘hello’. E.g: “hello
there”
$ grep “^hello” file1
•Match all lines that end with ‘done’. E.g: “well
done”
$ grep “done$” file1
•Match all lines that contain any of the letters
‘a’, ‘b’, ‘c’, ‘d’ or ‘e’.
$ grep “[a-e]” file1
Examples
•Match all lines that do not contain a vowel
$ grep “[^aeiou]” file1
•Match all lines that start with a digit following
zero or more spaces. E.g: “ 1.” or “2.”
$ grep “ *[0-9]” file1
•Match all lines that contain the word hello in
upper-case or lower-case
$ grep -i “hello”
Fun with
the
Dictionary
contains about 25,000 words
/usr/dict/words
◦ egrep hh /usr/dict/words
◦ beachhead
◦ highhanded
◦ withheld
◦ withhold
egrep as a simple spelling checker: Specify plausible alternatives
you know
egrep “n(ie|ei)ther” /usr/dict/words
neither
How many words have 3 a’s one letter apart?
◦ egrep a.a.a /usr/dict/words | wc –l
◦ 54
◦ egrep u.u.u /usr/dict/words
◦ cumulus
Other Notes
Use /dev/null as an extra file name
◦ Will print the name of the file that matched
◦ grep test bigfile
◦ This is a test.
◦ grep test /dev/null bigfile
◦ bigfile:This is a test.
Return code of grep is useful
◦ grep fred filename > /dev/null && rm filename
This is one line of text
o.*o
x
xyz
\m
^
$
.
[xy^$x]
[^xy^$z]
[a-z]
r*
r1r2
\(r\)
\n
\{n,m\}
r+
r?
r1|r2
(r1|r2)r3
(r1|r2)*
{n,m}
Ordinary characters match themselves
(NEWLINES and metacharacters excluded)
Ordinary strings match themselves
Matches literal character m
Start of line
End of line
Any single character
Any of x, y, ^, $, or z
Any one character other than x, y, ^, $, or z
Any single character in given range
zero or more occurrences of regex r
Matches r1 followed by r2
Tagged regular expression, matches r
Set to what matched the nth tagged expression
(n = 1-9)
Repetition
One or more occurrences of r
Zero or one occurrences of r
Either r1 or r2
Either r1r3 or r2r3
Zero or more occurrences of r1|r2, e.g., r1, r1r1,
r2r1, r1r1r2r1,…)
Repetition
input line
regular expression
fgrep, grep, egrep
grep, egrep
grep
egrep
Quick
Reference
References
1. Regular Expressions by Ananda Gunawardena
2. Regular expressions and automata by Prof. Dan Moldovan
3. Regular expressions grep by Prof. Hugh Murrell
Processes
1
Outline
What Is A Process?
Process States; Process Control Block (PCB)
Process Memory Layout
Process Scheduling
Context Switch
Process Operations
Inter-Process Communication
Client-Server Communication
2
ps
ps
Check process id’s
ps: ps
Check process id’s – consecutive most likely
ps: ps: ps
Check process id’s – consecutive most likely
ps: cat hello.c ps:
Check process id’s – will not be consecutive because of
cat command in between
3
Users, Programs, Processes
Users have accounts on the system
Users launch programs
Many users may launch same program
One user may launch many instances of the same program
Processes: an executing program
Question: Real life analogy?
4
Real Life Analogy?
One example:
Recipes ⟺ Programs
Step 1: xxx
Step 2: yyy
Step 3: zzz
Step 4: www
Making dishes ⟺ Processes
Action
Others? (Group discussion)
5
Windows Task Manager
6
windowscentral.com/how-identify-and-terminate-high-resource-processes-using-
Unix Processes: ps
7
So What Is A Process?
It’s one executing instance of a “program”
It’s separated from other instances
It can start (“launch”) other processes
It can be launched by other processes
8
Outline
What Is A Process?
Process States; Process Control Block (PCB)
Process Memory Layout
Process Scheduling
Context Switch
Process Operations
Inter-Process Communication
Client-Server Communication
9
The Process Model
•
•
•
Multiprogramming of four programs
Conceptual model of four independent,
sequential processes
Only one program active at any instant
10
Process Control Block (PCB):
Why?
• PCB contains information
associated with a given
process:
– Process state
– Process identification (pid)
– Program counter
– CPU registers
– CPU scheduling info
– Memory-mgmt. info
– Accounting info
– I/O status info
– pid of parent process
11
Process Control Block (PCB):
Why?
Process control information is used
by the OS to manage the process
itself. This includes:
•Process scheduling state – The
state of the process in terms of
“ready”, “suspended”, etc., and other
scheduling information as well, such
as priority value, the amount of time
elapsed since the process gained
control of the CPU or since it was
suspended. Also, in case of a
suspended process, event
identification data must be recorded
for the event the process is waiting
for;
12
PCB
•Process structuring information – the
process’s children id’s, or the id’s of other
processes related to the current one in some
functional way, which may be represented as
a queue, a ring or other data structures;
•Interprocess communication information –
flags, signals and messages associated with
the communication among independent
processes;
13
PCB
•Process Privileges – allowed/disallowed
access to system resources;
•Process State – new, ready, running,
waiting, dead;
•Process Number (PID) – unique
identification number for each process (also
known as Process ID);
•Program Counter (PC) – a pointer to the
address of the next instruction to be
executed for this process;
14
PCB
•CPU Registers – register set where process
needs to be stored for execution for running
state;
•CPU Scheduling Information – information
scheduling CPU time;
•Memory Management Information – page
table, memory limits, segment table;
•Accounting Information – amount of CPU
used for process execution, time limits,
execution ID etc.;
•I/O Status Information – list of I/O devices
allocated to the process.
15
Process Descriptor in Linux
(1)
16
Process Descriptor in Linux
• In(2)
:
https://github.com/torvalds/linux/blob/master/kernel/sched/sche
d.h
• In :
https://github.com/torvalds/linux/blob/master/arch/x86/include/a
sm/thread_info.h
17
Process States
As a process executes, it changes its state:
New: The process is being created.
Running: Instructions are being executed.
Waiting (blocked): The process is waiting for some event to occur.
Ready: The process is waiting to be assigned to a CPU.
Terminated: The process has finished execution.
18
Questions
Using “working on a lab assignment” as an example:
What corresponds to “running”?
What corresponds to “waiting”?
What corresponds to “ready”?
19
So What Is A Process?
It’s one executing instance of a “program”
It’s separated from other instances
It can start (“launch”) other processes
It can be launched by other processes
20
What Does This Program Do?
int myval;
int main(int argc, char *argv[]) {
myval = atoi(argv[1]);
while (1)
printf(“myval is %d, loc 0x%lx\n”, myval, (long) &myva
}
Now simultaneously start two instances of this
program
myval
5
myval
6
What will the outputs be?
21
Here’s The Output
22
Instances Of Programs
The address was always the same
The values were different
Implies that the processes aren’t seeing each other
But they think they’re using the same address
Conclusion: addresses are not
absolute/physical
Implication: memory mapping
What’s the benefit?
23
Outline
What Is A Process?
Process States; Process Control Block (PCB)
Process Memory Layout
Process Scheduling
Context Switch
Process Operations
Inter-Process Communication
Client-Server Communication
24
Remember This?
Application
Libraries
User space
Kernel space level
Portable OS layer
Machine-dependent layer
25
Address Space (1)
One (common) approach
Kernel is high memory
User is low memory
What restrictions apply?
read(f, buf, nbytes)
0xffff….
Kernel space
User space
0x0000…
26
Address Space (2)
Program segments
Text
Data
Stack
Heap
What is text?
What is data?
What is stack?
What is heap?
0xffff….
Kernel space
User space
0x0000…
27
One Common Layout
Lots of flexibility
Allows stack growth
Allows heap growth
No predetermined division
0xffff….
Kernel space
Stack
Heap
Code & Data
0x0000…
28
Outline
What Is A Process?
Process States; Process Control Block (PCB)
Process Memory Layout
Process Scheduling
Context Switch
Process Operations
Inter-Process Communication
Client-Server Communication
29
Remember This?
30
Process Scheduling Queues
• Job queue: set of all processes in the system
• Ready queue: set of all processes in main memory, ready and
waiting to run
• Device queues: – set of processes waiting for an I/O device
• Processes migrate among various queues
31
Process Scheduling
32
Schedulers
Long-term scheduler (or job scheduler)
Selects which processes should be brought into the
ready queue
Invoked very infrequently (seconds, minutes) (may be
slow)
Controls the degree of multiprogramming
Should balance different types of processes:
I/O-bound process: spends more time doing I/O than
computations, many short CPU bursts
CPU-bound process: – spends more time doing computations;
few very long CPU bursts
Short-term scheduler (or CPU scheduler)
Selects which process should be executed next and
allocates CPU
33
Addition of Medium Term Scheduling
34
Outline
What Is A Process?
Process States; Process Control Block (PCB)
Process Memory Layout
Process Scheduling
Context Switch
Process Operations
Inter-Process Communication
Client-Server Communication
35
Context Switch
During context switch, the running process is stopped and another process
runs. The kernel must stop the execution of the running process, copy out
the values in hardware registers to its PCB, and update the hardware
registers with the values from the PCB of the new process.
36
Context Switch
Switch CPU from one process to another
Performed by scheduler (dispatcher)
It includes:
Save PCB state of the old process;
Load PCB state of the new process;
Flush memory cache;
Change memory mapping (TLB);
Context switch is expensive (1–1000 μs)
No useful work is done (pure overhead)
Can become a bottleneck
Real life analogy?
37
CPU Switching Among
Processes
running
38
Outline
What Is A Process?
Process States; Process Control Block (PCB)
Process Memory Layout
Process Scheduling
Context Switch
Process Operations
Inter-Process Communication
Client-Server Communication
39
Process Creation
System initialization
Reboot
Process creation
System call: fork()
Users request new process creation
Command line or click an icon
Initiation of a batch job
cron jobs
Try crontab or at
40
Process Termination
Normal exit (voluntary)
Error exit (voluntary)
exit(2)
Fatal error (involuntary)
End of main()
Divide by 0, core dump
Killed by another process (involuntary)
kill , end task
41
Process Hierarchies
Parent creates a child process; child can create its
own processes…
42
Unix Process-Related System
Callsfork(void);
(1)
pid_t
//
A new process is created that’s an exact copy of the process
making the system call (i.e., a copy of the calling process is
made; the copy runs as a new process). Copy is of memory
image of calling process at the moment of the fork() system
call, not the program the calling process was started from.
New process does not start at the beginning but at the exact
point of the fork() system call.
Thus, right after fork() there are two processes (issuing
process and newly-created process) with identical memory
images.
43
Return value to the parent is the process identifier
(pid) of
the new process. The return value to the child process is 0.
Processes after fork()
parent
parent
fork(
)
child
Before
fork()
After fork()44
Unix Process-Related System
Calls
(2)
int execv(char *programName, char *argv[]); //
The program programName is loaded in the calling process’s address space.
Thus, the old program in the calling process is overwritten and no longer exists.
The arguments are in the argument vector argv, which is an array of strings
(i.e., an array of pointers to characters). There are 6 versions of the exec
system call.
void exit(int returnCode); //
This system call makes a process exit. The returnCode is returned to the
parent process if it waits for its child process to terminate.
pid_t wait(int *returnCode); // ,
This system call makes the calling process wait until any process created by the
calling process exits. The return value is the pid of the process that exited. The
return code is stored in returnCode.
45
int waitpid(pid_t pid, int *returnCode, int options);
// same
Like wait(), but has more options. Type man 2 waitpid for more info.
Unix Processes: Example 1
What’s the functionality of the following
code snippet?
ProgA {
int x; char *arg[1]={0};
x = fork();
if (x==0) execv(“ProgB”,arg);
exit(3);
}
46
Unix Processes: Example 2
Write C code for a process A which creates another process with
code from ProgB file; then the process A waits for its child
process to terminate, before it exits.
ProgA {
int x,y,z; char
*arg[1]={0};
x = fork();
if (x==0)
execv(“ProgB”,arg);
y = wait(&z);
exit(3)
}
ProgB {
// exit(5); /*point
A*/
// exit(1); /*point
B*/
}
If the child process exits at point A, then z=5;
if it exits at point B, then z=1.
47
Unix Processes: Example
Example illustrates how Unix commands (e.g., ls)
3
can be issued from a program.
void main (int argc, char *argv []) {
int pid;
pid = fork (); /* fork another process*/
if (pid