C++ Unix文件描述符
今天,我发现Linux中的文件描述符的行为非常有趣。看看这个代码:C++ Unix文件描述符,c++,c,linux,unix,C++,C,Linux,Unix,今天,我发现Linux中的文件描述符的行为非常有趣。看看这个代码: #include <dirent.h> /* Defines DT_* constants */ #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/syscall.h&
#include <dirent.h> /* Defines DT_* constants */
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <errno.h>
#define handle_error(msg) \
do { trace(msg); exit(0); } while (0)
#define trace printf
int createFile(const char* name) {
int r;
r = ::open( name, 0 );
if (r < 0)
{
trace("create file : %s\n", name);
r = ::open( name, O_CREAT, 0666 );
if (r < 0)
trace("error r < 0 %d\n",errno);
}
return r;
}
int createDir(const char* name) {
int r = ::mkdir( name, 0777 );
if (r != 0) {
trace("error r!=0\n");
}
r = open(name, 0);
if (r < 0) {
trace("error create dir r <0\n");
}
return r;
}
struct linux_dirent {
long d_ino;
off_t d_off;
unsigned short d_reclen;
char d_name[];
};
#include <sys/types.h>
#include <dirent.h>
void test123(int fd) {
int nread;
char buf[1024];
unsigned char buffer[1024];
struct linux_dirent *d;
int bpos,r;
char d_type;
if (fd == -1)
handle_error("open");
for ( ; ; ) {
nread = syscall(SYS_getdents, fd, buf, 1024);
if (nread == -1)
handle_error("getdents");
if (nread == 0)
break;
trace("--------------- nread=%d ---------------\n", nread);
trace("i-node# file type d_reclen d_off d_name\n");
for (bpos = 0; bpos < nread;) {
d = (struct linux_dirent *) (buf + bpos);
trace("%8ld ", d->d_ino);
d_type = *(buf + bpos + d->d_reclen - 1);
trace("%4d %10lld %s\n", d->d_reclen,
(long long) d->d_off, d->d_name);
bpos += d->d_reclen;
}
}
}
int main(int argc, const char * argv[]) {
int dir = createDir("test");
int file = createFile("test/file.gg");
test123(dir);
close(dir);
close(file);
return 0;
}
该文件夹中没有file.gg文件。所以,我的问题是-它是如何实现的,以及如何正确使用文件描述符?据我所知,文件描述符只是本地进程表中所有打开的文件和目录的索引。但看起来文件夹描述符以某种方式将文件缓存在该文件夹中。
在我的例子中,如何正确使用描述符?尝试在您的目录上进行fsync。您应该使用O_RDONLY标志打开目录。O_WRONLY将失败。创建文件,同步可能不会同步此文件的元数据。中的更多信息请在读取目录之前尝试关闭新创建的文件。奇怪的是,该代码对我有效。如果您添加正在使用的内核版本/体系结构/文件系统等,也许有人可以找到一些线索。在仍然打开的描述符上调用fsync()的一些尝试可能也是值得的。
r=::open(name,0)代码>语法错误。你是否混淆C和C++?在读取目录之前关闭文件不修复这个问题,文件仍然是不可见的:我使用:Linux版本2.632-38-通用(Ubuntu 10.04)。我也尝试使用FSyc函数——当我在文件描述符上使用它时,它什么也不做,当我在目录描述符上使用它时,我得到了EnVar错误代码(无效的参数)是的,对不起,代码是C++,不是纯C,我的错
create file : test/file.gg
--------------- nread=32 ---------------
i-node# file type d_reclen d_off d_name
48879 16 1 .
48880 16 2 ..