重新打开与另一个访问的文件描述符? [英] Reopen a file descriptor with another access?
问题描述
假设操作系统是Linux。假设我打开写的文件,并得到一个文件描述符 FDW
。是否有可能得到另一个文件描述符 FDR
,与该文件只读访问,而无需调用打开
一遍吗?我不想打电话的原因打开
是底层文件可能已被移动或甚至被其他进程的文件系统中取消链接,所以重复使用相同的文件名不反对这样的行动可靠。所以我的问题是:反正有权利,如果只给一个文件描述符打开不同的访问文件描述符? DUP
或 dup2
不改变访问权,我想。
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.
推荐答案
是的!诀窍是通过来访问已删除的文件/ proc /自/ FD / N
。这是一个只有Linux帽子戏法,据我所知。
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.
运行此程序:
#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!\n", 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;
}
它写入一些文本文件,将其删除,但保持文件描述符打开,然后通过不同的路线重新打开它。文件不会被真正删除,直到最后一个进程抱着最后的文件描述符关闭它,在那之前,你可以通过的/ 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!
这篇关于重新打开与另一个访问的文件描述符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!