Bitcoin source code 1 SetupEnvironment, noui_connect - killelder/cryptocurrency GitHub Wiki

從bitcoind.cpp裡面可以看到main函數
初始化過程解析
main -> SetupEnvironment(設置環境) -> noui_connect(連接bitcoind信號處理對象)
-> AppInit(初始化) -> ParseParameters(參數解析) -> 參數處理
-> InitLogging(初始化Log) -> InitParameterInteraction(初始化參數)
-> AppInitBasicSetup(初始化基本上下文環境) -> AppInitSanityChecks(應用程序完整性檢查)
-> AppInitMain(應用程序運行主函數) -> WaitForShutdown(循環等待關閉信息)
-> Shutdown(關閉)

比特幣源代碼研讀之一

SetupEnvironment 設置環境

將會涉及到的文件包括
src/bitcond.cpp、src/util.h、src/util.cpp、src/noui.h、src/noui.cpp、
ui_interface.h、ui_interface.cpp

SetupEnvironment在src/util.cpp中
util.cpp主要實現了服務器/客戶端環境的設置, 包括參數處理, 配置文件解析, Log紀錄以及線程封裝等等的初始化

SetupEnvironment分成3個部分組成

  1. 配置內存
#ifdef HAVE_MALLOPT_ARENA_MAX
    // glibc-specific: On 32-bit systems set the number of arenas to 1.
    // By default, since glibc 2.10, the C library will create up to two heap
    // arenas per core. This is known to cause excessive virtual address space
    // usage in our usage. Work around it by setting the maximum number of
    // arenas to 1.
    if (sizeof(void*) == 4) {
        mallopt(M_ARENA_MAX, 1);
    }
#endif

這邊的目的是為了防止32位操作系統中虛擬地址空間過度使用(不是很了解)

  1. 本地化設置
#if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
    try {
        std::locale(""); // Raises a runtime error if current locale is invalid
    } catch (const std::runtime_error&) {
        setenv("LC_ALL", "C", 1);
    }
#endif

配置區域, 國家, 編碼, 日期格式, 區域有關的設置, 當無效的時候使用C語言的環境做後備

  1. 本地化文件路徑設置
    // The path locale is lazy initialized and to avoid deinitialization errors
    // in multithreading environments, it is set explicitly by the main thread.
    // A dummy locale is used to extract the internal default locale, used by
    // fs::path, which is then used to explicitly imbue the path.
    std::locale loc = fs::path::imbue(std::locale::classic());
    fs::path::imbue(loc);

信號處理noui_connect

noui_connect在noui.cpp中, 表示的是no ui的信息連接
處理的信息包括三類: 消息彈出框提示信息, 對用戶問題詢問的交互提示信息, 程序初始化過程的信息
noui_connect()3行代碼中, uiInterface調用了三個變量

void noui_connect()
{
    // Connect bitcoind signal handlers
    uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox);
    uiInterface.ThreadSafeQuestion.connect(noui_ThreadSafeQuestion);
    uiInterface.InitMessage.connect(noui_InitMessage);
}

uiInterface是客戶端UI通訊信號接口, 定義在"ui_interface.cpp"