gpt4 book ai didi

c - 如何在 Linux 中获取 USB 连接的硬盘串口?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:54:34 24 4
gpt4 key购买 nike

我有一个需求,在外接硬盘上创建一个文件。创建的文件应该包含硬盘的序列号,并且该文件可以被其他进程使用。

我尝试使用下面的代码

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/hdreg.h>

int main(int argc, char *argv[])
{
static struct hd_driveid hd;
int fd;

if (geteuid() > 0) {
printf("ERROR: Must be root to use\n");
exit(1);
}

if ((fd = open(argv[1], O_RDONLY|O_NONBLOCK)) < 0) {
printf("ERROR: Cannot open device %s\n", argv[1]);
exit(1);
}

if (!ioctl(fd, HDIO_GET_IDENTITY, &hd)) {
printf("Hard Disk Model: %.40s\n", hd.model);
printf(" Serial Number: %.20s\n", hd.serial_no);
} else if (errno == -ENOMSG) {
printf("No hard disk identification information available\n");
} else {
perror("ERROR: HDIO_GET_IDENTITY");
exit(1);
}

exit(0);
}

这对内部硬盘工作正常,但是当我对外部硬盘(usb)执行此操作时,出现以下错误

ERROR: HDIO_GET_IDENTITY: Invalid argument

最佳答案

因为设备连接到 USB 桥,您无法发送 HDIO_GET_IDENTITY 命令。您可以尝试使用 hdparm 来查询设备的身份。使用默认选项,hdparm 无法识别设备,因此您必须使用 -d 指定设备类型(参见 USB devices and smartmontools )。

没有 -d 选项,我得到:

$ sudo smartctl /dev/sdc
/dev/sdc: Unknown USB bridge [0x059f:0x1011 (0x000)]
Please specify device type with the -d option.

使用 -d sat,autohdparm 设法显示有关设备的一些信息:

$ sudo smartctl -d sat,auto -i /dev/sdc
/dev/sdc [SCSI]: Device open changed type from 'sat,auto' to 'scsi'
=== START OF INFORMATION SECTION ===
Vendor: ST2000VN
Product: 000-1H3164
User Capacity: 2 000 398 934 016 bytes [2,00 TB]
Logical block size: 512 bytes
Device type: disk
Local Time is: Thu Mar 13 09:41:32 2014 CET
SMART support is: Unavailable - device lacks SMART capability.

您可以尝试在 C 程序中执行与 smartctl 相同的操作,但编写调用 smartctl 的脚本可能更容易。

关于c - 如何在 Linux 中获取 USB 连接的硬盘串口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22372316/

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