# FastCGI + fork

**URL:** <https://www.ruby-forum.com/t/fastcgi-fork/239606>\
**Category:** NGINX\
**Created:** [March 6, 2014, 4:41pm UTC](https://www.ruby-forum.com/t/fastcgi-fork/239606 "2014-03-06T16:41:28Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![musicdenotation](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ea666f/32.png) [@musicdenotation](https://www.ruby-forum.com/u/musicdenotation)\
**Post date:** [March 6, 2014, 4:41pm UTC](https://www.ruby-forum.com/t/fastcgi-fork/239606/1 "2014-03-06T16:41:28Z")

</div>

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;

```

}
