---
title: "pg启动过程中的那些事二：初始化PostmasterContext"
author: "BeiGang"
date: "2011-11-27T09:11:31Z"
tags: []
categories: ["数据库"]
slug: "pg-postmastercontext"
draft: false
lastmod: "2011-11-27T09:11:31Z"
id: 1279177
url: "https://beigang.iteye.com/blog/1279177"
---

**1先上个示意图，看一下函数调用过程梗概，中间略过部分细节**

**![](http://dl.iteye.com/upload/attachment/596007/a5f2140d-5265-3d41-983c-aa47dded37bf.bmp)**  
 

前面标3的是初始化PostmasterContext

**初始化PostmasterContext的方法调用流程图**

 

**2初始化PostmasterContext的过程**

话说main()-&gt;…-&gt;PostmasterMain()-&gt;…-&gt;MemoryContextInit()-&gt;AllocSetContextCreate()（“-&gt;” 表示调用），初始化完TopMemoryContext和ErrorContext，这之后，main()-&gt;…-&gt;PostmasterMain()-&gt;AllocSetContextCreate()初始化PostmasterContext，PostmasterContext是MemoryContext类型的全局变量，定义如下：

MemoryContext PostmasterContext = NULL;

 

PostmasterContext的类型和TomMemoryContext、ErrorContext是一样的，都是MemoryContext。有了《pg启动过程中的那些事一》垫底，这个写起来就容易了。初始化PostmasterContext的过程和ErrorContext基本上是一样的。所以下面就直接上初始化完以后的结构图了。不过前面只有TomMemoryContext和ErrorContext的内存结构图加上内存空间管理的AllocBlock和AllocChunk，看起来已经让人眼花缭乱了，这里把AllocBlock和AllocChunk相关部分删掉，突出MemoryContext全局变量之间的关系。

 

 

**![](http://dl.iteye.com/upload/attachment/596009/acf096c8-a5a5-3c60-bdc5-420581e34a00.bmp)**

PostmasterContext、TomMemoryContext、ErrorContext的结构图

TomMemoryContext的firstchild指向PostmasterContext，PostmasterContext的nextchild指向ErrorContext，形成了树形结构。PostmasterContext、ErrorContext的parent成员指向TomMemoryContext，形成了环。整体上构成了图。

    PostmasterContext在AllocBlock和AllocChunk中的位置，见下面示意图，图中红色的那一块就是PostmasterContext，里面的成员和其他细节就不画了，要不然看起来就天下大乱了。

 

 

![](http://dl.iteye.com/upload/attachment/596011/c782ea50-fcf1-3d51-a527-e48bdef2d085.bmp)  
 

 

 

PostmasterContext在内存中的AllocBlock和AllocChunk中的位置

       有了《pg启动过程中的那些事一》和这篇文章垫底，再要理解pg中内存分配的机制就容易了。