简体   繁体   中英

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM