Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views22 pages

11.2 IPC SharedMemory C

The document discusses inter-process communication through shared memory, focusing on memory mapping techniques using mmap() for both related and unrelated processes. It explains the differences between shared and private mappings, and introduces shm_open() for creating shared memory objects. Key functions include mmap(), munmap(), and shm_unlink(), which facilitate memory management and communication between processes.

Uploaded by

akaaljot.mathoda
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)
5 views22 pages

11.2 IPC SharedMemory C

The document discusses inter-process communication through shared memory, focusing on memory mapping techniques using mmap() for both related and unrelated processes. It explains the differences between shared and private mappings, and introduces shm_open() for creating shared memory objects. Key functions include mmap(), munmap(), and shm_unlink(), which facilitate memory management and communication between processes.

Uploaded by

akaaljot.mathoda
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/ 22

Inter-Process

Communication:
Shared
Memory

25-03-25 CMPT 201 Slides 11.2 © Dr. B. Fraser 1


Topics


Since memory is so useful and easy to access,
can we load a whole file into memory?

If processes have separate memory spaces,
how can two processes share memory?

25-03-25 2
Memory Mapping

25-03-25 3
Intro to Memory Mapping

Memory mapping
– It’s not just for IPC, but we'll need it!

Uses for Memory Mapping:
– .. roading file into memory
a

vs using read()/write()
– Allocating memory
– .. Accessing memory mapped devices using /dimim
(useful for embedded systems; shared between processors!)

Memory mapping is the process of mapping a file or device (or just plain memory) into your process’s virtual memory
space, so you can access it like a regular array or pointer, instead of reading or writing with system calls like read() or
write().

25-03-25 4
mmap()
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
.. mmap)) reats a memory mapping
– addr: starting address of the
new mapping.
-
Usually NULL so OS pick the address.
– length: # bytes in mapping.
– prot:
-
Memory protection for executable, readable, writable, or
not accessible.
-

– flags: MAP_SHARED or MAP_PRIVATE, and optionally


MAP_ANONYMOUS. (explained below)
– fd: .. the open fets to be mapped (explained below)
– offset: the offset into the file to be mapped.

Returns a pointer to the beginning of the new mapping.
-

25-03-25 5
int fd = open("example.txt", O_RDONLY);
char *data = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, fd, 0);

printf("First byte: %c\n", data[0]);


munmap(data, 4096);
close(fd);
Types of Memory Mapping

Two types of memory mappings Fits
1/0 becomes

..
aa
simple

Filmapping inter

File is loaded into a memory region for
read
no
need
went

File I/O becomes memory access: - on

– Replace read()/write() calls with pointer access to


read or write file.

This is called a.. memory-mapped file.

flag argument:-
MAP_ANONYMOUS flag is not set.
– .. Anonymous Mafting
X

memory region

This is another way to allocate memory to our process
-
is mapped not (in addition to sbrk()).
fils
with
&
a

-
malloc() uses both sbrk() and mmap().
lives
memory ●
flag argument: MAP_ANONYMOUS flag is set.
25-03-25 in RAM -
6
disk
not on not making a
file means
From RAM
which is for sharch
getting memory directly
Shared vs Private

-
Memory Mapping can be shared or private.

Shared Mapping:
– .. Multiple processes can share a mapping
anonymous) & fork Is child
– E.g., .. crets mapping fets a
or a

Since memory is cloned, the parent and the child


will share the same mapping.


– independent
Or, multiple processes can map the same file.

Private Mapping:
– Changes in one process's memory mapping
.. do not not written to
appear for other processes & fil
Used when you want to read from a file and possibly modify it
without affecting the original file or other processes.

25-03-25 7
putting memory just O'S
4 Possiblities
contents
putting memory using
of a
file

Private file mapping: ●
Private anonymous mapping:
– A file is mapped to a process – More memory is allocated
as a private mapping. to the calling process.
– ..
Changes not written
to fils – ..
fork I copes memory
Each process
but
has
or shared with other processes
private copy
.
Mine calling mulloe)) (changes not shared).
mulloe & read fils to memory

