[cs631apue] Midterm Question

Jan Schaumann jschauma at stevens.edu
Tue Sep 25 23:58:21 EDT 2012


tparisi <tparisi at stevens.edu> wrote:
> Then I am confused because st_blocks holds the number of blocks the file 
> is allocated.  What size blocks would that be calculated for?

The hard drive presented to the OS has physical blocks.  These are 512
bytes in size.  The Unix File System makes the number of these physical
blocks occupied by a file available via the st_blocks member of the
struct stat.

When you test this, make sure to compare output on a local file system.
(On linux-lab.cs.stevens.edu your home directory is on a network file
system, which may cause some unexpected results.  Make sure to change to
a local directory.)

This is on linux-lab.cs.stevens.edu:

$ cd /tmp
$ mkdir d
$ cd d
$ dd if=/dev/zero of=file bs=512 count=500
500+0 records in
500+0 records out
256000 bytes (256 kB) copied, 0.00294901 s, 86.8 MB/s

We just created a file containing 500 512 byte blocks.

$ du -h file
256K    file

The file is -- in "human" units -- 256K (256K = 256000 bytes = 500 * 512
bytes).

$ ls -ls file
256 -rw------- 1 jschauma professor 256000 Sep 25 23:44 file

Note: linux's ls(1) appears to default to a blocksize of 1K (on this
system), showing that this file uses 256 blocks.  You can confirm this
by running:

$ export BLOCKSIZE=512
$ ls -ls file          
512 -rw------- 1 jschauma professor 256000 Sep 25 23:44 file
$ export BLOCKSIZE=4096
$ ls -ls file
64 -rw------- 1 jschauma professor 256000 Sep 25 23:44 file
$ ls -lsk file
256 -rw------- 1 jschauma professor 256000 Sep 25 23:44 file

(-k overwrites whatever BLOCKSIZE is set in the environment and sets a
blocksize of 1K)


If you were to repeat the same commands on a different unix system, you
might get slightly different results, depending on what the tool assumes
as the default.  I admit it is confusing that linux's ls(1) does not use
512 bytes for '-s', and doesn't even mention in the manual page what its
default blocksize is.


Let me know if this doesn't help clear things up for you.

-Jan


More information about the cs631apue mailing list