2017-02-10 107 views
0

我想用mount函数来实现NFS。如何从c中使用mount函数?

int mount(const char *source, const char *target, 
       const char *filesystemtype, unsigned long mountflags, 
       const void *data); 

我可以用mount命令 e.g mount 172.16.0.144:/tmp/test /tmp/test实现它。但是当我使用mount()函数时,它不起作用。这是我的代码。

#include<sys/mount.h> 
#include<iostream> 
#include<errno.h> 
#include<fstream> 
#include<string.h> 
using namespace std; 

int main(int argc, char**argv) { 
    const char* srcPath = "/tmp/watchman"; 
    const char* targetPath = "172.16.0.144:/tmp/watchman"; 
    if (argc == 3) { 
     srcPath = argv[1]; 
     targetPath = argv[2]; 
     cerr << "reset the src && target path\n"; 
    } else { 
     if (argc != 1) { 
      cerr << "wrong input argument!\n"; 
      return 0; 
     } 
    } 
    cerr << "srcPath = " << srcPath << endl; 
    cerr << "target = " << targetPath << endl; 
    int ret_val = mount(srcPath, targetPath, "", MS_SHARED, ""); 
    if (ret_val == 0) { 
     cerr << "mount succeed\n"; 
     string filename = string(srcPath) + "/" + "tmp.txt"; 
     fstream fin(filename.c_str(), ios::out); 
     fin << "there is a write test from client\n"; 
     fin.close(); 
     ret_val = umount(srcPath); 
     if (ret_val == 0) { 
      cerr << "umount succeed \n"; 
     } else { 
      cerr << "umount failed \n"; 
      printf("%s/n", strerror(errno)); 
     } 
    } else { 
     cout<<"ret_val = "<<ret_val<<endl; 
     cerr << "mount failed \n"; 
     cerr << strerror(errno) << endl; 
    } 
    return 0; 
} 

它printf挂载失败,没有这样的文件或目录。任何人都可以帮助我?请 !!!

+0

使用正确的标签。这是C++,而不是C. – Olaf

回答

1

如果read the mount manual page你会看到

mount()重视通过source指定的文件系统(通常是指到设备的路径名,也可以是一个目录或文件的路径名,或一个虚拟字符串)添加到由target中的路径名指定的位置(目录或文件)。

您已在应用程序中切换源和目标。

+0

我尝试了它,但它仍然不起作用。你能举个例子吗?我很困惑。 –

+0

@CloriaD目录'/ tmp/watchman'是否存在?它必须存在,然后才能将其用作装载目标。 –

+0

是的,当然存在。 NFS服务器和本地的/ tmp/watchman文件夹都存在。那么你有没有这个例子可以运行,并有一个很好的结果?请帮帮我。 –