接上节, 上节只有响应---cout, 本节获取地址栏的QUERY_STRING, 然后响应.
一. req_resp.cpp.
#include <stdlib.h> #include <string.h> #include <unistd.h> #include "fcgio.h" #include "fcgi_config.h" using namespace std; int main (void) { int count = 0; long pid = getpid(); streambuf * cin_streambuf = cin.rdbuf(); streambuf * cout_streambuf = cout.rdbuf(); streambuf * cerr_streambuf = cerr.rdbuf(); 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); cout << "Content-type: text/html\r\n" "\r\n" "<H4>PID: " << pid << "</H4>\n" "<H4>Request Number: " << ++count << "</H4>\n"; cout << "<H4>Request Environment</H4>\n"; for(int i = 0; request.envp[i]; ++i) { char* findQueryStr = NULL; findQueryStr = strstr(request.envp[i], "QUERY_STRING"); if (findQueryStr) { cout << request.envp[i] << '\n'; } } } cin.rdbuf(cin_streambuf); cout.rdbuf(cout_streambuf); cerr.rdbuf(cerr_streambuf); return 0; }
二. 编译运行.
#g++ -o req_resp req_resp.cpp -I /usr/local/include -L /usr/local/lib -lfcgi -lstdc++ -lfcgi++
#./req_resp
若编译或运行时出错(一般是库问题), 参考上几节解决办法.
三. 将cgi拷贝到ngix(目标路径没有则手动创建)
cp ***/req_resp /usr/local/nginx/cgibin
四. 启动Spawn-fcgi.
/usr/local/nginx/sbin/spawn-fcgi -a 127.0.0.1 -p 8088 -f /usr/local/nginx/cgibin/req_resp
五. 访问.
注: python index.py已经运行的情况下.
浏览器地址栏: localhost/req_resp.cgi?his_is_from_brower_input&hello=1&world=2
注意显示的QUERY_STRING就是地址栏问号后的内容.
浏览器显示为:
PID: 4072
Request Number: 2
Request Environment
QUERY_STRING=this_is_from_brower_input&hello=1&world=2