用进程池实现的简单CGI服务器

33 篇文章 2 订阅
8 篇文章 0 订阅

参考自《Linux高性能服务器编程》

半同步/半异步进程池实现

半同步/半异步模式是由主进程管理所有监听socket,而各个子进程分别管理属于自己的连接socket。这种模式灵活性强,子进程可用自己调用accept来接收新的连接,这样父进程就无需向子进程传递socket,只需简单通知一声:“(父进程)我检测到新的连接,(子进程)你来接收它”。

在这里插入图片描述

进程池是单例模式,对外只提供一个进程池对象

进程类和进程池类的定义

由于通过进程池类的构造函数来创建进程初始化进程池,所以,进程池类中的成员变量对于每个子进程都有一份拷贝。

class process
{
public:
    process():m_pid(-1) {}

public:
    pid_t m_pid;
    int m_pipefd[2]; // 父子进程通信的管道
};

// 进程池类,注意模板用法
template<typename T>
class processpool
{
private:
    // 构造函数定义为私有
    // 只允许通过后面create静态函数来创建processpool实例
    processpool(int listenfd, int process_number = 4);
public:
    // 单例模式,保证程序最多撞见一个processpool实例
    // 这是程序正确处理信号的必要条件
    static processpool<T>* create(int listenfd, int process_number = 4)
    {
        if(!m_instance)
        {
            m_instance = new processpool<T> (listenfd, process_number);
        }
        return m_instance;
    }
    ~processpool()
    {
        delete []m_sub_process;
    }
    // 启动进程池
    void run();
private:
    void setup_sig_pipe();
    void run_parent();
    void run_child();

private:
    // 进程池允许的最大子进程数量
    static const int MAX_PROCESS_NUMBER = 16;
    // 每个子进程最多能处理的客户端数量
    static const int USER_PER_PROCESS = 65536;
    // epoll最多能处理的事件数
    static const int MAX_EVENT_NUMBER = 10000;
    // 进程池中进程总数
    int m_process_number;
    // 子进程在池中的序号,从0开始
    int m_idx;
    // 每个进程都有一个epoll内核事件表用m_epollfd标识
    int m_epollfd;
    // 监听socket
    int m_listenfd;
    // 子进程通过m_stop来决定是否停止运行
    int m_stop;
    // 保存所有子进程描述信息
    // 存放进程池中可供使用的子进程
    process* m_sub_process;
    // 进程池静态实例
    static processpool<T>* m_instance;
};
进程池类构造函数

注意父进程在池中的序号m_idx 被设置为-1

// listenfd 是监听sokcet,必须在创建进程前被创建
// process_number指定进程池中子进程数量
template<typename T>
processpool<T>::processpool(int listenfd, int process_number)
    :m_listenfd(listenfd), m_process_number(process_number), m_idx(-1), m_stop(false)
{
    assert((process_number > 0) && (process_number <= MAX_PROCESS_NUMBER));

    m_sub_process = new process[process_number];
    assert(m_sub_process);

    // 创建process_number个子进程,并建立它们和父进程之间的管道
    for(int i = 0; i < process_number; ++i)
    {
        int ret = socketpair(PF_UNIX, SOCK_STREAM, 0, m_sub_process[i].m_pipefd);
        assert(ret == 0);

        // 经过下面操作后,m_pid = -1 为主进程或没分配
        m_sub_process[i].m_pid = fork(); //
        assert(m_sub_process[i].m_pid >= 0);
        // 父子进程管道都只留一个口,可读可写
        if( m_sub_process[i].m_pid > 0) // parent only one
        {
            close( m_sub_process[i].m_pipefd[1]);
            continue;
        }
        else // child
        {
            close( m_sub_process[i].m_pipefd[0]);
            m_idx = i; // 每个子进程拥有自己的m_idx
            break;
        }
    }
}
其他重要函数
  • 子进程运行函数 void processpool<T>::run_child()
  • 父进程运行函数void processpool<T>::run_parent()
完整代码

具体细节参见代码

// 半同步/半异步进程池
#ifndef PROCESSPOOL_H
#define PROCESSPOOL_H

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <signal.h>
#include <sys/stat.h>

