【问题标题】:Mount a network drive in linux using c++使用 C++ 在 linux 中挂载网络驱动器
【发布时间】:2015-01-20 19:31:50
【问题描述】:

我想使用 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。我哪里错了?

【问题讨论】:

  • C 不是 C++,请解决您的问题。然后,为了将来,请在发布之前一致地缩进您的代码并删除不必要的部分。顺便说一句:您还可以查看 mount 程序的来源。
  • 你在shell中使用哪个命令来挂载你的网盘?我想可能string src = "//192.168.4.11/c$/Users";有问题
  • 我使用下面的shell命令“mount //192.168.4.11/c$/Users /mnt/test_mount -o username=uname,password=pswd”,效果很好。

标签: c++ c linux mount


【解决方案1】:

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 地址(将我的bubble 替换为 ip 选项中的127.0.1.1),并将带有反斜杠的完整 UNC 传递给 mount 系统调用。

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

#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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多