This file is indexed.

/usr/share/doc/libapache2-mod-perl2-doc/docs/2.0/user/coding/coding.html is in libapache2-mod-perl2-doc 2.0.8+httpd24-r1449661-6ubuntu2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:root@localhost" />
</head>

<body style="background-color: white">



<ul id="index">
  <li><a href="#NAME">NAME</a></li>
  <li><a href="#Description">Description</a></li>
  <li><a href="#Prerequisites">Prerequisites</a></li>
  <li><a href="#Where-the-Methods-Live">Where the Methods Live</a></li>
  <li><a href="#Techniques">Techniques</a>
    <ul>
      <li><a href="#Method-Handlers">Method Handlers</a></li>
      <li><a href="#Cleaning-up">Cleaning up</a></li>
    </ul>
  </li>
  <li><a href="#Goodies-Toolkit">Goodies Toolkit</a>
    <ul>
      <li><a href="#Environment-Variables">Environment Variables</a></li>
      <li><a href="#Threaded-MPM-or-not">Threaded MPM or not?</a></li>
      <li><a href="#Writing-MPM-specific-Code">Writing MPM-specific Code</a></li>
    </ul>
  </li>
  <li><a href="#Code-Developing-Nuances">Code Developing Nuances</a>
    <ul>
      <li><a href="#Auto-Reloading-Modified-Modules-with-Apache2::Reload">Auto-Reloading Modified Modules with Apache2::Reload</a></li>
    </ul>
  </li>
  <li><a href="#Integration-with-Apache-Issues">Integration with Apache Issues</a>
    <ul>
      <li><a href="#HTTP-Response-Headers">HTTP Response Headers</a>
        <ul>
          <li><a href="#Generating-HTTP-Response-Headers">Generating HTTP Response Headers</a></li>
          <li><a href="#Forcing-HTTP-Response-Headers-Out">Forcing HTTP Response Headers Out</a></li>
        </ul>
      </li>
      <li><a href="#Sending-HTTP-Response-Body">Sending HTTP Response Body</a></li>
      <li><a href="#Using-Signal-Handlers">Using Signal Handlers</a></li>
    </ul>
  </li>
  <li><a href="#Perl-Specifics-in-the-mod_perl-Environment">Perl Specifics in the mod_perl Environment</a>
    <ul>
      <li><a href="#BEGIN-Blocks">BEGIN Blocks</a></li>
      <li><a href="#CHECK-and-INIT-Blocks">CHECK and INIT Blocks</a></li>
      <li><a href="#END-Blocks">END Blocks</a></li>
      <li><a href="#Request-localized-Globals">Request-localized Globals</a></li>
      <li><a href="#exit">exit</a></li>
    </ul>
  </li>
  <li><a href="#ModPerl::Registry-Handlers-Family">ModPerl::Registry Handlers Family</a>
    <ul>
      <li><a href="#A-Look-Behind-the-Scenes">A Look Behind the Scenes</a></li>
      <li><a href="#Getting-the-r-Object">Getting the $r Object</a></li>
    </ul>
  </li>
  <li><a href="#Threads-Coding-Issues-Under-mod_perl">Threads Coding Issues Under mod_perl</a>
    <ul>
      <li><a href="#Thread-environment-Issues">Thread-environment Issues</a></li>
      <li><a href="#Deploying-Threads">Deploying Threads</a></li>
      <li><a href="#Shared-Variables">Shared Variables</a></li>
    </ul>
  </li>
  <li><a href="#Maintainers">Maintainers</a></li>
  <li><a href="#Authors">Authors</a></li>
</ul>

<h1 id="NAME">NAME</h1>

<p>Writing mod_perl Handlers and Scripts</p>

<h1 id="Description">Description</h1>

<p>This chapter covers the mod_perl coding specifics, different from normal Perl coding. Most other perl coding issues are covered in the perl manpages and rich literature.</p>

<h1 id="Prerequisites">Prerequisites</h1>

<h1 id="Where-the-Methods-Live">Where the Methods Live</h1>

<p>mod_perl 2.0 has all its methods spread across many modules. In order to use these methods the modules containing them have to be loaded first. If you don&#39;t do that mod_perl will complain that it can&#39;t find the methods in question. The module <code><a>ModPerl::MethodLookup</a></code> can be used to find out which modules need to be used.</p>

<h1 id="Techniques">Techniques</h1>

