0% found this document useful (0 votes)
8 views109 pages

CH 3

Uploaded by

rudrabhishekjain
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)
8 views109 pages

CH 3

Uploaded by

rudrabhishekjain
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/ 109

Chapter 3: Processes

Operating System Concepts – 9th Edition Silberschatz, Galvin and Gagne ©2013
Chapter 3: Processes
Process Concept
Process Scheduling
Operations on Processes

Operating System Concepts – 9th Edition 3.2 Silberschatz, Galvin and Gagne ©2013
Objectives

To introduce the notion of a process –


a program in execution, which forms the basis of
all computation.
To describe the various features of processes–
including scheduling, creation and termination,
and communication

Operating System Concepts – 9th Edition 3.3 Silberschatz, Galvin and Gagne ©2013
Process Management
Process Thread
A process can be taught A thread is the unit of
of as a program in execution within a
execution. process. A process can
have anywhere from just
one thread to many
threads.

Operating System Concepts – 9th Edition 3.4 Silberschatz, Galvin and Gagne ©2013
Process Concept

An operating system executes a variety of programs:


Batch system – jobs
Time-shared systems – user programs or tasks
Textbook uses the terms job and process almost interchangeably
Process – a program in execution; process execution must progress
in a sequential fashion
Multiple Parts
The program code, also called the 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 containing memory dynamically allocated during run time

Operating System Concepts – 9th Edition 3.5 Silberschatz, Galvin and Gagne ©2013
Process Concept (Cont.)
Program is a passive entity stored on disk (executable file), the
process is active
Program becomes process when executable file loaded into
memory
Execution of program started via GUI mouse clicks, command line
entry of its name, etc
One program can be several processes
Consider multiple users executing the same program

Operating System Concepts – 9th Edition 3.6 Silberschatz, Galvin and Gagne ©2013
Process in Memory

• The program code, also called


the 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 containing memory


dynamically allocated during run
time

Operating System Concepts – 9th Edition 3.7 Silberschatz, Galvin and Gagne ©2013
Process State

As a process executes, it changes state.


The state of a process is defined by the current activity of
that process.
Each process may be in one of the following states:
new: The process is being created
running: Instructions are being executed
waiting: The process is waiting for some event to occur
ready: The process is waiting to be assigned to a processor
terminated: The process has finished execution

Operating System Concepts – 9th Edition 3.8 Silberschatz, Galvin and Gagne ©2013
Diagram of Process State

Operating System Concepts – 9th Edition 3.9 Silberschatz, Galvin and Gagne ©2013
Diagram of Process State (Advanced)

Operating System Concepts – 9th Edition 3.10 Silberschatz, Galvin and Gagne ©2013
Process Control Block (PCB)
Information associated with each process
(also called Task Control Block)
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 the start, time
limits
I/O status information – I/O devices
allocated to process, list of open files

Operating System Concepts – 9th Edition 3.11 Silberschatz, Galvin and Gagne ©2013
CPU Switch From Process to Process

Operating System Concepts – 9th Edition 3.12 Silberschatz, Galvin and Gagne ©2013
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 that users can interact with each program while it is
running.
To meet these objectives, the process schedular selects an available
process (possibly from a set of several available processes) for
program execution on the CPU.
For a single processor system, there will never be more than one
running process.
If there are more processes, the rest will have to wait until the
CPU is free and can be rescheduled.

Operating System Concepts – 9th Edition 3.13 Silberschatz, Galvin and Gagne ©2013
Process Scheduling Queues
Process scheduler selects among available processes for the next
execution on the CPU.
Maintains scheduling queues of processes
Job queue – All processes are stored in the job queue.
Ready queue – set of all processes residing in main memory, ready
and waiting to execute.
Device queues – Processes waiting for a device to become
available or to deliver data are placed in device queues. There is
generally a separate device queue for each device.

Operating System Concepts – 9th Edition 3.14 Silberschatz, Galvin and Gagne ©2013
Process Scheduling Queues

Operating System Concepts – 9th Edition 3.15 Silberschatz, Galvin and Gagne ©2013
Ready Queue And Various I/O Device Queues

Operating System Concepts – 9th Edition 3.16 Silberschatz, Galvin and Gagne ©2013
Representation of Process Scheduling

Queueing diagram represents queues, resources, flows

