Dumb little shared memory descriptor question

Yes its me again =)

For those who remember me, new drivers are almost compelte.

This little bug is bothering me, even though I could leave it alone and its unlikely that it would ever bring things down, I’m just curious:

I create a shared memory object using shm_open in a driver process. Client processes then also shm_open into this shared memory and it is used as a mass data transfer buffer. Now, multiple client processes should, in theory, be able to open and close this file descriptor, however it seems that whenever a client processes attempts to close its file descriptor (through shm_unlink() or through standard close()) , the shared memory object is removed from the directory path and all other open attempts fail.

Now it seems to me that for every open call there should be a close call. If a cilent opens the shared memory descriptor, there should be some way for that client to call a close without destroying the object entirely, otherwise a bunch of dangling open file descriptors could pile up.

The shm_unlink documentation states that calling it will remove the file path entry for the object, but not destroy it until other all other connections using the object close out. (Though no new connections are allowed). A simple close(fd) call seems to just destroy the object outright.

Is it considered correct to just open a shared descriptor and not call some sort of close when finished with it? I’ll be the first to admit I’m not terribly familiar with the theory behind this stuff. If its not, then what call is correct?

(Back I go to see if i’m just making some stupid msitake)

Hmm… You’re close and certainly correct in your assumptions about closing.

shm_open() will open a shared memory object, optionally creating it if it doesn’t exist (just like open does with a file).

close() will close your access to it (just like a file)

shm_unlink() will remove the directory entry for the shared object - and if there are no open file descriptors to it, release the resources (the memory) used.

So you can create the object, then close the file descriptor and it will still exist (using up your memory) until you reboot. You can, of course, open it again with shm_open(). The behaviour is modeled and open()/close()/unlink() and work just like they do.

One “trick” is to have the server and all the clients shm_open() the object, then you shm_unlink() it and only the processes with existing open file descriptors can access it. In fact if you shm_open() it with create again, you will get a different shared object. Again this is the same behaviour you can get with a file and open()/unlink().