五花八门客户问题(BUG) - 重复打印

根据commit猜测客户问题

git://sourceware.org / glibc.git / commitcommitsummary | shortlog | log | commit | commitdiff | tree
(parent: 4573c6b) | patch
Don't flush write buffer for ftell
author	Siddhesh Poyarekar <siddhesh@redhat.com>	
Fri, 28 Sep 2012 13:07:23 +0000 (18:37 +0530)
committer	Siddhesh Poyarekar <siddhesh@redhat.com>	
Fri, 28 Sep 2012 13:08:14 +0000 (18:38 +0530)
commit	adb26faefe47b7d34c941cbfc193ca7a5fde8e3f
tree	799a1e10dae3c9aac2b9c2c79e0b8adaaa1eae90	tree
parent	4573c6b09884a93fffa3a754678ef881cadebfb3	commit | diff
Don't flush write buffer for ftell

真实客户问题

客户发现打印到文件的内容重复了。这不是普通文件,我们是做数据库的,影响很大。

问题所在

大喜的是问题很好重现,所以直接debug吧。在所有的fwrite函数上下断点,愣是没看出来怎么重复的。后来才怀疑到fwrite+fork这项操作上。如下是一个简易版的重现代码。踩踩结果吧:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>void main(){FILE* file=fopen("test.txt", "a+");fwrite("First", 1, 5, file);fwrite("Secon", 1, 5, file);ftell(file); /*NOTE: redhat 6/AIX7  flushs the data, while centos 7 doesn't flush!!!!*///setbuf(file, 0);if(fork()>0){fwrite("In Parent", 1, 9, file);exit(0);}else{fclose(file);}
}

结果:FirstSeconIn ParentFirstSecon

相信读者应该已经注意到上面的注释了,与glibc中的ftell有关系,redhat6中ftell不会强刷缓冲中的数据到磁盘,但是redhat7却会,这是文章一开始的glibc的commit导致的。基础软件的一点点更新都是影响巨大啊。

fix办法

fix也很简单,只需要在fork之前调用下fflush即可。