Operating System Concepts – 9th Edition 3.17 Silberschatz, Galvin and Gagne ©2013
Schedulers
Short-term scheduler (or CPU scheduler) – selects which process should
be executed next and allocates CPU
Sometimes the only scheduler in a system
Short-term scheduler is invoked frequently (milliseconds)  (must be
fast)
Long-term scheduler (or job scheduler) – selects which processes should
be brought into the ready queue
Long-term scheduler is invoked infrequently (seconds, minutes) 
(may be slow)
The long-term scheduler controls the degree of multiprogramming
Processes can be described as either:
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

Operating System Concepts – 9th Edition 3.18 Silberschatz, Galvin and Gagne ©2013
Addition of Medium-Term Scheduling
Medium-term scheduler can be added if the degree of multiple
programming needs to decrease
Remove a process from memory, store on disk, bring back in
from disk to continue execution: swapping

Operating System Concepts – 9th Edition 3.19 Silberschatz, Galvin and Gagne ©2013
Context Switch
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 dependent on hardware support
Some hardware provides multiple sets of registers per CPU ➔
multiple contexts loaded at once

Operating System Concepts – 9th Edition 3.20 Silberschatz, Galvin and Gagne ©2013
Operations on Processes

System must provide mechanisms for:


process creation,
process termination,
and so on as detailed next

Operating System Concepts – 9th Edition 3.21 Silberschatz, Galvin and Gagne ©2013
Process Creation
The process may create several new processes, via a create-process
system call or fork(), during execution.
The creating process is called the parent process and new processes
are called the child of that process.
Each of these new processes may in turn create other processes
forming a tree of the processes.

Operating System Concepts – 9th Edition 3.22 Silberschatz, Galvin and Gagne ©2013
Process Creation
Each process is given an integer identifier, termed its process
identifier, or PID. The parent PID ( PPID ) is also stored for each
process.
Resource-sharing options
Parent and children share all resources
Children share a subset of parent’s resources
Parent and child share no resources
There are two options for the parent process after creating the
child:
Parent and children execute concurrently.
Parent waits until children terminate.

Operating System Concepts – 9th Edition 3.23 Silberschatz, Galvin and Gagne ©2013
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

Operating System Concepts – 9th Edition 3.24 Silberschatz, Galvin and Gagne ©2013
Process Creation (Cont.)
Two possibilities for the address space of the child relative to the
parent:
The child may be an exact duplicate of the parent, sharing the same
program and data segments in memory. Each will have its own PCB,
including program counter, registers, and PID. This is the behavior of the
fork system call in UNIX.
The child process may have a new program loaded into its address
space, with all new code and data segments. This is the behavior of the
spawn system calls in Windows. UNIX systems implement this as a
second step, using the exec system call.

Operating System Concepts – 9th Edition 3.25 Silberschatz, Galvin and Gagne ©2013
Process Creation (Cont.)
Address space
Child duplicate of parent
Child has a program loaded into it
UNIX examples
fork() system call creates new process
exec() system call used after a fork() to replace the
process’ memory space with a new program

Operating System Concepts – 9th Edition 3.26 Silberschatz, Galvin and Gagne ©2013
Process creation
Process creation is achieved through the fork() system call.
The newly created process is called the child process and the
process that initiated it (or the process when execution is started)
is called the parent process.
After the fork() system call, now we have two processes - parent
and child processes.
How to differentiate them? Very simple, it is through their return
values.

Operating System Concepts – 9th Edition 3.27 Silberschatz, Galvin and Gagne ©2013
Process creation (fork())

Operating System Concepts – 9th Edition 3.28 Silberschatz, Galvin and Gagne ©2013
Process creation (fork())

Operating System Concepts – 9th Edition 3.29 Silberschatz, Galvin and Gagne ©2013
Process creation (fork())

Usually after the fork() call, the child process and the parent
process would perform different tasks. If the same task needs to
be run, then for each fork() call it would run 2 power n times,
where n is the number of times fork() is invoked.
In the above case, fork() is called once, hence the output is
printed twice (2 power 1). If fork() is called, say 3 times, then the
output would be printed 8 times (2 power 3). If it is called 5
times, then it prints 32 times and so forth.

Operating System Concepts – 9th Edition 3.30 Silberschatz, Galvin and Gagne ©2013
Operating System Concepts – 9th Edition 3.31 Silberschatz, Galvin and Gagne ©2013
Process Termination

