Nginx + FastCgi + Spawn-fcgi + c 的架构

参考:php

nginx+c/c++ fastcgi:http://www.yis.me/web/2011/11/01/66.htmhtml

cgi探索之路:http://github.tiankonguse.com/blog/2015/01/19/cgi-nginx-three/nginx

  有些性能要求很高的后端CGI都是用C写的,以lighthttp为server 。虽然php结合php-fpm的fastcgi模式也有不错的性能,但某些状况下C的性能仍是php没法比拟的。c++

  先有必要有这样第一个认识:ngxin做为一个webserver,自己并不包含CGI的解释器,须要经过一个中间件【例如php-fpm】来运行CGI。他们之间的模式大体是:
  nginx <-- socket --> php-fpm-------->phpgit

  那么nginx既然要运行c写的CGI那么也应该有相似php-fpm的东西。这个就是spawn-fcgi。本来是lighttp 内的fastcgi进程管理器。 github

下面是具体步骤:web

1.安装Spawn-fcgi 【提供调度cig application】json

wget   http://download.lighttpd.net/spawn-fcgi/releases-1.6.x/spawn-fcgi-1.6.4.tar.gz
tar zxvf spawn-fcgi-1.6.4.tar.gz
cd  spawn-fcgi-1.6.4
./configure --prefix=/usr/local/spawn-fcgi
make & make install

 

二、安装fastcgi库 【提供编写cgi时的类库】后端

wget  http://www.fastcgi.com/dist/fcgi.tar.gz
tar zxvf  fcgi.tar.gz
cd  fcgi
./configure --prefix=/usr/local/fastcgikit/make & make install

注意:app

cp /usr/local/fastcgikit/lib/libfcgi.so.0 /usr/lib64

必定要这样复制过来,不然会报错找不到文件:

 

3.nginx安装配置【提供web访问】

location ~ \.cgi$ {
        #proxy_pass   http://127.0.0.1;
        root    /cgi;
        fastcgi_pass    127.0.0.1:9001;//让其监听9001端口,与spawn-cgi监听端口一致
        fastcgi_index   index.cgi;
        fastcgi_param   SCRIPT_FILENAME /cgi$fastcgi_script_name;
        include fastcgi_params;
}

4.测试代码fcgi_hello.c:(c代码)

#include "fcgi_stdio.h" //要写在行首(fcgi_stdio.h里定义的printf与c里的冲突),且用冒号(引用路径而非全局)
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int count = 0;
    while(FCGI_Accept() >= 0) {
        printf("Content-type: text/html\r\n");
        printf("\r\n");
        printf("Hello world!<br>\r\n");
        printf("Request number %d.", count++);
    }
    return 0;
}

编译测试代码:(必需要有-lfcgi参数)

g++ fcgi_hello.c -o fcgi_hello -L /usr/local/fastcgikit/lib/ -lfcgi

 

注意:

(1).该代码要放在/usr/local/fastcgikit/include这个目录下编译,由于要包含头文件fcgi_stdio.h进来;

5.启动spawn-cgi

/usr/local/spawn-fcgi/bin/spawn-fcgi -a 127.0.0.1 -p 9001 -F 10  -f /usr/local/fastcgikit/include/fcgi_hello -u json

查看效果:ps -ef|grep fcgi_hello

 

问题:

相关文章
相关标签/搜索