How to reinitialize Boost Log library on fork?
Asked Answered
S

1

9

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.

Shaikh answered 31/8, 2013 at 16:4 Comment(1)
@marathon, unfortunately, no, I did not.Shaikh
P
1

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 ...).

Prison answered 15/9, 2015 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.