A Process terminates when it finishes executing its last statement and asks
the operating system to delete it using the exit() system call. Typically
returning an int.
Returns status data from child to parent (via wait())
Process’ resources are deallocated by the operating system.
Parent may terminate the execution of children’s processes using the
abort() system call. Some reasons for doing so:
Child has exceeded allocated resources
Task assigned to the child is no longer required
The parent is terminated, and the operating system does not allow a
child to continue if its parent terminates

Operating System Concepts – 9th Edition 3.32 Silberschatz, Galvin and Gagne ©2013
Process Termination

Some operating systems do not allow the child to exist if its parent has
terminated. If a process terminates, then all its children must also be
terminated.
cascading termination. All children, grandchildren, etc. are
terminated.
The termination is initiated by the operating system.
The parent process may wait for the termination of a child process by
using the wait()system call. The call returns status information and
the pid of the terminated process
pid = wait(&status);

Operating System Concepts – 9th Edition 3.33 Silberschatz, Galvin and Gagne ©2013
Wait() System Call
Program for wait() system call which makes the parent process wait for the
child to finish.

Operating System Concepts – 9th Edition 3.34 Silberschatz, Galvin and Gagne ©2013
Wait(&status) System Call

Operating System Concepts – 9th Edition 3.35 Silberschatz, Galvin and Gagne ©2013
Inter-process Communication

Processes executing concurrently in the operating system may be


either independent processes or cooperating processes.
• Independent Processes: They cannot affect or be affected by other
processes executing in the system.
• Cooperating Processes: They can affect or be affected by other
processes executing in the system.
Any process that shares data with other processes is a Cooperating
Process.

Operating System Concepts – 9th Edition 3.36 Silberschatz, Galvin and Gagne ©2013
Inter-process Communication
There are several reasons why cooperating processes are allowed:
Information Sharing
- There may be several processes that need access to the same file.
( e.g., pipelines)
Computation Speedup
- Often a solution to a problem can be solved faster if the problem can be
broken down into sub-tasks to be solved simultaneously.
Modularity
- The most efficient architecture may be to break a system down into
cooperating modules.
Convenience
- Even a single user may be multi-tasking, such as editing, compiling, printing,
and running the same code in different windows.

Operating System Concepts – 9th Edition 3.37 Silberschatz, Galvin and Gagne ©2013
Communications Models
Cooperating processes require an inter-process communication (IPC)
mechanism that will allow them to exchange data and information.
There are two fundamental models of inter-process communication:
1. Shared Memory systems or
2. Message Passing systems

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


Operating System Concepts – 9th Edition 3.38 Silberschatz, Galvin and Gagne ©2013
Communications Models

Operating System Concepts – 9th Edition 3.39 Silberschatz, Galvin and Gagne ©2013
Communications Models
Shared Memory Systems
Shared Memory is faster once it is set up because no system calls are
required, and access occurs at normal memory speeds.
However it is more complicated to set up and 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 systems
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.

Operating System Concepts – 9th Edition 3.40 Silberschatz, Galvin and Gagne ©2013
Shared-Memory Systems
• Inter-process communication using shared
memory requires communicating processes
to establish a region of shared memory.
• Typically, a shared memory region resides
in the address space of the process creating
the shared memory segment.
• Other processes that wish to communicate
using this shared memory segment must
attach it to their address space.
Normally the operating system tries to
prevent one process from accessing
another process’s memory.
Shared memory requires that two or more
processes agree to remove this restriction.

Operating System Concepts – 9th Edition 3.41 Silberschatz, Galvin and Gagne ©2013
Producer-Consumer Problem
Paradigm for cooperating processes, The producer process produces
information that is consumed by a consumer process.
For example, a compiler may produce assembly code that is
consumed by an assembler.
The assembler may produce object modules, which are consumed
by the loader.

Operating System Concepts – 9th Edition 3.42 Silberschatz, Galvin and Gagne ©2013
Producer-Consumer Problem
One solution for the Producer-Consumer Problem uses shared memory.
To allow the producer and consumer to run concurrently, we must have
available a buffer of items that can be filled by the producer and
consumed by the consumer.
This buffer will reside in the region of memory that is shared by the
producer and consumer processes.
A producer can produce one item while the consumer can consume
another item.
The producer and consumer must be synchronized, so the consumer
must not try to consume an item that has not yet been produced.

