gpt4 book ai didi

c - 如何通过 ioctl 调用或其他方式确定 SCSI 设备(例如/etc/sda)是否为磁盘?

转载 作者:IT王子 更新时间:2023-10-29 00:50:37 24 4
gpt4 key购买 nike

如何通过 ioctl 调用或其他方式确定 SCSI 设备(例如/dev/sda)是否为磁盘?我已尝试以下操作,但 ioctl 调用失败。我的/dev/sda是U盘。

#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

最佳答案

我已经使用 SG_IO 解决了这个问题,并根据 INQUIRY command 的规范直接解释二进制数据。 (field: peripheral device type) 并根据 SCSI Peripheral Device Types 解释(如果 per.dev.type 为 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;
}
}

关于c - 如何通过 ioctl 调用或其他方式确定 SCSI 设备(例如/etc/sda)是否为磁盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2698465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com