Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reinitialize Boost Log library on fork?

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

[..] so for now it's up to users to reinitialize the library at fork. You can use pthread_atfork to do such reinitialization.

Thus my question: how exactly do I re-initialize Boost.Log after a fork()?

Code example much appreciated.

like image 620
maxschlepzig Avatar asked Aug 31 '13 16:08

maxschlepzig


1 Answers

You have to take care of all the sinks, and recreate them in the pthread_atfork handler in the child process_. I.e. the add_console_log or add_file_log functions return a boost::shared_ptr to the sink. Reset that, and initialize it 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 fork may leave more things behind than just broken log sink. Stay away from multi-threading and fork by all means (its some irony that pthread library provides the handler for fork, which you want to avoid if there are threads ...).

like image 88
schroder Avatar answered Nov 02 '22 06:11

schroder