How to reinitialize Boost Log library on fork?

Boost.Log does not support fork () . This is unbelievable, but the comment describes a workaround:

[..], so now for users you need to reinitialize the library in fork. You can use pthread_atfork for such reinitialization.

So my question is: how exactly do I reinitialize Boost.Log after fork ()?

Sample code is very appreciated.

+8
c ++ boost logging fork boost-log
source share
1 answer

You must take care of all the receivers and recreate them in the pthread_atfork handler in the child process_. That is, the add_console_log or add_file_log return a boost::shared_ptr to the receiver. Reset, and initialize again.

 ... boost::shared_ptr< sinks::synchronous_sink< sinks::text_ostream_backend > > console_sink = logging::add_console_log(); ... void fork_child_handler(void) { console_sink = logging::add_console_log(); return; } // in some global setup code of your application pthread_atfork(NULL /*prepare*/, NULL /* parent */, &fork_child_handler); 

Take care that a fork can leave more than just broken logs. Stay away from multithreading and fork all means (its some irony that the pthread library provides a fork handler that you want to avoid if there are threads ...).

+1
source share

All Articles