Skip to content
Advertisement

Playing with shmat and shm_open

I just read the manpages for shm_open and shmat and was trying out the following example. In a file test.c I do,

int main(int argc, char **argv) {
  void *retval;
  long shmid = atol(argv[1]);

  retval = shmat(shmid, NULL, SHM_RDONLY);
  printf("%pn", retval);
}

And in a wrapper file I do,

int setupshm(char *name) {
  int shmid;
  shmid = shm_open(name, O_CREAT|O_RDWR, 0666);
  return shmid;
}

int main() {
  char **envp = NULL;
  char *argv[3];
  char num[10];

  sprintf(num, "%d", setupshm("whatever"));

  argv[1] = "./test";
  argv[2] = num;
  argv[3] = NULL;

  execve("./test", argv, envp);
}

I tried adding in a strerror(errno) at test.c and I get Identifier removed. What does that mean? What am I doing wrong? Given a shared memory identifier(shmid), shouldn’t I be able to access the shared memory from any process?

Advertisement

Answer

shm_open belongs to the POSIX shared memory API; shmat belongs to the older SysV shared memory API. POSIX shm uses file descriptors. SysV shm uses identifiers that exist in a separate space. They don’t work together.

To use SysV shm successfully, you must use shmget to get an identifier you can shmat.

To use POSIX shm successfully, you must mmap the file descriptor you got from shm_open.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement