简单的多线程fastcgi应用程序总是崩溃

Simple multithreaded fastcgi application always crashing

本文关键字:崩溃 应用程序 fastcgi 多线程 简单      更新时间:2023-10-16

我正在努力了解如何在多线程环境中正确使用FastCGI。然而,在编译时,该程序在Apache上总是生成Internal Server Error。我觉得我对FastCGI和Apache都不够熟悉,无法诊断我的错误。

这个程序的一个简单的单线程等效程序运行得非常好。

我正在使用带有标志-std=c++11 -lfcgi++ -lfcgi -lpthreadg++进行编译

以下是我正在使用的代码:

#include "fcgio.h"
#include <vector>
#include <ostream>
#include <istream>
#include <thread>
#include <mutex>
std::mutex accept_mutex;
#define THREAD_COUNT (10)
void respond(){
  FCGX_Request request;
  FCGX_InitRequest(&request, 0, 0);
  fcgi_streambuf cout_fcgi_streambuf(request.out);
  std::ostream cout(&cout_fcgi_streambuf);
  for(;;) {
    accept_mutex.lock();
    if (FCGX_Accept_r(&request) < 0)
      break;
    accept_mutex.unlock();
    cout << "Content-type: text/htmlrn"
      << "rn"
      << "<html>n"
      << "  <head>n"
      << "    <title>Testing!</title>n"
      << "  </head>n"
      << "  <body>n"
      << "    <h1>Hello, World!</h1>n"
      << "</body>n"
      << "</html>n";
    FCGX_Finish_r(&request);
  }
}
int main(){
  FCGX_Init();
  std::vector<std::thread> threads(THREAD_COUNT);
  for(int i = 0 ; i < THREAD_COUNT ; i++)
    threads[i] = std::thread(respond);
  for(auto & x : threads)
    x.join();
}

这是我在Apache错误日志中发现的错误:

[Wed Mar 25 00:22:10.693368 2015] [fcgid:warn] [pid 11386:tid 139946920691456] (104)Connection reset by peer: [client 10.0.2.2:63490] mod_fcgid: error reading data from FastCGI server
[Wed Mar 25 00:22:10.693396 2015] [core:error] [pid 11386:tid 139946920691456] [client 10.0.2.2:63490] End of script output before headers: home2.fcgi
[Wed Mar 25 00:22:13.695752 2015] [fcgid:error] [pid 11384:tid 139947238573952] mod_fcgid: process /home/web/web/home2.fcgi(27007) exit(communication error), get unexpected signal 6

我解决了问题中提出的问题。

我在for(;;)循环之前制作ofstream cout,而它应该在循环内部创建。

这是有道理的,因为每个单独的连接都有自己的流,应该写入

-

我的大型多线程应用程序仍然存在问题——在我的大型程序中,我正确地实例化了ofstream。在创建我的最小示例时,我犯了一个错误,恰好在Apache中有相同的错误日志。然而,我的错误似乎与我发布的问题无关,现在我开始寻找最初造成错误的原因。