參考:
nginx+c/c++ fastcgi:http://www.yis.me/web/2011/11/01/66.htm
cgi探索之路:http://github.tiankonguse.com/blog/2015/01/19/cgi-nginx-three/
有些性能要求很高的后端CGI都是用C寫的,以lighthttp為server 。雖然php結合php-fpm的fastcgi模式也有不錯的性能,但某些情況下C的性能還是php無法比擬的。
先有必要有這樣第一個認識:ngxin作為一個webserver,本身並不包含CGI的解釋器,需要通過一個中間件【例如php-fpm】來運行CGI。他們之間的模式大致是:
nginx <-- socket --> php-fpm-------->php
那么nginx既然要運行c寫的CGI那么也應該有類似php-fpm的東西。這個就是spawn-fcgi。原本是lighttp 內的fastcgi進程管理器。
下面是具體步驟:
1.安裝Spawn-fcgi 【提供調度cig application】
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
2、安裝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
注意:
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
問題: