0% found this document useful (0 votes)
12 views65 pages

Lec03 SOFE3950 Processes

The document discusses the concept of processes in operating systems, including their scheduling, creation, termination, and interprocess communication. It covers the structure and states of processes, the role of the Process Control Block (PCB), and the mechanisms for process creation and termination. Additionally, it explains interprocess communication methods such as shared memory and message passing, along with examples like the producer-consumer problem.

Uploaded by

asah
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)
12 views65 pages

Lec03 SOFE3950 Processes

The document discusses the concept of processes in operating systems, including their scheduling, creation, termination, and interprocess communication. It covers the structure and states of processes, the role of the Process Control Block (PCB), and the mechanisms for process creation and termination. Additionally, it explains interprocess communication methods such as shared memory and message passing, along with examples like the producer-consumer problem.

Uploaded by

asah
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/ 65

Operating Systems

Lecture 03

Processes

Dr. Khalid A. Hafeez

Ontario Tech University logo


Processes
• Process Concept
• Process Scheduling
• Operations on Processes
• Interprocess Communication
• Examples of IPC Systems
• Communication in Client-Server Systems

2
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
• To explore interprocess communication using shared memory and message passing
• To describe communication in client-server systems

3
Process Concept
• An operating system executes a variety of programs:
• Batch system: executes jobs (programs ) on a computer without manual intervention
• Time-shared systems: executes user programs or tasks at the same time
• the terms job and process are used interchangeably

• Process: it is a program in execution;


• process execution must progress in sequential fashion

• The process has multiple parts other than the code:


• 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 containing memory dynamically allocated during run time
Process in Memory

4
Process Concept
• Program is a passive entity stored on disk (executable file), but the process is an active entity with program
counter (PC) pointing to the next instruction o be executed
• Program becomes process when its executable file is loaded into memory

• Execution of program can be started via:


• GUI mouse clicks, or
• command line entry of its name, etc

• One program can be of several processes


• Consider multiple users executing the same program
• Or a user invoking many copies of the web browser

5
Process Concept
• Process State
• A process may be in one of the following states during execution:
• New: The process is being created
• Running: Instructions are being executed
• Waiting: The process is waiting for some event to occur (such as an I/O completion or reception of
a signal).
• Ready: The process is waiting to be assigned to a processor
• Terminated: The process has finished execution

6
Process Concept
• Process Control Block (PCB)
• Each process is represented in the OS by a process control block (PCB),
that contains:
• Process state: ready, running, waiting, etc
• Program counter: location of next instruction to be executed
• 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: amount of CPU used, clock time elapsed
since start, time limits, process numbers
• I/O status information: list of I/O devices allocated to the process, list
of open files

7
Process Concept
• Threads
• So far, a process is a program that performs a single thread of execution.
• Most OSes allow a process to have multiple threads of execution and thus to perform more than one task
at a time.
• It is beneficial on multicore systems, where multiple threads can run in parallel.
• Consider having multiple program counters per process
• Then multiple locations can execute at once
• Multiple threads of control -> threads
• The PCB is expanded to include information for each thread, such as multiple program counters

8
Process Concept
• Process Representation in Linux
Represented by the C structure task_struct stored in <linux/sched.h> that has many field, some of them are:

pid_t pid; /* process identifier */


long state; /* state of the process */
unsigned_int time_slice /* scheduling information */
struct task_struct *parent; /* this process’s parent */
struct list_head children; /* this process’s children */
struct files_struct *files; /* list of open files */
struct mm_struct *mm; /* address space of this process*/

9
Process Scheduling
• The objective of multiprogramming is to have some process
always running to maximize CPU utilization.
• The objective of time sharing is to switch the CPU among
processes
• For a single-processor system, there will never be more than
one running process.

I/O device queues


• Process scheduler selects among available processes for next
execution on CPU
• 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 Ready Queue And Various I/O Device Queues
• Device queues: set of processes waiting for an I/O device
• Each device has its own device queue
• Processes migrate among the various queues

10
Process Scheduling
Queueing diagram: is a common representation of process scheduling
• Each rectangular box represents a queue
• The circles represent the resources that serve the queues,
• The arrows indicate the flow of processes in the system.
• A new process is initially put in the ready queue. It waits there until it is selected for execution, one of
several events could occur while executing:
• The process issues an I/O request, then placed in an I/O queue.
• The process creates a new child process, wait for the child’s termination.
• The process is removed from the CPU, because of an interrupt.

