2
votes

The OS I'm working on (IBM CNK, which is not Linux, but somewhat POSIX-compliant) doesn't allow me to simply create a new file or directory in /dev/shm using fopen() or mkdir(), respectively. It looks like I have to use shm_open() to get a file descriptor and then fdopen() to use the shared region for file I/O.

  • Do I need to set the size of the shared region using ftruncate(), or does it grow automatically? I've tried it and I can simply fprintf into the region and it works, but is it safe? The manpage only says:

    A new shared memory object initially has zero length — the size of the object can be set using ftruncate(2). The newly allocated bytes of a shared memory object are automatically initialized to 0.

  • Do I want to mmap() the region? I simply want to have a directory with files in it in memory.

  • How would I create a new directory in /dev/shm? Is this "work with /dev/shm as if it was a normal filesystem" a new thing? Are directories in /dev/shm maybe not standard?

2
> Recent 2.6 Linux kernel builds have started to offer /dev/shm as shared memory in the form of a RAM disk, more specifically as a world-writable[clarification needed] directory that is stored in memory with a defined limit in /etc/default/tmpfs. /dev/shm support is completely optional within the kernel configuration file. It is included by default in both Fedora and Ubuntu distributions. Aha ...nisc
y: He wrote that he is NOT using Linux...DarkDust
OP and niscy are the same person :Pnisc

2 Answers

0
votes

Does your OS provide a full-featured mmap ? Do you only need the shared memory area in relatives, i.e. processes that you forked off ? If those two conditions are met you don't need any files at all, just use mmap:

char *shm_area;
shm_area = mmap(NULL, mySHMsize, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, 0, 0);

if (fork() == 0) {
  // Child, can access shm_area.
} else {
  // Parent, can access shm_area.
}
0
votes

I've never heard of IBM CNK before… but let's make some generalizations from POSIX/SUS.

It's not portable to mmap beyond the end of a file. You should call ftruncate to set the end of the file before mapping it.

The presence of /dev/shm is purely an implementation detail of shm_open. It would be POSIX-compliant to have no /dev/shm and implement shm_open in some other way. On Linux, /dev/shm happens to be a normal (though memory-backed) filesystem, but you can't portably expect /dev/shm to act filesystem-like, or even exist.