參考: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
問題: