PE-1 (Unix Programming) - Unit - 5 IPC

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 52

PE-1 (Unix Programming)

Unit – V
IPCs

Sandeep Singh Rawat

Department of Computer Science & Engineering


Anurag University, Hyderabad, India

https://sites.google.com/view/sandeeprawat
Agenda

• Introduction to IPC, Pipe & FIFOs


• IPCs/Processes on single computer & different systems
• Types of IPC –
• Message queues
• Semaphores
• Shared Memory
• Unix V APIs message passing, semaphore, & shared memory
• Kernel supports for message passing, semaphore, & shared memory
• Related examples.

07/21/2021
Introduction to IPC

07/21/2021
Inter Process Communication
• The communication of more one process with another process is
known as the inter process communication.
set processes may be involved in the inter process communication,
where they communicate and exchange information among them.

• IPC is categorized into various forms pipes,FIFOs, message


queues, semaphores, and shared memory.

07/21/2021
IPC between process on a single computer system
IPC between process on a single computer system is referred as Local
IPC.

This can exist between one or more processes on a single host. Examples
of the mechanisms of Local IPC are:
signals, pipes (unnamed, named, and STREAM pipes), shared memory,
message queues, semaphores, UNIX-domain sockets, file/record
locking, memory-mapped files. Signals are nothing but software
interrupts.

07/21/2021
Pipes allow for half-duplex (uni-directional), reliable, FIFO, byte-stream
IPC between parent and children on same machine;

Sockets allow for full duplex (bi-directional), reliable local and remote
IPC between potentially unrelated processes;

Shared Memory is implemented via the mmap system call and


Synchronization requires file and record locking.

07/21/2021
IPC between process on a different computer systems
IPC between process on a different computer systems is
referred as Remote IPC.

This involves networking protocols.


The different mechanisms for this type of IPC are

• Internet-domain sockets
• Transport Layer Interface (TLI)
• Remote Procedure Calls (RPC)

07/21/2021
Pipes

07/21/2021
Pipes:
Pipe is a connection between two processes.
Pipes are the oldest form of UNIX System IPC and are
provided by all UNIX systems. Pipes have two limitations.
1.They have been half duplex.
2.Pipes can be used only between processes that have a
common ancestor.
• A pipe is a one-way mechanism that allows two related
processes to send data from one of them to the other
one.

07/21/2021
• A pipe is created by calling the pipe function.
#include <unistd.h>
int pipe(int filedes[2]);
Returns: 0 if OK, 1 on error.

Two file descriptors are returned through the filedes


argument: filedes[0] is open for reading, and filedes[1] is
open for writing. The output of filedes[1] is the input for
filedes[0].

07/21/2021
popen and pclose :
• A common operation is to create a pipe to another
process, to either read its output or send it input, the
standard I/O library has historically provided the popen
and pclose functions.
#include <stdio.h>
FILE *popen (const char *cmdstring, const char *type);
Returns: file pointer if OK, NULL on error.
int pclose(FILE *fp);
Returns: termination status of cmdstring, or -1 on error

07/21/2021
• The function popen does a fork and exec to execute the
cmdstring, and returns a standard I/O file pointer. If type is
"r", the file pointer is connected to the standard output of
cmdstring.

• If type is "w", the file pointer is connected to the standard


input of cmdstring.

• The pclose function closes the standard I/O stream, waits


for the command to terminate, and returns the
termination status of the shell.

07/21/2021
FIFOs:
• FIFOs are sometimes called named pipes. Pipes can be
used only between related processes when a common
ancestor has created the pipe. With FIFOs, unrelated
processes can exchange data.
• Creating a FIFO is similar to creating a file.
#include <sys/ stat.h>
int mkfifo( const char *pathname, mode_t mode);
Returns: 0 if OK,-1 on error.

07/21/2021
07/21/2021
07/21/2021
Uses for FIFOs:

• FIFOs are used by shell commands to pass data from one


shell pipeline to another without creating intermediate
temporary files.

• FIFOs are used in client-server applications to pass data


between the clients and the servers.
[Demo]

07/21/2021
Three types of IPC

07/21/2021
Command-line IPC control

• ipcs [different options]


• Lists all IPC objects owned by the user

• ipcrm
• Removes specific IPC object
1 . Message Queues:
• A message queue is a linked list of messages stored within the
kernel and identified by a message queue identifier.
• We'll call the message queue just a queue and its identifier a queue
ID.
• A new queue is created or an existing queue opened by msgget.
• New messages are added to the end of a queue by msgsnd.
• Every message has a positive long integer type field, a non-negative
length, and the actual data bytes all of which are specified to
msgsnd when the message is added to a queue.