11
Process Scheduling
• Schedulers
• Short-term scheduler (or CPU scheduler): selects which process from ready processes should be
executed next and allocates CPU
• Sometimes it is 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 (the number of processes in
memory).

• 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

• The long-term scheduler should select a good process mix of I/O-bound and CPU-bound processes.

12
Process Scheduling
Time-sharing operating systems may introduce an additional, intermediate level of scheduling
Medium-term scheduler can be added if degree of multiple programming needs to decrease
Remove process from memory, store it on disk, bring it back in from disk to continue execution: this
is called swapping
Swapping may be necessary to improve the process mix, or the memory is been overused

13
Process Scheduling
• 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 is represented in its PCB
• Context-switch time is an 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 ➔ context switch requires
changing the pointer to the current register
set

14
Process Scheduling
• Multitasking in Mobile Systems
• Some mobile systems (e.g., early version of iOS) allow only one process to run, others are suspended
• Apple now provides a limited form of multitasking for user applications:
• Single foreground process- controlled via user interface
• Multiple background processes– in memory, running, but not on the display, and with limits
• Limits include single, short task, receiving notification of events, specific long-running tasks
like audio playback

• Android runs foreground and background, with fewer limits


• Background process uses a service to perform tasks
• Service can keep running even if background process is suspended
• Service has no user interface, hence small memory use

15
Operations on Processes
• Operating system must provide mechanisms for:
• process creation,
• process termination,

• The processes in most systems can execute concurrently, and they may be created and deleted dynamically

16
Operations on Processes
• Process Creation
• Parent process create children processes, which, in turn create other processes, forming a tree of
processes
• Generally, process identified and managed via a process identifier (pid)
• A Tree of Processes in Linux
• The init process (which always has a pid = 1) serves as the root parent process for all user processes
• Use command ps –el to list all active processes in the system

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
Operations on Processes
Process Creation
Resource sharing options
 A child process may obtain its resources directly from the OS,

 A child process may share subset of parent’s resources


– This prevents any process from overloading the system by creating too many child processes

When a process creates a new process, two possibilities for execution exist:
1. The parent continues to execute concurrently with its children.

2. The parent waits until some or all its children have terminated.

There are also two address-space possibilities for the new process:
1. The child process is a duplicate of the parent process (it has the same program and data as the
parent).
2. The child process has a new program loaded into it.

18
Operations on Processes
Process Creation - UNIX examples
fork(): system call is for creating a new process
 The new process consists of a copy of the address space of the original process.

 Both processes (the parent and the child) continue execution at the instruction after the fork(), with
one difference:
– The return code for the fork() is pid=0 for the new (child) process, whereas the (pid >0) of the
child is returned to the parent.

exec(): system call which is used after a fork() to replace the process’s memory space with a new
program
 So, the two processes can communicate and then go their separate ways.

 The parent can then create more children; or, if it may issue a wait() system call to move itself off
the ready queue until the termination of the child

19
Operations on Processes
• C Program Forking Separate Process

20
Operations on Processes
• Creating a Separate Process via Windows API

21
Operations on Processes
• Process Termination
• Process executes last statement and then asks the operating system to delete it using the exit() system call.
• Returns status data from child to parent (via wait())
• Process’ resources are deallocated by the operating system
• 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

22
Operations on Processes
• Process Termination
• Some OSes do not allow a child to exists if its parent has terminated. If a process terminates, then all its
children must also be terminated.
• This termination is initiated by the operating system and called cascading termination
• The parent process may wait for 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);
• When a process terminates, its resources are deallocated by the OS.
• But, its entry in the process table must remain there until the parent calls wait().
• If the parent did not invoke wait(), the process is called a zombie
• If parent terminated without invoking wait(), process is an orphan
• The init process becomes the parent and issues wait() periodically to clear the orphans

23
Multiprocess Architecture – Chrome Browser
• Many web browsers run as a single process (some still do)
• If one web site causes trouble, entire browser will hang or crash

• Google Chrome Browser is a multiprocess with 3 types of processes:


• Browser process manages user interface, disk and network I/O
• Only one browser process is created when Chrome is started
• Renderer process renders web pages, deals with HTML, Javascript. A new renderer process is created
for each website opened in a new tab
• Runs in sandbox restricting access to disk and network I/O, minimizing the effect of any security
exploits
• Plug-in process is created for each type of plug-in (Flash, or QuickTime) in use.
• Advantage: websites run in isolation from one another. If one website crashes, only its renderer process is
affected

