Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 22 Jun 2006 20:33:45 -0500
From:      Eric Anderson <anderson@centtech.com>
To:        Dan Nelson <dnelson@allantgroup.com>
Cc:        freebsd-hackers@freebsd.org, Mike Meyer <mwm-keyword-freebsdhackers2.e313df@mired.org>, Andrew <andrew.chace@gmail.com>
Subject:   Re: Coding question: finding the size of a block device
Message-ID:  <449B44F9.70006@centtech.com>
In-Reply-To: <20060622220127.GE74589@dan.emsphone.com>
References:  <1151008839.2360.30.camel@LatitudeFC5.network>	<17563.3550.496244.953904@bhuda.mired.org> <20060622220127.GE74589@dan.emsphone.com>

next in thread | previous in thread | raw e-mail | index | archive | help
Dan Nelson wrote:
> In the last episode (Jun 22), Mike Meyer said:
>> In <1151008839.2360.30.camel@LatitudeFC5.network>, Andrew <andrew.chace@gmail.com> typed:
>>> So I guess my question is: is there a POSIX compatible function that
>>> will allow me to check the size of a given block device?
>> I'd be surprised - POSIX doesn't seem to deal with block devices at all.
>>
>> Checking the sources to df, it uses statfs to get the
>> information. Linux appears to have it as well, so it may be portable.
> 
> statfs only works on mounted filesystems, not arbitrary block devices.
> 
> /usr/sbin/diskinfo uses ioctl(fd, DIOCGMEDIASIZE, &mediasize), where
> mediasize is an off_t.  
> 


Maybe something like this?
-----------


#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdint.h>

#include <sys/disk.h>

int main(int argc, char **argv)
{
         int                     devfd, error;

         if (argc != 2) {
                 fprintf(stderr, "Need to specify device\n");
                 exit(1);
         }
				
         devfd = open(argv[1], O_RDONLY);
         if (devfd < 0) {
                 fprintf(stderr, "Failed to open device\n");
                 exit(1);
         }
				
				error = getdiskinfo(devfd);
				
	return (0);
}

int
getdiskinfo (int fd)
{
	int error;
	off_t	mediasize;
	u_int	sectorsize;

	error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
	if (error)
		printf("ioctl(DIOCGMEDIASIZE) failed, probably not a disk.");
		
	error = ioctl(fd, DIOCGSECTORSIZE, &sectorsize);
	if (error)
		printf("DIOCGSECTORSIZE failed, probably not a disk.");

	printf("Sector size: %d \n", sectorsize);
	printf("Media size: %jd\n", (intmax_t)mediasize);
	printf("Media: %jd sectors\n", (intmax_t)mediasize/sectorsize);

	return(error);
}

---------------



-- 
------------------------------------------------------------------------
Eric Anderson        Sr. Systems Administrator        Centaur Technology
Anything that works is better than anything that doesn't.
------------------------------------------------------------------------



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?449B44F9.70006>