C: nftw() 的奇怪行为
我有这样的代码:
#include <ftw.h>
#include <stdio.h>
#include <string.h>
int nftw_stat(const char *path, const struct stat *stat, int flags,
struct FTW *ftw)
{
if (strcmp(path, "/home/pf/.gvfs\0") == 0) {
printf("nftw()\n");
printf("mode = %d\n", stat->st_mode);
printf("size = %d\n", (int) stat->st_size);
}
return 0;
}
int main()
{
if (nftw("/home/pf", &nftw_stat, 1, FTW_PHYS)) {
perror("nftw");
return 2;
}
}
如果我正常执行它,它返回的方式与 stat() 函数相同:
mode = 16704 (S_IFDIR | S_IRUSR | S_IXUSR) size = 0
但是当我使用 sudo
执行它时,它返回这样:
mode = 16832 (S_IFDIR | S_IRWXU) size = 4096
会发生什么?如果我将 stat() 与 sudo 一起使用,则会出现“权限被拒绝”错误。仅当 .gvfs
目录的权限为 500 (dr-x-----) 时才会发生这种情况。如果 sudo
无法使用 stat()
读取,为什么它可以与 nftw()
一起使用? :|
I've this code:
#include <ftw.h>
#include <stdio.h>
#include <string.h>
int nftw_stat(const char *path, const struct stat *stat, int flags,
struct FTW *ftw)
{
if (strcmp(path, "/home/pf/.gvfs\0") == 0) {
printf("nftw()\n");
printf("mode = %d\n", stat->st_mode);
printf("size = %d\n", (int) stat->st_size);
}
return 0;
}
int main()
{
if (nftw("/home/pf", &nftw_stat, 1, FTW_PHYS)) {
perror("nftw");
return 2;
}
}
If I execute it normally, it returns the same way as stat() function:
mode = 16704 (S_IFDIR | S_IRUSR | S_IXUSR) size = 0
But when I execute it with sudo
, it returns this:
mode = 16832 (S_IFDIR | S_IRWXU) size = 4096
What happens? If I use stat()
with sudo
it give me the Permission denied error. This happens only with .gvfs
directory, whose permissions are 500 (dr-x------). If sudo
can't read with stat()
, why it works with nftw()
? :|
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能发生的情况是 stat 在目录上失败,但无论如何你都会打印 stat 结构的值,这意味着你得到的是垃圾。您需要检查 typeflag 的值,您在 nftw_stat 例程中将其称为“flags”,以确保 stat 已成功设置 stat 结构。
What's probably happening is that stat has failed on the directory, but you are printing the values of the stat structure regardless, meaning you get rubbish. You need to check the value of the typeflag, which you call "flags" in your nftw_stat routine to make sure that stat has successfully set the stat structure.