ebbd421b15d6f9004317127276a035e784c6eba5
[catagits/fcgi2.git] / doc / fastcgi-prog-guide / ch2c.htm
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
2 <HTML>
3    <HEAD>
4       <TITLE>
5          FastCGI Programmer&#39;s Guide - Chapter 2, Developing FastCGI Applications in C
6       </TITLE>
7 <STYLE TYPE="text/css">
8  body {
9   background-color: #ffffff;
10  }
11  li.c2 {list-style: none}
12  div.c1 {text-align: center}
13 </STYLE>
14    </HEAD>
15    <BODY>
16       <A HREF="cover.htm">[Top]</A> <A HREF="ch1intro.htm">[Prev]</A> <A HREF="ch3perl.htm">[Next]</A> <A HREF=
17       "ap_guida.htm">[Bottom]</A> 
18       <HR>
19       <BR>
20        <A NAME="3659"></A>
21       <DIV CLASS="c1">
22          <H1>
23             2 Developing FastCGI<BR>
24             Applications in C
25          </H1>
26       </DIV>
27       <A NAME="917"></A>
28       <P>
29          This chapter explains how to code FastCGI applications in C and how to build them into executables.
30       </P>
31       <P>
32          <A NAME="4230"></A> If you are converting a CGI application into a FastCGI application, in many cases you will
33          only need to add a few lines of code. For more complex applications, you may also need to rearrange some code.
34       </P>
35       <BR>
36       <BR>
37       <H1>
38          The I/O Libraries
39       </H1>
40       <A NAME="5384"></A>
41       <P>
42          The FastCGI Software Development Kit that accompanies Open Market WebServer 2.0 includes I/O libraries to
43          simplify the job of converting existing CGI applications to FastCGI or writing new FastCGI applications. There
44          are two libraries in the kit: fcgi_stdio and fcgiapp. You must include one of these header files in your
45          program:
46       </P>
47       <BR>
48       <BR>
49       <UL>
50          <LI CLASS="c2">
51             <A NAME="5386"></A>
52          </LI>
53          <LI>
54             <CODE>fcgi_stdio.h</CODE> <A NAME="4237"></A>
55          </LI>
56          <LI>
57             <CODE>fcgiapp.h</CODE>
58          </LI>
59       </UL>
60       <A NAME="4199"></A>
61       <P>
62          The <CODE>fcgi_stdio</CODE> library is a layer on top of the <CODE>fcgiapp</CODE> library, and we recommend
63          strongly that you use it, both for converting existing CGI applications and for writing new FastCGI
64          applications. The fcgi_stdio library offers several advantages:
65       </P>
66       <BR>
67       <BR>
68       <UL>
69          <LI CLASS="c2">
70             <A NAME="5811"></A>
71          </LI>
72          <LI>
73             Simplicity: there are only 3 new API calls to learn <A NAME="5828"></A>
74          </LI>
75          <LI>
76             Familiarity: If you are converting a CGI application to FastCGI, you will find few changes between CGI and
77             FastCGI. We designed our library to make the job of building a FastCGI application as similar as possible
78             to that of building a FastCGI application: you use the same environment variables, same techniques for
79             parsing query strings, the same I/O routines, and so on. <A NAME="5817"></A>
80          </LI>
81          <LI>
82             Convenience: the library provides full binary compatibility between CGI and FastCGI. That is, you can run
83             the same binary as either CGI or FastCGI.
84          </LI>
85       </UL>
86       <A NAME="5399"></A>
87       <P>
88          The fcgiapp library is more specific to FastCGI, without trying to provide the veneer of familiarity with CGI.
89          This manual describes the fcgi_stdio library; the fcgiapp library is documented in the header files that
90          accompany the development kit.
91       </P>
92       <BR>
93       <BR>
94       <H1>
95          Code Structure
96       </H1>
97       <A NAME="4240"></A>
98       <P>
99          To structure code for FastCGI, you separate your code into two sections:
100       </P>
101       <BR>
102       <BR>
103       <UL>
104          <LI CLASS="c2">
105             <A NAME="4200"></A>
106          </LI>
107          <LI>
108             Initialization section, which is executed only once. <A NAME="4201"></A>
109          </LI>
110          <LI>
111             Response loop section, which gets executed every time the FastCGI script gets called.
112          </LI>
113       </UL>
114       <A NAME="4202"></A>
115       <P>
116          A response loop typically has the following format:
117       </P>
118       <BR>
119       <BR>
120 <PRE>
121 <A NAME="4203">while (FCGI_Accept() &gt;= 0) {
122 </A>
123 <A NAME="4204"># body of response loop
124 </A>
125 <A NAME="4205">}
126 </A>
127 </PRE>
128       <A NAME="4206"></A>
129       <P>
130          The <CODE>FCGI_Accept</CODE> blocks until a client request comes in, and then returns 0. If there is a system
131          failure, or the system administrator terminates the process, Accept will return -1.
132       </P>
133       <P>
134          <A NAME="5852"></A> If the application was invoked as a CGI program, the first call to Accept returns 0 and
135          the second always returns -1, producing CGI behavior. (See <A HREF="apaman.htm#95683">&quot;FCGI_Accept
136          (3)&quot; on page  21</A> for details.)
137       </P>
138       <P>
139          <A NAME="5909"></A> Also note that the CGI world encourages small scripts, whereas FastCGI encourages
140          combining scripts. You may choose to rethink the overall structure of your applications to take better
141          advantage of FastCGI performance gains.
142       </P>
143       <BR>
144       <BR>
145       <H1>
146          Example 1: TinyFastCGI
147       </H1>
148       <A NAME="4263">Here is a simple example of a responder FastCGI application written in C:</A><BR>
149       <BR>
150 <PRE>
151 #include &quot;fcgi_stdio.h&quot; /* fcgi library; put it first*/<BR>
152 #include &lt;stdlib.h&gt;
153
154 int count;
155
156 void initialize(void)
157 {
158   count=0;
159 }
160
161 void main(void)
162 {
163 /* Initialization. */  
164   initialize();
165
166 /* Response loop. */
167   while (FCGI_Accept() &gt;= 0)   {
168     printf(&quot;Content-type: text/html\r\n&quot;
169            &quot;\r\n&quot;
170            &quot;&lt;title&gt;FastCGI Hello! (C, fcgi_stdio library)&lt;/title&gt;&quot;
171            &quot;&lt;h1&gt;FastCGI Hello! (C, fcgi_stdio library)&lt;/h1&gt;&quot;
172            &quot;Request number %d running on host &lt;i&gt;%s&lt;/i&gt;\n&quot;,
173             ++count, getenv(&quot;SERVER_HOSTNAME&quot;));
174   }
175 }
176 </PRE>
177       <H1>
178          Example 2: Prime Number Generator
179       </H1>
180       <A NAME="4182"></A>
181       <P>
182          Consider a responder application that generates the n-th prime number.
183       </P>
184       <P>
185          <A NAME="5217"></A> A CGI application would have no efficient way of solving this problem. For example, if the
186          user asks for the 50,000th prime number, a CGI application would have to calculate the first prime number,
187          then the second, and so on, up until the 50,000th. The application would then terminate, taking with it all
188          its hard-earned calculations. If a client then asks for the 49,000th prime number, the server will have to
189          spawn a new CGI application which will have to start calculating prime numbers from scratch.
190       </P>
191       <P>
192          <A NAME="4315"></A> FastCGI applications can be much more efficient at this sort of problem, since they can
193          maintain state. A FastCGI application can calculate an extensive table of prime numbers in its initialization
194          phase and then keep the table around indefinitely. Whenever a client requests a particular prime number, the
195          response loop merely needs to look it up in the table.
196       </P>
197       <P>
198          <A NAME="4343"></A> Here is the code for the prime number example:
199       </P>
200       <BR>
201       <BR>
202 <PRE>
203 #include &quot;fcgi_stdio.h&quot;
204 #include &lt;stdlib.h&gt;
205 #include &lt;string.h&gt;
206
207 #define POTENTIALLY_PRIME 0
208 #define COMPOSITE 1
209 #define VALS_IN_SIEVE_TABLE 1000000
210 #define MAX_NUMBER_OF_PRIME_NUMBERS 78600 
211
212 /* All initialized to POTENTIALLY_PRIME */
213 long int  sieve_table[VALS_IN_SIEVE_TABLE]; 
214 long int  prime_table[MAX_NUMBER_OF_PRIME_NUMBERS];  
215 /* Use Sieve of Erastothenes method of building 
216    a prime number table. */
217 void
218 initialize_prime_table(void)
219 {
220  long int prime_counter=1;
221  long int current_prime=2, c, d; 
222   
223   prime_table[prime_counter]=current_prime;
224
225   while (current_prime &lt; VALS_IN_SIEVE_TABLE)   {
226    /* Mark off composite numbers. */
227      for (c = current_prime; c &lt;= VALS_IN_SIEVE_TABLE; 
228           c += current_prime)  {
229         sieve_table[c] = COMPOSITE;  
230      }
231
232    /* Find the next prime number. */
233      for (d=current_prime+1; sieve_table[d] == COMPOSITE; d++); 
234    /* Put the new prime number into the table. */ 
235      prime_table[++prime_counter]=d; 
236      current_prime=d;
237   }
238 }
239
240
241 void main(void)
242 {
243     char *query_string;
244     long int n;
245
246     initialize_prime_table();
247
248     while(FCGI_Accept() &gt;= 0) {
249         /*
250          * Produce the necessary HTTP header.
251          */
252         printf(&quot;Content-type: text/html\r\n&quot;
253                &quot;\r\n&quot;);
254         /*
255          * Produce the constant part of the HTML document.
256          */
257         printf(&quot;&lt;title&gt;Prime FastCGI&lt;/title&gt;\n&quot;
258                &quot;&lt;h1&gt;Prime FastCGI&lt;/h1&gt;\n&quot;);
259         /*
260          * Read the query string and produce the variable part
261          * of the HTML document.
262          */
263         query_string = getenv(&quot;QUERY_STRING&quot;);
264         if(query_string == NULL) {
265             printf(&quot;Usage: Specify a positive number in the query string.\n&quot;);
266         } else {
267             query_string = strchr(query_string, `=&#39;) + 1;
268             n = strtol(query_string);
269             if(n &lt; 1) {
270                 printf(&quot;The query string `%s&#39; is not a positive number.\n&quot;,
271                        query_string);
272             } else if(n &gt; MAX_NUMBER_OF_PRIME_NUMBERS) {
273                 printf(&quot;The number %d is too large for this program.\n&quot;, n);
274             } else
275                 printf(&quot;The %ldth prime number is %ld.\n&quot;, prime_table[n]);
276             }
277         }
278     } /* while FCGI_Accept */
279 }
280 </PRE>
281       <A NAME="5349"></A>
282       <P>
283          This application has a noticeable start up cost while it initializes the table, but subsequent accesses are
284          fast.
285       </P>
286       <BR>
287       <BR>
288       <H1>
289          Building
290       </H1>
291       <A NAME="4630"></A>
292       <P>
293          This section explains how to build and debug FastCGI applications written in C.
294       </P>
295       <P>
296          <A NAME="4629"></A> The C preprocessor needs to know the location of the <CODE>fcgi_stdio.h</CODE> header
297          file, which is at the following pathname:
298       </P>
299       <BR>
300       <BR>
301 <PRE>
302 <A NAME="4642"><EM>$toolkit</EM>/include/fcgi_stdio.h
303 </A>
304 </PRE>
305       <A NAME="4645"></A>
306       <P>
307          where <EM>$toolkit</EM> symbolizes the directory in which you have installed the Software Development Kit for
308          FastCGI.
309       </P>
310       <P>
311          <A NAME="4760"></A> The linker needs to know the location of the <CODE>libfcgi.a</CODE> library file, which is
312          at the following pathname:
313       </P>
314       <BR>
315       <BR>
316 <PRE>
317 <A NAME="4647"><EM>$toolkit</EM>/libfcgi/libfcgi.a 
318 </A>
319 </PRE>
320       <A NAME="4648"></A>
321       <P>
322          If your linker does not search the Berkeley socket library, then you must add linker directives to force this
323          search.
324       </P>
325       <P>
326          <A NAME="4773"></A> We provide a sample application <CODE>Makefile</CODE> at the following pathname:
327       </P>
328       <BR>
329       <BR>
330 <PRE>
331 <A NAME="4649"><EM>$toolkit</EM>/examples/Makefile
332 </A>
333 </PRE>
334       <A NAME="4652"></A>
335       <P>
336          This <CODE>Makefile</CODE> contains the necessary rules and pathnames to build the C FastCGI applications
337          accompanying the toolkit. To build all the applications, type:
338       </P>
339       <BR>
340       <BR>
341 <PRE>
342 <A NAME="4653">$ ./configure<BR>
343 $ make 
344 </A>
345 </PRE>
346       <H1>
347          Memory Leaks
348       </H1>
349       <A NAME="4178"></A>
350       <P>
351          Memory leaks are seldom a problem in CGI programming because CGI applications rarely run long enough to be
352          concerned with leaks. However, memory leaks can become a problem in FastCGI applications, particularly if each
353          call to a popular FastCGI application causes additional memory to leak.
354       </P>
355       <P>
356          <A NAME="4785"></A> When converting to FastCGI, you can either use a tool such as Purify from Pure Software to
357          discover and fix storage leaks or you can run a C garbage collector such as Great Circle from Geodesic
358          Systems.
359       </P>
360       <P>
361          <A NAME="4972"></A>
362       </P>
363       <P>
364       </P>
365       <HR>
366       <BR>
367        <A HREF="cover.htm">[Top]</A> <A HREF="ch1intro.htm">[Prev]</A> <A HREF="ch3perl.htm">[Next]</A> <A HREF=
368       "ap_guida.htm">[Bottom]</A> 
369       <HR>
370       <BR>
371        <!-- This file was created with Quadralay WebWorks Publisher 3.0.3 -->
372       <!-- -->
373       <!-- For more information on how this document, and how the rest of -->
374       <!-- this server was created, email yourEmail@xyzcorp.com -->
375       <!-- -->
376       <!-- Last updated: 04/15/96 08:00:16 -->
377    </BODY>
378 </HTML>
379