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

转载http://www.jb51.net/article/69806.htm

 

#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, 0, 0, 0, 0};
  unsigned char startStop1Blk[6] = {START_STOP, 0, 0, 0, 1, 0};
  unsigned char startStop2Blk[6] = {START_STOP, 0, 0, 0, 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 driver\n");
   goto out;
  }
  memset(&io_hdr, 0, 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, SG_IO, (void *)&io_hdr);
  if (status < 0)
  {
   goto out;
  }
  io_hdr.cmdp = startStop2Blk;
  status = ioctl(fd, SG_IO, (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

sudo usb-s /dev/sdb1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值