24
Interprocess Communication
• Processes within a system may be independent or cooperating
• Independent process cannot affect or be affected by the execution of another
• Cooperating process (sharing data with other processes) can affect or be affected by other processes

• Reasons for cooperating processes:


• Information sharing (e.g. shared file)
• Computation speedup: break the task into multiple tasks, but you need a multicore processor.
• Modularity: divide the system functions into separate processes or threads
• Convenience: a user may work on many tasks at the same time
• may be editing, listening to music, and compiling in parallel.

25
Interprocess Communication
• Communications Models
• Two interprocess communication (IPC) mechanisms are available to the cooperating processes to allow
them exchange data and information:
• Shared memory: System calls only needed for creating the shared memory → fast
• Message passing: System calls are needed for every exchanged message → slow

Message passing. shared memory.


26
Interprocess Communication
• Shared-Memory Systems
• An area of memory shared among the processes that wish to communicate
• Typically, a shared-memory region resides in the address space of the process creating it.
• Other processes must attach it to their address space
• The communication is under the control of the users processes not the operating system.
• System calls are required only to establish shared memory regions
• Major issues is to provide a mechanism that will allow the user processes to synchronize their
actions when they access the shared memory.

27
Interprocess Communication
• Shared-Memory Systems - Producer-Consumer Problem
• It is a common paradigm for cooperating processes,
• 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
• To allow producer and consumer processes to run concurrently, we must have available a buffer of
items that can be filled by the producer and emptied by the consumer.
• Two types of buffers can be used:
• unbounded-buffer places no practical limit on the size of the buffer
• The consumer may have to wait for new items, but the producer can always produce new
items
• bounded-buffer assumes that there is a fixed buffer size
• The consumer must wait if the buffer is empty, and the producer must wait if the buffer is
full.

28
Interprocess Communication
• Bounded-Buffer – Shared-Memory Solution
• The shared buffer is implemented as a circular array with two logical pointers: in and out.
• The following variables reside in a region of memory shared by the producer and consumer processes:
• The variable in points to the next free position in the buffer; out points to the first full position in the
buffer.
• The buffer is empty when in ==out;
• The buffer is full when ((in + 1) % BUFFER SIZE) == out.
#define BUFFER_SIZE 10
typedef struct {
...
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
• Solution is correct, but can only use BUFFER_SIZE-1 elements

29
Interprocess Communication
• Bounded-Buffer – Shared-Memory Solution
• Producer code
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;
}
• Consumer code
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 */
}

30
Examples of IPC Systems - POSIX
• Several IPC mechanisms are available for POSIX systems,
• shared memory and message passing
• POSIX shared memory is organized using memory-mapped files, which associate the region of shared memory
with a file
• POSIX Shared Memory
• Process first creates shared memory segment
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
• Also used to open an existing segment to share it

• Set the size of the object to 4K


• ftruncate(shm_fd, 4096);
• Memory map it
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
Addr: starting address if null, then the kernel decides where to put the memory
Offset: from where to start using it

• Now the process could write to the shared memory


• sprintf(shared_memory, "Writing to shared memory"); 31
Examples of IPC Systems - POSIX
• IPC POSIX Producer

32
Examples of IPC Systems - POSIX
• IPC POSIX Consumer

33
Interprocess Communication: Message-Passing

• Message-Passing Systems
• Mechanism provided by the OS for processes to communicate and to synchronize their actions without
sharing the same address space
• It is useful in a distributed environment, where the communicating processes may reside on different
computers connected by a network.
• For example, an Internet chat program
• Message system: processes communicate with each other without resorting to shared variables
• Problem : slow since all messages should go through the kernel
• Message-passing facility provides at least two operations:
• send(message)
• receive(message)

• The message size is either fixed or variable

34
Interprocess Communication: Message-Passing
• If processes P and Q wish to communicate, they need to:
• Establish a communication link between them
• Exchange messages via send/receive operations

• 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?

35
Interprocess Communication: Message-Passing
• Implementation of communication link
• Physical implementation:
• Shared memory
• Hardware bus
• Network
• Logical implementation issues:
• Direct or indirect communication
• Synchronous or asynchronous communication
• Automatic or explicit buffering

• To solve these issues, the OS should provide mechanisms for naming process, synchronizing their
actions, and buffering

