Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

44 AM

11/1/22, 8

Shared Memory

two or more processes. Ho need


is a memory
shared between ever, why do we
Shared memory of communication?
other m e a n s
or s o m e
memory
to share
if process wants
S tto communicate with
process has
its own address space, any
each
To reiterate, other processes, tnen it is only Dossible with
from its own address space to
information
As we are already aware, COmmunication can he
communication) techniques.
PC inter process
unrelated processes.
related or
between

communication is performed using Pipes or Named Pipes


process
Usually, inter-related in another
terminal and another process
one process running in one
Unrelated processes (say
can be performed using Named Pipes or
through popular PC
terminal) Ccommunication
Shared Memory and Message Queues.
techniques of
and Named pipes and now it is time to know the
seen the IPC techniques of Pipes
We have
Shared Memory, Message Queues, Semaphores, Signals, and
remaining IPC techniques viz.,
Memory Mapping.

In this chapter, we will know all about shared memory.

Process 1| Process 2

Shared Memory

We know that to communicate between two or more processes, we use shared memory but
before using the shared memory what needs to be done with the system calls, let us see this -

Create the shared memory segment or use an already created shared memory segment
(shmget())
Attach the process to the already created shared memory segment (shmat))

Detach the process from the already attached shared memory segment (shmdt())

Control operations on the shared memory segment (shmctl())

Let us look at a few details of the system calls related to shared memory.

1/9
www.tutorialspoint.com/inter_process communication/inter_process_communication_shared_memory.ntnn*
22 84
#include sys/ 1p.hs

sys/shm.hs
sinclude

sat shmget (key_t key, S1ze_t size, int shmflg)

t . The arguments
The above system all creates or allocates a System V shared memory segment The

need to be passed are as follows


that an
e i t h e r

The first argu


qument, key, recognizes the shared memory segment. The key c a n
be
be
also

or
arbitrary value or one that can be derived from the
library function ftok(). The
can

