Getting the size of a block device

In Linux at least, one cannot simply get the size of a block device file
(e.g., /dev/sda) by using the normal means of requesting the file size.
One must use a special command, such as

/sbin/blockdev --getsz /dev/sda

Likewise, my experimentation shows that File.size(’/dev/sda’) in Ruby
returns a bogus value. How does one get the size of a block device file
in Ruby?

Obviously, I could wrap a system call around a Linux utility or read a
proc file… but I am curious if there is a ‘built-in’ Ruby method.

Terry M. wrote:

Obviously, I could wrap a system call around a Linux utility or read a
proc file… but I am curious if there is a ‘built-in’ Ruby method.

The ioctl is called BLKGETSIZE/BLKGETSIZE64, and a quick grep of the
ruby source code doesn’t find it.

Maybe someone else has published an extension which wraps the API
directly, but you could just use IO.ioctl directly.

$ sudo blockdev --getsz /dev/sda
976773168

$ sudo strace blockdev --getsz /dev/sda 2>&1 | grep ioctl
ioctl(3, BLKGETSIZE64, 0x7fff486af378) = 0

$ sudo strace -e raw=ioctl blockdev --getsz /dev/sda 2>&1 | grep ioctl
ioctl(0x3, 0x80081272, 0x7fffacd73d68) = 0

$ sudo ruby -e ‘v = [0].pack(“Q”);
File.open("/dev/sda").ioctl(0x80081272, v); v = v.unpack(“Q”)[0]; puts
v’
500107862016

But I’m not sure that’s exactly right; it gives the size in bytes rather
than blocks.

On 10/09/2010 05:35 AM, Brian C. wrote:

Terry M. wrote:

Obviously, I could wrap a system call around a Linux utility or read a
proc file… but I am curious if there is a ‘built-in’ Ruby method.

The ioctl is called BLKGETSIZE/BLKGETSIZE64, and a quick grep of the
ruby source code doesn’t find it.

Maybe someone else has published an extension which wraps the API
directly, but you could just use IO.ioctl directly.

Does the sys-filesystem gem have something like that?

http://rubyforge.org/docman/view.php/610/1562/sys-filesystem.html

Joel VanderWerf wrote in post #946983:

On 10/09/2010 05:35 AM, Brian C. wrote:

Terry M. wrote:

Obviously, I could wrap a system call around a Linux utility or read a
proc file… but I am curious if there is a ‘built-in’ Ruby method.

The ioctl is called BLKGETSIZE/BLKGETSIZE64, and a quick grep of the
ruby source code doesn’t find it.

Maybe someone else has published an extension which wraps the API
directly, but you could just use IO.ioctl directly.

Does the sys-filesystem gem have something like that?

http://rubyforge.org/docman/view.php/610/1562/sys-filesystem.html

I think this only tells the the block size of a mounted file-system. I
would want to be able to find the size of any block device passed in to
my program. Examples: unformatted hard drive; LVM partition; loop
device.