加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++实现Linux下弹出U盘的方法

发布时间:2020-12-16 03:29:52 所属栏目:百科 来源:网络整理
导读:本篇章节讲解C++实现Linux下弹出U盘的方法。供大家参考研究。具体如下: 在linux下,对于usb设备,我们一般都是mount上使用,不使用时umount掉就可以了。 在ubuntu10.04中,当我们插入u盘时,会出现u盘设备,当我点击这个设备就可以mount上u盘,并读

本篇章节讲解C++实现Linux下弹出U盘的方法。分享给大家供大家参考。具体如下:

在linux下,对于usb设备,我们一般都是mount上使用,不使用时umount掉就可以了。

在ubuntu10.04中,当我们插入u盘时,会出现u盘设备,当我点击这个设备就可以mount上u盘,并读取里面的文件,当我们不使用时,我们再次点击这个设备就可以弹出这个设备,如果想再次使用U盘,那么就得必须再次插拔u盘才可以。

umount和弹出u盘是不同的,umount后我们还可以再次mount上使用,我们的u盘的设备还在,但弹出u盘后,我们想使用就的再此插入u 盘才可以。例如,我有个u盘,设备是sdb,里面有个分区sdb1,在弹出u盘后,我们使用fdisk来列出磁盘时就不会在看到sdb的设备了。

在linux下弹出u盘我们可以使用如下命令(例如我的u盘设备是sdb1):

复制代码 代码如下:
sudo eject -s /dev/sdb1

这里可以查看eject的代码,提取出来就成这样了:

main.cpp文件如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <string.h>
#include <linux/fd.h>
#include <sys/mount.h>
#include <scsi/scsi.h>
#include <scsi/sg.h>
#include <scsi/scsi_ioctl.h>
int main(int argc,char *argv[])
{
  int fd = -1;
  char *device;
  if (argc != 2)
  {
    printf("usage: usb-s /dev/sde1");
    return -1;
  }
  device = strdup(argv[1]);
  if ((fd = open(device,O_RDONLY|O_NONBLOCK)) < 0)
  {
    printf("open device %s failed!n",device);
    free(device);
    return -1;
  }
  int status,k;
  sg_io_hdr_t io_hdr;
  unsigned char allowRmBlk[6] = {ALLOW_MEDIUM_REMOVAL,0};
  unsigned char startStop1Blk[6] = {START_STOP,1,0};
  unsigned char startStop2Blk[6] = {START_STOP,2,0};
  unsigned char inqBuff[2];
  unsigned char sense_buffer[32];
  if ((ioctl(fd,SG_GET_VERSION_NUM,&k) < 0) || (k < 30000)) {
   printf("not an sg device,or old sg drivern");
   goto out;
  }
  memset(&io_hdr,sizeof(sg_io_hdr_t));
  io_hdr.interface_id = 'S';
  io_hdr.cmd_len = 6;
  io_hdr.mx_sb_len = sizeof(sense_buffer);
  io_hdr.dxfer_direction = SG_DXFER_NONE;
  io_hdr.dxfer_len = 0;
  io_hdr.dxferp = inqBuff;
  io_hdr.sbp = sense_buffer;
  io_hdr.timeout = 10000;
  io_hdr.cmdp = allowRmBlk;
  status = ioctl(fd,SG_IO,(void *)&io_hdr);
  if (status < 0)
  {
   goto out;
  }
  io_hdr.cmdp = startStop1Blk;
  status = ioctl(fd,(void *)&io_hdr);
  if (status < 0)
  {
   goto out;
  }
  io_hdr.cmdp = startStop2Blk;
  status = ioctl(fd,(void *)&io_hdr);
  if (status < 0)
  {
   goto out;
  }
  /* force kernel to reread partition table when new disc inserted */
  status = ioctl(fd,BLKRRPART);
out:
  close(fd);
  free(device);
  return 0;
}

编译和运行:

编译:

复制代码 代码如下:
g++ -g -Wall main.cpp -o usb-s

 
现在,我们要弹出sdb1的u盘的话就可以这样了。
复制代码 代码如下:
sudo usb-s /dev/sdb1

希望本文所述对大家的C++程序设计有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读