|
|
Log in / Subscribe / Register

The curious case of O_DIRECTORY|O_CREAT

The curious case of O_DIRECTORY|O_CREAT

Posted Mar 29, 2023 5:37 UTC (Wed) by NYKevin (subscriber, #129325)
In reply to: The curious case of O_DIRECTORY|O_CREAT by interalia
Parent article: The curious case of O_DIRECTORY|O_CREAT

It is possible for A to use unlinkat(2) to remove the directory immediately after creating it (with AT_REMOVEDIR). In principle, I imagine that you might be able to continue using other fooat syscalls on the unlinked directory until you close it, thus creating a "true" temporary directory, but I have not tried it.

That still doesn't work because you race against someone else opening the directory before you can unlink it, but it's a neat party trick (if it works).


to post comments

The curious case of O_DIRECTORY|O_CREAT

Posted Mar 30, 2023 2:20 UTC (Thu) by josh (subscriber, #17465) [Link]

Sadly, that doesn't work. Once you've unlinked a directory, attempting to create something in that directory produces ENOENT.

The curious case of O_DIRECTORY|O_CREAT

Posted Mar 30, 2023 6:50 UTC (Thu) by donald.buczek (subscriber, #112892) [Link]

Yes, anonymous directories would be nice to have. Of course, with `dfd = mkdirat(parentfd, optional_name, mode, O_TMPDIR)` ínstead of a non-atomic `mkdir()`, `unlinkat()` combination. But I assume, that would be far from trivial to implement, because filesystems are not prepared to handle trees of unlinked directories.

If you want a directory tree and its contents to go away by kernel cleanup when the last access is gone and have privilege, you can use a lazily unmounted mount on top of a lazily detached loop device on top of an unlinked file like this:

root@theinternet:~# fallocate -l 10G /tmp/x.dat
root@theinternet:~# losetup --find --show /tmp/x.dat
/dev/loop0
root@theinternet:~# mkfs.ext4 -q /dev/loop0
root@theinternet:~# mount /dev/loop0 /mnt
root@theinternet:~# cd /mnt
root@theinternet:/mnt# umount -l /mnt
root@theinternet:/mnt# losetup -d /dev/loop0
root@theinternet:/mnt# rm /tmp/x.dat
root@theinternet:/mnt# ls -l
total 16
drwx------ 2 root root 16384 Mar 30 08:43 lost+found
root@theinternet:/mnt# df /tmp
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 268304384 44856232 223448152 17% /
root@theinternet:/mnt# cd
root@theinternet:~# df /tmp
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 268304384 44786364 223518020 17% /

But there is no way to create this stack atomically.

Another ugliness here is, that the system will unnecessarily flush modified data during (auto-)umount.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds