Coding question: finding the size of a block device

Eric Anderson anderson at centtech.com
Fri Jun 23 01:55:29 UTC 2006


Dan Nelson wrote:
> In the last episode (Jun 22), Mike Meyer said:
>> In <1151008839.2360.30.camel at LatitudeFC5.network>, Andrew <andrew.chace at 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.
------------------------------------------------------------------------


More information about the freebsd-hackers mailing list