-1

I have a variable with a value and I want to share it with the proccesses.

Ex:

typedef struct {
  unsigned int a;
  unsigned int b;
  another_struct * c;
} struct1;
...
struct1 A ={...};
...

Now, I want to create a shared memory region and put the A variable in this region. How can i do this?

Vivi
  • 693
  • 2
  • 11
  • 21

2 Answers2

4

Shared memory is an operating system feature (which does not exist in C11). It is not "provided" by the C standard.

I guess that you are coding for Linux. BTW, read Advanced Linux Programming.

Read first shm_overview(7). You'll need to synchronize, so read also sem_overview(7).

You'll get some shared memory segment into a pointer and you'll use that pointer.

First, open the shared memory segment with shm_open(3):

int shfd = shm_open("/somesharedmemname", O_RDWR|O_CREAT, 0750);
if (shfd<0) { perror("shm_open"); exit(EXIT_FAILURE); };

Then use mmap(2) on that shfd:

void* ad = mmap(NULL, sizeof(struct1), PROT_READ|PROT_WRITE, MAP_SHARED, 
                shfd, (off_t)0);
if (ad==MAP_FAILED) { perror("mmap"); exit(EXIT_FAILURE); };

Then you can cast that address into a pointer:

struct1* ptr = (struct1*)ad;

and use it. (Don't forget to close).

BTW, you don't and you cannot put a variable into a shared memory. You get a pointer to that shared memory and you use it, e.g. ptr->a = 23;

Of course, don't expect the same shared segment to be mapped at the same address (so you can't easily deal with pointer fields like c) in different processes. You probably should avoid pointer fields in shared struct-s.

Notice that C variables exist only at compile time. At runtime, you only have locations and pointers.

PS. Shared memory is a quite difficult inter-process communication mechanism. You should perhaps prefer pipe(7)-s or fifo(7)-s and you'll need to multiplex using poll(2).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • yes I know, but i want to know if there is any way to put a variable into the shared memory. I can create a shared memory region but i couldn't put a variable in it. – Vivi May 11 '17 at 19:02
  • You can't put a *variable* in a shared memory. You should use *pointers*. – Basile Starynkevitch May 11 '17 at 19:11
1

Take a look at Beej's Guide to IPC.

I would basically treat the whole shard memory segment as a void* that you can place items at. You could use memcpy, of string.h, to copy A into your shared memory space. However your pointer in A would become invalid and cause a segfault if you attempted to use it in another process connected to shared memory segment.

HSchmale
  • 1,838
  • 2
  • 21
  • 48