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的代码,提取出来就成这样了:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/ioctl.h>
  6. #include <fcntl.h>
  7. #include <string.h>
  8. #include <linux/fd.h>
  9. #include <sys/mount.h>
  10. #include <scsi/scsi.h>
  11. #include <scsi/sg.h>
  12. #include <scsi/scsi_ioctl.h>
  13. int main(int argc, char *argv[])
  14. {
  15.     int fd = -1;
  16.     char *device;
  17.     if (argc != 2)
  18.     {
  19.         printf(“usage: usb-s /dev/sde1”);
  20.         return -1;
  21.     }
  22.     device = strdup(argv[1]);
  23.     if ((fd = open(device, O_RDONLY|O_NONBLOCK)) < 0)
  24.     {
  25.         printf(“open device %s failed!/n”, device);
  26.         free(device);
  27.         return -1;
  28.     }
  29.     int status, k;
  30.     sg_io_hdr_t io_hdr;
  31.     unsigned char allowRmBlk[6] = {ALLOW_MEDIUM_REMOVAL, 0, 0, 0, 0, 0};
  32.     unsigned char startStop1Blk[6] = {START_STOP, 0, 0, 0, 1, 0};
  33.     unsigned char startStop2Blk[6] = {START_STOP, 0, 0, 0, 2, 0};
  34.     unsigned char inqBuff[2];
  35.     unsigned char sense_buffer[32];
  36.     if ((ioctl(fd, SG_GET_VERSION_NUM, &k) < 0) || (k < 30000)) {
  37.       printf(“not an sg device, or old sg driver/n”);
  38.       goto out;
  39.     }
  40.     memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
  41.     io_hdr.interface_id = ‘S’;
  42.     io_hdr.cmd_len = 6;
  43.     io_hdr.mx_sb_len = sizeof(sense_buffer);
  44.     io_hdr.dxfer_direction = SG_DXFER_NONE;
  45.     io_hdr.dxfer_len = 0;
  46.     io_hdr.dxferp = inqBuff;
  47.     io_hdr.sbp = sense_buffer;
  48.     io_hdr.timeout = 10000;
  49.     io_hdr.cmdp = allowRmBlk;
  50.     status = ioctl(fd, SG_IO, (void *)&io_hdr);
  51.     if (status < 0)
  52.     {
  53.       goto out;
  54.     }
  55.     io_hdr.cmdp = startStop1Blk;
  56.     status = ioctl(fd, SG_IO, (void *)&io_hdr);
  57.     if (status < 0)
  58.     {
  59.       goto out;
  60.     }
  61.     io_hdr.cmdp = startStop2Blk;
  62.     status = ioctl(fd, SG_IO, (void *)&io_hdr);
  63.     if (status < 0)
  64.     {
  65.       goto out;
  66.     }
  67.     /* force kernel to reread partition table when new disc inserted */
  68.     status = ioctl(fd, BLKRRPART);
  69. out:
  70.     close(fd);
  71.     free(device);
  72.     return 0;
  73. }

 

编译:g++ -g -Wall main.cpp -o usb-s

 

现在,我们要弹出sdb1的u盘的话就可以这样了。

 

sudo usb-s /dev/sdb1

 

上一篇
下一篇