key
he key
PRIVATE, means, running processes as server and client (parent and
child relatio
this key, then

inter-related process communiation. If the client wants


related proce to shared memory with tn
use the
after
hild
be a chil process of the server.
Also, the child process needs to De
it must be creal
c r e a t e d

obtained a shared memory


parent has
of
ument,
The second argum size, is the size of the shared to
multiple

memory segment rounded


Ounded

PAGE_SIZE
REAT
The third argument, shmflg, specifes the required shared memory flag/s such as P
nt and the
(creating new segment) or C_EXCL (Used with IPC_CREAT to create new seg.

call fails, if the segment already exists). Need to pass the permissions as well.
Note - Refer earlier sections for details on permissions.

This call would return a valid shared memory identifier (used for further calls of shared memoiy

on success and -1 in case of failure. To know the cause of failure, check with erno variable o
perror() function.

#incLude <sys/types.h>
#include <sys/shm.h>

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

The above system call performs shared memory operation for System V shared memory
segment i.e., attaching a shared memory segment to the address space of the calling process.
The arguments that need to be passed are as follows-

The first argument, shmid, is the identifier of the shared memory segment. This id is the shared
memory identifier, which is the return value of shmget() system call.

The second argument, shmaddr, is to specify the attaching address. If shmadr is NULL, the
system by default chooses the suitable address to attach the segment. If shmaddr is not NULL
and SHM_RND is specified in shmfig, the attach is equal to the address of the nearest multiple of
SHMLBA (Lower Boundary Address). Otherwise, shmaddr must be a page aligned address at
which the shared memory attachment occurs/starts.
3:44 AM
Shared Memory
hasSHMRND
he third argument, shmflg, specifies the required shared
ared memory
memory flag/ss segmentto be

(rounding off address to SHMLBA) or SHM_EXEC (allows the contents read-

of is
executed) or SHM_RDONLY (attaches the segment for read-only purpose it

by
b y s h m a d d ra n d
d e f a u l t

write) or SHM_REMAP (replaces the existing mapping in the range specifiad


ied
continuing till the end of segment).
in
-1
and

This call would return the address of attached shared memory segment on Uccess

case of failure. To know the cause of failure, check With errno variable or pere 0 f u n c t i o n .

#include <sys/types.h>
#incLude <sys/shm.h>

int shmdt (const void *shmaddr)

V s h a r e d m e m o r y

The above system call performs shared memory operation for System V shared
the calling
segment of detaching the shared memory segment from the address space of t

argument that needs to be passed is


-

process. The
to-be-
1ne
The argument, shmaddr, is the address of shared memory segment to be detached.
must be the address returned by the shmat() system call.
detached segment
eck
and -1 in case of failure. To know the cause of failure, u
This call would return 0 on success

with errno variable or perror() function.

#include <sys/ipc.h>
#include <sys/shm. h>

int cmd, struct shmid_ds *buf)


int shmct1(int shmid,

segment. The
control operation for a System V shared memory
The above system call performs
to be passed
-

following arguments needs


This id is the shared
shmid, is the identifier of the shared memory segment.
The first argument,
call.
which is the return value of shmget() system
memory identifier,
control operation on the
is the command to perform the required
The second argument, cmd,
shared memory segment.

Valid values for cmd are


-

each member of struct


information of the current values of
IPC_STAT Copies the
buf. This command requires read permission to
shmid_ds to the passed structure pointed by
the shared memory segment.
permissIons, erc. pointed to by
IPC_SET- Sets the user ID, group ID of the owner,

structure buf.
8:44 AM Shared Memory
the
a f t e r

IPC_RMID Marks the segment to be destroyed. he segment is destroved oonly


nly
Yed

last process has detached it. the


in
Darameters
IPC_INFO Returns the information about the shared memory l limits and
structure pointed by buf. Out t h e c o n s u m e d

SHM_INFO Returns a shm_info structure containing information about the con


system resources by the shared memory.

The
struct sshmid
The third argument, buf, is a pointer to the shared memory structure nameda Struct hmid_ds.

cmd.
values of this structure would be used for either set or get as per

This call returns the value depending upon the passed command. Upon success of IP"
tor 0
and SHM_INFO or SHM_STAT returns the index or identifier of the shared memory segmel
for other operations and -1 in case of failure. To know the cause of failure, check with
variable or perror() function.

Let us consider the following sample program.


another
Create two processes, one is for writing into the shared memory (shm write.c) and
is for reading from the shared memory (shm_read.c)
and
The program performs writing into the shared memory by write process (shm_write.c)
reading from the shared memory by reading process (shm_read.c)

In the shared memory, the writing process, creates a shared memory of size 1K (and flags)
and attaches the shared memory

The write process writes 5 times the Alphabets


from 'A' to E' each of 1023 bytes into the
shared memory. Last byte signifies the end
of buffer

and write to the standard output


Read process would read from the shared memory

Reading and writing process actions are performed simultaneously


After completion of writing, the write process updates to indicate completion of writing into

the shared memory (with complete variable in struct shmseg)


Reading process performs reading from the shared memory and displays on the output until

it gets indication of write process completion (complete variable in struct shmseg)

Performs reading and writing process for a few times for simplication and also in order
er to
avoid infinite loops and complicating the program

Following is the code for write process (Writing into Shared Memory File: shm_write.cl

*Filename: shm_write. c *7
#incLude<stdio.h>
#incLude <sys/ipc.h>
#inc Lude <sys/shm . h>
Shared Memory

shared memory is
Inter Process Communication throughcommon a c o n . cept ere

two or more process memory. And com


can access the IMuniccaation

Ss can b e

is done via this shared memory where changes made by one


viewed by another process.
The problem with pipes, fifo and message queue - Is that for two nracess t

exchange information. The information has to go through the kernel


.
Server reads from the input file.
The server writes this data in a message using either a pipe, fifo or

message queue.
data
The client reads the data from the IPC channel,again requiring the
buffer.
be copied from kernel's IPC buffer to the client's
buffer.
Finally the data is copied from the client's
read and 2 write). So, shared
A total of four copies of data are required (2
two or more processes share a memory
memory provides a way by letting twice from input 1
Shared Memory the data is only copied
-

segment. With
the output file.
and from shared memory to
into shared memory
USED ARE:
SYSTEM CALLS
a unique key.
ftok): is use to generate size_tsize, intshmflg); upon successful completion, shmget)
shmget(): int shmget(key_t,
the shared memory segment.
identifier for have to attach yourself
returns an shared memory segment, you
can use a
shmat(): Before you void "shmaddr,int shmfig);
shmat(). void "shmat(int shmid, address to use but we should
set
to it using id. shmaddr specities speciic
memory
shmid is shared choose the address.
will automatically should
and OS segment, your program
it to zero the shared memory
with
shmdt): When you're done int shmdt{void "shmaddr);
it using shmdtO). is not destroyed. So, to destroy
detach itself from shared memory, it
detach from
shmctl): when you shmid, IPC_RMID,
NULL);
is used. shmctl(int
shmctl()
PROCESS
MEMORY FOR WRITER
SHARED

#include <iostream>

#include <sys/ipc.h>
#include <sys/shm. h>

#include <stdio.h>

using namespace std;

int main ()

ftok to generate
un.ique key
/
ftok ( "shmfile ", 65) ;
key_t key
=

an
identifier in shmid
returns
shmget ;
int shmid =
shmget (key, 1024,0666|
IPC_CREAT)

I shmat to attach to shared memory


char s t r =
(char*) shmat (shmid, (void*) 0, 0) ;
Cout<"Write Data ";
gets (str) ;

written in memory: %s\n", str);


printf ("Data

//detach from shared memory


shmdt (str);

return 0;

SHARED MEMORY FOR READER PROCESS

#include <iostream>
#include <sys/ipc. h>
#include <sys/shm. h>
#include <stdio.hn>
using namespace std;

int main ()

// ftok to generate unique key


key_t key = f t o k ( " s h m f i l e " , 65)

/ / shmget returns an identifier in shmid


i n t shmid = shmget (key, 1024,0666 | IPC_CREAT);

/ / shmat to attach to shared memory


char * s t r = (char*) shmat (shmid, (void* ) 0, 0)

printf ("Data read from memory: s\n", str)

7/detach from shared memory

shmdt(str);
// destroy the shared memory
shmctl (shmid, IPC_RMID, NULL);

return 0;

Output: a n d r e s @ a n d r e s "jPrograms/os

andres@andres: -/programs/os

File Edit Vies Seerch Terminal Helo andres@andres-/Prograns/0S$ ./reader


andres@andres:-/Prograns/0SS ./writer Data read fron menory: Geeks for GeeksS
Write Data : GeekS for Ceeks
written in memory: Ceeks for Ceeks
Data andres@andres:-/prograns/0s$

andresgandres:-/Prograns/0ss

You might also like