07/21/2021
• Messages are fetched from a queue by msgrcv.
• Each queue has the following msqid_ds structure associated with it:
struct msqid_ds
{
struct ipc_perm msg_perm;
msgqnum_t msg_qnum;
msglen_t msg_qbytes;
pid_t msg_lspid;
pid_t msg_lrpid;
time_t msg_stime; time_t msg_rtime;}

07/21/2021
• msgget is used to either open an existing queue or create
a new queue.
#include <sys/ msg.h>
int msgget( key_t key, int flag);
Returns: message queue ID if OK,-1 on error.
• On success, msgget returns the non-negative queue ID.
This value is then used with the other three message
queue functions.

07/21/2021
• The msgctl function performs various operations on a
queue.
#include <sys/msg.h>
int msgctl(int msqid, int cmd, struct msqid_ds *buf );
Returns: 0 if OK,-1 on error.
• The cmd argument specifies the command to be
performed on the queue specified by msqid.
• IPC_STAT --- Fetch the msqid_ds structure for this queue,
storing it in the structure pointed to by buf.

07/21/2021
• IPC_SET ---- Copy the following fields from the structure
pointed to by buf to the msqid_ds structure associated
with this queue: msg_perm.uid, msg_perm.gid,
msg_perm.mode, and msg_qbytes.
• IPC_RMID ---- Remove the message queue from the
system and any data still on the queue. This removal is
immediate.

07/21/2021
• Data is placed onto a message queue by calling msgsnd.
#include <sys/msg.h>
int msgsnd(int msqid, const void *ptr, size_t nbytes, int
flag);
Returns: 0 if OK, -1 on error.
• When msgsnd returns successfully, the msqid_ds
structure associated with the message queue is updated
to indicate the process ID that made the call (msg_lspid),
the time that the call was made (msg_stime), and that
one more message is on the queue (msg_qnum).

07/21/2021
Messages are retrieved from a queue by msgrcv.
#include <sys/msg.h>
ssize_t msgrcv(int msqid, void *ptr, size_t nbytes , long
type, int flag);
Returns: size of data portion of message if OK, -1 on error.
When msgrcv succeeds, the kernel updates the msqid_ds
structure associated with the message queue to indicate
the caller's process ID (msg_lrpid), the time of the call
(msg_rtime), and that one less message is on the queue
(msg_qnum).

07/21/2021
IPC using Message Queues

• A message queue is a linked list of messages stored within the kernel and
identified by a message queue identifier. A new queue is created or an existing
queue opened by msgget(). 
• New messages are added to the end of a queue by msgsnd().
• Messages are fetched from a queue by msgrcv().
• Each message is given an identification or type so that processes can select the
appropriate message.
• Process must share a common key in order to gain access to the queue in the first
place.

07/21/2021
System calls used for message queues: 
 
•ftok(): is use to generate a unique key.
•msgget(): either returns the message queue identifier for a newly created message queue or returns the
identifiers for a queue which exists with the same key value.
•msgsnd(): Data is placed on to a message queue by calling msgsnd().
•msgrcv(): messages are retrieved from a queue.
•msgctl(): It performs various operations on a queue. Generally it is use to destroy message queue.

07/21/2021
2. semaphore

07/21/2021
Resource Sharing
• Problem – two process were accessing the same file and one that got
the time slice would initialize a variable before working on the file.
• When other process is given the time slice it would first check the
value of this variable realize it has been initialized by some other
process.

29
Semaphore
• In Unix operating system, for resources conflicts can be solved by a
variable is called semaphore
• Semaphore is a integer variable for each resource
• Act as a counter in critical section
• Value of semaphore depends on number of resources

30
Example:
•A file is to be share then semaphore value is
0 or 1

•Semaphore = 0 , when the file is use,


therefore process wait
•Semaphore = 1, when the file is not in use
•Semaphore is a global variable shared by all
process

31
Process A Process B

User
Space

Semaphore
0 or 1

Kernel Space

32
Uses
• Semaphore can be used to restrict two process from accessing the
same file simultaneously
• Help in resource synchronization

33
Why would we need to use a semaphore on
a file when we have powerful locking
functions?

• If many process using this file there would be a lot of


time spent in reading it from disk very time an access
was required.
Solution: Critical Section

34
Unix Kernel support for
semaphore

35
Semaphore operations
• Creating a semaphore
• Deleting a semaphore
• Setting value to the semaphore
• Getting value from the semaphore
• Control operations

36
Creating a Semaphore
• Semaphore can be created using the function called semget()
• Syntax:
int semget(int key, int nsem, int flag)
• Key- assigns a hexadecimal number
• Nsem- number of sub semaphores, not less than 1
• Flag- specifies IPC_CREATE, IPC_EXCL
• Mode- gives permissions only read and alter
• Semget() returns a identifier value of semaphore

