FastCGI + fork

Yasser Zamani yasser.zamani at live.com
Thu Mar 6 15:40:52 UTC 2014


Hi there,

I rewrote FastCGI's echo_cpp.cpp example to ridirect another process 
e.g. ls output DIRECTLY (to achieve high performance) to client but 
unfortunately does not work as expected!

P.S. if I simply read the pipe I get output but I lost performance. So, 
I need to directly redirect the output to client without any copying 
streams!

P.S. if I replace fork saffs with just a simple cout<<, I can see the 
output.

Anyone has any idea about how to correct it? I worked so hard with no 
success.

#include <stdlib.h>
#ifdef _WIN32
#include <process.h>
#else
#include <unistd.h>
extern char ** environ;
#endif
#include "fcgio.h"
#include "fcgi_config.h"  // HAVE_IOSTREAM_WITHASSIGN_STREAMBUF

//my includes
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

using namespace std;

int main (void)
{
     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

         cout << "Content-type: text/html\r\n"
                 "\r\n";

	cout.flush();

	int pipe_fd[2];
	pipe(pipe_fd);
	close(STDOUT_FILENO);
	dup2(pipe_fd[0], STDOUT_FILENO);// redirecting pipe read side to stdout

	int fid = fork();
	if(0==fid)
	{
//here we are in child prcess!
		close(STDOUT_FILENO);
		dup2(pipe_fd[1],STDOUT_FILENO);//redirecting pipe write side to stdout

		system("ls -l ./");
		close(pipe_fd[1]);
		return 0;
	}
	wait(0);//waiting for child process in parent
     }

#if HAVE_IOSTREAM_WITHASSIGN_STREAMBUF
     cin  = cin_streambuf;
     cout = cout_streambuf;
     cerr = cerr_streambuf;
#else
     cin.rdbuf(cin_streambuf);
     cout.rdbuf(cout_streambuf);
     cerr.rdbuf(cerr_streambuf);
#endif

     return 0;
}



More information about the nginx mailing list