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

标签 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 下运行。

有什么想法吗?

最佳答案

您正在尝试打印 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);

关于c++ - 使用nginx在c++中使用fastcgi访问环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11547562/

相关文章:

c++ - 为 "adjacent"变量赋值时出现问题

c++ - 在opencv c++中绘制旋转矩形

c++ - 在类构造函数中动态分配数据成员

linux - 如何将索引页添加到 GitLab 捆绑的 NGINX?

amazon-web-services - 将 Go 项目文件部署到 AWS Elastic Beanstalk 时 make.service 失败

c++ - 调试 __do_global_dtors_aux 以查找代码位置

c++ - 如何通过指针打印二维数组? C++

node.js - Meteor 忘记密码邮件不发送

ruby-on-rails-3 - 使用 FastCGI 和 Url Rewrite 在 Windows IIS 7.5 上安装 RoR

python - 在 alwaysdata.com 上部署 Django