使用c ++在linux中挂载网络驱动器

时间:2015-01-19 13:30:47

标签: c++ c linux mount

我想使用c ++在linux上安装网络驱动器。使用“mount”命令行,我可以安装我想要的任何驱动器。但是使用C ++,只有成功安装了那些由用户共享的驱动器。

这是我的测试代码:

#include <sys/mount.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <string>

using namespace std;

int main()
{
  string src = "//192.168.4.11/c$/Users";
  string dst = "/home/krahul/Desktop/test_mount";
  string fstype = "cifs";

  printf("src: %s\n", src.c_str());

  if( -1 == mount(src.c_str(), dst.c_str(), fstype.c_str(), MS_MGC_VAL | MS_SILENT , "username=uname,password=pswd") )
  {
      printf("mount failed with error: %s\n",strerror(errno));
  }
  else
      printf("mount success!\n");

  if( umount2(dst.c_str(), MNT_FORCE) < 0 )
  {
      printf("unmount failed with error: %s\n",strerror(errno));
  }
  else
      printf("unmount success!\n");


  return 0;
}

我想挂载机器的“C:/ Users”驱动器。使用命令行,它可以工作,但不能通过此代码。我不知道为什么。 strerror()打印的错误是“没有这样的设备或地址”。我正在使用Centos,并为此机器配置了Samba。我哪里错了?

1 个答案:

答案 0 :(得分:3)

mount.cifs命令解析并更改传递给mount系统调用的选项。使用-v选项查看它用于系统调用的内容。

$ mount -v -t cifs -o username=guest,password= //bubble/Music /tmp/xxx
mount.cifs kernel mount options: ip=127.0.1.1,unc=\\bubble\Music,user=guest,pass=********

即。它获取目标系统的IP地址(在ip选项中将bubble替换为127.0.1.1),并将带有反斜杠的完整UNC传递给安装系统调用。

使用我们的挂载选项重写您的示例:

#include <sys/mount.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <string>

using namespace std;

int main()
{
  string host = "127.0.1.1";
  string src = "\\\\bubble\\Music";
  string dst = "/tmp/xxx";
  string fstype = "cifs";

  string all_string = "unc=" + src + ",ip=" + host + ",username=guest,password=";

  printf("src: %s\n", src.c_str());

  if( -1 == mount(src.c_str(), dst.c_str(), fstype.c_str(), MS_MGC_VAL | MS_SILENT , all_string.c_str()))
  {
      printf("mount failed with error: %s\n",strerror(errno));
  }
  else
      printf("mount success!\n");

  if( umount2(dst.c_str(), MNT_FORCE) < 0 )
  {
      printf("unmount failed with error: %s\n",strerror(errno));
  }
  else
      printf("unmount success!\n");


  return 0;
}

这可以帮助您在编写工具时调用mount2

相关问题