有时候真是庸人自扰

相信任何非自娱自乐的项目都会有日志这一功能,而稍微复杂一些的项目必然会有多进程多线程的实现,于是不管是自己造轮子还是网上扒代码,我们都会看到一堆在写操作上加锁的日志模块,又是IO,又是读写锁,看得真是头疼,容错率也是可以想象的低,一旦出了什么错误,估计就全部卡死。

悲剧的是实际上用个c标准库的fwrite,操作系统就帮你解决全部问题了,MSDN上是这么说得:

MSDN 写道
The fwrite function writes up to count items, of size length each, from buffer to the output stream. The file pointer associated with stream (if there is one) is incremented by the number of bytes actually written. If stream is opened in text mode, each carriage return is replaced with a carriage-return – linefeed pair. The replacement has no effect on the return value.

This function locks the calling thread and is therefore thread-safe. For a non-locking version, see _fwrite_nolock.

 而著名的APUE也差不多

APUE 写道
若有多个进程,线程用标准I/0添写方式打开同一个文件,那么来自每个进程,线程的数据都将正确地写到文件中。

那么,日志模块直接用fwrite追加就结了

猜你喜欢

转载自bukkake.iteye.com/blog/767759