Abhishek Gangwar
Abhishek Gangwar

Reputation: 1767

Copy a structure to a shared memory in C using POSIX standard

I need to access a structure between different processes. Is there any way to copy a structure in to a shared memory and then access the same structure in some other process.(using POSIX standards)

My structure is

typedef struct binary_semaphore {
    pthread_mutex_t mutex;
    sem_t *sem;
} binary_semaphore;

Upvotes: 0

Views: 3442

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148965

Do not even think of it !

If your structure just contained plain old data (integers, floating point numbers, characters or arrays of them) all would be fine: you get access to a share memory segment, copy the struct there with memcpy, and you can access it through any other process through the shared memory.

It becomes much more tricky as soon as the structure contains pointers to plain old data: you must copy the plain old data to shared memory, and replace the pointers with ids to shared memory, or offsets in a shared memory segment.

But here your struct contains a mutex and a pointer to a semaphore. They are by themselves inter process communication tools! Just get access to them from the other processes and use them directly.

Upvotes: 2

3442
3442

Reputation: 8576

It depends on what type of handle you have.

If you have a void*...

memcpy(sharedMemory, &myStruct, sizeof(struct MyStruct));

If you have an int from int shm_open(const char*, int, mode_t)...

void *sharedMemory = mmap(NULL, mySharedMemorySize, PROT_READ | PROT_WRITE, MAP_SHARED, myIntFromShmOpen, 0);
memcpy(sharedMemory, &myStruct, sizeof(struct MyStruct));

If you have an int from int shmget(key_t, size_t, int)...

void *sharedMemory = shmat(myIntFromShmGet, NULL, 0);
memcpy(sharedMemory, &myStruct, sizeof(struct MyStruct));

Hope this helps!

Upvotes: 1

Related Questions