本文實例講述了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):
這里可以查看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, 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;
- }
編譯和運行:
編譯:
希望本文所述對大家的C++程序設計有所幫助。
新聞熱點
疑難解答