简体   繁体   中英

which is better for writing a sensitive log file from C++, write() on a file descriptor or fprintf() on a FILE?

My understanding is that write() is a system call, which is extremely slow. (It's almost like a kind of inter-process communication.) Anything that works with FILE is buffered and only does a system call every 512 bytes or what have you. So speed-wise FILE should be much faster.

But if you have a log message followed by something that causes a coredump, there is no mechanism I know of whereby the OS could go dig up the FILE 's buffer and write it do disk. So, you could easily be missing the last 5-10 lines of your log file. For software like finance software, where bugs can literally cost billions and you don't want to have any bug twice, and therefore need great logging, that would be bad.

At least that was the stance 25 years ago. I'm curious whether things have changed these days? For instance is there a mechanism whereby OS's tell standard C libraries to flush output buffers even after a SEGV or something? If so then FILE suddenly looks a lot better: speed without the reliability. Plauger in his 1992 book on the Standard C Library mentioned that in theory write() could also be a buffered function of some sort instead of a system call.

Part of the question is: are there any compilation options on Windows or Linux that affects this tradeoff? Not just -O2 , say, but options that actually affect buffer flushing upon core dump?

This isn't a theoretical question into what's allowed, but rather a practical question about today's and upcoming Linux and Windows. While I know the various standards in question will promise some or another level of reliability or performance, often these are weakened to the point of uselessness as they're trying to cover rare situations like a C interpreter, or code running on an 80s Cray, or something. Also, while I can (and am) testing this myself, my question is a bit broader than just what today's software gives me with default compilation options.

Things has not changed. CRT and OS kernel still separate kingdoms. And there are no such options that would affect this. You have to take care yourself with special means. Hint: look into memory mapped files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM