static inline void native_cpuid(unsigned int *eax, unsigned int *ebx,
unsigned int *ecx, unsigned int *edx)
{
/* ecx is often an input as well as an output. */
asm volatile("cpuid"
: "=a" (*eax),
"=b" (*ebx),
"=c" (*ecx),
"=d" (*edx)
: "0" (*eax), "2" (*ecx))
}
int main(int argc, char **argv)
{
unsigned eax, ebx, ecx, edx
eax = 1/* processor info and feature bits */ native_cpuid(&eax, &ebx, &ecx, &edx)
printf("stepping %d\n", eax &0xF)
printf("model %d\n", (eax >>4) &0xF)
printf("family %d\n", (eax >>8) &0xF)
printf("processor type %d\n", (eax >>12) &0x3)
printf("extended model %d\n", (eax >>16) &0xF)
printf("extended family %d\n", (eax >>20) &0xFF)
}
1、在Linux系统中通过C语言获取硬盘序列号,可以借助于ioctl()函数,该函数原型如下:
int ioctl(int fd, unsigned long request, ...) ioctl的第一个参数是文件标识符,用open()函数打开设备时获取。ioctl第二个参数为用于获得指定文件描述符的标志号,获取硬盘序列号,一般指明为HDIO_GET_IDENTITY。
ioctl的第三个参数为一些辅助参数,要获取硬盘序列号,需要借助于struct hd_driveid结构体来保存硬盘信息 ,该结构体在Linux/hdreg.h中,struct hd_driveid的声明如下 struct hd_driveid {
unsigned short config / lots of obsolete bit flags */
unsigned short cyls /* Obsolete, "physical" cyls */
unsigned short reserved2 /* reserved (word 2) */
unsigned short heads /* Obsolete, "physical" heads */
unsigned short track_bytes /* unformatted bytes per track */
unsigned short sector_bytes /* unformatted bytes per sector */
unsigned short sectors /* Obsolete, "physical" sectors per track */
unsigned short vendor0 /* vendor unique */
unsigned short vendor1 /* vendor unique */
unsigned short vendor2 /* Retired vendor unique */
unsigned char serial_no[20] /* 0 = not_specified */
unsigned short buf_type /* Retired */
unsigned short buf_size /* Retired, 512 byte increments
* 0 = not_specified
*/
……
}
2、源代码如下
#include <stdio.h>//ioctl()的声明头文件
#include <sys/ioctl.h>
//硬盘参数头文件, hd_driveid结构声明头文件
#include <linux/hdreg.h>
//文件控制头文件
#include <sys/fcntl.h>
int main()
{
//用于保存系统返回的硬盘数据信息
struct hd_driveid id
//这里以第一块硬盘为例,用户可自行修改
//用open函数打开获取文件标识符,类似于windows下的句柄
int fd = open("/dev/sda", O_RDONLY|O_NONBLOCK)
//失败返回
if (fd < 0) {
perror("/dev/sda")
return 1 }
//调用ioctl()
if(!ioctl(fd, HDIO_GET_IDENTITY, &id))
{
printf("Serial Number=%s\n",id.serial_no)
}
return 0
}
编译完成后,执行效果如下:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)