Operating System Concepts – 9th Edition 3.43 Silberschatz, Galvin and Gagne ©2013
Buffer’s Type
The data is passed via an intermediary buffer, which may be either
unbounded or bounded.

unbounded-buffer: with an unbounded buffer the producer will never


need to wait.

bounded-buffer: With a bounded buffer the producer may have to wait


until there is space available in the buffer

Operating System Concepts – 9th Edition 3.44 Silberschatz, Galvin and Gagne ©2013
Bounded-Buffer

A bounded buffer lets multiple producers and multiple


consumers share a single buffer. Producers write data to the
buffer and consumers read data from the buffer.

•Producers must block if the buffer is full.


•Consumers must block if the buffer is empty.

Operating System Concepts – 9th Edition 3.45 Silberschatz, Galvin and Gagne ©2013
Bounded-Buffer
A bounded buffer with capacity N has can store N data items.
The places used to store the data items inside the bounded buffer
are called slots.
Without proper synchronization, the following errors may occur:
• The producers don’t block when the buffer is full.
• A Consumer consumes an empty slot in the buffer.
• A consumer attempts to consume a slot that is only half-filled
by a producer.
• Two producers write into the same slot.
• Two consumers read the same slot.

Operating System Concepts – 9th Edition 3.46 Silberschatz, Galvin and Gagne ©2013
Bounded-Buffer – Shared-Memory Solution
Shared data
#define BUFFER_SIZE 10
typedef struct {
. . .
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;

In the struct, there is an array value used to store integer values in the buffer and two
integer indexes in and out.
Index in is used to keep track of where to write the next data item to the buffer.
Index out is used to keep track of where to read the next data item from the buffer.

In the example, three data items B, C, and D are currently in the buffer. On the next
write data will be written to index in = 4. On the next read data will be read from index
out = 1.

Operating System Concepts – 9th Edition 3.47 Silberschatz, Galvin and Gagne ©2013
Bounded-Buffer – Producer

item next_produced;
while (true) {
/* produce an item in next produced */
while (((in + 1) % BUFFER_SIZE) == out)
; /* do nothing */
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
}

Operating System Concepts – 9th Edition 3.48 Silberschatz, Galvin and Gagne ©2013
Bounded Buffer – Consumer
item next_consumed;
while (true) {
while (in == out)
; /* do nothing */
next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;

/* consume the item in next consumed */


}

Operating System Concepts – 9th Edition 3.49 Silberschatz, Galvin and Gagne ©2013
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.

IPC facility provides two operations:


send(message)
receive(message)

The message size is either fixed or variable

Operating System Concepts – 9th Edition 3.50 Silberschatz, Galvin and Gagne ©2013
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?

Operating System Concepts – 9th Edition 3.51 Silberschatz, Galvin and Gagne ©2013
Message Passing (Cont.)

Implementation of the communication link


Physical:
Shared memory
 Hardware bus
 Network
Logical:
 Direct or indirect
 Synchronous or asynchronous
 Automatic or explicit buffering

Operating System Concepts – 9th Edition 3.52 Silberschatz, Galvin and Gagne ©2013
Direct Communication
Processes must name each other explicitly:
send (P, message) – send a message to process P
receive(Q, message) – receive a message from process Q
Properties of the communication link
Links are established automatically
A link is associated with exactly one pair of communicating
processes
Between each pair there exists exactly one link
The link may be unidirectional, but is usually bi-directional

Operating System Concepts – 9th Edition 3.53 Silberschatz, Galvin and Gagne ©2013
Indirect Communication

Messages are directed and received from mailboxes (also referred


to as ports)
Each mailbox has a unique id
Processes can communicate only if they share a mailbox
Properties of the communication link
Link established only if processes share a common mailbox
A link may be associated with many processes
Each pair of processes may share several communication links
Link may be unidirectional or bi-directional

Generally, a mailbox is associated with many senders


and receivers. In some systems, only one receiver is (statically)
associated with a particular mailbox; such a mailbox is often called a
port

Operating System Concepts – 9th Edition 3.54 Silberschatz, Galvin and Gagne ©2013
Operating System Concepts – 9th Edition 3.55 Silberschatz, Galvin and Gagne ©2013
Synchronization
Message passing may be either blocking or non-blocking
Blocking is considered synchronous
Blocking send -- the sender is blocked until the message is
received
Blocking receive -- the receiver is blocked until a message is
available
Non-blocking is considered asynchronous
Non-blocking send -- the sender sends the message and
continue
Non-blocking receive -- the receiver receives:
A valid message, or
Null message

Operating System Concepts – 9th Edition 3.56 Silberschatz, Galvin and Gagne ©2013
Buffering

Queue of messages attached to the link.


Implemented in one of three ways
1. Zero capacity – no messages are queued on a link.
The sender must wait for the receiver
2. Bounded capacity – finite length of n messages
The sender must wait if the link full
3. Unbounded capacity – infinite length
Sender never waits

Operating System Concepts – 9th Edition 3.57 Silberschatz, Galvin and Gagne ©2013
File Descriptor
A number to describe an open file or I/O resource in the system.
Unique non-negative integer.
Describes resources and how they can be accessed.
When a process request for a resource:
Kernal grants access (if valid).
Creates an entry in the global file table.
Provides process with the location of that entry.

Operating System Concepts – 9th Edition 3.58 Silberschatz, Galvin and Gagne ©2013
File Descriptor Table

Operating System Concepts – 9th Edition 3.59 Silberschatz, Galvin and Gagne ©2013
File Descriptor Table

Operating System Concepts – 9th Edition 3.60 Silberschatz, Galvin and Gagne ©2013
File Descriptor Table

Operating System Concepts – 9th Edition 3.61 Silberschatz, Galvin and Gagne ©2013
write() / read() System Call
read() and write() system calls are used to read and write data
respectively to a file descriptor.
write():
➢ write() system call is used to write to a file descriptor.
➢ In other words, write() can be used to write to any file in the system
but rather than specifying the file name, you need to specify its file
descriptor.
➢ Syntax for write():

Operating System Concepts – 9th Edition 3.62 Silberschatz, Galvin and Gagne ©2013
write() System Call
Program1: To write some data on the standard output device (by default –
monitor)

Operating System Concepts – 9th Edition 3.63 Silberschatz, Galvin and Gagne ©2013
write() System Call
➢ On success, the write() system call returns the ‘number of bytes written’ i.e.
the count of how many bytes it could write.
➢ This you can save in an integer variable and check.
➢ The write() system call on failure returns -1.

Operating System Concepts – 9th Edition 3.64 Silberschatz, Galvin and Gagne ©2013
read() System Call
The use of the read() system call is to read from a file descriptor.
The working is the same as write(), the only difference is that read()
will read the data from the file pointed to by the file descriptor.

Operating System Concepts – 9th Edition 3.65 Silberschatz, Galvin and Gagne ©2013
read() System Call
Program: To read data from the standard input device and write it on the screen

Operating System Concepts – 9th Edition 3.66 Silberschatz, Galvin and Gagne ©2013
open() system call
In the read/write system call we learned how to read from the
standard input device and how to write to a standard output device.
But normally we would either read from a user-created file or write to
a user-created file.
Hence, the question comes that how to know the file descriptor of
these files because to read or to write the first parameter in the
read()/write() system calls is the file descriptor.
We can use the open() system call to get the file descriptor of any file.

Operating System Concepts – 9th Edition 3.67 Silberschatz, Galvin and Gagne ©2013
• The first parameter is the name of the file that you want to open for
reading/writing.
• The second parameter is the mode in which to open the file i.e., for reading or for
writing.
• For a reading from a file, the flag used is O_RDONLY, for writing O_WRONLY, and for
both reading and writing O_RDWR.

Other commonly used flags are O_CREAT, O_APPEND, O_TRUNC, O_EXCL


On success, the open() system call return the file descriptor of the file.

Operating System Concepts – 9th Edition 3.68 Silberschatz, Galvin and Gagne ©2013
open() system call
Program: Write a program using an open() system call to read the first 10
characters of an existing file “test.txt” and print them on screen.

Operating System Concepts – 9th Edition 3.69 Silberschatz, Galvin and Gagne ©2013
open() system call
To read 10 characters from file “test.txt” and write them into non-existing file
“towrite.txt”

Operating System Concepts – 9th Edition 3.70 Silberschatz, Galvin and Gagne ©2013
dup() system call
Use
dup() system call is used to duplicate a file descriptor. It creates a copy of the
old file descriptor to a new file descriptor. The new file descriptor can be
system-generated or a number of your choice depending upon whether you
use dup() or dup2().

dup() takes the old file descriptor as the input parameter. On success, it
returns the lowest-numbered unused file descriptor as the new file descriptor.
dup2() system call is the same as dup() with the difference that here you can
give the value of a new file descriptor of your own choice. If the new file
descriptor is already open, it is silently closed and then reopened for reuse

Operating System Concepts – 9th Edition 3.71 Silberschatz, Galvin and Gagne ©2013
dup() system call
Program: Program for dup() system call in C to duplicate a file descriptor.

Operating System Concepts – 9th Edition 3.72 Silberschatz, Galvin and Gagne ©2013
dup() system call
Program: Program to use dup2() system call to duplicate a file descriptor.

Operating System Concepts – 9th Edition 3.73 Silberschatz, Galvin and Gagne ©2013
fork() system call
fork() is a system call used to create a new process. The new process is
called the child process and the original process is called the parent
process.
The child process by default is a duplicate of the parent process. By
duplicate, we mean that the child process has the same code as the
parent process but the memory space of both processes is separate.
The syntax of using fork() is :
#include<unistd.h>
pid_t fork(void);
fork() returns -1 on failure; On success, it returns ‘0’ in the child
process and process-id of the child in the parent process.

Operating System Concepts – 9th Edition 3.74 Silberschatz, Galvin and Gagne ©2013
What is the need to duplicate a process?

It may happen that a process is required to do two tasks that are


independent. Since the tasks are to be done by the same process, they
can be executed one after the other only.
Now to do the same task in roughly half the time the process (parent)
creates a new process (child).
One of the task is performed by the parent and the other by the child.
Consider it as a situation where you are supposed to do two tasks and
to complete them in quick time you take the help of your friend who
does one of the tasks for you.
If the same code is run both by the parent and the child then isn’t the
task done twice?
It’s the job of the programmer to write the code in such a manner that
only one of the tasks is done when the parent process runs the code
and the other task is done when the child runs the code.

Operating System Concepts – 9th Edition 3.75 Silberschatz, Galvin and Gagne ©2013
C Program Forking Separate Process

Operating System Concepts – 9th Edition 3.76 Silberschatz, Galvin and Gagne ©2013
Wait() System Call

Operating System Concepts – 9th Edition 3.77 Silberschatz, Galvin and Gagne ©2013
Sleep()

Operating System Concepts – 9th Edition 3.78 Silberschatz, Galvin and Gagne ©2013
Orphan Process
An orphan process is a process whose parent process has
finished or terminated, but the orphan process continues to
execute.
Orphan processes typically get adopted by the init process
(process ID 1 in Unix-like operating systems), which becomes
their new parent.

Operating System Concepts – 9th Edition 3.79 Silberschatz, Galvin and Gagne ©2013
Orphan Process
1. Parent Process Creation: Let's say a parent process (Process
A) creates a child process (Process B) using the fork() system
call.
2. Child Process Execution: Process B starts executing
independently.
3. Parent Process Termination: Suppose Process A terminates
or finishes execution for any reason, while Process B is still
running.
4. Orphaned Child Process: Since Process A was the parent of
Process B, but it terminated before Process B, Process B
becomes an orphan process.
5. Adoption by Init Process: In Unix-like systems, orphan
processes are automatically adopted by the init process
(process ID 1). Init becomes the new parent of the orphan
process.

