Writing A Simple CGI Program In C

If you want your Apache web server to do something more useful than just serve static pages, you'll need to write a CGI program in C, Python, etc. A CGI program is run by the web server: the program can create web pages, SVG pages, perform calculations and display the results or it can create other files that the browser can then request independently. There's more on the various methods to serve image files. The example below shows how to write a C program that displays the canonical "Hello World" message.

Step 1

Wheezy comes with the GCC C compiler already installed and ready to use so the first step is to write your program. Use nano to create a new file:

nano hello.c

Step 2

Type in a simple program. It's presumed that you know about the various HTML tags that are required and the nesting that's permitted. In this example, no newline characters are written to the output stream and so the HTML comprises one record. The purpose of adding newlines to each HTML statement and indenting the tags is purely for human readability. In this example, the program writes to stdout and this stream is intercepted by Apache and written to your browser.

#include <stdio.h>				// You need this #include to define the printf function

void main(int argc, char *argv[])
{
    printf("Content-type: text/html\n\n");	// Tell the browser the type of document being sent

    printf("<html>");
    printf("<head>");
    printf("<title>Test</title>");
    printf("</head>");
    printf("<body>");
    printf("<p>Hello world!</p>");
    printf("</body>");
    printf("</html>");
    return;
}

Step 3

Save the changes, exit nano and then compile. You need to prefix the command with sudo because only root will have write access to /usr/lib/cgi-bin.

sudo gcc hello.c -o /usr/lib/cgi-bin/hello

where hello.c is your source file. The -o /usr/lib/cgi-bin/hello specifies that the executable output file should be called hello and written to the /usr/lib/cgi-bin directory. By default, Apache looks in the /usr/lib/cgi-bin directory for its CGI programs. You can change this if you wish by modifying /etc/apache2/sites-enabled/000-default, or whatever the configuration file is called for your web server.

Step 5

You need to use a browser to connect to Apache and display the webpage. If you are using your Pi's GUI and its web browser, you can use the local loopback address of 127.0.0.1. Otherwise, if you're using a browser on a PC, you'll need the proper IP address. You can find this either by using the ifconfig or ip addr commands.

Step 6

In your browser's address field type:

http://your-Pi's-IP-address/cgi-bin/hello

Hello World screenshot

If everything's working properly, you should see the following web page: