简体   繁体   中英

Mount a network drive in linux using c++

I want to mount a network drive on linux using c++. Using the command line of "mount" , I am able to mount any drive I want. But using C++, Only those drives are mounted successfully which are shared by the user.

This is my test code:

#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;
}

I want to mount the "C:/Users" drive of the machine. Using the Command line, It works but not by this code. I don't know why. The error printed by strerror() is "No such device or address". I am using Centos and Samba is configured for this machine. Where am I going wrong?

The mount.cifs command parses and changes the options that are passed to the mount system call. Use the -v option to see what it uses for the system call.

$ 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=********

ie it gets the IP address of the target system (replacing my bubble for 127.0.1.1 in the ip option), and passing in the full UNC with backslashes to the mount system call.

Rewriting your example with my mount options we have:

#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;
}

This should help you when writing your tool to invoke mount2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM