Simplest Possible CGI Program in C: Example and Explanation

# Simplest Possible CGI Program in C: Example and Explanation

Last updated:

In these days of very advanced Web Application Frameworks like Ruby on Rails, Django et al, it's often refreshing to get back to the basics.

This is where it all began: CGI Programs.

At the most basic level, they are programs that are placed in a special directory and can be called via a browser. I'm running these tests on Apache 2.2 which is, in turn, running on an Ubuntu install.

• the C Program

Write this code into a file and name it cgitest.c

#include <stdio.h>

int main(int argc, char const *argv[])
{
printf("Content-Type: text/plain;charset=us-ascii\n\n");
printf("Hello World\nVia CGI!\n");
return 0;
}

• compiling the program

\$ gcc -o cgitest cgitest.c

• placing the executable file in apache's CGI directory

On Ubuntu, this is located in /usr/lib/cgi-bin. Use mv or cp to move/copy cgitest to that directory. Note that this might require root permissions (sudo).

• run the program on a web browser

Open a browser and type http://localhost/cgi-bin/cgitest. You'll probably see this on the screen:

This is a good reminder of where it all started (web programming dates back to when there was no perl, PHP or pyhton to create dynamic web pages) but it's also somewhat useful.

With this, you can serve any program or executable(bash scripts for instance) at all with Apache. Anything you need to make accessible on the Internet or on your local network you can serve with Apache via CGI.

• References