cpthreadsforkfastcgipreforking

FastCGI fork in c


I'm currently developing highload project, i need to use C/FastCGI/nginx combination.

The problem is, i need my FastCGI application to run in threads/processes.

I know two ways to do that:

1) Compile program and than use spawn-fcgi to fork processes. (I can't use this one)

2) Run FCGX_Init(), than pre-fork to 10 processess BEFORE while (FCGX_Accept_r(&request) >= 0)

3) Run pthreads AFTER while (FCGX_Accept_r(&request) >= 0)

So, my question is: whis is the fastest way to run fastcgi application. Can I pre-fork fastcgi application after this:

int sock = FCGX_OpenSocket(":9000", 10);
FCGX_InitRequest(&request, sock, 0);

Can 10 processes listen to single socket ? Do i have to use threads, if i have N processes running ? Is this will be enough ?


Solution

  • I don't know about the FastCGI API you're using specifically, but in general you can't hand off a file descriptor (i.e. socket) to another process unless it was open before you forked. Processes have independent file descriptor tables. Threads would all share the same file descriptor table, since they're in the same process.

    To the best of my knowledge, you can only have one process listening on a port at a time. What is usually done is to have one thread whose only job is to listen for connections. When it gets one, the connection is accepted and handed to the next worker thread in the pool, by having the thread take over the accepted socket (not the listening socket) until the socket closes. The listener thread immediately goes back to listening for a connection.

    This should give you minimal overhead.