next up previous contents
Next: Bibliography Up: Running Programs Previous: Running Programs   Contents

Hello, World

Hello, World is the standard first C program. It usually looks like this:
#include <stdio.h>

int main(int argc, char *argv)
{ printf("Hello, World\n");
}
However, a cgi-bin program (that is, a program run by a web server in response to a request) needs to output some header information and html code. We do this here. In a file called ``hello.c'' we put the following code:
#include <stdio.h>

int main(int argc, char *argv)
{ 
  char *result="<HTML><HEAD></HEAD><BODY>Hello, World\n</BODY></HTML>\n";
  printf("Content-type: text/html\n");
  printf("Content-Length: %d\n",strlen(result));
  printf("\n");
  printf("%s",result);
  return(0);
}
Next, we compile this code:
gcc -o hello hello.c
Since the compiled code doesn't depend on anything we can just run it and look at the result:
Content-type: text/html
Content-Length: 53

<HTML><HEAD></HEAD><BODY>Hello, World
</BODY></HTML>
Since it outputs valid html we copy it to the cgi-bin directory:
cp hello /var/www/cgi-bin
and then we ask for the code by going to a web browser (or using telnet) at the url:
  http://127.0.0.1/cgi-bin/hello


root 2004-02-18