Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block device information without mounting in Linux

I am trying to get some information (specifically block size) of block device in linux, in C++. Is it possible to get block size of a device without mounting it and possibly without looking into dynamic files (like the ones in /sys), but with a system call only.

I was trying with stat, but it returns data about /dev filesystem if I ask about /dev/sdb2.

If it's impossible with system call, where should i look in dynamic files (haven't been able to locate it either.)

like image 500
j_kubik Avatar asked Dec 07 '11 13:12

j_kubik


People also ask

What is block device file in Linux?

Block devices are nonvolatile mass storage devices whose information can be accessed in any order. Hard disks, floppy disks, and CD-ROMs are examples of block devices. OpenBoot typically uses block devices for booting.

How do I access a blocked device in Linux?

The block devices on a system can be discovered with the lsblk (list block devices) command. Try it in the VM below. Type lsblk at the command prompt and then press Enter.

Is not a block device mount?

mount attaches block storage devices that contain a filesystem to a directory, which is not what you're trying to do, hence the error message. What you want is to create a link from the new directory name to the old existing name. For that you must use the ln command to create a symbolic link.

What is block device name?

Examples of block devices are hard disk, flash drives, CD-ROM.


1 Answers

You want to use ioctl, in particular BLKSSZGET.

Quoting linux/fs.h:

#define BLKSSZGET  _IO(0x12,104)/* get block device sector size */

Untested example:

#include <sys/ioctl.h>
#include <linux/fs.h>

int fd = open("/dev/sda");
size_t blockSize;
int rc = ioctl(fd, BLKSSZGET, &blockSize);
like image 83
2 revs, 2 users 89% Avatar answered Oct 14 '22 15:10

2 revs, 2 users 89%