2010-04-23 36 views
6

如何通過ioctl調用或其他方式找出SCSI設備(如/ dev/sda)是否爲磁盤? 我試過以下,但ioctl調用失敗。我的/ dev/sda是​​一個USB閃存盤。如何通過ioctl調用或其他方式找出SCSI設備(如/ etc/sda)是否爲磁盤?

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <fcntl.h> 
#include <errno.h> 
#include <scsi/scsi.h> 
#include <scsi/sg.h> 
#include <sys/ioctl.h> 

int main(int argc, char** argv) { 
    char *dev = "/dev/sda"; 
    struct sg_scsi_id m_id; 
    int rc; 
    int fd; 

    fd = open(dev, O_RDONLY | O_NONBLOCK); 
    if (fd < 0) { 
     perror(dev); 
    } 
    memset(&m_id, 0, sizeof (m_id)); 
    rc = ioctl(fd, SG_GET_SCSI_ID, &m_id); 
    if (rc < 0) { 
     close(fd); 
     printf("FAIL: ioctl SG_GET_SCSI_ID, rc=%d, errno=%d\n", rc, errno); 
    } else { 
     if (m_id.scsi_type == TYPE_DISK || m_id.scsi_type == 14) { 
      printf("OK: is disk\n"); 
     } else { 
      printf("OK: is NOT disk\n"); 
     } 
    } 
    close(fd); 
    return (EXIT_SUCCESS); 
} 
// result is: FAIL: ioctl SG_GET_SCSI_ID, rc=-1, errno=22 

回答

5

我已經此使用SG_IO並直接解釋二進制數據根據INQUIRY command(字段:外圍設備類型)的說明書中得到解決,將它們解釋根據SCSI Peripheral Device Types(是如果每dev的磁盤類型是00H或0EH。 )

int is_disk_sd(char *dev) { 
    unsigned char sense[32]; 
    struct sg_io_hdr io_hdr; 
    char scsi_data[SCSI_LEN]; 
    struct hd_geometry geo; 
    // request for "standard inquiry data" 
    unsigned char inq_cmd[] = {INQUIRY, 0, 0, 0, SCSI_LEN, 0}; 
    int fd; 

    fd = open(dev, O_RDONLY | O_NONBLOCK); 
    if (fd < 0) { 
     perror(dev); 
    } 

    memset(&io_hdr, 0, sizeof (io_hdr)); 
    io_hdr.interface_id = 'S'; 
    io_hdr.cmdp = inq_cmd; 
    io_hdr.cmd_len = sizeof (inq_cmd); 
    io_hdr.dxferp = scsi_data; 
    io_hdr.dxfer_len = sizeof (scsi_data); 
    io_hdr.dxfer_direction = SG_DXFER_FROM_DEV; 
    io_hdr.sbp = sense; 
    io_hdr.mx_sb_len = sizeof (sense); 
    io_hdr.timeout = 5000; 

    if (ioctl(fd, SG_IO, &io_hdr) < 0) { 
     close(fd); 
     return 0; 
    } else { 
     close(fd); 
     if (scsi_data[1] & 0x80) { 
      return 0; // support is removable 
     } 
     if ((scsi_data[0] & 0x1f) || ((scsi_data[0] & 0x1f) != 0xe)) { // 0 or 14 (00h or 0Eh) 
      return 0; // not direct access neither simplified direct access device 
     } 
     return 1; 
    } 
} 
1

也許你可以得到有用的信息從/ SYS /巴士/ SCSI /設備/ * /文件系統。

+0

TY,它確實幫助,我會來挖一些通過ioctl很難做到這一點。 [根@本地〜]#執行cat/proc/SCSI/SCSI 連接設備: 主機:SCSI1頻道:00編號:00綸:00 供應商:SanDisk公司型號:的Cruzer修訂:8.01 **類型:指示按訪問** ANSI SCSI修訂版:02 – clyfe 2010-04-23 13:46:15

1

HDIO_GET_IDENTITY似乎適用於我在磁盤上但不在閃存驅動器上。我認爲這是hdparm -i使用。

+0

它可以在SCSI磁盤(/ dev/sd *)上運行? – clyfe 2010-04-24 14:36:23

+0

它在使用libata的SATA磁盤上顯示爲'/ dev/sda'。我沒有一個SCSI磁盤來檢查。 – 2010-04-26 01:31:40

相關問題