Thomas De Reyck's Blog

Getting started with FastCGI in C++

In an attempt to see how easy it is to create a web application with only basic technologies, I was looking into CGI scripts. CGI, or Common Gateway Interface, is a venerable technology where the web server just hands over all the request data to a separate process. That process can be a script or compiled executable, and is executed each time a request is made. Communication between the web server and the CGI script occurs via stdin (for POST data), stdout (for the response) and environment variables (for request headers and other information).

As you can use compiled executables for your CGI scripts, performance should be very good. However, because of a new process being spawned for each request, performance may suffer when a lot of requests are processed in a short time.

To overcome this issue, FastCGI was developed. It works very similarly to regular CGI, however it uses long living CGI scripts to avoid the overhead of spawning new processes. Additionally, some elements of the CGI script (such as database connections) don’t need to be reestablished each time. Communication between the web server and the CGI script now happens via a custom protocol.

Even though that protocol is not overly complex, it would be a hassle to implement it yourself. There are some libraries available for handling FastCGI connectivity. In this article, we’ll take a look at cgicc, which provides this functionality for C++ programs.

On debian, cgicc can be installed using this command:

apt install libcgicc-dev

cgicc, by default, uses regular CGI instead of FastCGI. In order to use FastCGI, we first need to install a dependency:

apt install libfcgi-dev

To learn how we can get started, the cgicc documentation includes an example, so let’s install the documentation as well.

apt install libcgicc-doc

Now we copy the example and some required files to our current folder:

cp /usr/share/doc/libcgicc-doc/examples/contrib/fcgi-test.cpp ./
cp /usr/share/doc/libcgicc-doc/examples/contrib/FCgiIO.* ./
gunzip ./FCgiIO.h.gz 

The cgi-test.cpp file contains the example. Have a look to see how it works.

Compiling it was, because of my rusty C++ knowledge, not so trivial, but I eventually figured out that the example can be compiled with the following command:

g++ -o fcgi-test.cgi  fcgi-test.cpp FCgiIO.cpp -lfcgi++ -lfcgi -lcgicc

The important part here is to also add the -lfcgi++ option. fcgi++ is a part of fcgi, but needs to be referenced explicitly for the example to compile.

Interfacing the CGI script with a web server, such as Apache or Nginx will be the topic for a future article.

#C++ #FastCGI