我正在编写一个函数,递归删除目录树中的所有文件和子目录,这个函数将在多线程环境中使用,所以我更喜欢opendir/readdir_r而不是nftw (代码是用于Linux/Mac /Solaris,而nftw在某些平台上并不是线程安全的)。
由于函数是删除文件,安全性是一个很大的关注。如果有指向敏感位置的链接(例如,/usr/lib系统目录),我不希望函数尝试删除该目录下的文件。对于符号/硬链接文件,lstat然后S_ISLNK将完成这项工作。但是,如果有挂载点,S_ISDIR就会返回true。
也许setmntent/getmntent会有所帮助,但我在Linux上的实验发现它无法处理以下情况:
getmntent仍然报告~/work/share作为挂载点。我想要的是像FTW_MOUNT标志到nftw
man nftw:
...
FTW_MOUNT
If set, stay within the same file system.我不确定来自st_dev的struct stat字段是否对此有好处,我不知道在挂载点之外,dev数是否总是不同的。
有了readdir_r,有办法找出挂载点吗?
谢谢!
发布于 2014-01-26 14:10:17
来自单一Unix规范-第7期
3.228点 系统根目录或结构的st_dev字段stat不同于其父目录的目录。 注意:stat结构是在中详细定义的。
换句话说,是的,您可以依靠设备ID来确定您是否处于安装点。要理解挂载点是什么,关键是要理解,如果像/usr这样的东西驻留在与/相同的文件系统中,则永远不会键入挂载 device /usr。
一个简单的示例,其中/home、/tmp、/usr和/usr/src都位于不同的设备上:
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
struct stat stbuf;
if (stat(".", &stbuf) == -1) {
perror("couldn't get working directory");
return 1;
}
printf("Device ID for directory .: %lX\n", stbuf.st_dev);
/* Loop through the command line arguments. */
while (*++argv) {
if (stat(*argv, &stbuf) == -1) {
fprintf(stderr, "error: couldn't get device ID for directory '%s': %s\n", *argv, strerror(error));
continue;
}
printf("Device ID for directory %s: %lX\n", *argv, stbuf.st_dev);
}
return 0;
}样本运行:
sh$ ./a.out /usr ~/misc\ files /nonexistent/path /usr/src /tmp
Device ID for directory .: 807
Device ID for directory /usr: 803
Device ID for directory /home/kit/misc files: 807
error: couldn't get device ID for directory '/nonexistent/path': No such file or directory
Device ID for directory /usr/src: 805
Device ID for directory /tmp: 802https://stackoverflow.com/questions/21363315
复制相似问题