Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

c - Reopen a file descriptor with another access?

Assume the OS is linux. Suppose I opened a file for write and get a file descriptor fdw. Is it possible to get another file descriptor fdr, with read-only access to the file without calling open again? The reason I don't want to call open is the underlying file may have been moved or even unlinked in the file system by other processes, so re-use the same file name is not reliable against such actions. So my question is: is there anyway to open a file descriptor with different access right if given only a file descriptor? dup or dup2 doesn't change the access right, I think.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes! The trick is to access the deleted file via /proc/self/fd/n. It’s a linux-only trick, as far as I know.

Run this program:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    FILE* out_file;
    FILE* in_file;
    char* dev_fd_path;
    char buffer[128];

    /* Write “hi!” to test.txt */
    out_file = fopen("test.txt", "w");
    fputs("hi!
", out_file);
    fflush(out_file);

    /* Delete the file */
    unlink("test.txt");

    /* Verify that the file is gone */
    system("ls test.txt");

    /* Reopen the filehandle in read-mode from /proc */
    asprintf(&dev_fd_path, "/proc/self/fd/%d", fileno(out_file));
    in_file = fopen(dev_fd_path, "r");
    if (!in_file) {
        perror("in_file is NULL");
        exit(1);
    }
    printf("%s", fgets(buffer, sizeof(buffer), in_file));

    return 0;
}

It writes some text to a file, deletes it, but keeps the file descriptor open and and then reopens it via a different route. Files aren’t actually deleted until the last process holding the last file descriptor closes it, and until then, you can get at the file contents via /proc.


Thanks to my old boss Anatoly for teaching me this trick when I deleted some important files that were fortunately still being appended to by another process!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...