web(六)---fastcgi进阶(请求和响应)

接上几节, 本节写有请求和响应的demo.

 

一. myecho.cpp如下:

#include <stdlib.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"

                "<TITLE>myecho</TITLE>\n"

                "<H1>myecho</H1>\n"

                "<H4>PID: " << pid << "</H4>\n"

                "<H4>Request Number: " << ++count << "</H4>\n";

    }



    cin.rdbuf(cin_streambuf);

    cout.rdbuf(cout_streambuf);

    cerr.rdbuf(cerr_streambuf);



    return 0;

}

 

二. 编译+运行测试.

#g++ -o myecho myecho.cpp -I /usr/local/include -L /usr/local/lib -lfcgi -lstdc++ -lfcgi++

#./myecho

若编译或运行时出错(一般是库问题), 参考上几节解决办法.

 

三. 将cgi拷贝到ngix(目标路径没有则手动创建)

cp ***/myecho  /usr/local/nginx/cgibin

 

四. 启动Spawn-fcgi.

/usr/local/nginx/sbin/spawn-fcgi -a 127.0.0.1 -p 8088 -f /usr/local/nginx/cgibin/myecho

 

五. 访问.

注: python index.py已经运行的情况下.

浏览器:    localhost/myecho.cgi

 

 

注: fastcgi的example下有许多例子可以参考.

你可能感兴趣的:(Web)