我正在尝试在Linux(Ubuntu16)中从生产者进程到消费者进程共享一些内存。
只有一个通用的标头定义了这个小结构
struct my_small_pod_structure {
void *handle;
int width;
int height;
};
生产者流程正在做
// 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
消费者:
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..
...
但是,即使生产者在消费者之前就开始了(尽管我认为由于信号量这没关系),我还是从消费者那里得到的。
shmget failed 13
生产者似乎正在工作并到达睡眠点,等待消费者拿起它。
我在做什么错?为什么13-权限被拒绝?