37
Example program to create semaphore
#include<sys/ipc.h>
#include<stdio.h>
#include<sys/types.h>
main()
{
int key,semid,nsem,flag;
key=(key_t)0*20;
nsem=1;
flag=IPC_CREAT|0664;
semid=semget(key,nsem,flag);
38
Example program to create semaphore

if(semid>0)
{
printf("\nsemaphore is created with identifier %d\n",semid);
}
else
{
printf("semaphore is not created \n");
}
}
39
Producer Consumer Problem using semaphore
• Problem: 
• Given the common fixed-size buffer, the task is to make sure that the producer can’t add data
into the buffer when it is full and the consumer can’t remove data from an empty buffer.
• Solution: 
• The producer is to either go to sleep or discard data if the buffer is full.
• The next time the consumer removes an item from the buffer, it notifies the producer, who
starts to fill the buffer again.
• In the same manner, the consumer can go to sleep if it finds the buffer to be empty.
• The next time the producer puts data into the buffer, it wakes up the sleeping consumer.

07/21/2021
#include <stdio.h>
#include <stdlib.h>
// Initialize a mutex to 1
int mutex = 1; // Number of full slots as 0
int full = 0; // Number of empty slots as size of buffer
int empty = 10, x = 0;
void producer() // Function to produce an item and add it to the buffer
{
--mutex; // Decrease mutex value by 1
++full; // Increase the number of full slots by 1
--empty; // Decrease the number of empty slots by 1
x++; // Item produced
printf("\nProducer produces – items: %d", x);
++mutex; // Increase mutex value by 1
07/21/2021
}
void consumer() // Function to consume an item and remove it from
buffer
{
--mutex; // Decrease mutex value by 1
--full; // Decrease the number of full slots by 1
++empty; // Increase the number of empty slots by 1
printf("\nConsumer consumes -- item %d", x);
x--;
++mutex; // Increase mutex value by 1
}
Shared Memory

07/21/2021
3. Shared Memory:
• Shared memory allows two or more processes to share a given region
of memory. This is the fastest form of IPC, because the data does not
need to be copied between the client and the server.
• The kernel maintains a structure with at least the following members
for each shared memory segment:

struct shmid_ds { shm_perm - This holds the permission information for the segment, including
struct ipc_perm shm_perm; the access permissions, and information about the creator of the segment (uid,
size_t shm_segsz; etc).
shm_segsz - Size of the segment (measured in bytes).
pid_t shm_lpid;
shm_atime -Time the last process attached the segment.
pid_t shm_cpid; shm_dtime -Time the last process detached the segment.
shmatt_t shm_nattch; shm_ctime -Time of the last change to this structure (mode change, etc).
time_t shm_atime; shm_cpid -The PID of the creating process.
shm_lpid -The PID of the last process to operate on the segment.
time_t shm_dtime; shm_nattch -Number of processes currently attached to the segment.
time_t shm_ctime;
}

07/21/2021
Shared Memory
Common chunk of read/write memory
among processes
MAX

Shared Memory
(unique key)
Create
ptr ptr
Attach 0 Attach
Proc. 1 Proc. 2

ptr ptr ptr

Proc. 3 Proc. 4 Proc. 5


45
Shared Memory operations

• Creating shared memory

• Attaching and detaching shared memory

• Deleting shared memory

46
Unix Kernel support for Shared Memory

47
Creating Shared Memory

• Create a shared memory using function called shmget()


• Syntax:
int shmget(key_t key, size_t size, int shmflg);
Where,
• key- identifier of shared memory
• size- size in bytes of the requested shared memory
• shmflg – specifies initial access permissions and control flags

48
Attach and Detach Shared Memory

• After allocate memory page, we need to add it to the memory page


table of the process
• This is done using shmat() (shared-memory attach ) system call

49
Attach and Detach Shared Memory

• Syntax of shmat() funtions:

void *shmat(int shmid, void *shmaddr, int shmflg);

int shmdt(void *shmaddr);

50
Deleting Shared Memory
• Using the funtions called shmctl(), we can delete the
shared memory
• Syntax:
int shmctl(int shmid, int cmd, struct shmid_ds *buf);

51
Summary:
• Introduction to IPC, Pipe & FIFOs
• IPCs/Processes on single computer & different systems
• Types of IPC –
• Message queues
• Semaphores
• Shared Memory
• Unix V APIs message passing, semaphore, & shared memory
• Kernel supports for message passing, semaphore, & shared memory
• Producer/consumer problems and other examples.

You might also like