UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2008-11-20 03:32 PM

lvasilis22
Member
Registered: 2008-11-17
Posts: 8

Re: write into shared memory segment

I have created a shared memory segment (which size is 64 bytes) using shmget, shmat e.t.c and i want to divide it into 2 areas. One area for input data and one area for output? How can i do that?

Furthermore, When i have to write my input data into the shared memory segment i want to write something like this:

{a text messase, an integer, another integer}

Which function of c should i use? If i had to write only a text message and read it from another process i would use memcpy, but now i have the text messase and two integers (which i use as flags in my code).

Offline

#2 2008-11-20 07:00 PM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: write into shared memory segment

lvasilis22;25499 wrote:

I have created a shared memory segment (which size is 64 bytes) using shmget, shmat e.t.c and i want to divide it into 2 areas. One area for input data and one area for output? How can i do that?

Shared memory works the same as any other kind of memory... just treat it as you would any array of 64 bytes... except of course in this case there is the potential for other processes to read/write the array as well.

Furthermore, When i have to write my input data into the shared memory segment i want to write something like this:

{a text messase, an integer, another integer}

Which function of c should i use? If i had to write only a text message and read it from another process i would use memcpy, but now i have the text messase and two integers (which i use as flags in my code).

How about using a struct?

struct myStruct {
   char textMessage[16];
   int int1;
   int int2;
};
struct myStruct tmp;
strcpy(&tmp.textMessage, "hello");
tmp.int1 = 5;
tmp.int2 = 15;
memcpy(sharedMemoryArea, &tmp, sizeof(tmp));

Of course sizeof(tmp) will need to be small enough to fit in the shared memory region that you are copying it to, or you will have trouble.

One last note though... you may be barking up the wrong tree here.  If you want to do things like input and output streams, you should be using a stream-oriented communication system (e.g. sockets or pipes), not shared memory.

-Jeremy

Offline

#3 2017-03-18 07:27 PM

Rafael
Guest

Re: write into shared memory segment

Jeremy, i know it's 9 years later but your response perfectly fit what I was looking for. Thanks!

Board footer

Powered by FluxBB