C语言开发CGI程序的简单例子

时间:2023-03-09 16:26:58
C语言开发CGI程序的简单例子

这年头用C语言开发cgi的已经不多,大多数的web程序都使用java、php、python等这些语言了。

但是本文将做一些简单的cgi实例。

首先配置环境

#这里是使用的apache

AddHandler cgi-script .cgi
#下面的配置 一般在httpd.conf都已经配好了
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
<Directory "/var/www/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>

例子

//在目录 /var/www/cgi-bin 下

//添加test.c 文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h> int main(){
char * out;
char * method; printf("Content-type: text/html\n\n");
printf("<h3>CGI test</h3><hr/>"); method = getenv("REQUEST_METHOD"); //get
if(!strcmp(method,"GET")){
out = getenv("QUERY_STRING");
printf("get reuslt:<br><br>");
printf("%s\n", out);
}
} //编译的时候把后缀改为.cgi
gcc test.c -o test.cgi

访问  http://localhost/cgi-bin/test.cgi?test=1&asd=1  

看到如下结果

CGI test


get reuslt:

test=1&asd=1