Nginx内存池(六)——内存池源码编译测试

Nginx源码编译

jyhlinux@ubuntu:~/nginx-1.12.2$ sudo ./configure 

jyhlinux@ubuntu:~/nginx-1.12.2$ sudo ./configure --without-http_rewrite_module

jyhlinux@ubuntu:~/nginx-1.12.2$ sudo make

测试代码如下

#include <ngx_config.h>
#include <nginx.h>
#include <ngx_core.h>
#include <ngx_palloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void ngx_log_error_core(ngx_uint_t level, ngx_log_t *log, ngx_err_t err,
            const char *fmt, ...)
{
    
    

}

typedef struct Data Data_t;
struct Data
{
    
    
    char *ptr;
    FILE *pfile;
};

void func1(char *p)
{
    
    
    printf("free ptr mem!\n");
    free(p);
}

void func2(FILE *pf)
{
    
    
    printf("close file!\n");
    fclose(pf);
}

void main()
{
    
    
    // 创建内存池,小块内存池可分配最大内存为512
    ngx_pool_t *pool = ngx_create_pool(512, NULL);
    if(NULL == pool)
    {
    
    
        printf("ngx_create fail...");
        return;
    }

    void *p1 = ngx_palloc(pool, 128); // 从小块内存分配
    if(NULL == p1)
    {
    
    
        printf("ngx_palloc 128 bytes fail...");
        return;
    }

    Data_t *p2 = ngx_palloc(pool, 512); // 从大块内存分配
    if(NULL == p2)
    {
    
    
        printf("ngx_palloc 512 bytes fail...");
        return;
    }

    p2->ptr = malloc(12);
    strcpy(p2->ptr, "hello world");
    p2->pfile = fopen("data.txt", "w");

    ngx_pool_cleanup_t *c1 = ngx_pool_cleanup_add(pool, sizeof(char*));
    c1->handler = func1;
    c1->data = p2->ptr;

    ngx_pool_cleanup_t *c2 = ngx_pool_cleanup_add(pool, sizeof(FILE*));
    c2->handler = func2;
    c2->data = p2->pfile;

    // 1. 调用所有预置的清理函数
    // 2. 释放大块内存
    // 3. 释放小块内存池所有内存
    ngx_destroy_pool(pool);
    return ;
}

将测试代码文件移动到nginx-1.12.2根目录下,然后执行相应的编译指令

gcc -c -g -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs -I src/http -I src/http/modules -o ngx_testpool.o  ngx_testpool.c


gcc -o ngx_testpool ngx_testpool.o objs/src/core/ngx_palloc.o objs/src/os/unix/ngx_alloc.o

运行程序

在这里插入图片描述

清理操作对象的添加函数ngx_pool_cleanup_add头插法,所以析构时先调用func2()在调用fun1()

nginx编译安装出错解决

错误1

src/os/unix/ngx_user.c:36:7: error: ‘struct crypt_data’ has no member named ‘current_salt’

  36 |   cd.current_salt[0] = ~salt[0];

解决方法:

vim src/os/unix/ngx_user.c

将对应代码注释掉

在这里插入图片描述

错误2

error: cast between incompatible function types from ‘size_t (*)(ngx_http_script_engine_t *)’ {aka ‘long unsigned int (*)(struct <anonymous> *)’} to ‘void (*)(ngx_http_script_engine_t *)’ {aka ‘void (*)(struct <anonymous> *)’} [-Werror=cast-function-type]

在这里插入图片描述

解决办法

打开 vim objs/Makefile-Werror删掉 (-Werror,它要求GCC将所有的警告当成错误进行处理)

猜你喜欢

转载自blog.csdn.net/qq_42120843/article/details/130725833