接触web技术这么久,应该对fastcgi不陌生了,我一直以为只有php可以使用fastcgi配置多个cgi程序解释webserver发来的请求,这几天查看官方介绍,发现perl,python,java甚至C语言与shell也是可以开发fastcgi程序的。下面演示一个用C实现Hello World网页的输出。(互联网初期没有php等脚本语言时,网页开发者应该就是按照这种方式用C来做网页的吧)
首先安装fastcgi,cgicc等乱七八糟的依赖以及spawn-fcgi等工具,然后编写如下cgi程序。(大致功能是接受请求返回Hello World的网页)
#include
#include
#include "fcgi_config.h"
#include
#ifdef HAVE_UNISTD_H
#include
#endif
using namespace std;
int main(void)
{
int i;
while(FCGI_Accept() >= 0){
printf("Content-type: text/html\r\n" \
"\r\n" \
"
Test" \"
%s","Hello World");}
return 0;
}
g++ -o hello.cgi hello.cpp -lfcgi 编译生成hello.cgi程序,然后调用spawn-fcgi使得程序以fastcgi方式运行(具体底层运行方式由fastcgi实现,我们不用考虑)
spawn-fcgi -a 127.0.0.1 -p 2222 -f ./hello.cgi
然后配置nginx.conf文件
location ~ \.cgi$ {
fastcgi_pass 127.0.0.1:2222;
#rewrite (.*).cgi /$1 break;
fastcgi_param SCRIPT_FILENAME /usr/local/nspnp/html/$fastcgi_script_name;
fastcgi_index index.cgi;
}
location指令中指定将cgi后缀名的请求转发给2222端口(上面spawn-fcgi指定的端口),然后用浏览器访问127.0.0.1/hello.cgi,就可以看到结果了。
这里仅仅是一个最简单的功能演示,表单的交互还在研究中,cgicc封装了很好用的处理网页元素的方法,推荐使用。