Operating System Concepts – 9th Edition 3.80 Silberschatz, Galvin and Gagne ©2013
Orphan Process
An orphan process is a process
whose parent has finished.
Suppose P1 and P2 are two
processes such that P1 is the
parent process and P2 is the
child process of P1.
Now, if P1 finishes before P2
finishes, then P2 becomes an
orphan process. In the
following programs, we will
see how to create an orphan
process.

Operating System Concepts – 9th Edition 3.81 Silberschatz, Galvin and Gagne ©2013
Zombie Process

A zombie is a process that has terminated but its entry still


exists in the process table until the parent terminates
normally, or calls wait().
Suppose you create a child process and the child finishes
before the parent process does. If you run the ps command
before the parent gets terminated the output of ps will
show the entry of a zombie process(denoted by defunct ).
This happens because the child is no longer active, but its
exit code needs to be stored in case the parent
subsequently calls to wait.

Operating System Concepts – 9th Edition 3.82 Silberschatz, Galvin and Gagne ©2013
Zombie Process

In order to prevent this use the wait() system call in the parent process.
The wait() system call makes the parent process wait for the child process to change
state.
Operating System Concepts – 9th Edition 3.83 Silberschatz, Galvin and Gagne ©2013
L20: Processes CSE351, Autumn 2017

