Linux下彈出U盤的代碼

轉自http://www.oschina.net/code/snippet_4873_2205

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

01 #include <stdio.h>
02 #include <stdlib.h>
03 #include <unistd.h>
04 #include <sys/types.h>
05 #include <sys/ioctl.h>
06 #include <fcntl.h>
07 #include <string.h>
08 #include <linux/fd.h>
09 #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  
30     int status, k;
31     sg_io_hdr_t io_hdr;
32     unsigned char allowRmBlk[6] = {ALLOW_MEDIUM_REMOVAL, 0, 0, 0, 0, 0};
33     unsigned char startStop1Blk[6] = {START_STOP, 0, 0, 0, 1, 0};
34     unsigned char startStop2Blk[6] = {START_STOP, 0, 0, 0, 2, 0};
35     unsigned char inqBuff[2];
36     unsigned char sense_buffer[32];
37     if ((ioctl(fd, SG_GET_VERSION_NUM, &k) < 0) || (k < 30000)) {
38       printf("not an sg device, or old sg driver\n");
39       goto out;
40     }
41     memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
42     io_hdr.interface_id = 'S';
43     io_hdr.cmd_len = 6;
44     io_hdr.mx_sb_len = sizeof(sense_buffer);
45     io_hdr.dxfer_direction = SG_DXFER_NONE;
46     io_hdr.dxfer_len = 0;
47     io_hdr.dxferp = inqBuff;
48     io_hdr.sbp = sense_buffer;
49     io_hdr.timeout = 10000;
50     io_hdr.cmdp = allowRmBlk;
51     status = ioctl(fd, SG_IO, (void *)&io_hdr);
52     if (status < 0)
53     {
54       goto out;
55     }
56     io_hdr.cmdp = startStop1Blk;
57     status = ioctl(fd, SG_IO, (void *)&io_hdr);
58     if (status < 0)
59     {
60       goto out;
61     }
62     io_hdr.cmdp = startStop2Blk;
63     status = ioctl(fd, SG_IO, (void *)&io_hdr);
64     if (status < 0)
65     {
66       goto out;
67     }
68     /* force kernel to reread partition table when new disc inserted */
69     status = ioctl(fd, BLKRRPART);
70 out:
71     close(fd);
72     free(device);
73     return 0;
74 }

[代碼] 編譯和運行

1 編譯:g++ -g -Wall main.cpp -o usb-s
2  
3 現在,我們要彈出sdb1的u盤的話就可以這樣了。
4  
5 sudo usb-s /dev/sdb1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章