更改文件描述符的读/写权限 [英] Change read/write permissions on a file descriptor
问题描述
我正在处理linux C项目,但是在处理文件描述符时遇到了麻烦.
I'm working on a linux C project and I'm having trouble working with file descriptors.
我有一个孤立的文件描述符(文件是open()然后是unlink(),但是fd仍然很好),它具有只写权限.原始备份文件具有完全权限(使用S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH创建),但是可惜文件是用O_WRONLY打开的.是否可以复制文件描述符并将副本更改为O_RDWR?
I have an orphan file descriptor (the file was open()'d then unlink()'d but the fd is still good) that has write-only permission. The original backing file had full permissions (created with S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), but alas the file was opened with O_WRONLY. Is it possible to duplicate the file descriptor and change the copy to O_RDWR?
伪代码:
//open orphan file
int fd = open(fname, O_WRONLY, ...)
unlink(fname)
//fd is still good, but I can't read from it
//...
//I want to be able to read from orphan file
int fd2 = dup(fd)
//----change fd2 to read/write???----
提前谢谢! -安德鲁(Andrew)
Thanks in advance! -Andrew
推荐答案
否,没有POSIX函数来更改打开模式.您将需要以读/写模式打开它.不过,由于创建的是临时文件,因此我强烈建议您使用 mkstemp 一个>.该功能可以在读/写模式中正确打开文件并取消链接.最重要的是,它避免了命名和创建文件时的竞争条件,从而避免了临时文件创建过程中的漏洞.
No, there is no POSIX function to change the open mode. You will need to open it in read / write mode. Since you are created a temporary file, though, I strongly recommend that you use mkstemp. That function properly opens the file in read/write mode and unlinks it. Most importantly, it avoids a race condition in naming and creating the file, thereby avoiding a vulnerability in the creation of temporary files.
这篇关于更改文件描述符的读/写权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!