Shared file mapping: ●
Shared anonymous mapping:
– A file is mapped to a process – More memory is allocated
as a shared mapping. to the calling process.
– Changes propagate to: – Memory is shared; changes

.. the real fils propagate to other process!

and other processes mmap() arguments: offset = 0
fd = -1 or shm_open()

25-03-25
mapping same file.
=flag |= MAP_ANONYMOUS
8
Unmap

int munmap(void *addr, size_t length);
– Unmaps the mapped memory.
-

25-03-25 9
ABCD: Memory Mapping

Which of the options below is best described by:
Y – Used to allow fast access to a temporary copy of a file.
2)
– Used to have two processes access the same memory so
they can both access a shared data structure.
3) – Used to allow any number of processes to edit a file and see
each others edits, plus reflect changes to file on disk.

a) Shared anonymous mapping


2) file fil
b) Private anonymous mapping
date structure fils
37 c) Shared file mapping
d) Private file mapping temp copy >
-
private
17 shard mem-> stored

25-03-25 10
Memory Mapping Activity

Activity: memory-mapped file I/O.
– Modify the example from man mmap as follows:
– Receive only one command-line argument,
which is a file name.
– Create a file memory mapping for the entire file.
– Print out the content of the entire memory mapping.

25-03-25 11
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

#define handle_error(msg) \
do { \
perror(msg); \
exit(EXIT_FAILURE); \
} while (0)

int main(int argc, char *argv[]) {


char *addr;
int fd;
struct stat sb;
size_t length;
ssize_t s;

if (argc != 2) {
fprintf(stderr, "%s file\n", argv[0]);
exit(EXIT_FAILURE);
}

fd = open(argv[1], O_RDONLY);
if (fd == -1)
handle_error("open");

if (fstat(fd, &sb) == -1) /* To obtain file size */


handle_error("fstat");

length = sb.st_size;

addr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);


if (addr == MAP_FAILED)
handle_error("mmap");

s = write(STDOUT_FILENO, addr, length);


if (s != length) {
if (s == -1)
handle_error("write");

fprintf(stderr, "partial write");


exit(EXIT_FAILURE);
}

munmap(addr, length);
close(fd);

exit(EXIT_SUCCESS);
}
Shared Memory

25-03-25 12
Sharing memory
Two different ways to share memory between processes.

For Related processes:
.. brate memory map then share with fork)
mmap() with MAP_SHARED | MAP_ANONYMOUS

-
(i.e., shared anonymous)

For Unrelated Processes:
.. use a shard memory object (shm-open 11) & the

minapl)
– man 7 shm_overview
-

shm_open(): Open a shared memory object

ftruncate(): Set size
-
mmap(): Create memory mapping
-

25-03-25 13
shm_open()
int shm_open(const char *name, int oflag, mode_t mode)
– Similar to opening a file, but it's shared memory.

Just like creating a file; listed in /dev/shm/

E.g., ls /dev/shm/somename
– hard
Returns: file descriptor for.. memory
object
– name: Known by all participating processes.
General form: /somename.
– flag: O_CREAT flag set when creating a new object.
– mode: For permissions on creation.

25-03-25 14
Size and Map
int ftruncate(int fd, off_t length)
– Memory object is created with size 0.
– ftruncate() sets its size.

void *mmap( void *addr, size_t length,


int prot, int flags, int fd, off_t offset)
– Create memory map for memory object
(after created by shm_open() and size set with ftruncate()).
– .. Pass shared memory object fil descriptor as
fel
(from shm_open()).

25-03-25 15
Cleanup
int munmap(void *addr, size_t length)
– Unmap shared memory when no longer needed.

int shm_unlink(const char *name)


– .. Rumour shared minors Obit
when done with shared memory.
-


Removes file from /dev/shm/.
– -
However, processes still using
-
the shared memory object
keep using it.
e-

25-03-25 16
ABCD: shm_open()

When do we need to call shm_open()?

a) When two processes want to share memory. almost


true

b) When a parent and child processes want to


Xshare memory without calling fork().