class process
{
public:
    process():m_pid(-1) {}

public:
    pid_t m_pid;
    int m_pipefd[2]; // 父子进程通信的管道
};

// 进程池类,注意模板用法
template<typename T>
class processpool
{
private:
    // 构造函数定义为私有
    // 只允许通过后面create静态函数来创建processpool实例
    processpool(int listenfd, int process_number = 4);
public:
    // 单例模式,保证程序最多撞见一个processpool实例
    // 这是程序正确处理信号的必要条件
    static processpool<T>* create(int listenfd, int process_number = 4)
    {
        if(!m_instance)
        {
            m_instance = new processpool<T> (listenfd, process_number);
        }
        return m_instance;
    }
    ~processpool()
    {
        delete []m_sub_process;
    }
    // 启动进程池
    void run();
private:
    void setup_sig_pipe();
    void run_parent();
    void run_child();

private:
    // 进程池允许的最大子进程数量
    static const int MAX_PROCESS_NUMBER = 16;
    // 每个子进程最多能处理的客户端数量
    static const int USER_PER_PROCESS = 65536;
    // epoll最多能处理的事件数
    static const int MAX_EVENT_NUMBER = 10000;
    // 进程池中进程总数
    int m_process_number;
    // 子进程在池中的序号,从0开始
    int m_idx;
    // 每个进程都有一个epoll内核事件表用m_epollfd标识
    int m_epollfd;
    // 监听socket
    int m_listenfd;
    // 子进程通过m_stop来决定是否停止运行
    int m_stop;
    // 保存所有子进程描述信息
    // 存放进程池中可供使用的子进程
    process* m_sub_process;
    // 进程池静态实例
    static processpool<T>* m_instance;
};

// 类内声明类外初始化
template<typename T>
processpool<T>* processpool<T>::m_instance = NULL;

// 用于处理事件的管道,以实现统一信号源
static int sig_pipefd[2];

static int setnonblocking(int fd)
{
    int old_option = fcntl(fd, F_GETFL);
    int new_option = old_option | O_NONBLOCK;
    fcntl(fd, F_SETFL, new_option);
    return old_option;
}

static void addfd(int epollfd, int fd)
{
    epoll_event event;
    event.data.fd = fd;
    event.events = EPOLLIN | EPOLLET; // 注册可读事件
    epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
    setnonblocking(fd);
}

// 从epollfd标识的epoll内核事件表中删除fd上所有注册的事件
static void removefd(int epollfd, int fd)
{
    epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, 0);
    close(fd);
}

// 信号处理函数
static void sig_handler(int sig)
{
    // 保留原来的errno,在函数最后恢复,以保证函数的可重入性
    int save_errno = errno;
    int msg = sig;
    send(sig_pipefd[1], (char *)&msg, 1, 0); // 将信号值写入管道,以通知主循环
    errno = save_errno;
}

static void addsig(int sig, void (*handler)(int), bool restart = true)
{
    struct sigaction sa;
    memset(&sa, '\0', sizeof(sa));
    sa.sa_handler = handler;
    if(restart)
        sa.sa_flags |= SA_RESTART;
    sigfillset(&sa.sa_mask); // 设置所有信号
    // 为信号注册处理函数
    assert(sigaction(sig, &sa, NULL) != -1);
}

// 进程池构造函数
// listenfd 是监听sokcet,必须在创建进程前被创建
// process_number指定进程池中子进程数量
template<typename T>
processpool<T>::processpool(int listenfd, int process_number)
    :m_listenfd(listenfd), m_process_number(process_number), m_idx(-1), m_stop(false)
{
    assert((process_number > 0) && (process_number <= MAX_PROCESS_NUMBER));

    m_sub_process = new process[process_number];
    assert(m_sub_process);

    // 创建process_number个子进程,并建立它们和父进程之间的管道
    for(int i = 0; i < process_number; ++i)
    {
        int ret = socketpair(PF_UNIX, SOCK_STREAM, 0, m_sub_process[i].m_pipefd);
        assert(ret == 0);

        // 经过下面操作后,m_pid = -1 为主进程或没分配
        m_sub_process[i].m_pid = fork(); //
        assert(m_sub_process[i].m_pid >= 0);
        // 父子进程管道都只留一个口,可读可写
        if( m_sub_process[i].m_pid > 0) // parent only one
        {
            close( m_sub_process[i].m_pipefd[1]);
            continue;
        }
        else // child
        {
            close( m_sub_process[i].m_pipefd[0]);
            m_idx = i; // 每个子进程拥有自己的m_idx
            break;
        }
    }
}

