문제

I am using shared memory to communicate between two processes. I am using a char** to attach to the shared address space. The problem is that when I populate the data on the producer and then attach the consumer to the address space no data is transferred. I just get null values

This is a snippet of my producer

// 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);
}

and the consumer

// 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]);
도움이 되었습니까?

해결책

Your code is not putting your strings in shared memory. It's putting them on the heap, as malloc always does, because you are doing:

buf = (char**) shmat(shm_handle, 0, 0);
...
/* now throw away the value of `buf` you got from shm */
buf = malloc(sizeof(char*) * BUFF_SIZE);

What you will have to do is:

  1. Not use the heap to allocate things you want in shared memory

  2. Instead, grab a large enough amount of shared memory for everything, then copy it in, entry by entry - i.e. lay it out in memory manually.

다른 팁

Allocating stuff in shared memory is tricky and error prone, as the addresses of the shared memory are not necessarily the same in every process. Unless you take steps to ensure that addresses are the same, you can't store pointers in the shared memory as they won't point to the right place -- you need to instead store offsets into the shared memory.

Once you get the chunk of memory back from shmat, you need to manage allocations within that space yourself, keeping track of what is in use and what is free. In the general case, you need to reimplement malloc/free using the shared space, as the system malloc/free always work with unshared heap memory. This is non-trivial.

If you just want some working code that manages this, you can look here, but its not a simple problem.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top