Understanding fork
Process X (parent) Process Y (child)
pid_t pid = fork(); pid_t pid = fork();
if (pid == 0) { if (pid == 0) {
printf("hello from child\n"); printf("hello from child\n");
} else { } else {
printf("hello from parent\n"); printf("hello from parent\n");
} }

84
L20: Processes CSE351, Autumn 2017

Understanding fork
Process X (parent) Process Y (child)
pid_t pid = fork(); pid_t pid = fork();
if (pid == 0) { if (pid == 0) {
printf("hello from child\n"); printf("hello from child\n");
} else { } else {
printf("hello from parent\n"); printf("hello from parent\n");
} }

pid_t pid = fork(); pid_t pid = fork();


pid = Y pid = 0
if (pid == 0) { if (pid == 0) {
printf("hello from child\n"); printf("hello from child\n");
} else { } else {
printf("hello from parent\n"); printf("hello from parent\n");
} }

85
L20: Processes CSE351, Autumn 2017

Understanding fork
Process X (parent) Process Y (child)
pid_t pid = fork(); pid_t pid = fork();
if (pid == 0) { if (pid == 0) {
printf("hello from child\n"); printf("hello from child\n");
} else { } else {
printf("hello from parent\n"); printf("hello from parent\n");
} }

pid_t pid = fork(); pid_t pid = fork();


