Article Title: how to obtain disk information in Linux. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
All users familiar with Linux know that the naming rules for hard disks in Linux are had, hdb, etc... Sda, sdb, etc. But how can we know how many hard disks are on the machine?
At the beginning, I thought the/dev directory would show some results. I found that the existence of the device file does not represent this device. So what should we do. Then I found that fdisk can get the number of hard disks. So I read the fdisk source code. We found a way to get the number of hard disks in Linux. The instance code is as follows:
# Include
# Include
Int GetDiskCount ()
{
FILE * f = fopen ("/proc/partitions", "r ");
If (! F)
{
Fprintf (stderr, "fopen/proc/partitions failed! Errno = % d \ n ", errno );
Return 0;
}
Char line [100], ptname [100], devname [120], * s;
Int ma, mi, sz;
Int nDiskCount = 0;
While (fgets (line, sizeof (line), f ))
{
If (sscanf (line, "% u % [^ \ n]",
& Ma, & mi, & sz, ptname )! = 4)
Continue;
For (s = ptname; * s; s ++)
Continue;
/* Note: excluding '0': e.g. mmcblk0 is not a partition name! */
If (s [-1]> = '1' & s [-1] <= '9 ')
Continue;
NDiskCount ++;
}
Fclose (f );
Return nDiskCount;
}
Int main (int argc, char * argv [])
{
Printf ("DiskCount: % d \ n", GetDiskCount ());
Return 0;
}
In fact, the principle is very simple. Is obtained through the proc file system. In the proc file system, there is a file named partitions. This file contains the hard disk and partition information of the local disk. According to the device naming rules in Linux, if the last character of the device name is a number, it should be a partition, otherwise it is a hard disk. Therefore, we can easily know several hard disks in the computer.
Of course, based on this file, you can also know the hard disk device name, the number of partitions in each hard disk, and the name of the device in each partition. Everyone should know how to get it.
[1] [2] Next page