Initial revision
[catagits/fcgi2.git] / doc / fastcgi-prog-guide / ch2c.htm
1 <html><head><title></title></head>
2 <body bgcolor=#ffffff>
3  
4 <a href="cover.htm">[Top]</a> <a href="ch1intro.htm">[Prev]</a> <a href="ch3perl.htm">[Next]</a> <a href="ap_guida.htm">[Bottom]</a>
5 <hr><br>
6  
7 <a name="3659">
8 <center><h1>2 Developing FastCGI <br>Applications in C</h1></center>
9 </a><a name="917">
10 This chapter explains how to code FastCGI applications in C and how to build them into executables. <p>
11 </a><a name="4230">
12 If you are converting a CGI application into a FastCGI application, in many cases you will only need to add a few lines of code. For more complex applications, you may also need to rearrange some code.<p>
13 </a><a name="5371">
14 <h1> The I/O Libraries</h1>
15 </a><a name="5384">
16 The FastCGI Software Development Kit that accompanies Open Market WebServer 2.0 includes I/O libraries to simplify the job of converting existing CGI applications to FastCGI or writing new FastCGI applications. There are two libraries in the kit: fcgi_stdio and fcgiapp. You must include one of these header files in your program:<p>
17 </a><ul><a name="5386">
18 <li><code>fcgi_stdio.h</code>
19 </a><a name="4237">
20 <li><code>fcgiapp.h</code>
21 </a></ul><a name="4199">
22 The <code>fcgi_stdio</code> library is a layer on top of the <code>fcgiapp</code> library, and we recommend strongly that you use it, both for converting existing CGI applications and for writing new FastCGI applications. The fcgi_stdio library offers several advantages:<p>
23 </a><ul><a name="5811">
24 <li>Simplicity: there are only 3 new API calls to learn
25 </a><a name="5828">
26 <li>Familiarity: If you are converting a CGI application to FastCGI, you will find few changes between CGI and FastCGI. We designed our library to make the job of building a FastCGI application as similar as possible to that of building a FastCGI application: you use the same environment variables, same techniques for parsing query strings, the same I/O routines, and so on. 
27 </a><a name="5817">
28 <li>Convenience: the library provides full binary compatibility between CGI and FastCGI. That is, you can run the same binary as either CGI or FastCGI. 
29 </a></ul><a name="5399">
30 The fcgiapp library is more specific to FastCGI, without trying to provide the veneer of familiarity with CGI. This manual describes the fcgi_stdio library; the fcgiapp library is documented in the header files that accompany the development kit. <p>
31 </a><a name="5847">
32 <h1> Code Structure</h1>
33 </a><a name="4240">
34 To structure code for FastCGI, you separate your code into two sections:<p>
35 </a><ul><a name="4200">
36 <li>Initialization section, which is executed only once.
37 </a><a name="4201">
38 <li>Response loop section, which gets executed every time the FastCGI script gets called.
39 </a></ul><a name="4202">
40 A response loop typically has the following format:<p>
41 </a><pre><a name="4203">
42 while (FCGI_Accept() &gt;= 0) {
43 </a>
44 <a name="4204">
45 # body of response loop
46 </a>
47 <a name="4205">
48 }
49 </a>
50 </pre><a name="4206">
51 The <code>FCGI_Accept</code> blocks until a client request comes in, and then returns 0. If there is a system failure, or the system administrator terminates the process, Accept will return -1. <p>
52 </a><a name="5852">
53 If the application was invoked as a CGI program, the first call to Accept returns 0 and the second always returns -1, producing CGI behavior. (See <a href="apaman.htm#95860">"FCGI_Accept (3)" on page &#32;21</a> for details.)<p>
54 </a><a name="5909">
55 Also note that the CGI world encourages small scripts, whereas FastCGI encourages combining scripts. You may choose to rethink the overall structure of your applications to take better advantage of FastCGI performance gains.<p>
56 </a><a name="5373">
57 <h1> Example 1: TinyFastCGI</h1>
58 </a><a name="4263">
59 Here is a simple example of a responder FastCGI application written in C:<p>
60 <pre>
61 #include "fcgi_stdio.h" /* fcgi library; put it first*/<br>#include &lt;stdlib.h&gt;
62
63 int count;
64
65 void initialize(void)
66 {
67   count=0;
68 }
69
70 void main(void)
71 {
72 /* Initialization. */  
73   initialize();
74
75 /* Response loop. */
76   while (FCGI_Accept() &gt;= 0)   {
77     printf("Content-type: text/html\r\n"
78            "\r\n"
79            "&lt;title&gt;FastCGI Hello! (C, fcgi_stdio library)&lt;/title&gt;"
80            "&lt;h1&gt;FastCGI Hello! (C, fcgi_stdio library)&lt;/h1&gt;"
81            "Request number %d running on host &lt;i&gt;%s&lt;/i&gt;\n",
82             ++count, getenv("SERVER_HOSTNAME"));
83   }
84 }
85 </pre>
86 <h1> Example 2: Prime Number Generator</h1>
87 </a><a name="4182">
88 Consider a responder application that generates the n-th prime number. <p>
89 </a><a name="5217">
90 A CGI application would have no efficient way of solving this problem. For example, if the user asks for the 50,000th prime number, a CGI application would have to calculate the first prime number, then the second, and so on, up until the 50,000th. The application would then terminate, taking with it all its hard-earned calculations. If a client then asks for the 49,000th prime number, the server will have to spawn a new CGI application which will have to start calculating prime numbers from scratch.<p>
91 </a><a name="4315">
92 FastCGI applications can be much more efficient at this sort of problem, since they can maintain state. A FastCGI application can calculate an extensive table of prime numbers in its initialization phase and then keep the table around indefinitely. Whenever a client requests a particular prime number, the response loop merely needs to look it up in the table. <p>
93 </a><a name="4343">
94 Here is the code for the prime number example:<p>
95 <pre>
96 #include "fcgi_stdio.h"
97 #include &lt;stdlib.h&gt;
98 #include &lt;string.h&gt;
99
100 #define POTENTIALLY_PRIME 0
101 #define COMPOSITE 1
102 #define VALS_IN_SIEVE_TABLE 1000000
103 #define MAX_NUMBER_OF_PRIME_NUMBERS 78600 
104
105 /* All initialized to POTENTIALLY_PRIME */
106 long int  sieve_table[VALS_IN_SIEVE_TABLE]; 
107 long int  prime_table[MAX_NUMBER_OF_PRIME_NUMBERS];  
108 /* Use Sieve of Erastothenes method of building 
109    a prime number table. */
110 void
111 initialize_prime_table(void)
112 {
113  long int prime_counter=1;
114  long int current_prime=2, c, d; 
115   
116   prime_table[prime_counter]=current_prime;
117
118   while (current_prime &lt; VALS_IN_SIEVE_TABLE)   {
119    /* Mark off composite numbers. */
120      for (c = current_prime; c &lt;= VALS_IN_SIEVE_TABLE; 
121           c += current_prime)  {
122         sieve_table[c] = COMPOSITE;  
123      }
124
125    /* Find the next prime number. */
126      for (d=current_prime+1; sieve_table[d] == COMPOSITE; d++); 
127    /* Put the new prime number into the table. */ 
128      prime_table[++prime_counter]=d; 
129      current_prime=d;
130   }
131 }
132
133
134 void main(void)
135 {
136     char *query_string;
137     long int n;
138
139     initialize_prime_table();
140
141     while(FCGI_Accept() &gt;= 0) {
142         /*
143          * Produce the necessary HTTP header.
144          */
145         printf("Content-type: text/html\r\n"
146                "\r\n");
147         /*
148          * Produce the constant part of the HTML document.
149          */
150         printf("&lt;title&gt;Prime FastCGI&lt;/title&gt;\n"
151                "&lt;h1&gt;Prime FastCGI&lt;/h1&gt;\n");
152         /*
153          * Read the query string and produce the variable part
154          * of the HTML document.
155          */
156         query_string = getenv("QUERY_STRING");
157         if(query_string == NULL) {
158             printf("Usage: Specify a positive number in the query string.\n");
159         } else {
160             query_string = strchr(query_string, `=') + 1;
161             n = strtol(query_string);
162             if(n &lt; 1) {
163                 printf("The query string `%s' is not a positive number.\n",
164                        query_string);
165             } else if(n &gt; MAX_NUMBER_OF_PRIME_NUMBERS) {
166                 printf("The number %d is too large for this program.\n", n);
167             } else
168                 printf("The %ldth prime number is %ld.\n", prime_table[n]);
169             }
170         }
171     } /* while FCGI_Accept */
172 }
173 </pre><a name="5349">
174 This application has a noticeable start up cost while it initializes the table, but subsequent accesses are fast.<p>
175 </a><a name="5151">
176 <h1> Building</h1>
177 </a><a name="4630">
178 This section explains how to build and debug FastCGI applications written in C.<p>
179 </a><a name="4629">
180 The C preprocessor needs to know the location of the <code>fcgi_stdio.h</code> header file, which is at the following pathname:<p>
181 </a><pre><a name="4642">
182 <em>$toolkit</em>/include/fcgi_stdio.h
183 </a>
184 </pre><a name="4645">
185 where <em>$toolkit</em> symbolizes the directory in which you have installed the Software Development Kit for FastCGI. <p>
186 </a><a name="4760">
187 The linker needs to know the location of the <code>libfcgi.a</code> library file, which is at the following pathname:<p>
188 </a><pre><a name="4647">
189 <em>$toolkit</em>/libfcgi/libfcgi.a 
190 </a>
191 </pre><a name="4648">
192 If your linker does not search the Berkeley socket library, then you must add linker directives to force this search.<p>
193 </a><a name="4773">
194 We provide a sample application <code>Makefile</code> at the following pathname: <p>
195 </a><pre><a name="4649">
196 <em>$toolkit</em>/examples/Makefile
197 </a>
198 </pre><a name="4652">
199 This <code>Makefile</code> contains the necessary rules and pathnames to build the C FastCGI applications accompanying the toolkit. To build all the applications, type:<p>
200 </a><pre><a name="4653">
201 $ ./configure<br>$ make 
202 </a>
203 </pre><a name="4190">
204 <h1> Memory Leaks</h1>
205 </a><a name="4178">
206 Memory leaks are seldom a problem in CGI programming because CGI applications rarely run long enough to be concerned with leaks. However, memory leaks can become a problem in FastCGI applications, particularly if each call to a popular FastCGI application causes additional memory to leak. <p>
207 </a><a name="4785">
208 When converting to FastCGI, you can either use a tool such as Purify from Pure Software to discover and fix storage leaks or you can run a C garbage collector such as Great Circle from Geodesic Systems. <p>
209 </a><a name="4972">
210 <p>
211 </a>
212 <hr><br>
213  
214 <a href="cover.htm">[Top]</a> <a href="ch1intro.htm">[Prev]</a> <a href="ch3perl.htm">[Next]</a> <a href="ap_guida.htm">[Bottom]</a>
215 <hr><br>
216  
217
218 <!-- This file was created with Quadralay WebWorks Publisher 3.0.3 -->
219 <!-- -->
220 <!-- For more information on how this document, and how the rest of -->
221 <!-- this server was created, email yourEmail@xyzcorp.com -->
222 <!-- -->
223 <!-- Last updated: 04/15/96 08:00:16 -->
224
225 </body>
226 </html>