pid = Y pid = 0
if (pid == 0) { if (pid == 0) {
printf("hello from child\n"); printf("hello from child\n");
} else { } else {
printf("hello from parent\n"); printf("hello from parent\n");
} }

hello from parent hello from child

Which one appears first?


86
L20: Processes CSE351, Autumn 2017

Fork Example
void fork1() {
int x = 1;
pid_t pid = fork();
if (pid == 0)
printf("Child has x = %d\n", ++x);
else
printf("Parent has x = %d\n", --x);
printf("Bye from process %d with x = %d\n", getpid(), x);
}

❖ Both processes continue/start execution after fork


▪ Child starts at instruction after the call to fork (storing into pid)
❖ Can’t predict execution order of parent and child
❖ Both processes start with x=1
▪ Subsequent changes to x are independent
❖ Shared open files: stdout is the same in both parent and child
87
L20: Processes CSE351, Autumn 2017

Modeling fork with Process Graphs


88
L20: Processes CSE351, Autumn 2017

Fork Example: Possible Output


void fork1() {
int x = 1;
pid_t pid = fork();
if (pid == 0)
printf("Child has x = %d\n", ++x);
else
printf("Parent has x = %d\n", --x);
printf("Bye from process %d with x = %d\n", getpid(), x);
}

x=2 Child Bye


++x printf printf

x=0 Parent Bye


x=1 fork --x printf printf

89
L20: Processes CSE351, Autumn 2017

Peer Instruction Question


❖ Are the following sequences of outputs possible?
Seq 1: Seq 2:
void nestedfork() { L0 L0
printf("L0\n");
if (fork() == 0) { L1 Bye
printf("L1\n"); Bye L1
if (fork() == 0) {
printf("L2\n"); Bye L2
} Bye Bye
}
printf("Bye\n"); L2 Bye
}

90
L20: Processes CSE351, Autumn 2017

exit: Ending a process


❖ void exit(int status)
▪ Exits a process
• Status code: 0 is used for a normal exit, nonzero for an abnormal exit

91
L20: Processes CSE351, Autumn 2017

wait: Synchronizing with Children


void fork_wait() {
int child_status;

if (fork() == 0) {
printf("HC: hello from child\n");
exit(0);
} else {
printf("HP: hello from parent\n");
wait(&child_status);
printf("CT: child has terminated\n");
}
printf("Bye\n");
} forks.c
HC exit
printf
Feasible output: Infeasible output:
HC HP
CT HP CT
HP Bye CT Bye
fork printf wait printf Bye HC
92
L20: Processes CSE351, Autumn 2017

Example: Two consecutive forks


Bye
void fork2() { printf
printf("L0\n"); L1 Bye
fork(); printf fork printf
printf("L1\n"); Bye
fork(); printf
printf("Bye\n");
} L0 L1 Bye
printf fork printf fork printf

Feasible output: Infeasible output:


