http://hi.baidu.com/clusterlee/item/aa9a122c84cf94d40e37f985
一 .下载
FastCGI模块 http://www.fastcgi.com/dist/mod_fastcgi-2.4.6.tar.gz
FastCGI开发库 http://www.fastcgi.com/dist/fcgi-2.4.0.tar.gz(C, C++, Perl, and Java)
二.FastCGI模块的安装
1. tar xvf mod_fastcgi-2.4.6.tar.gz
2. cd mod_fastcgi-2.4.6/
3. vi Readme 注意一下这段话
4. vi INSTALL.AP2 注意一下这段话
5. cp Makefile.AP2 Makefile
6 . make top_dir = /usr/local/apache-2
7 . make install top_dir = /usr/local/apache-2
8 .cd /usr/local/apache-2/modules/ 查看是否有 mod_fastcgi.so
三.Apache的配置
1. vi /usr/local/apache-2/conf/httpd.conf 打开apache配置文件 加入以下几行
LoadModule fastcgi_module modules/mod_fastcgi.so
ScriptAlias /cgi-bin/ "/usr/local/apache-2/cgi-bin/" #CGI目录
ScriptAlias /fcg-bin/ "/usr/local/apache-2/fcg-bin/" #FastCGI目录
AllowOverride None
Options FollowSymLinks
Order allow,deny
Allow from all
SetHandler fastcgi-script # 设置本目录下cgi使用FastCGI处理
# AddHandler fastcgi-script .fcgi
# 或使用AddHandler只设置后缀为fcgi的文件以FastCGI处理
2. Apachectl -k restart 重启
四.FastCGI开发库的安装
1. tar xvf fcgi-2.4.0.tar..gz
2. cd fcgi-2.4.0
3. ./configure
4. Make
5. Make install
开发库头文件默认安装在 /usr/local/include 下,动态库和静态库在 /usr/local/lib 下
五.代码示例
Makefile 注意 引用
gcc -I/usr/local/include -L/usr/local/lib -lfcgi++
Fastcgi_demo.cpp
----------------------------------------------
#include
#include
#define REQMAX 5242880
#define BUFSIZE 65536
using namespace std;
//得到环境变量
string safeGetEnv(const char* name,FCGX_Request * request)
{
const char* ptr = FCGX_GetParam(name, request->envp);
if(ptr == NULL){
return "";
}else{
return string(ptr);
}
}
//取得输入
long gstdin(FCGX_Request *request,string &reqstr,string &ip,string &cookie)
{
long reqlength=-1,len=0,i;
//得到IP地址
ip = safeGetEnv("REMOTE_ADDR",request);
if(ip==""){
ip="0.0.0.0";
}
//得到cookie
cookie = safeGetEnv("HTTP_COOKIE",request);
//判断请求类型
string reqmtd=safeGetEnv("REQUEST_METHOD",request);
if(reqmtd=="POST"){
string reqlen = safeGetEnv("CONTENT_LENGTH",request);
char buffer[BUFSIZE+1];
if(reqlen!=""){
reqlength=strtoul(reqlen.c_str(), NULL, 10);
}
if(reqlength<=0){
return -1; //错误
}
if(reqlength>REQMAX+1024){
return -2; //请求忒长了
}
//读标准输入
while(len { cin.read(buffer,BUFSIZE); i=cin.gcount(); if(i<=0){ return -1; //错误 } len+=i; reqstr.append(buffer,i); } }else{ reqstr=safeGetEnv("QUERY_STRING",request); reqlength=reqstr.length(); } return reqlength; } int main(int argc,char *argv[]) { FCGX_Request request; FCGX_Init(); FCGX_InitRequest(&request, 0, 0); while (FCGX_Accept_r(&request) == 0) { fcgi_streambuf cin_fcgi_streambuf(request.in); fcgi_streambuf cout_fcgi_streambuf(request.out); fcgi_streambuf cerr_fcgi_streambuf(request.err); cin.rdbuf(&cin_fcgi_streambuf); cout.rdbuf(&cout_fcgi_streambuf); cerr.rdbuf(&cerr_fcgi_streambuf); string reqstr="",ip="",cookie=""; long reqlen=gstdin(&request,reqstr,ip,cookie); if(reqlen<0){ continue; } cout<<"Content-Type: text/plain\r\n\r\n"; cout<<"IP:["< cout<<"Cookie:["< cout<<"REQUEST:\n"< } return 0; }