Inter-Process Communication using Shared Memory - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Inter-Process Communication using Shared Memory

Share This

shm_com.c
1
2
3
4
5
6
7
8
#define SIZE 2048
struct shared_mem_st {
int written_by;
char text[SIZE];
};
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
shm1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#include "shm_com.h"
int main() {
int running = 1;
void *shared_memory = (void *) 0;
struct shared_mem_st *shared_stuff;
int shmid;
srand((unsigned int) getpid());
shmid = shmget((key_t) 1234, sizeof(struct shared_mem_st),
0666 | IPC_CREAT);
if (shmid == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
shared_memory = shmat(shmid, (void *) 0, 0);
if (shared_memory == (void *) -1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %X\n", (int)shared_memory);
shared_stuff = (struct shared_mem_st *) shared_memory;
shared_stuff->written_by = 0;
while (running) {
if (shared_stuff->written_by) {
printf("You wrote: %s", shared_stuff->text);
sleep(rand() % 4); /* make the other process wait for us ! */
shared_stuff->written_by = 0;
if (strncmp(shared_stuff->text, "end", 3) == 0) {
running = 0;
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
shm2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#include "shm_com.h"
int main()
{
int running = 1;
void *shared_memory = (void *) 0;
struct shared_mem_st *shared_stuff;
char buffer[BUFSIZ];
int shmid;
shmid = shmget((key_t) 1234, sizeof(struct shared_mem_st), 0666 | IPC_CREAT);
if (shmid == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
shared_memory = shmat(shmid, (void *) 0, 0);
if (shared_memory == (void *) -1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %X\n", (int)shared_memory);
shared_stuff = (struct shared_mem_st *) shared_memory;
while (running) {
while (shared_stuff->written_by == 1) {
sleep(1);
printf("waiting for client...\n");
}
printf("Enter some text: ");
fgets(buffer, BUFSIZ, stdin);
strncpy(shared_stuff->text, buffer, SIZE);
shared_stuff->written_by = 1;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.