gjulianm
gjulianm

Reputation: 834

Is it a good practice to store a struct in shared memory?

I've been searching and I didn't found anything valuable, so I'm asking here.

Is it a good practice to save structs directly in the shared memory in C? I mean, something like this:

typedef struct {
    ...
} foo;

int id = shmget(sizeof(foo), ...);
foo* bar = (foo*) shmat(id, ...);

Or is it better to allocate an array and storing there only the fields you need, for example

#define SHM_FIELD_A(shm) (*(shm))
#define SHM_FIELD_B(shm) (*(shm) + 1)

If I wanted to store a complex struct (with doubles, chars, different size data) it would probably be better to use a struct. But, if I only want to store integers, which would be better?

Upvotes: 1

Views: 449

Answers (3)

Roman Saveljev
Roman Saveljev

Reputation: 2594

By storing the structure you will delegate all the boring work (field access, allocation size, alignment) to the compiler. I see no danger in having it as a structure. Structure or array - it is still a chunk of memory. Structure layout tells compiler what offsets to generate, when you want to access something inside by meaningful name.

Upvotes: 1

hazzelnuttie
hazzelnuttie

Reputation: 1481

The main purpose of shared memory is the Inter-process communication (IPC). If it is not the goal I don't find any reason in saving in shared memory

Upvotes: 0

unwind
unwind

Reputation: 399949

First, please don't cast the return value of shmat() in C, there's no point in doing so and it can hide errors.

Second, you never say what you mean by "good" and "better"; what are you optimizing for?

I would certainly recommend storing structures if that make sense to the application, if the values are related enough to warrant storing them in a structure, then sharing that structure should make just as much sense.

Of course this implies that the applications sharing this access are so tighly coupled that having to share a struct declaration is no problem.

Upvotes: 3

Related Questions