-
c) When two unrelated processes want to share
memory.
d) When two processes share access to a file and
X
each process knows the file’s name.

25-03-25 17
Activity: Shared Memory

Activity
– Write two programs that communicates
with each other via shared memory.
– They should each receive a shared memory object file name
as the only command-line argument.
– One program should write an integer to the shared memory
– The other program should read the integer written by the first
program from the shared memory.

25-03-25 18
// writer.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> // For O_* constants
#include <sys/mman.h> // For shm_open, mmap
#include <sys/stat.h> // For mode constants

Reader
#include <unistd.h> // For ftruncate

int main(int argc, char *argv[]) {


if (argc != 2) {
fprintf(stderr, "Usage: %s <shm_name>\n", argv[0]);
exit(EXIT_FAILURE);
}

const char *shm_name = argv[1];


int shm_fd = shm_open(shm_name, O_CREAT | O_RDWR, 0666); // reader.c
if (shm_fd == -1) { #include <stdio.h>
perror("shm_open"); #include <stdlib.h>
exit(EXIT_FAILURE);
}
#include <fcntl.h>
#include <sys/mman.h>
// Set the size of shared memory to store 1 int #include <sys/stat.h>
if (ftruncate(shm_fd, sizeof(int)) == -1) { #include <unistd.h>
perror("ftruncate");
exit(EXIT_FAILURE);
int main(int argc, char *argv[]) {
}
if (argc != 2) {
// Map shared memory fprintf(stderr, "Usage: %s <shm_name>\n", argv[0]);
int *shared_int = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); exit(EXIT_FAILURE);
if (shared_int == MAP_FAILED) { }
perror("mmap");
exit(EXIT_FAILURE);
}
const char *shm_name = argv[1];
int shm_fd = shm_open(shm_name, O_RDONLY, 0666);
// Write an integer if (shm_fd == -1) {
*shared_int = 42; perror("shm_open");
printf("Writer: Wrote %d to shared memory.\n", *shared_int); exit(EXIT_FAILURE);
}
// Cleanup
munmap(shared_int, sizeof(int));
close(shm_fd); // Map the shared memory
=
return 0; int *shared_int = mmap(NULL, sizeof(int), PROT_READ, MAP_SHARED, shm_fd, 0);
} if (shared_int == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);

writin
}

// Read the integer


printf("Reader: Read %d from shared memory.\n", *shared_int);

// Cleanup
munmap(shared_int, sizeof(int));
close(shm_fd);
=
// Optionally remove the shared memory object
shm_unlink(shm_name);
-
return 0;
}
#include <fcntl.h> #include <fcntl.h>
#include <sys/mman.h> #include <sys/mman.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <unistd.h> #include <unistd.h>
#include <stdint.h> #include <stdint.h>
#include <stdio.h>
int main() {
int main() {
const char *name = "/my_shared_mem";
const char *name = "/my_shared_mem";
int shm_fd = shm_open(name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); int shm_fd = shm_open(name, O_RDONLY, S_IRUSR);
ftruncate(shm_fd, sizeof(uint8_t)); // Allocate space for one uint8_t
uint8_t *ptr = mmap(NULL, sizeof(uint8_t),
uint8_t *ptr = mmap(NULL, sizeof(uint8_t), PROT_READ, MAP_SHARED, shm_fd, 0);
PROT_WRITE, MAP_SHARED, shm_fd, 0);
printf("Read value: %u\n", *ptr); // Print the value
*ptr = 42; // Write a value (e.g., 42) to shared memory
munmap(ptr, sizeof(uint8_t));
close(shm_fd);
munmap(ptr, sizeof(uint8_t));
return 0;
close(shm_fd); }
return 0;
}
Summary


Two processes can communicate by sharing memory.

mmap()
– Creates a memory mapping of a file or some memory.
– Usually copied by fork()
– Useful for parent-child shared memory.
– mmap(), munmap()

shm_open()
– Creates a named shared memory object.
– Useful for unrelated processes to share memory.
– shm_open(), ftruncate(), mmap(), munmap(), shm_unlink()

25-03-25 19

You might also like