L0 L0
L1 Bye
Bye L1
Bye Bye
L1 L1
Bye Bye
Bye Bye
93
L20: Processes CSE351, Autumn 2017

Example: Three consecutive forks


❖ Both parent and child can continue forking

void fork3() { Bye


printf("L0\n"); L2 Bye
fork(); Bye
printf("L1\n"); L1 L2 Bye
fork();
Bye
printf("L2\n");
L2 Bye
fork();
printf("Bye\n"); Bye
} L0 L1 L2 Bye

94
L20: Processes CSE351, Autumn 2017

replace process image using execl( )

95
L20: Processes CSE351, Autumn 2017

Excel()

96
L20: Processes CSE351, Autumn 2017

Excel()

97
L20: Processes CSE351, Autumn 2017

Execl System Call

98
Pipes
Acts as a pipe allowing two processes to communicate
Pipes represent a channel for Interprocess Communication(IPC)
Issues:
Is communication unidirectional or bidirectional?
In the case of two-way communication, is it half or full-duplex?
Must there exist a relationship (i.e., parent-child) between the
communicating processes?
Can the pipes be used over a network?
Ordinary pipes – cannot be accessed from outside the process that
created it. Typically, a parent process creates a pipe and uses it to
communicate with a child process that it created.
Named pipes – can be accessed without a parent-child relationship.

Operating System Concepts – 9th Edition 3.99 Silberschatz, Galvin and Gagne ©2013
Ordinary Pipes

Ordinary Pipes allow communication in a standard producer-


consumer style.
Producer writes to one end (the write-end of the pipe)
Consumer reads from the other end (the read-end of the pipe)
Ordinary pipes are therefore unidirectional
Require a parent-child relationship between communicating
processes.

Operating System Concepts – 9th Edition 3.100 Silberschatz, Galvin and Gagne ©2013
Ordinary Pipes (pipe System Call)

pipe() function creates a unidirectional pipe for IPC.


On success, it return two file descriptors pipefd[0] and pipefd[1].
pipefd[0] is the reading end of the pipe. So, the process which will receive the
data should use this file descriptor.
pipefd[1] is the writing end of the pipe. So, the process that wants to send the
data should use this file descriptor.

Operating System Concepts – 9th Edition 3.101 Silberschatz, Galvin and Gagne ©2013
Ordinary Pipes (pipe System Call)

Operating System Concepts – 9th Edition 3.102 Silberschatz, Galvin and Gagne ©2013
Ordinary Pipes (pipe System Call)

Operating System Concepts – 9th Edition 3.103 Silberschatz, Galvin and Gagne ©2013
Ordinary Pipes (Features)

Features of Pipes
As a rule, one process will write to the pipe (as if it
were a file), while another process will read from the
pipe.
Data is written to one end of the pipe and read from
the other end.
A pipe exists until both file descriptors are closed in
all processes

Operating System Concepts – 9th Edition 3.104 Silberschatz, Galvin and Gagne ©2013
Named Pipes

Named Pipes are more powerful than ordinary pipes.


Communication is bidirectional.
No parent-child relationship is necessary between the communicating
processes
Several processes can use the named pipe for communication
Provided on both UNIX and Windows systems

Operating System Concepts – 9th Edition 3.105 Silberschatz, Galvin and Gagne ©2013
Communications in Client-Server Systems

Sockets
Remote Procedure Calls
Pipes
Remote Method Invocation (Java)

Operating System Concepts – 9th Edition 3.106 Silberschatz, Galvin and Gagne ©2013
Sockets

A socket is defined as an endpoint for communication.


A pair of processes communicating over a network employ a pair of
sockets – one for each process.
A socket is identified by an IP address concatenated with a port number.
The server waits for incoming client requests by listening to a specified
port. Once a request is received, the server accepts a connection from
the client socket to complete the connection.
Servers implementing specific services (such as telnet, FTP, HTTP)
listen to well-known ports (a telnet server listens to port 23, an FTP
server listens to port no 21, and a web or HTTP, server listens to port
80).
All ports below 1024 are considered well-known; we can use them to
implement standard services.

Operating System Concepts – 9th Edition 3.107 Silberschatz, Galvin and Gagne ©2013
Socket Communication

Operating System Concepts – 9th Edition 3.108 Silberschatz, Galvin and Gagne ©2013
End of Chapter 3

Operating System Concepts – 9th Edition Silberschatz, Galvin and Gagne ©2013

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy