1

I don't understand why my script below seems to work without creating any files.

script.c:

#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]){
    printf("P_tmpdir is '%s'\n", P_tmpdir);
    FILE *tmp = tmpfile();
    if(tmp == NULL){
        printf("Unable to create temp file");
        exit(1);
    }
    else{
        printf("Temporary file is created\n");
    }
    for(int i = 0; string[i] != '\0'){
        fputc(string[i], tmp);
    }
    rewind(tmp);
    while(!feof(tmp)){
        putchar(fgetc(tmp));
    }
    sleep(3);
    return(0);
}

The P_tmpdir variable returns me the "/tmp" directory although in the sleeping time no new file is created in it... can you help me or explain me plz ?

John S
  • 231
  • 3
  • 11

1 Answers1

7

Quoting cppreference.com (emphasis mine):

On some implementations (e.g. Linux), this function actually creates, opens, and immediately deletes the file from the file system: as long as an open file descriptor to a deleted file is held by a program, the file exists, but since it was deleted, its name does not appear in any directory, so that no other process can open it.

The file does not have to be "visible" in the file system tree, as long as a process has a handle on it, the file continues to exist.

If you want a file that's visible in the file system tree you should use mkstemp.

zwol
  • 135,547
  • 38
  • 252
  • 361
Marco
  • 7,007
  • 2
  • 19
  • 49
  • 2
    this is a common pattern on Linux, for example most terminals that are configured to have infinite scrolling history will create a file for backing up the screen data and unlink it immediately – phuclv Apr 13 '22 at 01:24
  • @phuclv I'm assuming one could still open the file via `/proc/[pid]/fd/[fd]` right? – Marco Apr 14 '22 at 02:49
  • 1
    probably. The point is to automatically clear the current session when the terminal crashes or exits, not to hide the file from anyone – phuclv Apr 14 '22 at 03:32
  • @phuclv That's actually pretty smart, cleaning up temporary files is always a pain – Marco Apr 14 '22 at 03:33
  • 1
    Though we know nothing about the OP platform, because didn't bothered to tell.. on glibc at least tmpfile() opens a O_TMPFILE|O_EXCL fd that is never materialized on the filesystem and no matter what happens the kernel will destroy it when the program terminates. (old versions use the racy create and unlink trick though) – Cristian Rodríguez Apr 16 '22 at 16:57