C: Temp file deleted immediately after opening

116 views Asked by At

I'm trying to make a temp file, to which I want write a bunch of stuff, and then print out upon receiving a signal. However, after some diagnostics with lsof it looks like the temp file is deleted immediately after opening it. Take the following snippet:

FILE *tmp;

int main(int argc, char *argv[]) {

    if ((tmp = tmpfile()) == NULL)
        err_sys("tmpfile error");

    sleep(60);

Now if I go do a ps aux, get the pid of my process, and then do a lsof -p <pid>, I see the following:

10.06   1159 daniel    3u   REG    0,1     0 10696049115128289 /tmp/tmpfCrM7Jn (deleted)

This is a bit of a head-scratcher for me. Considering that it's really only a single built in function call, which is not causing an error when being called, I'm not sure what the problem is.

1

There are 1 answers

0
user3386109 On BEST ANSWER

From the man page:

The created file is unlinked before tmpfile() returns, causing the file to be automatically deleted when the last reference to it is closed.

The output from lsof simply indicates that the path pointing to the inode was removed. However, the current file handle FILE *tmp should still be valid, until the file is closed, or the program exits.