// 统一事件源
template<typename T>
void processpool<T>::setup_sig_pipe()
{
    // 创建epoll事件监听表和信号管道
    m_epollfd = epoll_create(5);
    assert(m_epollfd != -1);

    int ret = socketpair(PF_UNIXs, SOCK_STREAM, 0, sig_pipefd);
    assert(ret != -1);

    setnonblocking(sig_pipefd[1]); // 使得能够非阻塞send
    addfd(m_epollfd, sig_pipefd[0]); // 管道读端监视其读事件

    // 设置信号处理函数
    addsig(SIGCHLD, sig_handler);
    addsig(SIGTERM, sig_hadnler);
    addsig(SIGPIPE, SIG_IGN);
}

// 父进程中m_idx 值为-1,子进程中m_idx值大于等于0,
// 据此判断接下来运行的是子进程还是父进程代码
template<typename T>
void processpool<T>::run()
{
    if(m_idx != -1)
    {
        run_child();
        return;
    }
    run_parent();
}

// 重要
template<typename T>
void processpool<T>::run_child()
{
    // 每个子进程都通过其在进程池中的序号值m_idx找到与父进程通信的管道
    int pipefd = m_sub_process[m_idx].m_pipefd[1];
    // 子进程需要监听管道文件描述符 pipefd, 因为父进程将通过它来通知子进程accept新连接
    addfd(m_epollfd, pipefd);

    epoll_event events[MAX_EVENT_NUMBER];
    T *users = new T[USER_PER_PROCESS];
    assert(users);
    int number = 0;
    int ret = -1;
    while(!m_stop)
    {
        number = epoll_wait(m_epollfd, events, MAX_EVENT_NUMBER, -1);
        if((number < 0) && (errno != EINTR))
        {
            printf("epoll failure\n");
            break;
        }
        for(int i = 0; i < number; i++)
        {
            int sockfd = events[i].data.fd;
            // 客户连接有数据来
            if((sockfd == pipefd) && (events[i].events & EPOLLIN))
            {
                int client = 0;
                // 从父子进程之间的管道读取数据,并保存在变量client中。
                // 如果成功,表示有新客户连接到来
                ret = recv(sockfd, (char*)&client, sizeof(client), 0);
                // 连接断开 或 recv失败
                if(((ret < 0) && (errno != EAGAIN)) || ret == 0) 
                {
                    continue;
                }
                else  // 子进程处理连接请求
                {
                    struct sockaddr_in client_address;
                    struct scoklen_t client_addrlength = sizeof(client_address);
                    int connfd = accept(m_listenfd, (struct sockaddr *)&client_address, &client_addrlength);
                    if(connfd < 0)
                    {
                        printf("errno is :%d\n", errno);
                        continue;
                    }
                    addfd(m_epollfd, connfd);
                    // 模板类T必须实现init方法,这里是连接类
                    // 直接使用connfd来索引逻辑处理对象(T类型对象),提高程序效率
                    users[connfd].init(m_epollfd, connfd, client_address);
                }
            }
            // 处理子进程接收到的信号
            else if((sockfd == sig_pipefd[0]) && (events[i].events & EPOLLIN))
            {
                int sig;
                char signals[1024];
                ret = recv(sig_pipefd[0], signals, sizeof(signals), 0);
                if(ret <= 0)
                {
                    continue;
                }
                else
                {
                    for(int i = 0; i < ret; ++i)
                    {
                        switch(signals[i])
                        {
                            case SIGCHILD:
                            {
                                pid_t pid;
                                int stat;
                                while((pid = waitpid(-1, &stat, WNOHANG)) > 0)
                                {
                                    continue;
                                }
                                break;
                            }
                            case SIGTERM:
                            case SIGINT:
                            {
                                m_stop = true;
                                break;
                            }
                            default:
                            {
                                break;
                            }
                        }
                    } 
                }
            }
            // 若是其他可读数据,必然是客户请求到来,调用处理逻辑处理对象的process方法处理即可
            else if(events[i].events & EPOLLIN)
            {
                users[sockfd].process();
            }
            else 
            {
                continue;
            }
        }
    }
    delete []users;
    users = NULL;
    close(pipefd);
    //close(m_listenfd); 哪个创建的listenfd,应该由哪个函数销毁 ,后面cgi服务器程序中销毁
    close(m_epollfd); // 每个子进程都有一个m_epollfd的副本
    return 0;
}

