Skip to content

Commit 0f1496d

Browse files
committed
POSIX: producer-consumer using shared memory
1 parent 536ca17 commit 0f1496d

File tree

5 files changed

+67
-1
lines changed

5 files changed

+67
-1
lines changed

3-Process Concept/a.out

-88 Bytes
Binary file not shown.

3-Process Concept/consumer

8.52 KB
Binary file not shown.

3-Process Concept/consumer.c

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <fcntl.h>
4+
#include <sys/shm.h>
5+
#include <sys/stat.h>
6+
#include <sys/mman.h>
7+
8+
int main()
9+
{
10+
/* size (in bytes) of shared memory object */
11+
const int SIZE = 4096;
12+
/* name of the shared memory object */
13+
const char *name = "OS";
14+
/* shared memory file descriptor */
15+
int shm_fd;
16+
/* pointer to shared memory object */
17+
void *ptr;
18+
19+
/* open the shared memory object */
20+
shm_fd = shm_open(name, O_RDONLY, 0666);
21+
22+
/* memory map the shared memory object */
23+
ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
24+
25+
/* read from the shared memory object */
26+
printf("%s\n", (char *)ptr);
27+
28+
/* remove the shared memory object */
29+
shm_unlink(name);
30+
31+
return 0;
32+
}

3-Process Concept/producer

8.56 KB
Binary file not shown.

3-Process Concept/producer.c

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,38 @@
22
#include <stdlib.h>
33
#include <string.h>
44
#include <fcntl.h>
5-
#include <sys/shm.h>
5+
#include <sys/mman.h>
6+
#include <sys/stat.h>
7+
8+
int main()
9+
{
10+
/* size (in bytes) of shared memory object */
11+
const int SIZE = 4096;
12+
/* name of the shared memory object */
13+
const char *name = "OS";
14+
/* strings written to shared memory */
15+
const char *message_0 = "Hello";
16+
const char *message_1 = "World";
17+
18+
/* shared memory file descriptor */
19+
int shm_fd;
20+
/* pointer to shared memory object */
21+
void *ptr;
22+
23+
/* create the shared memory object */
24+
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
25+
26+
/* configure the size of the shared memory object */
27+
ftruncate(shm_fd, SIZE);
28+
29+
/* memory map the shared memory object */
30+
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
31+
32+
/* write to the shared memory object */
33+
sprintf(ptr, "%s", message_0);
34+
ptr += strlen(message_0);
35+
sprintf(ptr, "%s", message_1);
36+
ptr += strlen(message_1);
37+
38+
return 0;
39+
}

0 commit comments

Comments
 (0)