<h2 id="Method-Handlers">Method Handlers</h2>

<p>In addition to function handlers method handlers can be used. Method handlers are useful when you want to write code that takes advantage of inheritance. To make the handler act as a method under mod_perl 2, use the <code>method</code> attribute.</p>

<p>See the Perl <i>attributes</i> manpage for details on the attributes syntax (<code>perldoc attributes</code>).</p>

<p>For example:</p>

<pre><code>  package Bird::Eagle;
  @ISA = qw(Bird);
  
  sub handler : method {
      my ($class_or_object, $r) = @_;
      ...;
  }
  
  sub new { bless {}, __PACKAGE__ }</code></pre>

<p>and then register it as:</p>

<pre><code>  PerlResponseHandler Bird::Eagle</code></pre>

<p>When mod_perl sees that the handler has a method attribute, it passes two arguments to it: the calling object or a class, depending on how it was called, and the request object, as shown above.</p>

<p>If <code>Class-&gt;method</code> syntax is used for a <code>Perl*Handler</code>, e.g.:</p>

<pre><code>  PerlResponseHandler Bird::Eagle-&gt;handler;</code></pre>

<p>the <code>:method</code> attribute is not required.</p>

<p>In the preceding configuration example, the <code>handler()</code> method will be called as a class (static) method.</p>

<p>Also, you can use objects created at startup to call methods. For example:</p>

<pre><code>  &lt;Perl&gt;
      use Bird::Eagle;
      $Bird::Global::object = Bird::Eagle-&gt;new();
  &lt;/Perl&gt;
  ...
  PerlResponseHandler $Bird::Global::object-&gt;handler</code></pre>

<p>In this example, the <code>handler()</code> method will be called as an instance method on the global object $<code>Bird::Global::object</code>.</p>

<h2 id="Cleaning-up">Cleaning up</h2>

<p>It&#39;s possible to arrange for cleanups to happen at the end of various phases. One can&#39;t rely on <code>END</code> blocks to do the job, since these <a href="#C_END__Blocks">don&#39;t get executed</a> until the interpreter quits, with an exception to the <a>Registry</a> handlers.</p>

<p>Module authors needing to run cleanups after each HTTP request, should use <code><a>PerlCleanupHandler</a></code>.</p>

<p>Module authors needing to run cleanups at other times can always register a cleanup callback via <code><a>cleanup_register</a></code> on the pool object of choice. Here are some examples of its usage:</p>

<p>To run something at the server shutdown and restart use a cleanup handler registered on <code><a>server_shutdown_cleanup_register()</a></code> in <i>startup.pl</i>:</p>