template<typename T>
void processpool<T>::run_parent()
{
    // 设置信号管道
    setup_sig_pipe();

    // 父进程监听m_listenfd
    addfd(m_epollfd, m_listenfd);
    epoll_event events[MAX_EVENT_NUMBER];
    int sub_process_counter = 0;
    int new_conn = 1;
    int number = 0;
    int ret = -1;

    while(!m_stop)
    {
        number = epoll_wait(m_epollfd, events, MAX_EVENT_NUMBER, -1);
        if((number < 0) && (errno != EINTR))
        {
            printf("epoll failure\n");
            break;
        }
        for(int i = 0; i < number; i++)
        {
            int sockfd = events[i].data.fd;
            // 客户连接有数据来
            if(sockfd == m_listenfd)
            {
                // 若有新连接到来,就用Round Robin方式将其分配给一个子进程处理
                int i = sub_process_counter;
                do
                {
                    // 父进程pid = -1
                    // 遇到第一个子进程就退出循环
                    if(m_sub_process[i].m_pid != -1)
                    {
                        break;
                    }
                    i = (i + 1) % m_process_number;
                } while (i != sub_process_counter); // 只RR一圈
                
                if(m_sub_process[i].m_pid == -1)
                {
                    m_stop = true;
                    break;
                }
                sub_process_counter = (i + 1) % m_process_number;
                // 通知一个子进程有客户连接到来
                send(m_sub_process[i].m_pipefd[0], (char*)&new_conn, sizeof(new_conn), 0);
                printf("send request to child %d\n", i);
            }
            // 处理父进程接收到的信号
            else if((sockfd == sig_pipefd[0]) && (events[i].events & EPOLLIN))
            {
                int sig;
                char signals[1024];
                ret = recv(sig_pipefd[0], signals, sizeof(signals), 0);
                if(ret <= 0)
                {
                    continue;
                }
                else
                {
                    for(int i = 0; i < ret; ++i)
                    {
                        switch(signals[i])
                        {
                            case SIGCHILD:
                            {
                                pid_t pid;
                                int stat;
                                while((pid = waitpid(-1, &stat, WNOHANG)) > 0)
                                {
                                    for(int i = 0; i < m_process_number; ++i)
                                    {
                                        // 如果进程池中第i个子进程退出了,则主进程关闭相应的通信管道
                                        // 并设置相应的m_pid为-1,标记该子进程退出
                                        if(m_sub_process[i].m_pid == pid)
                                        {
                                            printf("child %d join \n", i);
                                            close(m_sub_process[i].m_pipefd[0]);
                                            m_sub_process[i].m_pid = -1;    // 
                                        }
                                    }
                                }
                                // 若所有子进程都退出了,则父进程也退出
                                m_stop = true;
                                for(int i = 0; i < m_process_number; ++i)
                                {
                                    if(m_sub_process[i].m_pid != -1)
                                    {
                                        m_stop = false;
                                    }
                                }
                                break;
                            }
                            case SIGTERM:
                            case SIGINT:
                            {
                                // 若父进程收到终止信号,那么就杀死所有子进程
                                // 并等待它们全部结束。当然,通知子进程结束更好的方法是
                                // 向父子进程间的通信管道发送特殊数据。
                                printf("kill all the child now\n");
                                for(int i = 0; i < m_process_number; ++i)
                                {
                                    int pid = m_sub_process[i].m_pid;
                                    if(pid != -1)
                                    {
                                        kill(pid, SIGTERM);
                                    }
                                }
                                break;
                            }
                            default:
                            {
                                break;
                            }
                        }
                    } 
                }
            }
            else 
            {
                continue;
            }
        }
    }
    close(m_epollfd);
}

