模組載入
php載入模組會統一呼叫zm_startup_xxx(int type, int module_number)
函式(xxx為模組名),在swoole原始碼中實際為swoole.cc的PHP_MINIT_FUNCTION(swoole)
部分程式碼。
在PHP_MINIT_FUNCTION(swoole)
裡主要是向php註冊模組相關的內容,如類、函式、常量、別名。我們所需要關注的是swoole_init();
這個函式的呼叫。
void swoole_init(void)
{
if (SwooleG.init)
{
return;
}
bzero(&SwooleG, sizeof(SwooleG));
bzero(&SwooleWG, sizeof(SwooleWG));
bzero(sw_error, SW_ERROR_MSG_SIZE);
SwooleG.running = 1;
SwooleG.init = 1;
SwooleG.enable_coroutine = 1;
SwooleG.log_fd = STDOUT_FILENO;
SwooleG.write_log = swLog_put;
SwooleG.fatal_error = swoole_fatal_error;
SwooleG.cpu_num = SW_MAX(1, sysconf(_SC_NPROCESSORS_ONLN));
SwooleG.pagesize = getpagesize();
//get system uname
uname(&SwooleG.uname);
//random seed
srandom(time(NULL));
SwooleG.pid = getpid();
#ifdef SW_DEBUG
SwooleG.log_level = 0;
SwooleG.trace_flags = 0x7fffffff;
#else
SwooleG.log_level = SW_LOG_INFO;
#endif
//init global shared memory
SwooleG.memory_pool = swMemoryGlobal_new(SW_GLOBAL_MEMORY_PAGESIZE, 1);
if (SwooleG.memory_pool == NULL)
{
printf("[Core] Fatal Error: global memory allocation failure");
exit(1);
}
if (swMutex_create(&SwooleG.lock, 0) < 0)
{
printf("[Core] mutex init failure");
exit(1);
}
SwooleG.max_sockets = 1024;
struct rlimit rlmt;
if (getrlimit(RLIMIT_NOFILE, &rlmt) < 0)
{
swSysWarn("getrlimit() failed");
}
else
{
SwooleG.max_sockets = MAX((uint32_t) rlmt.rlim_cur, 1024);
SwooleG.max_sockets = MIN((uint32_t) rlmt.rlim_cur, SW_SESSION_LIST_SIZE);
}
SwooleG.socket_buffer_size = SW_SOCKET_BUFFER_SIZE;
SwooleG.socket_array = swArray_new(1024, sizeof(swSocket));
if (!SwooleG.socket_array)
{
swSysWarn("[Core] Fatal Error: socekt array memory allocation failure");
exit(1);
}
SwooleTG.buffer_stack = swString_new(SW_STACK_BUFFER_SIZE);
if (SwooleTG.buffer_stack == NULL)
{
exit(3);
}
if (!SwooleG.task_tmpdir)
{
SwooleG.task_tmpdir = sw_strndup(SW_TASK_TMP_FILE, sizeof(SW_TASK_TMP_FILE));
SwooleG.task_tmpdir_len = sizeof(SW_TASK_TMP_FILE);
}
char *tmp_dir = swoole_dirname(SwooleG.task_tmpdir);
//create tmp dir
if (access(tmp_dir, R_OK) < 0 && swoole_mkdir_recursive(tmp_dir) < 0)
{
swWarn("create task tmp dir(%s) failed", tmp_dir);
}
if (tmp_dir)
{
sw_free(tmp_dir);
}
//init signalfd
#ifdef HAVE_SIGNALFD
swSignalfd_init();
SwooleG.use_signalfd = 1;
SwooleG.enable_signalfd = 1;
#endif
}
swoole_init()
中主要是對SwooleG
做一個初始化的賦值操作。SwooleG
是一個本地的全域性變數,記錄的swoole的基礎資訊,具體可搜尋swGlobal_t
。重點的初始化包括共享記憶體、鎖、訊號。接下來會依次講解它們相關的概念以及執行過程。