<pre><code>  #PerlPostConfigRequire startup.pl
  use Apache2::ServerUtil ();
  use APR::Pool ();
  
  warn &quot;parent pid is $$\n&quot;;
  Apache2::ServerUtil::server_shutdown_cleanup_register((\&amp;cleanup);
  sub cleanup { warn &quot;server cleanup in $$\n&quot; }</code></pre>

<p>This is usually useful when some server-wide cleanup should be performed when the server is stopped or restarted.</p>

<p>To run a cleanup at the end of each connection phase, assign a cleanup callback to the connection pool object:</p>

<pre><code>  use Apache2::Connection ();
  use APR::Pool ();
  
  my $pool = $c-&gt;pool;
  $pool-&gt;cleanup_register(\&amp;my_cleanup);
  sub my_cleanup { ... }</code></pre>

<p>You can also create your own pool object, register a cleanup callback and it&#39;ll be called when the object is destroyed:</p>

<pre><code>  use APR::Pool ();
  
  {
      my @args = 1..3;
      my $pool = APR::Pool-&gt;new;
      $pool-&gt;cleanup_register(\&amp;cleanup, \@args);
  }
  
  sub cleanup {
      my @args = @{ +shift };
      warn &quot;cleanup was called with args: @args&quot;;
  }</code></pre>

<p>In this example the cleanup callback gets called, when <code>$pool</code> goes out of scope and gets destroyed. This is very similar to OO <code>DESTROY</code> method.</p>

<h1 id="Goodies-Toolkit">Goodies Toolkit</h1>

<h2 id="Environment-Variables">Environment Variables</h2>

<p>mod_perl sets the following environment variables:</p>

<ul>

<li><p><code>$ENV{MOD_PERL}</code> - is set to the mod_perl version the server is running under. e.g.:</p>

<pre><code>  mod_perl/2.000002</code></pre>

<p>If <code>$ENV{MOD_PERL}</code> doesn&#39;t exist, most likely you are not running under mod_perl.</p>

<pre><code>  die &quot;I refuse to work without mod_perl!&quot; unless exists $ENV{MOD_PERL};</code></pre>

<p>However to check which version is used it&#39;s better to use the following technique:</p>

<pre><code>  use mod_perl;
  use constant MP2 =&gt; ( exists $ENV{MOD_PERL_API_VERSION} and 
                        $ENV{MOD_PERL_API_VERSION} &gt;= 2 ); 

  # die &quot;I want mod_perl 2.0!&quot; unless MP2;</code></pre>

</li>
</ul>

<p>mod_perl passes (exports) the following shell environment variables (if they are set) :</p>

<ul>

<li><p><code>PATH</code> - Executables search path.</p>

</li>
<li><p><code>TZ</code> - Time Zone.</p>

</li>
</ul>

<p>Any of these environment variables can be accessed via <code>%ENV</code>.</p>

<h2 id="Threaded-MPM-or-not">Threaded MPM or not?</h2>

<p>If the code needs to behave differently depending on whether it&#39;s running under one of the threaded MPMs, or not, the class method <code>Apache2::MPM-&gt;is_threaded</code> can be used. For example:</p>

<pre><code>  use Apache2::MPM ();
  if (Apache2::MPM-&gt;is_threaded) {
      require APR::OS;
      my $tid = APR::OS::current_thread_id();
      print &quot;current thread id: $tid (pid: $$)&quot;;
  }
  else {
      print &quot;current process id: $$&quot;;
  }</code></pre>

<p>This code prints the current thread id if running under a threaded MPM, otherwise it prints the process id.</p>

<h2 id="Writing-MPM-specific-Code">Writing MPM-specific Code</h2>

<p>If you write a CPAN module it&#39;s a bad idea to write code that won&#39;t run under all MPMs, and developers should strive to write a code that works with all mpms. However it&#39;s perfectly fine to perform different things under different mpms.</p>

<p>If you don&#39;t develop CPAN modules, it&#39;s perfectly fine to develop your project to be run under a specific MPM.</p>

<pre><code>  use Apache2::MPM ();
  my $mpm = lc Apache2::MPM-&gt;show;
  if ($mpm eq &#39;prefork&#39;) {
      # prefork-specific code
  }
  elsif ($mpm eq &#39;worker&#39;) {
      # worker-specific code
  }
  elsif ($mpm eq &#39;winnt&#39;) {
      # winnt-specific code
  }
  else {
      # others...
  }</code></pre>

<h1 id="Code-Developing-Nuances">Code Developing Nuances</h1>

<h2 id="Auto-Reloading-Modified-Modules-with-Apache2::Reload">Auto-Reloading Modified Modules with Apache2::Reload</h2>

<p>META: need to port Apache2::Reload notes from the guide here. but the gist is:</p>

<pre><code>  PerlModule Apache2::Reload
  PerlInitHandler Apache2::Reload
  #PerlPreConnectionHandler Apache2::Reload
  PerlSetVar ReloadAll Off
  PerlSetVar ReloadModules &quot;ModPerl::* Apache2::*&quot;</code></pre>

<p>Use:</p>

<pre><code>  PerlInitHandler Apache2::Reload</code></pre>

<p>if you need to debug HTTP protocol handlers. Use:</p>

<pre><code>  PerlPreConnectionHandler Apache2::Reload</code></pre>

<p>for any handlers.</p>

<p>Though notice that we have started to practice the following style in our modules:</p>

<pre><code>  package Apache2::Whatever;
  
  use strict;
  use warnings FATAL =&gt; &#39;all&#39;;</code></pre>

<p><code>FATAL =&gt; &#39;all&#39;</code> escalates all warnings into fatal errors. So when <code>Apache2::Whatever</code> is modified and reloaded by <code>Apache2::Reload</code> the request is aborted. Therefore if you follow this very healthy style and want to use <code>Apache2::Reload</code>, flex the strictness by changing it to:</p>

<pre><code>  use warnings FATAL =&gt; &#39;all&#39;;
  no warnings &#39;redefine&#39;;</code></pre>

<p>but you probably still want to get the <i>redefine</i> warnings, but downgrade them to be non-fatal. The following will do the trick:</p>

<pre><code>  use warnings FATAL =&gt; &#39;all&#39;;
  no warnings &#39;redefine&#39;;
  use warnings &#39;redefine&#39;;</code></pre>

<p>Perl 5.8.0 allows one to do all this in one line:</p>

<pre><code>  use warnings FATAL =&gt; &#39;all&#39;, NONFATAL =&gt; &#39;redefine&#39;;</code></pre>

<p>but if your code may be used with older perl versions, you probably don&#39;t want to use this new functionality.</p>

<p>Refer to the <i>perllexwarn</i> manpage for more information.</p>

<h1 id="Integration-with-Apache-Issues">Integration with Apache Issues</h1>

<p>In the following sections we discuss the specifics of Apache behavior relevant to mod_perl developers.</p>

<h2 id="HTTP-Response-Headers">HTTP Response Headers</h2>

<h3 id="Generating-HTTP-Response-Headers">Generating HTTP Response Headers</h3>

<p>The best approach for generating HTTP response headers is by using the <a>mod_perl API</a>. Some common headers have dedicated methods, others are set by manipulating the <code><a>headers_out</a></code> table directly.</p>

<p>For example to set the <i>Content-type</i> header you should call <code><a>$r-&gt;content_type</a></code>:</p>

<pre><code>  use Apache2::RequestRec ();
  $r-&gt;content_type(&#39;text/html&#39;);</code></pre>

<p>To <code><a>set</a></code> a custom header <i>My-Header</i> you should call:</p>

<pre><code>  use Apache2::RequestRec ();
  use APR::Table;
  $r-&gt;headers_out-&gt;set(My-Header =&gt; &quot;SomeValue&quot;);</code></pre>

<p>If you are inside a registry script <a>you can still access</a> the <code><a>Apache2::RequestRec</a></code> object.</p>

<p>Howerever you can choose a slower method of generating headers by just printing them out before printing any response. This will work only if <code><a>PerlOptions +ParseHeaders</a></code> is in effect. For example:</p>

<pre><code>   print &quot;Content-type: text/html\n&quot;;
   print &quot;My-Header: SomeValue\n&quot;;
   print &quot;\n&quot;;</code></pre>

<p>This method is slower since Apache needs to parse the text to identify certain headers it needs to know about. It also has several limitations which we will now discuss.</p>

<p>When using this approach you must make sure that the <code>STDOUT</code> filehandle is not set to flush the data after each print (which is set by the value of a special perl variable <code>$|</code>). Here we assume that STDOUT is the currently <code>select()</code>ed filehandle and <code>$|</code> affects it.</p>

<p>For example this code won&#39;t work:</p>

<pre><code>   local $| = 1;
   print &quot;Content-type: text/html\n&quot;;
   print &quot;My-Header: SomeValue\n&quot;;
   print &quot;\n&quot;;</code></pre>

<p>Having a true <code>$|</code> causes the first print() call to flush its data immediately, which is sent to the internal HTTP header parser, which will fail since it won&#39;t see the terminating <code>&quot;\n\n&quot;</code>. One solution is to make sure that STDOUT won&#39;t flush immediately, like so:</p>

<pre><code>   local $| = 0;
   print &quot;Content-type: text/html\n&quot;;
   print &quot;My-Header: SomeValue\n&quot;;
   print &quot;\n&quot;;</code></pre>

<p>Notice that we <code>local()</code>ize that change, so it <a>won&#39;t affect any other code</a>.</p>

<p>If you send headers line by line and their total length is bigger than 8k, you will have the header parser problem again, since mod_perl will flush data when the 8k buffer gets full. In which case the solution is not to print the headers one by one, but to buffer them all in a variable and then print the whole set at once.</p>

<p>Notice that you don&#39;t have any of these problems with mod_cgi, because it ignores any of the flush attempts by Perl. mod_cgi simply opens a pipe to the external process and reads any output sent from that process at once.</p>

<p>If you use <code>$r</code> to set headers as explained at the beginning of this section, you won&#39;t encounter any of these problems.</p>

<p>Finally, if you don&#39;t want Apache to send its own headers and you want to send your own set of headers (non-parsed headers handlers) use the <code><a>$r-&gt;assbackwards</a></code> method. Notice that registry handlers will do that for you if the script&#39;s name start with the <code>nph-</code> prefix.</p>

<h3 id="Forcing-HTTP-Response-Headers-Out">Forcing HTTP Response Headers Out</h3>

<p>Apache 2.0 doesn&#39;t provide a method to force HTTP response headers sending (what used to be done by <code>send_http_header()</code> in Apache 1.3). HTTP response headers are sent as soon as the first bits of the response body are seen by the special core output filter that generates these headers. When the response handler sends the first chunks of body it may be cached by the mod_perl internal buffer or even by some of the output filters. The response handler needs to flush the output in order to tell all the components participating in the sending of the response to pass the data out.</p>

<p>For example if the handler needs to perform a relatively long-running operation (e.g. a slow db lookup) and the client may timeout if it receives nothing right away, you may want to start the handler by setting the <i>Content-Type</i> header, following by an immediate flush:</p>

<pre><code>  sub handler {
      my $r = shift;
      $r-&gt;content_type(&#39;text/html&#39;);
      $r-&gt;rflush; # send the headers out
  
      $r-&gt;print(long_operation());
      return Apache2::Const::OK;
  }</code></pre>

<p>If this doesn&#39;t work, check whether you have configured any third-party output filters for the resource in question. <a>Improperly written filter</a> may ignore the command to flush the data.</p>

<h2 id="Sending-HTTP-Response-Body">Sending HTTP Response Body</h2>

<p>In mod_perl 2.0 a response body can be sent only during the response phase. Any attempts to do that in the earlier phases will fail with an appropriate explanation logged into the <i>error_log</i> file.</p>

<p>This happens due to the Apache 2.0 HTTP architecture specifics. One of the issues is that the HTTP response filters are not setup before the response phase.</p>

<h2 id="Using-Signal-Handlers">Using Signal Handlers</h2>

<p>3rd party Apache 2 modules should avoid using code relying on signals. This is because typical signal use is not thread-safe and modules which rely on signals may not work portably. Certain signals may still work for non-threaded mpms. For example <code>alarm()</code> can be used under prefork MPM, but it won&#39;t work on any other MPM. Moreover the Apache developers don&#39;tq guarantee that the signals that currently happen to work will continue to do so in the future Apache releases. So use them at your own risk.</p>

<p>It should be possible to rework the code using signals to use an alternative solution, which works under threads. For example if you were using <code>alarm()</code> to trap potentially long running I/O, you can modify the I/O logic for select/poll usage (or if you use APR I/O then set timeouts on the apr pipes or sockets). For example, Apache 1.3 on Unix made blocking I/O calls and relied on the parent process to send the SIGALRM signal to break it out of the I/O after a timeout expired. With Apache 2.0, APR support for timeouts on I/O operations is used so that signals or other thread-unsafe mechanisms are not necessary.</p>

<p>CPU timeout handling is another example. It can be accomplished by modifying the computation logic to explicitly check for the timeout at intervals.</p>

<p>Talking about <code>alarm()</code> under prefork mpm, POSIX signals seem to work, but require Perl 5.8.x+. For example:</p>

<pre><code>  use POSIX qw(SIGALRM);
  my $mask      = POSIX::SigSet-&gt;new( SIGALRM );
  my $action    = POSIX::SigAction-&gt;new(sub { die &quot;alarm&quot; }, $mask);
  my $oldaction = POSIX::SigAction-&gt;new();
  POSIX::sigaction(SIGALRM, $action, $oldaction );
  eval {
      alarm 2;
      sleep 10 # some real code should be here
      alarm 0;
  };
  POSIX::sigaction(SIGALRM, $oldaction); # restore original
  warn &quot;got alarm&quot; if $@ and $@ =~ /alarm/;</code></pre>

<p>For more details see: http://search.cpan.org/dist/perl/ext/POSIX/POSIX.pod#POSIX::SigAction.</p>

<p>One could use the <code>$SIG{ALRM}</code> technique, working for 5.6.x+, but it works <b>only</b> under DSO modperl build. Moreover starting from 5.8.0 Perl delays signal delivery, making signals safe. This change may break previously working code. For more information please see: http://search.cpan.org/dist/perl/pod/perl58delta.pod#Safe_Signals and http://search.cpan.org/dist/perl/pod/perlipc.pod#Deferred_Signals_%28Safe_Signals%29.</p>

<p>For example if you had the alarm code:</p>

<pre><code>  eval {
      local $SIG{ALRM} = sub { die &quot;alarm&quot; };
      alarm 3;
      sleep 10; # in reality some real code should be here
      alarm 0;
  };
  die &quot;the operation was aborted&quot; if $@ and $@ =~ /alarm/;</code></pre>

<p>It may not work anymore. Starting from 5.8.1 it&#39;s possible to circumvent the safeness of signals, by setting:</p>

<pre><code>  $ENV{PERL_SIGNALS} = &quot;unsafe&quot;;</code></pre>

<p>as soon as you start your program (e.g. in the case of mod_perl in startup.pl). As of this writing, this workaround fails on MacOSX, POSIX signals must be used instead.</p>

<p>For more information please refer to: http://search.cpan.org/dist/perl/pod/perl581delta.pod#Unsafe_signals_again_available and http://search.cpan.org/dist/perl/pod/perlrun.pod#PERL_SIGNALS.</p>

<p>Though if you use perl 5.8.x+ it&#39;s preferrable to use the POSIX API technique explained earlier in this section.</p>

<h1 id="Perl-Specifics-in-the-mod_perl-Environment">Perl Specifics in the mod_perl Environment</h1>

<p>In the following sections we discuss the specifics of Perl behavior under mod_perl.</p>

<h2 id="BEGIN-Blocks"><code>BEGIN</code> Blocks</h2>

<p>Perl executes <code>BEGIN</code> blocks as soon as possible, at the time of compiling the code. The same is true under mod_perl. However, since mod_perl normally only compiles scripts and modules once, either in the parent server (at the server startup) or once per-child (on the first request using a module), <code>BEGIN</code> blocks in that code will only be run once. As the <code>perlmod</code> manpage explains, once a <code>BEGIN</code> block has run, it is immediately undefined. In the mod_perl environment, this means that <code>BEGIN</code> blocks will not be run during the response to an incoming request unless that request happens to be the one that causes the compilation of the code, i.e. if it wasn&#39;t loaded yet.</p>

<p><code>BEGIN</code> blocks in modules and files pulled in via <code>require()</code> or <code>use()</code> will be executed:</p>

<ul>

<li><p>Only once, if pulled in by the parent process at the server startup.</p>

</li>
<li><p>Once per each child process or Perl interpreter if not pulled in by the parent process.</p>

</li>
<li><p>An additional time, once per each child process or Perl interpreter if the module is reloaded off disk again via <code><a>Apache2::Reload</a></code>.</p>

</li>
<li><p>Unpredictable if you fiddle with <code>%INC</code> yourself.</p>

</li>
</ul>

<p>The <code>BEGIN</code> blocks behavior is different in <code><a>ModPerl::Registry</a></code> and <code><a>ModPerl::PerlRun</a></code> handlers, and their subclasses.</p>

<h2 id="CHECK-and-INIT-Blocks"><code>CHECK</code> and <code>INIT</code> Blocks</h2>

<p><code>CHECK</code> and <code>INIT</code> blocks run when the source code compilation is complete, but before the program starts. <code>CHECK</code> can mean &quot;checkpoint&quot; or &quot;double-check&quot; or even just &quot;stop&quot;. <code>INIT</code> stands for &quot;initialization&quot;. The difference is subtle; <code>CHECK</code> blocks are run just after the compilation ends, <code>INIT</code> just before the runtime begins. (Hence the <code>-c</code> command-line perl option runs <code>CHECK</code> blocks but not <code>INIT</code> blocks.)</p>

<p>Perl only calls these blocks during <i>perl_parse()</i>, which mod_perl calls once at startup time. Under threaded mpm, these blocks will be called once per <code><a>parent perl interpreter startup</a></code>. Therefore <code>CHECK</code> and <code>INIT</code> blocks don&#39;t work after the server is started, for the same reason these code samples don&#39;t work:</p>

<pre><code>  % perl -e &#39;eval qq(CHECK { print &quot;ok\n&quot; })&#39;
  % perl -e &#39;eval qq(INIT  { print &quot;ok\n&quot; })&#39;</code></pre>

<h2 id="END-Blocks"><code>END</code> Blocks</h2>

<p>As the <code>perlmod</code> manpage explains, an <code>END</code> block is executed as late as possible, that is, when the interpreter exits. So for example mod_cgi will run its <code>END</code> blocks on each invocation, since on every invocation it starts a new interpreter and then kills it when the request processing is done.</p>

<p>In the mod_perl environment, the interpreter does not exit after serving a single request (unless it is configured to do so) and hence it will run its <code>END</code> blocks only when it exits, which usually happens during the server shutdown, but may also happen earlier than that (e.g. a process exits because it has served a <code>MaxRequestsPerChild</code> number of requests).</p>

<p>mod_perl does <a>make a special case</a> for scripts running under <code><a>ModPerl::Registry</a></code> and friends.</p>

<p>The <a href="#Cleaning_up">Cleaning up</a> section explains how to deal with cleanups for non-Registry handlers.</p>

<p><code><a>ModPerl::Global</a></code> API: <code><a>special_list_register</a></code>, <code><a>special_list_call</a></code> and <code><a>special_list_clear</a></code>, internally used by registry handlers, can be used to run <code>END</code> blocks at arbitrary times.</p>

<h2 id="Request-localized-Globals">Request-localized Globals</h2>

<p>mod_perl 2.0 provides two types of <code>SetHandler</code> handlers: <code><a>modperl</a></code> and <code><a>perl-script</a></code>. Remember that the <code>SetHandler</code> directive is only relevant for the response phase handlers, it neither needed nor affects non-response phases.</p>

<p>Under the handler:</p>

<pre><code>  SetHandler perl-script</code></pre>

<p>several special global Perl variables are saved before the handler is called and restored afterwards. This includes: <code>%ENV</code>, <code>@INC</code>, <code>$/</code>, <code>STDOUT</code>&#39;s <code>$|</code> and <code>END</code> blocks array (<code>PL_endav</code>).</p>

<p>Under:</p>

<pre><code>  SetHandler modperl</code></pre>

<p>nothing is restored, so you should be especially careful to remember localize all special Perl variables so the local changes won&#39;t affect other handlers.</p>

<h2 id="exit"><code>exit</code></h2>

<p>In the normal Perl code exit() is used to stop the program flow and exit the Perl interpreter. However under mod_perl we only want the stop the program flow without killing the Perl interpreter.</p>

<p>You should take no action if your code includes exit() calls and it&#39;s OK to continue using them. mod_perl worries to override the exit() function with <a>its own version</a> which stops the program flow, and performs all the necessary cleanups, but doesn&#39;t kill the server. This is done by overriding:</p>

<pre><code>  *CORE::GLOBAL::exit = \&amp;ModPerl::Util::exit;</code></pre>

<p>so if you mess up with <code>*CORE::GLOBAL::exit</code> yourself you better know what you are doing.</p>

<p>You can still call <code>CORE::exit</code> to kill the interpreter, again if you know what you are doing.</p>

<p>One caveat is when <code>exit</code> is called inside <code>eval</code> -- <a>the ModPerl::Util::exit documentation</a> explains how to deal with this situation.</p>

<h1 id="ModPerl::Registry-Handlers-Family"><code>ModPerl::Registry</code> Handlers Family</h1>

<h2 id="A-Look-Behind-the-Scenes">A Look Behind the Scenes</h2>

<p>If you have a CGI script <i>test.pl</i>:</p>

<pre><code>  #!/usr/bin/perl
  print &quot;Content-type: text/plain\n\n&quot;;
  print &quot;Hello&quot;;</code></pre>

<p>a typical registry family handler turns it into something like:</p>

<pre><code>  package foo_bar_baz;
  sub handler {
      local $0 = &quot;/full/path/to/test.pl&quot;;
  #line 1 test.pl
      #!/usr/bin/perl
      print &quot;Content-type: text/plain\n\n&quot;;
      print &quot;Hello&quot;;
  }</code></pre>

<p>Turning it into an almost full-fledged mod_perl handler. The only difference is that it handles the return status for you. (META: more details on return status needed.)</p>

<p>It then executes it as:</p>

<pre><code>  foo_bar_baz::handler($r);</code></pre>

<p>passing the <code><a>$r</a></code> object as the only argument to the <code>handler()</code> function.</p>

<p>Depending on the used registry handler the package is made of the file path, the uri or anything else. Check the handler&#39;s documentation to learn which method is used.</p>

<h2 id="Getting-the-r-Object">Getting the <code>$r</code> Object</h2>

<p>As explained in <a href="#A_Look_Behind_the_Scenes">A Look Behind the Scenes</a> the <code>$r</code> object is always passed to the registry script&#39;s special function <code>handler</code> as the first and the only argument, so you can get this object by accessing <code>@_</code>, since:</p>

<pre><code>  my $r = shift;
  print &quot;Content-type: text/plain\n\n&quot;;
  print &quot;Hello&quot;;</code></pre>

<p>is turned into:</p>

<pre><code>  sub handler {
      my $r = shift;
      print &quot;Content-type: text/plain\n\n&quot;;
      print &quot;Hello&quot;;
  }</code></pre>

<p>behind the scenes. Now you can use <code>$r</code> to call various mod_perl methods, e.g. rewriting the script as:</p>

<pre><code>  my $r = shift;
  $r-&gt;content_type(&#39;text/plain&#39;);
  $r-&gt;print();</code></pre>

<p>If you are deep inside some code and can&#39;t get to the entry point to reach for <code>$r</code>, you can use <code><a>Apache2-&gt;request</a></code>.</p>

<h1 id="Threads-Coding-Issues-Under-mod_perl">Threads Coding Issues Under mod_perl</h1>

<p>The following sections discuss threading issues when running mod_perl under a threaded MPM.</p>

<h2 id="Thread-environment-Issues">Thread-environment Issues</h2>

<p>The &quot;only&quot; thing you have to worry about your code is that it&#39;s thread-safe and that you don&#39;t use functions that affect all threads in the same process.</p>

<p>Perl 5.8.0 itself is thread-safe. That means that operations like <code>push()</code>, <code>map()</code>, <code>chomp()</code>, <code>=</code>, <code>/</code>, <code>+=</code>, etc. are thread-safe. Operations that involve system calls, may or may not be thread-safe. It all depends on whether the underlying C libraries used by the perl functions are thread-safe.</p>

<p>For example the function <code>localtime()</code> is not thread-safe when the implementation of <code>asctime(3)</code> is not thread-safe. Other usually problematic functions include <code>readdir()</code>, <code>srand()</code>, etc.</p>

<p>Another important issue that shouldn&#39;t be missed is what some people refer to as <i>thread-locality</i>. Certain functions executed in a single thread affect the whole process and therefore all other threads running inside that process. For example if you <code>chdir()</code> in one thread, all other thread now see the current working directory of that thread that <code>chdir()</code>&#39;ed to that directory. Other functions with similar effects include <code>umask()</code>, <code>chroot()</code>, etc. Currently there is no cure for this problem. You have to find these functions in your code and replace them with alternative solutions which don&#39;t incur this problem.</p>

<p>For more information refer to the <i>perlthrtut</i> (<i>http://perldoc.perl.org/perlthrtut.html</i>) manpage.</p>

<h2 id="Deploying-Threads">Deploying Threads</h2>

<p>This is actually quite unrelated to mod_perl 2.0. You don&#39;t have to know much about Perl threads, other than <a href="#Thread_environment_Issues">Thread-environment Issues</a>, to have your code properly work under threaded MPM mod_perl.</p>

<p>If you want to spawn your own threads, first of all study how the new ithreads Perl model works, by reading the <i>perlthrtut</i>, <i>threads</i> (<i>http://search.cpan.org/search?query=threads</i>) and <i>threads::shared</i> (<i>http://search.cpan.org/search?query=threads%3A%3Ashared</i>) manpages.</p>

<p>Artur Bergman wrote an article which explains how to port pure Perl modules to work properly with Perl ithreads. Issues with <code>chdir()</code> and other functions that rely on shared process&#39; datastructures are discussed. <i>http://www.perl.com/lpt/a/2002/06/11/threads.html</i>.</p>

<h2 id="Shared-Variables">Shared Variables</h2>

<p>Global variables are only global to the interpreter in which they are created. Other interpreters from other threads can&#39;t access that variable. Though it&#39;s possible to make existing variables shared between several threads running in the same process by using the function <code>threads::shared::share()</code>. New variables can be shared by using the <i>shared</i> attribute when creating them. This feature is documented in the <i>threads::shared</i> (<i>http://search.cpan.org/search?query=threads%3A%3Ashared</i>) manpage.</p>

<h1 id="Maintainers">Maintainers</h1>

<p>Maintainer is the person(s) you should contact with updates, corrections and patches.</p>

<ul>

<li><p></p>

</li>
</ul>

<h1 id="Authors">Authors</h1>

<ul>

<li><p></p>

</li>
</ul>

<p>Only the major authors are listed above. For contributors see the Changes file.</p>


</body>

</html>