使用nginx在c ++中使用fastcgi访问环境变量

时间:2012-07-18 18:02:53

标签: c++ nginx fastcgi environment

我正在尝试编写一个由nginx提供服务的c ++ fastcgi程序。我有程序编译,hello world示例有效,但我似乎无法从nginx获取任何环境变量(REQUEST_METHOD)等。据我所知,我正在关注教程并且具有相同的配置,所以我真的在这里拔出我的头发为什么它不起作用。这是我的配置:

location /cgi {
  fastcgi_pass 127.0.0.1:9000;
  fastcgi_index index.html;
  include /etc/nginx/fastcgi_params;
}

(fastcgi_params与默认的nginx安装相同)。

然后是c ++程序的相关代码:

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);

#if HAVE_IOSTREAM_WITHASSIGN_STREAMBUF
  cin  = &cin_fcgi_streambuf;
  cout = &cout_fcgi_streambuf;
  cerr = &cerr_fcgi_streambuf;
#else
  cin.rdbuf(&cin_fcgi_streambuf);
  cout.rdbuf(&cout_fcgi_streambuf);
  cerr.rdbuf(&cerr_fcgi_streambuf);
#endif

  //figure out what kind of request we have
  char * request_type = FCGX_GetParam("REQUEST_METHOD", request.envp);

  cout << "Content-type: text/html\r\n"
  "\r\n";
  cout << "Environment is: " << *request.envp;

}

对FCGX_GetParam的调用返回null,当我输出request.envp时,显示的唯一变量是FCGI_ROLE = RESPONDER。

我正在使用以下命令启动该过程:

spawn-fcgi -p 9000 -n FCGI-App

一切都在Ubuntu 11.10下运行。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您正尝试使用char **envp;打印cout << *request.envp。预计这只会从数组中打印出第一个字符串,这并不奇怪。

请尝试使用代码格式official FCGI example

static void penv(const char * const * envp)
{
    cout << "<PRE>\n";
    for ( ; *envp; ++envp)
    {
        cout << *envp << "\n";
    }
    cout << "</PRE>\n";
}

...

penv(request.envp);
相关问题