18 February 2011

Your First CGI script using C....

Hello buddies..

This is actually my first CGI script... at all..
So, let me transfer this piece of knowledge to you.

First we will install the server on our local machine. (I am assuming you are using Linux)

From you package manager, install mini-http (you can use apache server instead .. but step here is for mini-http)

In my case, I am using ubuntu, so from synabtic I searched for "mini-http" them mark it for installation.. and then I got installed in moments.

after installing mini-http.. cd your hame folder:
cd $HOME
#then:
mkdir cgi-bin

Now lets start the web server..
cd ~
sudo mini-httpd -c "cgi-bin/*" # now the mini-httpd should starts ..
#to stop it write:
#sudo fuser -k 80/tcp


start your browse at:
http://localhost/
it should show listing of files of the directory at which you started the server at (in our case, the home directory)

Now let's write our simple application... I'll used httputil which I created in a previous post

#include <stdio.h>
#include <stdlib.h>
#include "httputil.h"

static void writeHeaders();

int main(void)
{
    writeHeaders();
    char* empId = get_parameter("empId");
    printf("you enterd employee Id: %s\n", empId);

    free(empId);
    
    return 0;
}

static void writeHeaders()
{
    printf("content-type: text/plain;charset=UTF-8\n\n");
}


Now compile this source file ...
First, get the required .h and .c files from the link above:
so you'll have 5 files, 3 .c and 2.h
stringutil.h, stringutil.c, httputil.h, httputil.c and the one above, let's name "employee.c"
cc -c stringutil.c 
cc -c httputil.c
cc -o employee employee.c -L. *.o

then copy the generated "employee" file and past it in ~/cgi-bin/employee.cgi
Now restart the server:
sudo fuser -k 80/tcp
sudo mini-httpd -c "cgi-bin/*"

Now fire your browse at:
http://localhost/cgi-bin/employee.cgi?empId=20

You should see:

That's all...

Next post I'll try to making GWT make a cross-site call to another server running CGI
...

3 comments:

mohammad fathei said...

very very nice

i think CGI is very easy
but for you as expert in web applications ,do you think that u will use it in your work in a complete real application?
or it is just for learning?

thanks for this useful && nice blog

mhewedy said...

First, I am not an expert ... I just want to share a new knowledge with you.. :)

Second, CGI depends on the language you are using..
For real applications I think it will not be a good choice because of the process creation issue (see wiki link below)... new technologies such as Servlets came to solve cgi problems.

This post just for fun and to play more with C.

See:
http://en.wikipedia.org/wiki/Common_Gateway_Interface

mohammad fahtei said...

at the less u r an expert for me
beacause u have big experience

actually although c++ is difficult but i feel fun and enjoy programming in it

best regards