36
Interprocess Communication: Message-Passing
• Naming: Processes that want to communicate must have a way to refer to each other. They can use either
direct or indirect communication
• In 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 in this scheme:
• Links are established automatically: each process need to know only each other identity to
communicate
• 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 it is usually bi-directional

37
Interprocess Communication: Message-Passing

In indirect communication
Messages are sent and received from mailboxes (also know by ports)
 Each mailbox has a unique id

 Processes can communicate only if they share a mailbox

The send() and receive() primitives are defined as follows:


 send(A, message): Send a message to mailbox A.

 receive(A, message): Receive a message from mailbox A.

Properties of the communication link in this scheme:


 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, with each link corresponding to one
mailbox
 Link may be unidirectional or bi-directional

38
Interprocess Communication: Message-Passing

• A mailbox that is owned by the operating system is independent and is not attached to any
particular process.
• The operating system then must provide a mechanism that allows a process to do the
following:
• Create a new mailbox (port)
• Send and receive messages through mailbox
• Delete a mailbox

• The process that creates a new mailbox is its owner and is the only one that can receive
messages through this mailbox.
• However, the ownership and receiving privilege may be passed to other processes
through appropriate system calls.

39
Interprocess Communication: Message-Passing
• Mailbox sharing
• Suppose that processes P1, P2, and P3 share mailbox A
• P1, sends; and P2 and P3 receive
• Who will get the message?
• It depends on which of the following solutions is implemented:
• Allow a link to be associated with at most two processes
• Allow only one process at a time to execute a receive operation
• Allow the system to select arbitrarily the receiver (e.g. round robin). Sender is notified who the
receiver was.

40
Interprocess Communication: Message-Passing

• Synchronization
• There are many design options for implementing send() and receive() primitives:
• Message passing may be either blocking or non-blocking
• Blocking is considered synchronous
• Blocking send: sender is blocked until the message is received
• Blocking receive: receiver is blocked until a message is available
• Non-blocking is considered asynchronous
• Non-blocking send: sender sends the message and resumes operation
• Non-blocking receive: the receiver receives either a valid message, or null message
• Different combinations from blocking and non-blocking are possible
• If both send and receive are blocking, we have a rendezvous between the sender and the receiver.

41
Interprocess Communication: Message-Passing

• Synchronization
• The solution to producer-consumer problem becomes trivial when using blocking send() and receive()

• The producer process using message passing.


message next_produced;
while (true) {
/* produce an item in next produced */
send(next_produced);
}

• The consumer process using message passing.


message next_consumed;
while (true) {
receive(next_consumed);

/* consume the item in next consumed */


}
42
Interprocess Communication: Message-Passing

• Buffering
• Whether communication is direct or indirect, messages exchanged by communicating processes reside in
a temporary queue. Which can be implemented in three ways:
1. Zero capacity: no messages are queued on a link.
• Sender must wait (block) for receiver to receive (rendezvous)
2. Bounded capacity: queue has finite length of n messages
• Sender must wait if link is full, otherwise can resume operation
3. Unbounded capacity: queue with infinite length,
• Sender never waits (blocks)

