0% found this document useful (0 votes)
9 views43 pages

Lect 2

Chapter 2 discusses processes in operating systems, defining a process as a program in execution with various states such as new, ready, running, waiting, and terminated. It covers process control blocks (PCBs), process scheduling, context switching, and inter-process communication methods like shared memory and message passing. The chapter highlights the importance of process creation and termination, as well as the advantages and challenges of cooperating processes.

Uploaded by

asnake ketema
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views43 pages

Lect 2

Chapter 2 discusses processes in operating systems, defining a process as a program in execution with various states such as new, ready, running, waiting, and terminated. It covers process control blocks (PCBs), process scheduling, context switching, and inter-process communication methods like shared memory and message passing. The chapter highlights the importance of process creation and termination, as well as the advantages and challenges of cooperating processes.

Uploaded by

asnake ketema
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Chapter 2: Processes

Chapter 2: Processes

Process Concept
Process Scheduling
Context Switching
Operations on Processes
Inter-process Communication

2
Process Concept
A computer program is a collection of instructions
performing a specific task.
Process – sometimes called a task/job is, informally, a
program in execution
 process execution is done in sequential fashion
Components of a process
 The program code, also called text section
 Current activity including
 program counter,
 processor registers

 Stack containing temporary data


 Function parameters, return addresses, local variables
 Data section containing global variables
 Heap :- a memory that is dynamically allocated during
run time 3
Memory Layout of a C Program

4
Process Concept (Cont.)
―Process‖ is not the same as ―program‖

Program is passive entity stored on disk (executable file), While


process is active
 Program becomes process when executable file loaded into
memory
 The program is only part of a process;
 The process contains the execution state

Execution of program started via GUI mouse clicks, command line entry
of its name, by execution of another program etc

One program can be several processes


 Consider multiple users executing the same program or
 A single user executing multiple instances of the same program E.g.
web browsers
5
Process State
When a process executes, it passes through different states:
 new: The process is being created
 ready: The process is waiting to be assigned to a processor
 running: Instructions are being executed
 waiting: The process is waiting for some event to occur
 terminated: The process has finished execution

6
Cont’d …
new →ready
 Admitted to ready queue;
 can now be considered by CPU scheduler
ready →running
 CPU scheduler chooses that process to execute next, according to
some scheduling algorithm
running →ready
 Process has used up its current time slice or
 Interrupt has been detected
running →waiting
 Process is waiting for some event to occur (for I/O operation to
complete, etc.)
Waiting → ready
 Whatever event the process was waiting on has occurred

7
Process Control Block (PCB)

It is a data structure in OS that contains information


associated with each process (also called task control
block/task descriptor)
A PCB is created in the kernel whenever a new process is
started.

A PCB will include:


a process identifier (PID)
Process state – running, waiting, etc
Program counter – location of instruction to next execute
CPU registers – contents of all process-centric registers
CPU scheduling information- priorities, scheduling queue
pointers
Memory-management information – memory allocated to the
process
Accounting information – CPU used, clock time elapsed since
start, time limits
I/O status information – I/O devices allocated to process, list
of open files

8
Process Scheduling
The Objective of multiprogramming is to have some process
running at all times (to maximize CPU utilization.)

The objective of time sharing is to switch the CPU among processes


so frequently

To meet these objectives Process scheduler selects among


available processes for next execution on CPU

Process scheduler maintains scheduling queues of processes


 Job queue: Set of all processes in the system
 Ready queue – set of all processes residing in main memory,
ready and waiting to execute
 Device queues – set of processes waiting for an I/O device

 Note:-
 Processes migrate among the various queues till it finishes
execution
10
Ready and Wait Queues

11
Representation of Process Scheduling
 Queuing diagram is a common representation of process scheduling
 Rectangles represents queues (ready and device queues),
 Circles represents resources that serve queues,
 Arrows indicates flows of process in the system

12
Context Switch
The process of changing the CPU hardware state from one process to
another is called a context switch
 This can happen 100 or 1000 times a second!
When CPU switches to another process,
 The system must save the state of the old process and
 Load the saved state for the new process via a context switch
Context of a process represented in the PCB
Context-switch time is overhead;
 the system does no useful work while switching
 The more complex the OS and the PCB  the longer the context
switch
Time for context switch is dependent on hardware support
 Some hardware provides multiple sets of registers per CPU
  multiple contexts loaded at once
  context switch time will be minimal

