Why are most posix named objects designed with unlink?

Viewed 124

Most POSIX named objects (or all?) have unlink functions. e.g: shm_unlink mq_unlink

They all have in common, that they remove the name of the object from the system, causing next opens to fail or create a new object.

Why is this designed like this? I know, this is connected to the "everything is a file" policy, but why not delete the file on close? Would you do this the same if you create a new interface?

I think, this has a big drawback. Say, we have a server process and several client processes. If any process unlinks the object (by mistake) all new clients would not find the server. (This can be prohibited by user permissions on the according file, but still...)

Would it not be better, if it had reference counting and the name would be removed automatically when the last object is closed? Why would you want to keep it open?

2 Answers

Because they are low level tools that could be used when performance matters. Deleting the object when it is not used to create it again on next use has a (slight) performance penalty against keeping it alive.

I once used a named semaphore that I used to synchronize accesses to a spool with various producers and consumers. I used an init module to create the named semaphore that was called as part of the boot process, and all other processes knew that the well known semaphore should exist.

If you want a more programmer friendly way that creates the object on demand and destroys it when it is no longer used, you can build a higher level library and encapsulate the creation/unlink operations in it. But if the system call included it, it would not be possible to build a user level library avoiding it.

Would it not be better, if it had reference counting and the name would be removed automatically when the last object is closed?

No.

Because unlink() can fail and because always unlinking a resource that can be shared between processes when all processes merely close that resource simply doesn't fit the paradigm of a shared resource.

You don't demolish a roller coaster just because there's no one waiting in line to ride it again at that moment in time.

Related