我正在使用共享内存在两个进程之间进行通信 . 我使用char **附加到共享地址空间 . 问题是当我在 生产环境 者上填充数据然后将消费者附加到地址空间时,没有数据被传输 . 我只是得到空值
这是我的制片人的片段
// create shared memory
shm_handle = shmget(key, BUFF_SIZE * PAGE_SIZE, IPC_CREAT | 0644);
printf("\nhandle is %d\n", shm_handle);
// valid handle?
if (shm_handle == -1) {
printf("shared memory creation failed\n");
exit(0);
}
// attach to shared block, see man pages for detail
buf = (char**) shmat(shm_handle, 0, 0);
if (buf == (char **) -1) {
printf("Shared memory attach failed");
exit(0);
}
int a = 0;
buf = malloc(sizeof(char*) * BUFF_SIZE);
for (a = 0; a < BUFF_SIZE; a++) {
buf[a] = malloc(sizeof(char) * PAGE_SIZE);
}
和消费者
// create shared memory
shm_handle = shmget(key, BUFF_SIZE * PAGE_SIZE, IPC_CREAT | 0644);
printf("handle is %d", shm_handle);
// valid handle?
if (shm_handle == -1) {
printf("shared memory creation failed\n");
exit(0);
}
char ** buft;
int a = 0;
// attach to shared block
buf = (char**) shmat(shm_handle, 0, 0);
if (buf == (char **) -1) {
printf("Shared memory attach failed");
exit(0);
}
buf = malloc(sizeof(char*) * BUFF_SIZE);
buft = malloc(sizeof(char*) * PAGE_SIZE);
for (a = 0; a < BUFF_SIZE; a++) {
buf[a] = malloc(sizeof(char) * PAGE_SIZE);
buft[a] = malloc(sizeof(char) * PAGE_SIZE);
}
printf("%s", buf[0]);