13
CPU Switch From Process to Process

14
Operations on Processes
System must provide mechanisms for:
 Process creation,
 Process termination,
 Inter-process communication and so on as detailed next

15
Process Creation
Processes are created and deleted dynamically
The system creates the first process (init in Linux)
The first process then creates other processes such that:
 the creator is called the parent process
 the created is called the child process
 the parent/child relationships can be expressed by a process tree

Resources required when creating process


 CPU time, files, memory, I/O devices etc.

16
A Tree of Processes in Linux

init
pid = 1

login kthreadd sshd


pid = 8415 pid = 2 pid = 3028

bash khelper pdflush sshd


pid = 8416 pid = 6 pid = 200 pid = 3610

emacs tcsch
ps
pid = 9204 pid = 4005
pid = 9298

17
Cont...
Reasons for process creation
 User logs on
 User starts a program
 OS creates process to provide a service
 (e.g., printer daemon to manage printer)
 Program starts another process (e.g., Microsoft word calls Microsoft
excel to edit numerical data)

Some commands to List processes (UNIX):


 ps — my processes, little detail
 ps -fl — my processes, more detail
 ps -efl — all processes, more detail

18
Process Creation
Two ways to create a process
 Build a new empty process from scratch
 Example: Windows using createProcess() system call

 Copy an existing process and change it appropriately


 Example: Unix using fork(), exec() system calls

19
Process Creation: Windows
Option 1: New process from scratch
 Steps
 Create and initialize the process control block (PCB) in the
kernel
 Create and initialize a new address space
 Load the program into the address space
 Copy arguments into memory in the address space
 Initialize the hardware context to start execution at ``start'’
 Places the PCB on the ready queue

 Advantages:
 No wasted work
 Disadvantages: Difficult to setup process correctly and to express
all possible options
 Process permissions, where to write I/O, environment variables
 Example: WindowsNT has to call with 10 arguments

20
Creating a Separate Process via Windows API

21
Process Creation
Option 2: Clone existing process and change (UNIX)
Some unix system calls
 fork() – system call to create a new process
 No arguments!
 fork() returns PID of the child to parent, and 0 to the child
 exec() – system call used after a fork() to replace the process’ memory
space with a new program
 wait() – system call to wait for a process to finish

22
Process Creation (Cont.)
Resource sharing options (parent/child )
 Parent and children share all resources
 Children share subset of parent’s resources
 Parent and child share no resources
Execution options(parent/child )
 Parent and children execute concurrently
 Parent waits until children terminate
Address space- a separate address space created for the child.
 Child duplicate of parent (sharing the same program and data
segments in memory )
 Child has a program loaded into it (all new code and data segments)

23
UNIX Process Management

24
C Program Forking Separate Process

25
Question: What does this code print?

int child_pid = fork();


if (child_pid == 0) { // I'm the child process
printf("I am process #%d\n", getpid());
return 0;
} else { // I'm the parent process
printf("I am parent of process #%d\n", child_pid);
return 0;
}

Parent could print first, or child could print first – you don’t know!

26
Question: What does this code print?

int child_pid = fork();


if (child_pid == 0) { // I'm the child process
printf("I am process #%d\n", getpid());
return 0;
} else { // I'm the parent process
wait(NULL) ;
printf("I am parent of process #%d\n", child_pid);
return 0;
}

27
Process Termination

Process may terminate in one of the three ways


 By its own request using exit () sys call – return 0 in c++
 By its parent using the abort () sys call
 By the OS
When a process terminates
 Returns status data from child to parent (via wait())
 Process’ resources are deallocated by operating
system

29
Cont…
Parent may terminate the execution of children processes
using the abort() system call.
Some reasons for doing so:
 Child has exceeded allocated resources
 Task assigned to child is no longer required
 The parent is exiting and the operating systems does
not allow a child to continue if its parent terminates
 Arithmetic error, or data misuse (e.g.,wrong type)
 Invalid instruction execution
 Insufficient memory available, or memory bounds
violation
 I/O failure

30
Inter-process communication

32
Interprocess Communication
Processes within a system may be independent or cooperating
 Cooperating process can affect or be affected by other processes,
including sharing data
 Independent process cannot affect or be affected by the execution of
another process

