Frage

This is something I can't really figure out: if you call shmget() on linux with the same key but in different processes, will you get back the same shmid or not? Is shmid an ephemeral value like a file descriptor number or something you can persist across invocations?

War es hilfreich?

Lösung

Yes, you will receive the same shmid. Shared memory descriptors are kernel-level, not process-level. ipcs -m lists shared memory segments.

from man shmctl:

A successful IPC_INFO or SHM_INFO operation returns the index of the highest used entry in the kernel's internal array recording information about all shared memory segments. (This information can be used with repeated SHM_STAT operations to obtain information about all shared memory segments on the system.) A successful SHM_STAT operation returns the identifier of the shared memory segment whose index was given in shmid. Other operations return 0 on success.

And from man shmoverview

POSIX shared memory objects have kernel persistence: a shared memory object will exist until the system is shut down, or until all processes have unmapped the object and it has been deleted with shm_unlink(3)

Andere Tipps

A fundamental problem common to shared memory, semaphores, and message queues is how do distinct processes find the proper communication instance? Note that POSIX (and hence Linux) have two different families of IPC - system V and "posix" - that are both part of the POSIX standard. They solve the problem in more or less the same way but sysV is a bit more convoluted and shmget comes from the sysV lineage.

The solution is basically to use a pathname so multiple processes can access the same resource. Posix IPC just use the pathname (e.g. the 1st parameter of shm_open). SysV runs the pathname (along with a "project id") through the function ftok, that is "File-To-Key" to arrive at the "key" used by shmget. Passing the same pathname and project id to ftok will result in the same unique key regardless of which process is doing it.

These IPC all have kernel persistence. They are removed when no process is any longer using them (they call shmdt in this case) and a process deletes them with the appropriate call (shmctl with the IPC_RMID option in this case).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top