[cs631apue] block sizes

Jan Schaumann jschauma at stevens.edu
Mon Oct 19 09:24:05 EDT 2015


Julian Sexton <jsexton at stevens.edu> wrote:
> The stat values of files seem to return the block count of the file based on
> blocks of size 512 bytes. Is there an API to change this? Also, is the
> default for ls 1024 byte blocks? It seems to consistently return half of
> what stat does.

The '-s' option is documented as reporting the blocks used by the file
in 512 bytes (the common standard physical block size of most hard
drives) or in BLOCKSIZE bytes.  That is, the behaviour can be changed by
setting the BLOCKSIZE variable in your environment.

(This can be confusing if the filesystem does not use or report using 512
byte blocks in the struct stat's st_blksize.  For example, on NFS, you
get very different results from the local ext3 file system.)

$ cd /var/tmp
$ dd if=/dev/zero of=foo count=1024 bs=512k
1024+0 records in
1024+0 records out
536870912 bytes (537 MB) copied, 0.818751 s, 656 MB/s
$ ls -lsk foo
524804 -rw------- 1 jschauma professor 536870912 Oct 19 09:17 foo
$ stat -c "%b" foo
1049608
$ 

What's worse, the linux ls(1) has a bug in that it actually reports
1024k sized blocks by default, ie as if '-sk' had been given, even
though stat(2) correctly returns the number of 512 byte blocks.

This illustrates that unfortunately sometimes the system tools we rely
on still contain bugs or behave differently from the documented
behaviour even after decades of use.

Your version should behave as documented and report the number of 512
byte blocks (or BLOCKSIZE if set in the environment).

Compare output of the following invocations:

ls -s
ls -sk
BLOCKSIZE=1024 ls -s
BLOCKSIZE=512 ls -s
BLOCKSIZE=2048 ls -s
BLOCKSIZE=-512000 ls -s
BLOCKSIZE= ls -s
BLOCKSIZE="this is not a number" ls -s


You can also find similar discussions of the block size in the mailing
list archives from previous semesters, which is often a useful source of
information.

-Jan


More information about the cs631apue mailing list