テスト用に10MBのループバックデバイスを作成、ext3でフォーマット、マウント、オーナーを変更して書き込み出来るようにしておく。
# dd if=/dev/zero of=./disk bs=1M count=10
10+0 records in
10+0 records out
10485760 bytes (10 MB) copied, 0.312561 s, 33.5 MB/s
# mkfs.ext3 disk
mke2fs 1.41.12 (17-May-2010)
disk is not a block special device.
Proceed anyway? (y,n) y
Filesystem label=
OS type: Linux
Block size=1024 (log=0)
Fragment size=1024 (log=0)
Stride=0 blocks, Stripe width=0 blocks
2560 inodes, 10240 blocks
512 blocks (5.00%) reserved for the super user
First data block=1
Maximum filesystem blocks=10485760
2 block groups
8192 blocks per group, 8192 fragments per group
1280 inodes per group
Superblock backups stored on blocks:
8193
Writing inode tables: done
Creating journal (1024 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem will be automatically checked every 30 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.
# mount -o loop -t ext3 disk /*********/mnt
# chown ****:**** /*********/mnt
マウントされたファイルシステムの中に適当なファイルを作成し、これに1バイトごと書き込む。エラーが10回起きたら終了させる。エラーの判定はfprintfの戻り値が1でないこと。これを行うコードが以下。
#include <stdio.h>
int main(int argvc, char *argv[])
{
FILE *fp;
if ((fp = fopen(argv[1], "w")) == NULL) {
printf("Can't open %s\n", argv[1]);
return 1;
}
int i = 0;
int j = 0;
int a = 0;
for (i = 0; j < 10; i++) {
a = fprintf(fp, "%s", "a");
if (a != 1) {
printf("%d\t%d\t%d\n", j, i, a);
j++;
}
}
fclose(fp);
return 0;
}
結果が以下。ファイルが書き込めなくなるとfprintf文は-1を返すが、そのタイミングは、バッファフラッシュが起こるタイミングで、このシステムの場合、1024バイトごとにエラーになっていることがわかる。
$ ./print_test ~/mnt/test0 0 8468480 -1 1 8469505 -1 2 8470530 -1 3 8471555 -1 4 8472580 -1 5 8473605 -1 6 8474630 -1 7 8475655 -1 8 8476680 -1 9 8477705 -1 $ ./print_test ~/mnt/test1 0 1024 -1 1 2049 -1 2 3074 -1 3 4099 -1 4 5124 -1 5 6149 -1 6 7174 -1 7 8199 -1 8 9224 -1 9 10249 -1