Reasons for cooperating processes (Advantages):


 Computation speedup
 By overlapping activities or performing work in parallel
 Modularity
 Better code structure and hence easier to work with
 Convenience
 Even an individual user may work on many tasks at the same time. For
instance, editing, listening to music, and compiling in parallel.
 Information sharing
 Providing concurrent access to shared information for all users interested in that
information
Issues:
 How do the processes communicate?
 How do the processes share data? 33
Communications Models
Cooperating processes need interprocess communication (IPC) mechanism
Two models of IPC
 Shared memory
 Message passing

(a) Message passing. (b) shared memory.


34
Producer-Consumer Problem
A common paradigm for cooperating processes is a producer-consumer
problem
 One process is a producer of information;
 another is a consumer of that information
For example:
 A compiler may produce assembly code that is consumed by an
assembler.
 The assembler, in turn, may produce object modules that are
consumed by the loader.

One solution to the producer–consumer problem uses shared memory.


 The data is passed via an intermediary buffer
 unbounded-buffer places no practical limit on the size of the buffer
 bounded-buffer assumes that there is a fixed buffer size

35
Bounded-Buffer – Shared-Memory Solution

Shared data
#define BUFFER_SIZE 10
typedef struct {
. . .
} item;

item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;

36
Bounded-Buffer – Producer

item next_produced;
while (true) {
/* produce an item in next produced */
nextProduced = makeNewItem( . . . );

/* Wait for space to become available */


while (((in + 1) % BUFFER_SIZE) == out)
; /* do nothing */
/* And then store the item and repeat the loop. */
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
}

37
Bounded Buffer – Consumer
item next_consumed;
while (true) {
/* Wait for an item to become available */
while (in == out)
; /* do nothing */

/* Get the next available item */


next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;

/* consume the item in next consumed */


}

• What is the problem with solution ?

38
Interprocess Communication – Shared Memory

An area of memory shared among the processes that


wish to communicate

The communication is under the control of the users


processes not the operating system.

Advantage:
 Fast and easy to share data
Disadvantage:
 Must synchronize data accesses; error prone

Synchronization is discussed in great details in Lecture


4.

39
Interprocess Communication – Message Passing
Mechanism for processes to communicate and to synchronize their actions
Message system – processes communicate with each other without
resorting to shared variables
 Explicitly pass data between sender (src) + receiver (destination)

IPC facility provides two operations:


 send(message)
 receive(message)
The message size is either fixed or variable

40
Message Passing (Cont.)

If processes P and Q wish to communicate, they need to:


 Establish a communication link between them
 Exchange messages via send/receive
Implementation issues:
 How are links established?
 Can a link be associated with more than two processes?
 How many links can there be between every pair of communicating
processes?
 What is the capacity of a link?
 Is the size of a message that the link can accommodate fixed or
variable?
 Is a link unidirectional or bi-directional?

41
Assignmen-1
Make group having 5-6 members
Pick 1 case/topic from the list below and prepare maximum
of 5 pages report and 15 minuets presentaiton
1. Shared memory implementation in Linux (Nathnael)
2. Remote Procedure call/Remote method Invoacaton (Tilahun)
3. Pipes (Abraham)
4. Socket (Tamagn)

Submission
 Summary of the topic not morethan 5 pages and Demo code
Deadline:
 September 10, 2023
Evaluation
 Presentaiton and the report
42
Summary

What are the units of execution?


 Processes
How are those units of execution represented?
 Process Control Blocks (PCBs)
How is work scheduled in the CPU?
 Process states, process queues, context switches
What are the possible execution states of a process?
 Running, ready, waiting, new and terminated
How does a process move from one state to another?
 Scheduling, I/O, creation, termination
How are processes created?
 CreateProcess (Windows), fork/exec (Unix)

43
IPC - Summary

Shared Memory is faster once it is set up


 because no system calls are required and access occurs at
normal memory speeds.
 Doesn't work as well across multiple computers.
 Shared memory is generally preferable when large amounts of
information must be shared quickly on the same computer.
Message Passing requires system calls for every
message transfer, and is therefore slower
 but it is simpler to set up and works well across multiple
computers.
 Message passing is generally preferable when the amount
and/or frequency of data transfers is small, or when multiple
computers are involved.

44
Additional readings
Operating system concepts, chapter 3
Modern Operating systems, chapter 2 of section 2.1

45
End of Chapter 2

You might also like