天天看點

Centos 安裝fastcgi詳解與用例

1、fastcgi簡介

fastcgi解決了cgi程式處理請求每次都要初始化和結束造成的性能問題。fastcgi并且是獨立于webserver的,fastcgi的crash并不影響webserver,然後他們之間通過soket通信。與fastcgi不同的另一種解決cgi程式反複建立,銷毀的方法是讓webserver開放api,然後編寫cgi的時候,把cgi嵌入到webserver中,這樣有個不好的地方就是cgi的crash會影響到webserver。

支援fastcgi的伺服器有很多比如,nginx IIS什麼的。他們都是把http請求轉換為stdin和一些環境變量傳遞給fastcgi程式,然後傳回stdout。編寫fastcgi程式最終要的一個api就是int FCGI_Accept(void);當一個請求被送達的時候傳回。

2、fastcgi安裝步驟:

step1:

下載下傳位址:

http://www.fastcgi.com/drupal/node/5

點選Current: download | docs | browse 中的download連結即可。

step2:

tar -zxvf fcgi.tar.gz

cd fcgi-2.4.1-SNAP-0311112127/

./configure –prefix=/etc/fcgi

make && make install

出現fcgio.cpp:50: error: ‘EOF’ was not declared in this scope的話隻需要 在/include/fcgio.h檔案中加上 #include

到此就安裝完了。

3、編寫并測試fcgi程式

1)Demo測試程式fcgi_test2.c如下:

#include "fcgi_stdio.h"

#include <stdlib.h>

int main(void)

{

int count = 0;

while(FCGI_Accept() >= 0)

printf("Content-type: text/html\r\n"

"\r\n"

"<title>FastCGI Hello!</title>"

"<h1>FastCGI Hello!</h1>"

"Request number %d running on host <i>%s</i>\n",

++count, getenv("SERVER_NAME"));

}

return 0;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

2)編譯

[root@cb24f769838b cgi-bin]# gcc -g fcgi_test2.c -o fcgi_test2.fcgi -lfcgi

//此時直接運作 fcgi_test2.fcgi 會報如下錯:

error while loading shared libraries: libfcgi.so.0:

3)連結庫錯誤解決方案:

參考:

https://www.apachelounge.com/viewtopic.php?p=8160

方案核心——“Link echo with the static library, libfcgi.a, instead of the shared library.”連結到靜态庫,而非共享庫。

[root@cb24f769838b cgi-bin]# gcc fcgi_test2.c -o fcgi_test2.fcgi -I/etc/fcgi/include /usr/local/lib/libfcgi.a

4)檢視關聯連結

[root@cb24f769838b cgi-bin]# ldd fcgi_test2.fcgi

linux-vdso.so.1 => (0x00007fff7fdc3000)

libc.so.6 => /lib64/libc.so.6 (0x00007fa0229ed000)

/lib64/ld-linux-x86-64.so.2 (0x00007fa022d86000)

4、正确運作結果如下

1)程式運作結果如下

[root@cb24f769838b cgi-bin]# ./fcgi_test2.fcgi

Content-type: text/html

<title>FastCGI Hello!</title><h1>FastCGI Hello!</h1>Request number 1 running on host <i>(null)</i>

2)浏覽器運作結果如下:

Centos 安裝fastcgi詳解與用例

5、常見出錯:

FastCGI: can’t create server “/var/www/fcgi/groundService.fcgi”: bind() failed [/etc/httpd/runtimedir/fastcgi/d2f3a2fea2f2f1b44954766d53644c3c]

解決方案:

修改配置:

586 #FastCgiIpcDir runtimedir/fastcgi

587 FastCgiIpcDir /tmp/fastcgi

第586行改為587行。

6、fastcgi部署參考

https://www.sympa.org/faq/fastcgi