简体   繁体   中英

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.

You have to take care of all the sinks, and recreate them in the pthread_atfork handler in the child process_. Ie 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 ...).

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