Build a web server in Linux and write CGI in C Language

Source: Internet
Author: User

I have been studying and writing CGI in Linux recently. I just completed a message book and wrote my own experiences to share with you. If not, please correct me.

(1) Installation of Linux.
I installed redhat9 (a little older, linux2.4 kernel) and used KDE (which is more beautiful than gnome). The editor in KDE has the syntax brightening function in multiple languages, especially Kate's built-in command line is very convenient for programming. apache (similar to IIS in Windows) is used for Web Services in Linux. MySQL can be installed for databases (recommended for beginners ). these two items are available on the RedHat installation disk.
I did not install Apache and MySQL that comes with RedHat. Instead, I downloaded the latest source code package from the official website and compiled and installed it myself (I think I am a newbie in Linux and installed it with a source code package without rpm ). install Apache and MySQL later.
(2) Apache installation
Go to http://httpd.apache.org/download.cgito download the latest apachesource code package. After downloading and decompressing the package, compile and install it. You can run the following command on the terminal (My bash shell ):
CD/root/Apache-Src suppose/root/Apache-Src is the path of the source code after extraction
./Configure -- prefix =/usr/local/path after the Apache prefix parameter is where you want to install Apache. Generally, large software uses/usr/local /....
Make
Make install
If there are no errors in the above configurations, Apache has been installed. the/usr/localapache directory contains multiple subdirectories. The/bin directory contains executable files,/htdocs stores your general webpage, And/cgi-bin stores your CGI program, /conf stores server configuration files
You can add the/usr/local/bin directory to the environment variable path to facilitate program execution. the httpd program in/bin is the daemon of the Apache service. you can enter httpd in the terminal to start it. enter http: // 127.0.0.1 in your browser to check whether your server is enabled.
Open httpd. conf in the/conf directory and you can edit the configuration information of the server. It is easy to understand the specific entries in English. If you don't understand them, Google it.
(3) install MySQL
Same as Apache. Download the source code package for compilation and installation. Use/usr/local/MySQL in the installation directory, and add the/bin directory to the path environment variable.
After the installation is complete, initialize the database (initialize user permissions, etc.). In/bin, there is a script for mysql_install_db to complete these tasks. after initialization, the database creates a root Super User (no password ).
Execute the mysqld_saef script in the/bin folder to start the MySQL server. add or delete the user to change the password and client usage can see the Chinese manual (http://www.linuxforum.net/books/mysqlmanual/manual_toc.html)
To program MySql in C language, header files and library files are indispensable. They are in/inlude and/lib of the installation directory, in C, you only need to use # include "/usr/local/MySQL/include/MySQL. H "to perform basic MySQL programming.
If you think this directory is too long, you can add the MySQL folder link in/usr/include (this is the inclusion path used by the GCC compiler, the specific command is ln-S/usr/local/MySQL/include/MySQL/usr/include/MySQL, so that you can # include "MySQL/MySQL. H "now. the default library file path used by GCC is/usr/lib. You can also create a folder link.
(4) Create a database and a table for the message book
Run the "mysql-u root-P" command and enter the password to log on to the MySQL server,
Run the "Create Database db_site;" command to create a database and then "Use it ".
Run the "create table note (ID int primary key auto_increment, name varchar (20), ntime datatime, content varchar (300)" command to create a note table to store messages, the auto_increment of the ID column is similar to the identity attribute in sqlserver.
The following is a typical query code (of course, this code is not secure and it does not check the return value of the function)
# Include "MySQL/MySQL. H"
......
Mysql_res * gl_res = NULL;
MySQL gl_mysql;
Mysql_row gl_row;
Mysql_init (& gl_mysql); // enter the initialization information, such as the Client IP address.
Mysql_real_connect (& gl_mysql, null, "testuser", "password", "db_site", 0, 0, 0); // connect to the database db_site
Mysql_query (& gl_mysql, "select count (*) from note;"); // query the number of data entries
Gl_res = mysql_store_result (& gl_mysql) '// Save the selected result, which is useless for the INSERT command.
Gl_row = mysql_fetch_row (gl_res);/obtain the first row in the result set.
Count = atoi (gl_row [0]); // the first column of the First row is the data to be obtained and converted to int.
Mysql_free_result (gl_res); // release the saved result
Mysql_close (& gl_mysql); // close the link
For compilation, you need to use the GCC l parameter to specify the search path. on my computer, this is the GCC-O note main. c-l/usr/lib-lmysqlclient-LZ. (I copied all the library files to the/usr/lib directory)
PS: GCC now supports C ++ annotations and bool variables!
(5) Compile CGI programs
There are a lot of CGI tutorials on the Internet, but most of them use Perl, with fewer C languages, one of the troubles with C language is that you need to write various string processing functions by yourself (HTTP is based on callback stream ). if you do not have a basic understanding of CGI programs, you should Google to understand the similarities and differences between CGI Environment Variables and post/get methods. you also need to have some knowledge about html and URL encoding. if the get method is used, the CGI program receives the encoding form from the input environment variable QUERY_STRING. if you use the POST method, your cgi program will receive the encoding form input to stdin. the server will not send an EOF at the end of the data,
Instead, you should use the environment variable content_length to determine how much data you want to read from stdin.
Use the char * getenv (char *) function in C to get the value of an environment variable. the customer data received by the CGI program is URL encoded. You need to write your own code in the C language to perform URL Decoding on the received data (Other Languages provide good decoding functions ). I used a previously written syntax analyzer during decoding (I can use a status conversion chart ).
The syntax analyzer can be found in my blog. This is the status Conversion Diagram of the latest version:
{Number, '0', '9', number },
{Number, 'A', 'z', identi },
{Number, 'A', 'z', identi },
{Number, '%', '%', identi },
{Number, 45, 46, identi },//'-''.'
{Number, '_', '_', identi },
{Number, identi}, // '*' +'
{Identi, 'A', 'z', identi },
{Identi, 'A', 'z', identi },
{Identi, '%', '%', identi },
{Identi, '0', '9', identi },
{Identi, 45, 46, identi },//'-''.'
{Identi, '_', '_', identi },
{Identi, identi}, // '* ''+'
{Start, '&', '&', ADDR },
{Start, '=', '=', assign },
{Start, '0', '9', number },
{Start, 'A', 'z', identi },
{Start, 'A', 'z', identi },
{Start, '%', '%', identi },
{Start, 45, 46, identi },//'-''.'
{Start, '_', '_', identi },
{Start, identi}, // '*' +'
After the CGI program is written, put it in the/cgi-bin directory (this is the default CGI path of Apache, of course, you can change it) and Type HTTP in the browser: // 127.0.0.1/cgi-bin/***** you can see your cgi running result.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.