您的位置:首页 > 运维架构 > Apache

Ubuntu + Apache2 环境下用C编写 一个简单的cgi脚本

2014-01-08 14:21 351 查看
我只学习过c语言,没有学习过prel,网上很多教程都是针对prel的,很少有针对c的。自己在Ubuntu下鼓捣了一下午,也总算是用c成功编写了一个helloworld的cgi,算是cgi入门的第一步。

一、安装及配置apache服务器

安装apache2服务器

#sudo apt-get install apache2

配置apache2服务器

配置文件位于 /etc/apache2/sites-enabled/000-default

用vi打开配置文件:

#sudo vi /etc/apache2/sites-enabled/000-default

修改其中两句为:

DocumentRoot /var/www/html

ScriptAlias /cgi-bin/ /var/www/html/cgi-bin/

注意其中空格的问题。

这两个目录你可以自己设定,并且设定的目录要真实存在,如果不存在就 mkdir 出一个。

DocumentRoot后面是放HTML文件的目录。

ScriptAlias后面是指定/cgi-bin/连接到/var/www/html/cgi-bin/ ,也就是在这个目录中的文件均被认作是cgi程序。

例如如果浏览器中访问 http://127.0.0.1/cgi-bin/hello.cgi 就可以执行cgi-bin下的hello.cgi

配置完保存。

重启apache2:

#sudo /etc/init.d/apache2 restart

二、编写hello.cgi程序

在cgi-bin/下新建一个hello.c文件:

#sudo vi hello.c

在其中写入以下内容:

#include <stdio.h>
int main()
{
printf("Content-Type:text/html\n\n");
printf("hello,world\n");
return  0;
}
保存退出。

编译:

#sudo gcc hello.c -o hello.cgi

这里可以先运行一下

#sudo ./hello.cgi

看看是不是输出helloworld。

然后可以在浏览器中键入http://127.0.0.1/cgi-bin/hello.cgi

浏览器就可以显示出helloworld了。

三、权限问题

我的方法比较野蛮就是把所有相关的文件和目录的权限均设置为777

#sudo chmod 777 [文件名或目录]

在这里主要是先入个门,以后有时间在慢慢研究权限的问题。

from:http://www.linuxidc.com/Linux/2010-11/29790.htm

当然可以写一个python运行的cgi,somescripts.cgi

#!/usr/bin/env python
#-*- coding:utf-8 -*-
print 'Content-type:text/plain'
print #打印空行,以结束首部
print 'Hello,world'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python apache 脚本