2017-02-10 306 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文件夾都存在。那麼你有沒有這個例子可以運行,並有一個很好的結果?請幫幫我。 –