Get disk physical size by ioctl

code:

/* 
 * gcc -g -o run-as-root run-as-root.c
 * chown root.root ./run-as-root
 * chmod 4755 ./run-as-root
 *
 * */
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

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

int blk_get_size (char *dev, unsigned long long *bytes)
{
  int ret = -1;
  int fd = open (dev, O_RDONLY);
  if (fd < 0) {
    printf ("dev: %s open error\n", dev);
    return ret;
  }
  if (ioctl(fd, BLKGETSIZE64, bytes) >= 0)
    ret = 0;
  close (fd);
  // KB not 1024
  int total = *bytes / 1000;
  // MB not 1024
  total = total / 1000;
  printf ("dev: %s size: %.1f %s byte: %lld\n", 
	  dev, 
	  (total > 1000) ? (float)total/1000 : total,
          (total > 1000) ? "GB" : "MB",
          *bytes);

  return ret;
}

int
main(int argc, char **argv)
{
  uid_t uid = getuid();
  if(setuid(0)) {
    printf ("dev: set root uid error\n");
    return 0;
  }

  unsigned long long bytes = 0;
  // test
  blk_get_size ("/dev/sda", &bytes);
  blk_get_size ("/dev/sda1", &bytes);
  blk_get_size ("/dev/sda2", &bytes);
  blk_get_size ("/dev/sda3", &bytes);
  blk_get_size ("/dev/sdaa", &bytes);
  blk_get_size ("/dev/sdb", &bytes);

  if(setuid(uid)) {
    printf ("dev: set user uid error\n");
  }

  return 0;
}

 

你可能感兴趣的:(C++,c,linux,C#,gcc)