Search code examples
c++filesystemsfuse

Can not "read" anything through the FUSE file system


I use fuse to build my own file system in MIT 6.824 lab, and the read operation is implemented in this function.

void
fuseserver_read(fuse_req_t req, fuse_ino_t ino, size_t size,
        off_t off, struct fuse_file_info *fi)
{
    std::string buf;
    int r;
    if ((r = yfs->read(ino, size, off, buf)) == yfs_client::OK) {

        char* retbuf = (char *)malloc(buf.size());
        memcpy(retbuf,buf.data(),buf.size());
        //Print the information of the result.
        printf("debug read in fuse: the content of %lu is %s, size %lu\n",ino,retbuf, buf.size());

       fuse_reply_buf(req,retbuf,buf.size());    
    } else {
        fuse_reply_err(req, ENOENT);
    }

//global definition
//struct fuse_lowlevel_ops fuseserver_oper;

//In main()
//    fuseserver_oper.read       = fuseserver_read;

I print the information of the buf before it return.

The write operation is also implemented, of course.

Then I run a simple test to read out some words.

//test.c
int main(){
    //./yfs1 is the mount point of my filesystem
    int fd = open("./yfs1/test-file",O_RDWR | O_CREAT,0777);
    char* buf = "123";
    char* readout;
    readout = (char *)malloc(3);
    int writesize = write(fd,buf,3);
    int readsize = read(fd,readout,3);
    printf("%s,%d\n",buf,writesize);
    printf("%s,%d\n",readout,readsize);
    close(fd);
}

I can get nothing by read(fd,readout,3), but the information printed by the fuseserver_read shows that the buffer is read out successfully before fuse_reply_buf

$ ./test
123,3
,0
debug read in fuse: the content of 2 is 123, size 3

So why the read() in test.c can not read anything from my file system??


Solution

  • Firstly, I've made a mistake to write my test file. The file pointer will point to the end of the file after "write" and of course can read nothing later. So simply reopen the file can make the test work. Secondly, before read() operation of FUSE, the FUSE will getattr() first and truncate the result of the read() operation with the "size" attribute of the file. So it must be very careful to manipulate the attribute of a file.