#endif

CGI服务器程序

完整代码
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <signal.h>
#include <sys/stat.h>

#include "processpool.h"

// 用于处理客户CGI请求的类,可作为processpool类的模板参数
class cgi_conn
{
public:
    cgi_conn(){}
    ~cgi_conn(){}
    // 初始化客户连接,清空读缓冲区
    void init(int epollfd, int sockfd, const sockaddr_in &client_addr)
    {
        m_epollfd = epollfd;
        m_sockfd = sockfd;
        m_address = client_addr;
        memset(m_buf, '\0', BUFFER_SIZE);
    }
    void process()
    {
        int idx = 0;
        int ret = -1;
        // 循环读取和分析客户数据
        while(true)
        {
            idx = m_read_idx;
            ret = recv(m_sockfd, m_buf + idx, BUFFER_SIZE - 1 - idx, 0);
            // 读操作错误,关闭客户连接
            // 若是暂时无数据可读,则退出循环
            if(ret < 0)
            {
                if(errno != EAGAIN)
                {
                    removefd(m_epollfd, m_sockfd);
                }
                break;
            }
            // 如果对方关闭连接,则服务器也关闭连接
            else if(ret == 0)
            {
                removefd(m_epollfd, m_sockfd);
                break;
            }
            else 
            {
                m_read_idx += ret; // 修改已读到的最后位置
                printf("user content is: %s\n", m_buf);
                // 若遇到"\r\n",则开始处理客户请求
                for(; idx < m_read_idx; ++idx)
                {
                    if((idx >= 1) && (m_buf[idx - 1] == '\r') && (m_buf[idx] == '\n'))
                    {
                        break;
                    }
                }
                //  若没遇到"\r\n",则需要读取更多客户端数据
                if(idx == m_read_idx)
                {
                    continue;
                }
                m_buf[idx - 1] = '\0';

                char *file_name = m_buf;
                // 判断客户要运行的CGI程序是否存在
                if(access(file_name, F_OK) == -1)
                {
                    removefd(m_epollfd, m_sockfd);
                    break;
                } 
                // 创建子进程来执行CGI程序
                ret = fork();
                if(ret == -1)
                {
                    // 将对m_sockfd事件监视从epoll内核事件表移除
                    removefd(m_epollfd, m_sockfd);
                }
                else if(ret > 0)
                {
                    // 父进程只需要关闭连接
                    removefd(m_epollfd, m_sockfd);
                    break;
                }
                else
                {
                    // 子进程将标准输出定向到m_sockfd,并执行CGI程序
                    close(STDOUT_FILENO);
                    dup(m_sockfd);
                    execl(m_buf, m_buf, 0);
                    exit(0);
                }
            }
        }
    }
private:
    // 读缓冲的大小
    static const int BUFFER_SIZE = 1024;
    static int m_epollfd;
    int m_sockfd;
    sockaddr_in m_address;
    char m_buf[BUFFER_SIZE];
    // 标记读缓冲已经读入客户数据的最后一个字节的下一个位置
    int m_read_idx;
};
int cgi_conn::m_epollfd = -1;

int main(int argc, char *argv[])
{
    if(argc < 2)
    {
        printf("usage: %s ip_address port_number\n", basename(argv[0]));
        return 1;
    }
    const char *ip = argv[1];
    int port = atoi(argv[2]);
    int listenfd = socket(PF_INET, SOCK_STREAM, 0);
    assert(listenfd >= 0);

    int ret = 0;
    struct sockaddr_in address;
    bzero(&address, sizeof(address));
    address.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &address.sin_addr);
    address.sin_port = htons(port);

    ret = bind(listenfd, (struct sockaddr *)&address, sizeof(address));
    assert(ret != -1);

    ret = listen(listenfd, 5);
    assert(ret != -1);

    // 只能通过类的静态成员函数获得唯一的进程池实例
    processpool<cgi_conn> *pool = processpool<cgi_conn>::create(listenfd);
    if(pool)
    {
        pool->run();
        delete pool;
    }
    // 谁创建,谁关闭
    close(listenfd);
    return 0;
}
函数调用流程

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值