AuxiliaryProcessMain函数是后台一等公民进程的入口,我们来看一看哪里调用了该入口函数:
StartChildProcess函数为postmaster启动一个an auxiliary process。为AuxiliaryProcessMain拼接输入参数数组argv:“postgres -x%d”。fork一个子进程,调用函数AuxiliaryProcessMain(ac, av)。
static pid_t StartChildProcess(AuxProcType type) { pid_t pid; char *av[10]; int ac = 0; char typebuf[32]; /* Set up command-line arguments for subprocess */ av[ac++] = "postgres"; snprintf(typebuf, sizeof(typebuf), "-x%d", type); av[ac++] = typebuf; av[ac] = NULL; Assert(ac < lengthof(av)); pid = fork_process(); if (pid == 0) { /* child 子进程 */ InitPostmasterChild(); ClosePostmasterPorts(false); /* Close the postmaster's sockets */ /* Release postmaster's working memory context */ MemoryContextSwitchTo(TopMemoryContext); MemoryContextDelete(PostmasterContext); PostmasterContext = NULL; AuxiliaryProcessMain(ac, av); ExitPostmaster(0); } if (pid < 0) { /* in parent, fork failed */ int save_errno = errno; errno = save_errno; switch (type) { case StartupProcess: ereport(LOG,(errmsg("could not fork startup process: %m"))); break; case BgWriterProcess: ereport(LOG, (errmsg("could not fork background writer process: %m"))); break; case CheckpointerProcess: ereport(LOG, (errmsg("could not fork checkpointer process: %m"))); break; case WalWriterProcess: ereport(LOG, (errmsg("could not fork WAL writer process: %m"))); break; case WalReceiverProcess: ereport(LOG, (errmsg("could not fork WAL receiver process: %m"))); break; default: ereport(LOG, (errmsg("could not fork process: %m"))); break; } /* fork failure is fatal during startup, but there's no need to choke immediately if starting other child types fails. 如果是StartupProcess子进程fork失败,fatal级别的错误,需要调用ExitPostmaster(1) */ if (type == StartupProcess) ExitPostmaster(1); return 0; } /* * in parent, successful fork */ return pid; }
AuxProcType的类型如下,下面就是后台一等公民进程,和PG的执行逻辑紧密耦合。
第一组一等公民:StartupProcess、BgWriterProcess、CheckpointerProcess、WalWriterProcess、WalReceiverProcess。调用流程如下:
第二组一等公民:CheckerProcess、BootstrapProcess