43
Examples of IPC Systems - POSIX
• Two processes communicate using message queues. The first, clientA.c adds messages to the message queue,
and clientB.c retrieves them. if ((key = ftok(“clientA.c", 'B')) == -1) {
/* clientA.c -- writes to a perror("ftok");
message queue */ exit(1);
#include <stdio.h> }
#include <stdlib.h> if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
#include <errno.h> perror("msgget");
#include <string.h> exit(1);
#include <sys/types.h> }
#include <sys/ipc.h> printf("Enter lines of text, ^D to quit:\n");
#include <sys/msg.h> while (fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL){
int len = strlen(buf.mtext);
struct my_msgbuf { /* ditch newline at end, if it exists */
char mtext[200]; if (buf.mtext[len - 1] == '\n')
}; buf.mtext[len - 1] = '\0';
if (msgsnd(msqid, &buf, len + 1, 0) == -1) /* +1 for '\0' */
int main(void){ perror("msgsnd");
struct my_msgbuf buf; }
int msqid; if (msgctl(msqid, IPC_RMID, NULL) == -1) {
key_t key; perror("msgctl");
exit(1);
}
return 0;
} 44
Examples of IPC Systems - POSIX
/* clientB.c -- reads int main(void){
from a message queue struct my_msgbuf buf;
*/ int msqid;
#include <stdio.h> key_t key;
if ((key = ftok(“clientA.c", 'B')) == -1) {/* same key as clientA.c */
#include <stdlib.h> perror("ftok");
#include <errno.h> exit(1);
#include <sys/types.h> }
#include <sys/ipc.h> if ((msqid = msgget(key, 0644)) == -1) {/* connect to the queue */
#include <sys/msg.h> perror("msgget");
exit(1);
struct my_msgbuf { }
long mtype; printf(“clientB: ready to receive messages, captain.\n");
for (;;) { /* clientB never quits! */
char mtext[200]; if (msgrcv(msqid, &buf, sizeof buf.mtext, 0, 0) == -1) {
}; perror("msgrcv");
exit(1);
}
printf(“clientB: \"%s\"\n", buf.mtext);
}
return 0;
}

45
Communications in Client-Server Systems
• The shared memory and message passing can be used for communication in client–server systems
• There are other strategies for communication in client–server systems
• Sockets
• Remote Procedure Calls
• Pipes
• Remote Method Invocation (Java)

46
Communications in Client-Server Systems
• Sockets
• A socket is defined as an endpoint for communication
• A pair of processes communicating over a network employs a pair of sockets
• It is identified by the concatenation of IP address and port which is a number included at start of message
packet to differentiate network services on a host
• The socket 161.25.19.8:1625 refers to port 1625 on host 161.25.19.8

• Communication consists between a pair of sockets


• All connections must be unique
• All ports below 1024 are well known, used for standard services
• FTP server listens to port 21; a web, or HTTP, server listens to port 80
• Special IP address 127.0.0.1 (loopback) to refer to system on which the process is running

47
Communications in Client-Server Systems
Sockets
Sockets use a client–server architecture: The server waits for incoming client requests by listening to a
specified port
When a client process initiates a request for a connection, it is assigned a port (>1024) by its host
computer.
Example:
 If a client on host X with IP address 146.86.5.20 wishes to establish a connection with a web server
(which is listening on port 80) at address 161.25.19.8, host X may be assigned port 1625.
 The connection consists of a pair of sockets: (146.86.5.20:1625) on host X and (161.25.19.8:80) on
the web server.

socket
(146.86.5.20:1670)

• The packets are delivered to the appropriate process


based on the destination port number.

48
Communications in Client-Server Systems
• Sockets in Java
• Three types of sockets
• Connection-oriented (TCP): implemented with the Socket class
• Connectionless (UDP): use the DatagramSocket class
• MulticastSocket class: is a subclass of the DatagramSocket class.
• It allows data to be sent to multiple recipients

• Example:
• Date server that uses connection-oriented TCP sockets.
• The operation allows clients to request the current date and time from the server.

49
Communications in Client-Server Systems
• Sockets in Java
• This is a “Date” server that allows clients
to request the current date and time from
the server.
• The server creates a ServerSocket that
specifies that it will listen to port 6013.
• The server then begins listening to the port
with the accept() method.
• The server blocks on the accept() method
waiting for a client to request a connection.
• When a connection request is received,
accept() returns a socket that the server can
use to communicate with the client.

50
Communications in Client-Server Systems
• Sockets in Java
• This is the “Date” client that
communicates with the server by
creating a socket and connecting to the
port on which the server is listening.
• The client creates a Socket and requests
a connection with the server at IP
address 127.0.0.1 on port 6013.
• Once the connection is made, the client
can read from the socket using normal
stream I/O statements.
• Close the connection

51
Communications in Client-Server Systems
• Remote Procedure Calls (RPC)
• RPC abstracts procedure calls between processes on networked systems
• It uses ports for service differentiation
• Each message is addressed to an RPC daemon listening to a port
• A port is a number included at the start of a message packet
• The system has one IP address and many ports
• RPC allows a client to invoke a procedure on a remote host as it would invoke a procedure locally
• The RPC system hides the details that allow communication to take place by providing a stub on the
client side.
• When the client invokes a remote procedure, the RPC system calls the appropriate stub
• The client-side stub locates the server and marshalls the parameters so they can be transmitted over
a network
• The server-side stub receives this message, unpacks the marshalled parameters, and performs the
procedure on the server
• If needed, result will be returned to the client using the same technique

52
Communications in Client-Server Systems
Remote Procedure Calls (RPC)
There could be differences in data representation on the client
and server machines, such as Big-endian and little-endian
Therefore, parameter marshalling will represent the data as
External Data Representation (XDL) format to account for
different architectures
 On the other side the parameters will be unmarshalled from
XDL to machine dependent format for the server
Remote communication has more failure scenarios than local
(due to network errors)
 Messages should be acted upon exactly once rather than at most
once. So, Implement a timestamp and an acknowledgement
Another issue: is how the client knows the port at the server:
 OS typically provides a rendezvous (or matchmaker) service to
connect client and server
 A client then sends a message containing the name of the RPC to
the rendezvous daemon requesting the port address of the RPC it
needs to execute. 53
Communications in Client-Server Systems
• Pipes
• Acts as a conduit allowing two processes to communicate
• In implementing a pipe, four issues must be considered:
• Is communication unidirectional or bidirectional?
• In the case of two-way communication, is it half or full-duplex?
• Must there exist a relationship (such as, parent-child) between the communicating processes?
• Can the pipes be used over a network?

• Two common types of pipes used on both UNIX and Windows systems:
• 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.

54
Communications in Client-Server Systems
• Ordinary Pipes
• Ordinary Pipes allow communication in 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
• If two-way communication is required, two pipes must be used, with each pipe sending data in a different
direction.
• They require parent-child relationship between communicating processes
• Therefore, these pipes can be used only between processes on the same machine
• Pipes will be deleted from the system if their processes are terminated
• Windows calls these anonymous pipes

55
Communications in Client-Server Systems
▪ Ordinary Pipes
▪ On UNIX systems, ordinary pipes are constructed using the function: pipe(int fd[])
▪ It creates a pipe that is accessed through the int fd[] file descriptors: fd[0] is the read-end of the
pipe, and fd[1] is the write-end.
▪ pipes can be accessed by read() and write() system calls just like files
#include <sys/types.h> if (pid < 0) { /* error occurred */
#include <stdio.h> fprintf(stderr, "Fork Failed");
#include <string.h> return 1;
#include <unistd.h> }
#define BUFFER_SIZE 25 if (pid > 0) { /* parent process */
#define READ_END 0 /* close the unused end of the pipe */
#define WRITE_END 1 close(fd[READ_END]);
int main(void) /* write to the pipe */
{ write(fd[WRITE_END], write_msg, strlen(write_msg)+1);
char write_msg[BUFFER_SIZE] = "Greetings"; /* close the write end of the pipe */
char read_msg[BUFFER_SIZE]; close(fd[WRITE_END]);
int fd[2]; }
Pid_t pid; else { /* child process */
/* create the pipe */ /* close the unused end of the pipe */
if (pipe(fd) == -1) { close(fd[WRITE_END]);
fprintf(stderr,"Pipe failed"); /* read from the pipe */
return 1; read(fd[READ_END], read_msg, BUFFER_SIZE);
} printf("read %s",read_msg);
/* fork a child process */ /* close the write end of the pipe */
pid = fork(); close(fd[READ_END]);
}
return 0;}
56
Communications in Client-Server Systems
• Named Pipes are more powerful than ordinary pipes: bidirectional and can be used by several processes
• No parent-child relationship is necessary between the communicating processes
• Provided on both UNIX and Windows systems
• On UNIX referred to as FIFOs.
• Once created, they appear as typical files in the file system.
• They will continue to exist even if the processes have terminated until they are explicitly deleted
from the file system
• A FIFO is created with the mkfifo() system call and manipulated with the ordinary open(), read(),
write(), and close() system calls.
• They are half-duplex. For full duplex use two FIFOs
• Can be used in the same machine only, otherwise use sockets for inter machine communication
• Example: ls | more
• Setting up a pipe ( | ) between the ls and more commands (which are running as individual
processes)
• The ls command serves as the producer, and its output is consumed by the more command

57
Communications in Client-Server Systems
• Named Pipes
• On Windows:
• Full-duplex communication is allowed, and the communicating processes may reside on either the
same or different machines.
• created with the CreateNamedPipe() function, and a client can connect to a named pipe using
ConnectNamedPipe().
• Communication over the named pipe can be accomplished using the ReadFile() and WriteFile()
functions.
• Example: dir | more

58
Exercises: Q1
• How many processes are created?
#include <stdio.h>
#include <unistd.h>
int main(){
/* fork a child process */
fork();
/* fork another child process */
fork();
/* and fork another */
fork();

return 0;
}

59
Exercises: Q2
• How many processes are created?
#include <stdio.h>
#include <unistd.h>
int main(){
int i;
for (i = 0; i < 4; i++)
fork();
return 0;
}

60
Exercises: Q3
• what will be the output at LINE A.
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int value = 5;
int main(){
pid_t pid;
pid = fork();
if (pid == 0) { /* child process */
value += 15;
return 0;
}
else if (pid > 0) { /* parent process */
wait(NULL);
printf("PARENT: value = %d", value); /* LINE A */
return 0;
}
}
61
Exercises: Q4
• How many unique processes will be created? Assuming that the system will generate process IDs sequentially starting
from 1000. what will be the output on the screen?
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int num = 15;
int main(){
pid_t pid1, pid2;
int status =0;
pid1 = fork(); /* assume fork not failed, if failed then pid1=-1*/
if (pid1 == 0) { /* child process */
num += 10;
printf("Process ID = %d %d \n", (int)getpid(), num);
}
else { /* parent process */
num -= 5;
wait(NULL);
printf("Process ID = %d %d \n", (int)getpid(), num);
}
pid2 = fork();
if (pid2 == 0) { /* child process */
num += 20;
printf("Process ID = %d %d \n", (int)getpid(), num);
}
else { /* parent process */
num -= 15;
wait(NULL);
printf("Process ID = %d %d \n", (int)getpid(), num);
}
return 0;
} 62
Exercises: Q4: Solution
#include <sys/types.h>
p(1000)
#include <stdio.h>
c(1001)
#include <unistd.h>
num = 15 fork()
#include <sys/wait.h>
num = 15
int num = 15;
(1)
int main(){
pid1=1001 c(1002)
pid_t pid1, pid2;
pid1= 0
int status =0; num = 25
pid1 = fork(); /* assume fork not failed, if failed then pid1=-1*/
num = 15-5=10
if (pid1 == 0) { /* child process */
num = 15+10=25
num += 10; (4)
fork() pid2 = 0
printf("Process ID = %d %d \n", (int)getpid(), num);
waiting num =
}
pid2 = 1002 (2)
else { /* parent process */ (5) fork() num = 25-15=10 25+20=45
num -= 5;
pid2 = 1003 (3)
wait(NULL);
waiting
num = 10-15=-5 return
printf("Process ID = %d %d \n", (int)getpid(), num);
}
waiting
pid2 = fork(); c(1003) return
if (pid2 == 0) { /* child process */
num += 20; num = 10 screen
printf("Process ID = %d %d \n", (int)getpid(), num);
} Process ID = 1001 num = 25
else { /* parent process */ pid2 = 0 Process ID = 1002 num = 45
num -= 15;
(6)
num = 10+20=30 Process ID = 1001 num = 10
wait(NULL);
printf("Process ID = %d %d \n", (int)getpid(), num); Process ID = 1000 num = 10
} return
return 0; Process ID = 1003 num = 30
} Process ID = 1000 num = -5
Exercises: Q5
• How many unique processes will be created? Assume that the system will generate process IDs sequentially starting from
1000. what will be the output on the screen?
int main(){
int num = 20;
pid_t pid1, pid2;
int status =0;
pid1 = fork(); /* assume fork not failed, if failed then pid1=-1*/
printf("Process ID = %d %d \n", (int)getpid(), num+5);
if (pid1 == 0) { /* child process */
num += 40;
printf("Process ID = %d %d \n", (int)getpid(), num);
}
else { /* parent process */
num -= 10;
wait(NULL);
printf("Process ID = %d %d \n", (int)getpid(), num);
}
return 0;
} 64
Exercises: Q6
• How many unique processes will be created? Assume that the system will generate process IDs sequentially starting from
1000. what will be the output on the screen?
int main(){
int num = 20;
pid_t pid1, pid2;
int status =0;
pid1 = fork(); /* assume fork not failed, if failed then pid1=-1*/
printf("Process ID = %d %d \n", (int)getpid(), num+5);
pid2 = fork();
printf("Process ID = %d %d \n", (int)getpid(), num +10);

if (pid2 == 0) { /* child process */


num += 40;
printf("Process ID = %d %d \n", (int)getpid(), num);
}
else { /* parent process */
num -= 10;
wait(NULL);
printf("Process ID = %d %d \n", (int)getpid(), num);
}
return 0;
}

65

You might also like