Search code examples
clinuxstructnfs

How to know free space and total space on nfs share through C program?


I want to know the free space and total space on a nfs share.
I am using ubuntu linux computers for this.
I can do that through commands but I need a C program for this.
I looked into libnfs.h, it contains some functions declarations that I think can be used :

EXTERN int nfs_stat(struct nfs_context *nfs, const char *path, struct stat *st);
EXTERN int nfs_fstat(struct nfs_context *nfs, struct nfsfh *nfsfh, struct stat *st);
EXTERN int nfs_statvfs(struct nfs_context *nfs, const char *path, struct statvfs *svfs);

But I don't know which one should be used and what to pass for the first parameter(what is context?)

Please help.
Thanks for help in advance.


As @remyabel suggested, I wrote following:

#include<sys/time.h>
#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/statvfs.h>
#include<nfsc/libnfs.h>
#define MAX 63
int main()
{
  struct nfs_context *nfs = NULL;
  struct statvfs st;
  char path[MAX];
  strcpy(path,"nfs://192.168.2.73/home/sumit/music2/");

  nfs = nfs_init_context();

  int ret;
  ret = nfs_mount(nfs, "192.168.2.73", path);
  perror("Err1");
  ret = nfs_statvfs(nfs, "//", &st);

  printf("\nret=%d",ret);
  printf("\nf_bsize= %lu",st.f_bsize);
  printf("\nf_frsize= %lu",st.f_frsize);
  printf("\nf_blocks= %lu",st.f_blocks);
  printf("\nf_bfree= %lu\n",st.f_bfree);

  return 0;
}

Now it works :)


Solution

  • First you declare the context at the beginning of your program:

    struct nfs_context *nfs = NULL;
    

    Here we'll hold the information you want:

    struct statvfs st;
    

    Then we initialize the context:

    nfs = nfs_init_context();
    

    Mount the share:

    struct client client;
    client.server = server;
    client.export = path;
    client.is_finished = 0;
    ret = nfs_mount(nfs, client.server, client.export);
    

    And you can use nfs_statvfs like so;

    ret = nfs_statvfs(nfs, path, &st);
    

    Where nfs is the context from earlier, path is some filename or directory, and st is the struct that will hold the information. ret contains errno if there was a problem.

    Here's statvfs:

    struct statvfs {
    
    uint32_t    f_bsize;
    
    uint32_t    f_frsize;
    
    uint64_t    f_blocks;
    
    uint64_t    f_bfree;