Create a hard link from a file handle on Unix?

前端 未结 3 1798
再見小時候
再見小時候 2021-02-07 03:39

If I\'ve got a handle to an open file, is it possible to create a hard link to that file after all references to it have been removed from the filesystem?

For example, s

3条回答
  •  醉酒成梦
    2021-02-07 04:02

    On Linux, you might try the unportable trick of using /proc/self/fd by trying to call

     char pbuf[64];
     snprintf (pbuf, sizeof(pbuf), "/proc/self/fd/%d", fd);
     link(pbuf, "/tmp/hello");
    

    I would be surprised if that trick worked after an unlink("/tmp/foo") ... I did not try that.

    A more portable (but less robust) way would be to generate a "unique temporary path" perhaps like

     int p = (int) getpid();
     int t = (int) time(0);
     int r = (int) random();
     sprintf(pbuf, sizeof(pbuf), "/tmp/out-p%d-r%d-t%d.tmp", p, r, t);
     int fd = open  (pbuf, O_CREAT|O_WRONLY);
    

    Once the file has been written and closed, you rename(2) it to some more sensible path. You could use atexit in your program to do the renaming (or the removing).

    And have some cron job to clean the [old] /tmp/out*.tmp every hour...

提交回复
热议问题