I'm trying to share some memory from a producer process to a consumer process in linux (Ubuntu16).
There's just a common header which defines this small structure
struct my_small_pod_structure {
void *handle;
int width;
int height;
};
The producer process is doing:
// Create a semaphore to synchronize
psem = sem_open ("producerSem", O_CREAT | O_EXCL, 0644, 0);
sem_unlink ("producerSem"); // Avoid persisting after the process closed
shmkey = ftok("/dev/null", 5);
int shmid = shmget(shmkey, sizeof(my_small_pod_structure), 0644 | IPC_CREAT);
if (shmid < 0) {
error("shmget failed");
exit(1);
}
my_small_pod_structure *shared_ptr = (my_small_pod_structure*) shmat (shmid, NULL, 0);
// populate shared_ptr with the producer data here..
...
sem_post (psem); // data is ready
sleep(1000000); // very long value, assured that the producer isn't exiting before the consumer pulls it
While the consumer:
sem_t *psem = sem_open ("producerSem", O_CREAT | O_EXCL, 0644, 0);
sem_unlink ("producerSem");
key_t shmkey = ftok("/dev/null", 5);
int shmid = shmget(shmkey, sizeof(my_small_pod_structure), 0644 | IPC_CREAT);
if (shmid < 0) {
int error = errno;
printf("shmget failed %d\n", error);
exit(1);
}
sem_wait (psem); // wait for data to be ready
// DATA IS READY!
my_small_pod_structure *shared_ptr = (my_small_pod_structure*) shmat (shmid, NULL, 0);
// use shared_ptr..
...
but even though the producer starts BEFORE the consumer (although I suppose it shouldn't matter because of the semaphores), I'm just getting from the consumer
shmget failed 13
The producer seems to work and reach the sleeping point waiting for the consumer to pick it up.
What am I doing wrong? Why the 13 - permission denied?