ioctl获取磁盘大小

37 views
Skip to first unread message

Zhang Jun

unread,
Sep 28, 2010, 8:05:10 PM9/28/10
to perlchina
有这样一些小程序, 不知道用perl如何实现:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <linux/fs.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ioctl.h>


int main(void) {

  int fd, ret;
  unsigned long long size;

  fd = open("/dev/sda", O_RDONLY);

  if (fd == -1)
    exit(-1);

  ret = ioctl(fd, BLKGETSIZE64, &size);

  if (ret == 0) {
    printf("disk size: %llu\n", size);
  }

  return(0);
}

% ./get_size
disk size: 160041885696


% cat size.pl
#!/usr/bin/perl

require "sys/ioctl.ph";

my $buf;
my $ret;

my $fd;

open($fd, "</dev/sda") or die "$!";

$ret = ioctl($fd, BLKGETSIZE64, $buf) || -1;

@data = unpack("LL", $buf);
print "ret = $ret\n";
print "disk size=", $data[0], "\n";
close($fd);
###########################################

% perl size.pl
ret = -1
disk size=0


返回值应该是64位无符号整形


PIG

unread,
Oct 2, 2010, 12:29:42 AM10/2/10
to perl...@googlegroups.com
`df -h`

> --
> 您收到此邮件是因为您订阅了 Google 网上论坛的"PerlChina Mongers 讨论组"论坛。
> 要向此网上论坛发帖,请发送电子邮件至 perl...@googlegroups.com
> 要取消订阅此网上论坛,请发送电子邮件至 perlchina+...@googlegroups.com
> 若有更多问题,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问此网上论坛。
>

Zhang Jun

unread,
Oct 5, 2010, 5:24:19 AM10/5/10
to perl...@googlegroups.com
解决了,
当时BLKGETSIZE64这个值不对, 直接写上BLKGETSIZE64对应的数字就可以了,
再把u_int64的返回值unpack成两个u_int, 位移相加,
或者有个名字类似convert::c的模块也可以的.
Reply all
Reply to author
Forward
0 new messages