Fun with openat(2) and friends....

So fun may not really be the right word, but for geekyness openat(2), renameat(2) and friends, that arrived in Solaris 9, offer some opportunities things that I just found useful. These system calls allow the manipulation of file attributes, which are really files in a hidden directory associated with each file. The nice/odd thing about file attributes is that they disappear when the file that they are associated with disappears.

This makes them great for keeping temporary files in, as you can have a whole directory full of temporary files which, if you have unlinked the original file can't be messed with by anyone else. So this code extract leaves us with a file descriptor pointing to a “directory” which can't be found in the normal file system space:

        if ((fd = open(path, O_EXCL|O_CREAT|O_RDWR, mode)) == -1) {
                return (-1);
        }
        if ((fd2 = openat(fd, ".", O_XATTR, 0)) == -1) {
                close(fd);
                return (-1);
        }
        (void) close(fd);
        unlink(path);
        fd = fd2;
        

Now by using openat(2) with fd you can create all you temporary files you wish, with no problems of a needing to delete them, when fd reaches it's last close all the “files” disappear.

What is even neater is that if you application wishes one of those temporary hidden files to be unhidden then you can use renameat(2) to bring the file from the attribute space into the real file system. So files can appear in the file system automatically.

Comments:

Pretty cool trick! However, I think the current implementation of renameat() doesn't allow the "unhide" described; you need to copy the file using e.g. sendfile(). Another nice thing of openat() is that you can emulate thread-local working directories.

Posted by guest on October 11, 2004 at 07:04 AM BST #

Doh, I was sure I had tried the unhide, but obviously I had not. thanks

Posted by Chris Gerhard on October 11, 2004 at 07:34 AM BST #

Post a Comment:
Comments are closed for this entry.
About

This is the old blog of Chris Gerhard. It has mostly moved to http://chrisgerhard.wordpress.com

Search

Archives
« April 2014
MonTueWedThuFriSatSun
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    
       
Today