File: perlipc.html

package info (click to toggle)
perl-doc-html 5.26.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 39,400 kB
  • sloc: xml: 36; makefile: 7
file content (1273 lines) | stat: -rw-r--r-- 207,548 bytes parent folder | download
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>perlipc - perldoc.perl.org</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta http-equiv="Content-Language" content="en-gb">
  <link rel="search" type="application/opensearchdescription+xml" title="Search perldoc.perl.org" href="/static/search.xml"/>
  <link href="static/css-20100830.css" rel="stylesheet" rev="stylesheet" type="text/css" media="screen">
  <link href="static/exploreperl.css" rel="stylesheet" rev="stylesheet" type="text/css">
</head>

<body onLoad="perldoc.startup();" onPageShow="if (event.persisted) perldoc.startup();">
    <div id="page">
      
      <div id="header">
	<div id="homepage_link">
	  <a href="index.html"></a>
	</div>
	<div id="strapline">
	  Perl Programming Documentation
	</div>
	<div id="download_link" class="download">
	  <a href="http://www.perl.org/get.html">Download Perl</a>
	</div>
	<div id="explore_link" class="download">
	  <a id="explore_anchor" href="#">Explore</a>
	</div>
      </div>
      
      <div id="body">
        <div id="left_column">
          <div class="side_group">
            
	    <div class="side_panel doc_panel">
              <p>Manual</p>
              <ul>
                <li><a href="index-overview.html">Overview</a>
                <li><a href="index-tutorials.html">Tutorials</a>
                <li><a href="index-faq.html">FAQs</a>
                <li><a href="index-history.html">History / Changes</a>
                <li><a href="index-licence.html">License</a>
              </ul>
            </div>
            <div class="side_panel doc_panel">
              <p>Reference</p>
              <ul>
                <li><a href="index-language.html">Language</a>
                <li><a href="index-functions.html">Functions</a>
                <li><a href="perlop.html">Operators</a>
                <li><a href="perlvar.html">Special Variables</a>
                <li><a href="index-pragmas.html">Pragmas</a>
                <li><a href="index-utilities.html">Utilities</a>
                <li><a href="index-internals.html">Internals</a>
                <li><a href="index-platforms.html">Platform Specific</a>
              </ul>
            </div>
            <div class="side_panel doc_panel">
              <p>Modules</p>
              <ul>
		<li>
		
                
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		
                  
		
		
                    <a href="index-modules-A.html">A</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-B.html">B</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-C.html">C</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-D.html">D</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-E.html">E</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-F.html">F</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-G.html">G</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-H.html">H</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-I.html">I</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-L.html">L</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-M.html">M</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-N.html">N</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-O.html">O</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-P.html">P</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-S.html">S</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-T.html">T</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-U.html">U</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-X.html">X</a>
                    
                
              </ul>
            </div>
            
	      <div class="side_panel doc_panel">
		<p>Tools</p>
		<ul>
		  <li><a href="preferences.html">Preferences</a>
		</ul>
	      </div>
            
          </div>
        </div>
        <div id="centre_column">
          <div id="content_header">
            <div id="title_bar">
              <div id="page_name">
                <h1>perlipc</h1>
              </div>
              <div id="perl_version">
                Perl 5 version 26.0 documentation
              </div>
              <div class="page_links" id="page_links_top">
                <a href="#" onClick="toolbar.goToTop();return false;">Go to top</a>
		
              </div>
	      <div class="page_links" id="page_links_bottom">
		
                  <a href="#" id="page_index_toggle">Show page index</a> &bull;
		
                <a href="#" id="recent_pages_toggle">Show recent pages</a>		
	      </div>
	      <div id="search_form">
		<form action="search.html" method="GET" id="search">
		  <input type="text" name="q" id="search_box" alt="Search">
		</form>
	      </div>
            </div>
            <div id="breadcrumbs">
                
    <a href="index.html">Home</a> &gt;
    
      
        <a href="index-language.html">Language reference</a> &gt;
      
    
    perlipc
  

            </div>
          </div>
          <div id="content_body">
	    <!--[if lt IE 7]>
 <div class="noscript">
   <p>
     <strong>It looks like you're using Internet Explorer 6. This is a very old
     browser which does not offer full support for modern websites.</strong>
   </p>
   <p>
     Unfortunately this means that this website will not work on
     your computer.
   </p>
   <p>
     Don't miss out though! To view the site (and get a better experience from
     many other websites), simply upgrade to
     <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet
Explorer 8</a>
     or download an alternative browser such as
     <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>,
     <a href="http://www.apple.com/safari/download/">Safari</a>, or
     <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
   </p>
   <p>
     All of these browsers are free. If you're using a PC at work, you may
     need to contact your IT administrator.
   </p>
 </div>
<![endif]-->
	    <noscript>
	      <div class="noscript">
	      <p>
                <strong>Please note: Many features of this site require JavaScript. You appear to have JavaScript disabled,
	        or are running a non-JavaScript capable web browser.</strong>
	      </p>
	      <p>
		To get the best experience, please enable JavaScript or download a modern web browser such as <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet Explorer 8</a>, <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>, <a href="http://www.apple.com/safari/download/">Safari</a>, or <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
              </p>
	      </div>
	    </noscript>

	    <div id="recent_pages" class="hud_container">
	      <div id="recent_pages_header" class="hud_header">
		<div id="recent_pages_close" class="hud_close"><a href="#" onClick="recentPages.hide();return false;"></a></div>
		<div id="recent_pages_title" class="hud_title"><span class="hud_span_top">Recently read</span></div>
		<div id="recent_pages_topright" class="hud_topright"></div>
	      </div>
	      <div id="recent_pages_content" class="hud_content">
	      </div>
	      <div id="recent_pages_footer" class="hud_footer">
		<div id="recent_pages_bottomleft" class="hud_bottomleft"></div>
		<div id="recent_pages_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
		<div id="recent_pages_resize" class="hud_resize"></div>
	      </div>
	    </div>
  
	    <div id="from_search"></div>
            <h1>perlipc</h1>


  <!--    -->
<ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><li><a href="#Signals">Signals</a><ul><li><a href="#Handling-the-SIGHUP-Signal-in-Daemons">Handling the SIGHUP Signal in Daemons</a><li><a href="#Deferred-Signals-(Safe-Signals)">Deferred Signals (Safe Signals)</a></ul><li><a href="#Named-Pipes">Named Pipes</a><li><a href="#Using-open()-for-IPC">Using open() for IPC</a><ul><li><a href="#Filehandles">Filehandles</a><li><a href="#Background-Processes">Background Processes</a><li><a href="#Complete-Dissociation-of-Child-from-Parent">Complete Dissociation of Child from Parent</a><li><a href="#Safe-Pipe-Opens">Safe Pipe Opens</a><li><a href="#Avoiding-Pipe-Deadlocks">Avoiding Pipe Deadlocks</a><li><a href="#Bidirectional-Communication-with-Another-Process">Bidirectional Communication with Another Process</a><li><a href="#Bidirectional-Communication-with-Yourself">Bidirectional Communication with Yourself</a></ul><li><a href="#Sockets%3a-Client%2fServer-Communication">Sockets: Client/Server Communication</a><ul><li><a href="#Internet-Line-Terminators">Internet Line Terminators</a><li><a href="#Internet-TCP-Clients-and-Servers">Internet TCP Clients and Servers</a><li><a href="#Unix-Domain-TCP-Clients-and-Servers">Unix-Domain TCP Clients and Servers</a></ul><li><a href="#TCP-Clients-with-IO%3a%3aSocket">TCP Clients with IO::Socket</a><ul><li><a href="#A-Simple-Client">A Simple Client</a><li><a href="#A-Webget-Client">A Webget Client</a><li><a href="#Interactive-Client-with-IO%3a%3aSocket">Interactive Client with IO::Socket</a></ul><li><a href="#TCP-Servers-with-IO%3a%3aSocket">TCP Servers with IO::Socket</a><li><a href="#UDP%3a-Message-Passing">UDP: Message Passing</a><li><a href="#SysV-IPC">SysV IPC</a><li><a href="#NOTES">NOTES</a><li><a href="#BUGS">BUGS</a><li><a href="#AUTHOR">AUTHOR</a><li><a href="#SEE-ALSO">SEE ALSO</a></ul><a name="NAME"></a><h1>NAME</h1>
<p>perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets, and semaphores)</p>
<a name="DESCRIPTION"></a><h1>DESCRIPTION</h1>
<p>The basic IPC facilities of Perl are built out of the good old Unix
signals, named pipes, pipe opens, the Berkeley socket routines, and SysV
IPC calls.  Each is used in slightly different situations.</p>
<a name="Signals"></a><h1>Signals</h1>
<p>Perl uses a simple signal handling model: the %SIG hash contains names
or references of user-installed signal handlers.  These handlers will
be called with an argument which is the name of the signal that
triggered it.  A signal may be generated intentionally from a
particular keyboard sequence like control-C or control-Z, sent to you
from another process, or triggered automatically by the kernel when
special events transpire, like a child process exiting, your own process
running out of stack space, or hitting a process file-size limit.</p>
<p>For example, to trap an interrupt signal, set up a handler like this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/our.html">our</a> <span class="i">$shucks</span><span class="sc">;</span></li><li></li><li><a name="catch_zap"></a>    sub <span class="m">catch_zap</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$signame</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="sc">;</span></li><li>        <span class="i">$shucks</span>++<span class="sc">;</span></li><li>        <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;Somebody sent me a SIG$signame&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li>    <span class="i">$SIG</span>{<span class="w">INT</span>} = <span class="w">__PACKAGE__</span> . <span class="q">&quot;::catch_zap&quot;</span><span class="sc">;</span></li><li>    <span class="i">$SIG</span>{<span class="w">INT</span>} = \<span class="i">&amp;catch_zap</span><span class="sc">;</span>  <span class="c"># best strategy</span></li></ol></pre><p>Prior to Perl 5.8.0 it was necessary to do as little as you possibly
could in your handler; notice how all we do is set a global variable
and then raise an exception.  That's because on most systems,
libraries are not re-entrant; particularly, memory allocation and I/O
routines are not.  That meant that doing nearly <i>anything</i> in your
handler could in theory trigger a memory fault and subsequent core
dump - see <a href="#Deferred-Signals-(Safe-Signals)">Deferred Signals (Safe Signals)</a> below.</p>
<p>The names of the signals are the ones listed out by <code class="inline"><a class="l_k" href="functions/kill.html">kill</a> -l</code>
 on your
system, or you can retrieve them using the CPAN module <a href="http://search.cpan.org/perldoc/IPC::Signal">IPC::Signal</a>.</p>
<p>You may also choose to assign the strings <code class="inline"><span class="q">&quot;IGNORE&quot;</span></code>
 or <code class="inline"><span class="q">&quot;DEFAULT&quot;</span></code>
 as
the handler, in which case Perl will try to discard the signal or do the
default thing.</p>
<p>On most Unix platforms, the <code class="inline"><span class="w">CHLD</span></code>
 (sometimes also known as <code class="inline"><span class="w">CLD</span></code>
) signal
has special behavior with respect to a value of <code class="inline"><span class="q">&quot;IGNORE&quot;</span></code>
.
Setting <code class="inline"><span class="i">$SIG</span>{<span class="w">CHLD</span>}</code>
 to <code class="inline"><span class="q">&quot;IGNORE&quot;</span></code>
 on such a platform has the effect of
not creating zombie processes when the parent process fails to <code class="inline"><a class="l_k" href="functions/wait.html">wait()</a></code>
on its child processes (i.e., child processes are automatically reaped).
Calling <code class="inline"><a class="l_k" href="functions/wait.html">wait()</a></code> with <code class="inline"><span class="i">$SIG</span>{<span class="w">CHLD</span>}</code>
 set to <code class="inline"><span class="q">&quot;IGNORE&quot;</span></code>
 usually returns
<code class="inline"><span class="n">-1</span></code>
 on such platforms.</p>
<p>Some signals can be neither trapped nor ignored, such as the KILL and STOP
(but not the TSTP) signals. Note that ignoring signals makes them disappear.
If you only want them blocked temporarily without them getting lost you'll
have to use POSIX' sigprocmask.</p>
<p>Sending a signal to a negative process ID means that you send the signal
to the entire Unix process group.  This code sends a hang-up signal to all
processes in the current process group, and also sets $SIG{HUP} to <code class="inline"><span class="q">&quot;IGNORE&quot;</span></code>

so it doesn't kill itself:</p>
<pre class="verbatim"><ol><li>    <span class="c"># block scope for local</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/local.html">local</a> <span class="i">$SIG</span>{<span class="w">HUP</span>} = <span class="q">&quot;IGNORE&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/kill.html">kill</a> <span class="w">HUP</span> <span class="cm">=&gt;</span> -<span class="i">$$</span><span class="sc">;</span></li><li>        <span class="c"># snazzy writing of: kill(&quot;HUP&quot;, -$$)</span></li><li>    <span class="s">}</span></li></ol></pre><p>Another interesting signal to send is signal number zero.  This doesn't
actually affect a child process, but instead checks whether it's alive
or has changed its UIDs.</p>
<pre class="verbatim"><ol><li>    unless <span class="s">(</span><a class="l_k" href="functions/kill.html">kill</a> <span class="n">0</span> <span class="cm">=&gt;</span> <span class="i">$kid_pid</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/warn.html">warn</a> <span class="q">&quot;something wicked happened to $kid_pid&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Signal number zero may fail because you lack permission to send the
signal when directed at a process whose real or saved UID is not
identical to the real or effective UID of the sending process, even
though the process is alive.  You may be able to determine the cause of
failure using <code class="inline"><span class="i">$!</span></code>
 or <code class="inline"><span class="i">%!</span></code>
.</p>
<pre class="verbatim"><ol><li>    unless <span class="s">(</span><a class="l_k" href="functions/kill.html">kill</a><span class="s">(</span><span class="n">0</span> <span class="cm">=&gt;</span> <span class="i">$pid</span><span class="s">)</span> || <span class="i">$!</span>{<span class="w">EPERM</span>}<span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/warn.html">warn</a> <span class="q">&quot;$pid looks dead&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>You might also want to employ anonymous functions for simple signal
handlers:</p>
<pre class="verbatim"><ol><li>    <span class="i">$SIG</span>{<span class="w">INT</span>} = <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;\nOutta here!\n&quot;</span> <span class="s">}</span><span class="sc">;</span></li></ol></pre><p>SIGCHLD handlers require some special care.  If a second child dies
while in the signal handler caused by the first death, we won't get
another signal. So must loop here else we will leave the unreaped child
as a zombie. And the next time two children die we get another zombie.
And so on.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="q">&quot;:sys_wait_h&quot;</span><span class="sc">;</span></li><li>    <span class="i">$SIG</span>{<span class="w">CHLD</span>} = <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span></li><li>        <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$child</span> = <a class="l_k" href="functions/waitpid.html">waitpid</a><span class="s">(</span><span class="n">-1</span><span class="cm">,</span> <span class="w">WNOHANG</span><span class="s">)</span><span class="s">)</span> &gt; <span class="n">0</span><span class="s">)</span> <span class="s">{</span></li><li>            <span class="i">$Kid_Status</span>{<span class="i">$child</span>} = <span class="i">$?</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span><span class="sc">;</span></li><li>    <span class="c"># do something that forks...</span></li></ol></pre><p>Be careful: qx(), system(), and some modules for calling external commands
do a fork(), then wait() for the result. Thus, your signal handler
will be called. Because wait() was already called by system() or qx(),
the wait() in the signal handler will see no more zombies and will
therefore block.</p>
<p>The best way to prevent this issue is to use waitpid(), as in the following
example:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="q">&quot;:sys_wait_h&quot;</span><span class="sc">;</span> <span class="c"># for nonblocking read</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">%children</span><span class="sc">;</span></li><li></li><li>    <span class="i">$SIG</span>{<span class="w">CHLD</span>} = <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span></li><li>        <span class="c"># don&#39;t change $! and $? outside handler</span></li><li>        <a class="l_k" href="functions/local.html">local</a> <span class="s">(</span><span class="i">$!</span><span class="cm">,</span> <span class="i">$?</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> <span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$pid</span> = <a class="l_k" href="functions/waitpid.html">waitpid</a><span class="s">(</span><span class="n">-1</span><span class="cm">,</span> <span class="w">WNOHANG</span><span class="s">)</span><span class="s">)</span> &gt; <span class="n">0</span> <span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/delete.html">delete</a> <span class="i">$children</span>{<span class="i">$pid</span>}<span class="sc">;</span></li><li>            <span class="i">cleanup_child</span><span class="s">(</span><span class="i">$pid</span><span class="cm">,</span> <span class="i">$?</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="n">1</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$pid</span> = <a class="l_k" href="functions/fork.html">fork</a><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;cannot fork&quot;</span> <a class="l_k" href="functions/unless.html">unless</a> <a class="l_k" href="functions/defined.html">defined</a> <span class="i">$pid</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$pid</span> == <span class="n">0</span><span class="s">)</span> <span class="s">{</span></li><li>            <span class="c"># ...</span></li><li>            <a class="l_k" href="functions/exit.html">exit</a> <span class="n">0</span><span class="sc">;</span></li><li>        <span class="s">}</span> <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span></li><li>            <span class="i">$children</span>{<span class="i">$pid</span>}=<span class="n">1</span><span class="sc">;</span></li><li>            <span class="c"># ...</span></li><li>            <a class="l_k" href="functions/system.html">system</a><span class="s">(</span><span class="i">$command</span><span class="s">)</span><span class="sc">;</span></li><li>            <span class="c"># ...</span></li><li>       <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>Signal handling is also used for timeouts in Unix.  While safely
protected within an <code class="inline"><a class="l_k" href="functions/eval.html">eval{}</a></code> block, you set a signal handler to trap
alarm signals and then schedule to have one delivered to you in some
number of seconds.  Then try your blocking operation, clearing the alarm
when it's done but not before you've exited your <code class="inline"><a class="l_k" href="functions/eval.html">eval{}</a></code> block.  If it
goes off, you'll use die() to jump out of the block.</p>
<p>Here's an example:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$ALARM_EXCEPTION</span> = <span class="q">&quot;alarm clock restart&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/eval.html">eval</a> <span class="s">{</span></li><li>        <a class="l_k" href="functions/local.html">local</a> <span class="i">$SIG</span>{<span class="w">ALRM</span>} = <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <a class="l_k" href="functions/die.html">die</a> <span class="i">$ALARM_EXCEPTION</span> <span class="s">}</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/alarm.html">alarm</a> <span class="n">10</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/flock.html">flock</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span>    <span class="c"># blocking write lock</span></li><li>                        || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;cannot flock: $!&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/alarm.html">alarm</a> <span class="n">0</span><span class="sc">;</span></li><li>    <span class="s">}</span><span class="sc">;</span></li><li>    if <span class="s">(</span><span class="i">$@</span> &amp;&amp; <span class="i">$@</span> !~ <a class="l_k" href="functions/quotemeta.html">quotemeta</a><span class="s">(</span><span class="i">$ALARM_EXCEPTION</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span> <a class="l_k" href="functions/die.html">die</a> <span class="s">}</span></li></ol></pre><p>If the operation being timed out is system() or qx(), this technique
is liable to generate zombies.    If this matters to you, you'll
need to do your own fork() and exec(), and kill the errant child process.</p>
<p>For more complex signal handling, you might see the standard POSIX
module.  Lamentably, this is almost entirely undocumented, but the
<i>ext/POSIX/t/sigaction.t</i> file from the Perl source distribution has
some examples in it.</p>
<a name="Handling-the-SIGHUP-Signal-in-Daemons"></a><h2>Handling the SIGHUP Signal in Daemons</h2>
<p>A process that usually starts when the system boots and shuts down
when the system is shut down is called a daemon (Disk And Execution
MONitor). If a daemon process has a configuration file which is
modified after the process has been started, there should be a way to
tell that process to reread its configuration file without stopping
the process. Many daemons provide this mechanism using a <code class="inline"><span class="w">SIGHUP</span></code>

signal handler. When you want to tell the daemon to reread the file,
simply send it the <code class="inline"><span class="w">SIGHUP</span></code>
 signal.</p>
<p>The following example implements a simple daemon, which restarts
itself every time the <code class="inline"><span class="w">SIGHUP</span></code>
 signal is received. The actual code is
located in the subroutine <code class="inline"><span class="i">code</span><span class="s">(</span><span class="s">)</span></code>
, which just prints some debugging
info to show that it works; it should be replaced with the real code.</p>
<pre class="verbatim"><ol><li>  <span class="c">#!/usr/bin/perl</span></li><li></li><li>  <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li>  <a class="l_k" href="functions/use.html">use</a> <span class="w">warnings</span><span class="sc">;</span></li><li></li><li>  <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>  <a class="l_k" href="functions/use.html">use</a> <span class="w">FindBin</span> <span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>  <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Basename</span> <span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>  <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Spec::Functions</span> <span class="q">qw(catfile)</span><span class="sc">;</span></li><li></li><li>  <span class="i">$|</span> = <span class="n">1</span><span class="sc">;</span></li><li></li><li>  <span class="c"># make the daemon cross-platform, so exec always calls the script</span></li><li>  <span class="c"># itself with the right path, no matter how the script was invoked.</span></li><li>  <a class="l_k" href="functions/my.html">my</a> <span class="i">$script</span> = <span class="i">File::Basename::basename</span><span class="s">(</span><span class="i">$0</span><span class="s">)</span><span class="sc">;</span></li><li>  <a class="l_k" href="functions/my.html">my</a> <span class="i">$SELF</span>  = <span class="i">catfile</span><span class="s">(</span><span class="i">$FindBin::Bin</span><span class="cm">,</span> <span class="i">$script</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>  <span class="c"># POSIX unmasks the sigprocmask properly</span></li><li>  <span class="i">$SIG</span>{<span class="w">HUP</span>} = <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span></li><li>      <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;got SIGHUP\n&quot;</span><span class="sc">;</span></li><li>      <a class="l_k" href="functions/exec.html">exec</a><span class="s">(</span><span class="i">$SELF</span><span class="cm">,</span> <span class="i">@ARGV</span><span class="s">)</span>        || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;$0: couldn&#39;t restart: $!&quot;</span><span class="sc">;</span></li><li>  <span class="s">}</span><span class="sc">;</span></li><li></li><li>  <span class="i">code</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="code"></a>  sub <span class="m">code</span> <span class="s">{</span></li><li>      <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;PID: $$\n&quot;</span><span class="sc">;</span></li><li>      <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;ARGV: @ARGV\n&quot;</span><span class="sc">;</span></li><li>      <a class="l_k" href="functions/my.html">my</a> <span class="i">$count</span> = <span class="n">0</span><span class="sc">;</span></li><li>      <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="n">1</span><span class="s">)</span> <span class="s">{</span></li><li>          <a class="l_k" href="functions/sleep.html">sleep</a> <span class="n">2</span><span class="sc">;</span></li><li>          <a class="l_k" href="functions/print.html">print</a> ++<span class="i">$count</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="sc">;</span></li><li>      <span class="s">}</span></li><li>  <span class="s">}</span></li></ol></pre><a name="Deferred-Signals-(Safe-Signals)"></a><h2>Deferred Signals (Safe Signals)</h2>
<p>Before Perl 5.8.0, installing Perl code to deal with signals exposed you to
danger from two things.  First, few system library functions are
re-entrant.  If the signal interrupts while Perl is executing one function
(like malloc(3) or printf(3)), and your signal handler then calls the same
function again, you could get unpredictable behavior--often, a core dump.
Second, Perl isn't itself re-entrant at the lowest levels.  If the signal
interrupts Perl while Perl is changing its own internal data structures,
similarly unpredictable behavior may result.</p>
<p>There were two things you could do, knowing this: be paranoid or be
pragmatic.  The paranoid approach was to do as little as possible in your
signal handler.  Set an existing integer variable that already has a
value, and return.  This doesn't help you if you're in a slow system call,
which will just restart.  That means you have to <code class="inline"><a class="l_k" href="functions/die.html">die</a></code> to longjmp(3) out
of the handler.  Even this is a little cavalier for the true paranoiac,
who avoids <code class="inline"><a class="l_k" href="functions/die.html">die</a></code> in a handler because the system <i>is</i> out to get you.
The pragmatic approach was to say "I know the risks, but prefer the
convenience", and to do anything you wanted in your signal handler,
and be prepared to clean up core dumps now and again.</p>
<p>Perl 5.8.0 and later avoid these problems by "deferring" signals.  That is,
when the signal is delivered to the process by the system (to the C code
that implements Perl) a flag is set, and the handler returns immediately.
Then at strategic "safe" points in the Perl interpreter (e.g. when it is
about to execute a new opcode) the flags are checked and the Perl level
handler from %SIG is executed. The "deferred" scheme allows much more
flexibility in the coding of signal handlers as we know the Perl
interpreter is in a safe state, and that we are not in a system library
function when the handler is called.  However the implementation does
differ from previous Perls in the following ways:</p>
<ul>
<li><a name="Long-running-opcodes"></a><b>Long-running opcodes</b>
<p>As the Perl interpreter looks at signal flags only when it is about
to execute a new opcode, a signal that arrives during a long-running
opcode (e.g. a regular expression operation on a very large string) will
not be seen until the current opcode completes.</p>
<p>If a signal of any given type fires multiple times during an opcode
(such as from a fine-grained timer), the handler for that signal will
be called only once, after the opcode completes; all other
instances will be discarded.  Furthermore, if your system's signal queue
gets flooded to the point that there are signals that have been raised
but not yet caught (and thus not deferred) at the time an opcode
completes, those signals may well be caught and deferred during
subsequent opcodes, with sometimes surprising results.  For example, you
may see alarms delivered even after calling <code class="inline"><a class="l_k" href="functions/alarm.html">alarm(0)</a></code> as the latter
stops the raising of alarms but does not cancel the delivery of alarms
raised but not yet caught.  Do not depend on the behaviors described in
this paragraph as they are side effects of the current implementation and
may change in future versions of Perl.</p>
</li>
<li><a name="Interrupting-IO"></a><b>Interrupting IO</b>
<p>When a signal is delivered (e.g., SIGINT from a control-C) the operating
system breaks into IO operations like <i>read</i>(2), which is used to
implement Perl's readline() function, the <code class="inline">&lt;&gt;</code>
 operator. On older
Perls the handler was called immediately (and as <code class="inline"><a class="l_k" href="functions/read.html">read</a></code> is not "unsafe",
this worked well). With the "deferred" scheme the handler is <i>not</i> called
immediately, and if Perl is using the system's <code class="inline"><span class="w">stdio</span></code>
 library that
library may restart the <code class="inline"><a class="l_k" href="functions/read.html">read</a></code> without returning to Perl to give it a
chance to call the %SIG handler. If this happens on your system the
solution is to use the <code class="inline"><span class="j">:</span><span class="w">perlio</span></code>
 layer to do IO--at least on those handles
that you want to be able to break into with signals. (The <code class="inline"><span class="j">:</span><span class="w">perlio</span></code>
 layer
checks the signal flags and calls %SIG handlers before resuming IO
operation.)</p>
<p>The default in Perl 5.8.0 and later is to automatically use
the <code class="inline"><span class="j">:</span><span class="w">perlio</span></code>
 layer.</p>
<p>Note that it is not advisable to access a file handle within a signal
handler where that signal has interrupted an I/O operation on that same
handle. While perl will at least try hard not to crash, there are no
guarantees of data integrity; for example, some data might get dropped or
written twice.</p>
<p>Some networking library functions like gethostbyname() are known to have
their own implementations of timeouts which may conflict with your
timeouts.  If you have problems with such functions, try using the POSIX
sigaction() function, which bypasses Perl safe signals.  Be warned that
this does subject you to possible memory corruption, as described above.</p>
<p>Instead of setting <code class="inline"><span class="i">$SIG</span>{<span class="w">ALRM</span>}</code>
:</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/local.html">local</a> <span class="i">$SIG</span>{<span class="w">ALRM</span>} = <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;alarm&quot;</span> <span class="s">}</span><span class="sc">;</span></li></ol></pre><p>try something like the following:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="q">qw(SIGALRM)</span><span class="sc">;</span></li><li> <span class="i">POSIX::sigaction</span><span class="s">(</span><span class="w">SIGALRM</span><span class="cm">,</span></li><li>                  <span class="w">POSIX::SigAction</span><span class="w">-&gt;new</span><span class="s">(</span><a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;alarm&quot;</span> <span class="s">}</span><span class="s">)</span><span class="s">)</span></li><li>          || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;Error setting SIGALRM handler: $!\n&quot;</span><span class="sc">;</span></li></ol></pre><p>Another way to disable the safe signal behavior locally is to use
the <code class="inline"><span class="w">Perl::Unsafe::Signals</span></code>
 module from CPAN, which affects
all signals.</p>
</li>
<li><a name="Restartable-system-calls"></a><b>Restartable system calls</b>
<p>On systems that supported it, older versions of Perl used the
SA_RESTART flag when installing %SIG handlers.  This meant that
restartable system calls would continue rather than returning when
a signal arrived.  In order to deliver deferred signals promptly,
Perl 5.8.0 and later do <i>not</i> use SA_RESTART.  Consequently,
restartable system calls can fail (with $! set to <code class="inline"><span class="w">EINTR</span></code>
) in places
where they previously would have succeeded.</p>
<p>The default <code class="inline"><span class="j">:</span><span class="w">perlio</span></code>
 layer retries <code class="inline"><a class="l_k" href="functions/read.html">read</a></code>, <code class="inline"><a class="l_k" href="functions/write.html">write</a></code>
and <code class="inline"><a class="l_k" href="functions/close.html">close</a></code> as described above; interrupted <code class="inline"><a class="l_k" href="functions/wait.html">wait</a></code> and
<code class="inline"><a class="l_k" href="functions/waitpid.html">waitpid</a></code> calls will always be retried.</p>
</li>
<li><a name="Signals-as-%22faults%22"></a><b>Signals as "faults"</b>
<p>Certain signals like SEGV, ILL, and BUS are generated by virtual memory
addressing errors and similar "faults". These are normally fatal: there is
little a Perl-level handler can do with them.  So Perl delivers them
immediately rather than attempting to defer them.</p>
</li>
<li><a name="Signals-triggered-by-operating-system-state"></a><b>Signals triggered by operating system state</b>
<p>On some operating systems certain signal handlers are supposed to "do
something" before returning. One example can be CHLD or CLD, which
indicates a child process has completed. On some operating systems the
signal handler is expected to <code class="inline"><a class="l_k" href="functions/wait.html">wait</a></code> for the completed child
process. On such systems the deferred signal scheme will not work for
those signals: it does not do the <code class="inline"><a class="l_k" href="functions/wait.html">wait</a></code>. Again the failure will
look like a loop as the operating system will reissue the signal because
there are completed child processes that have not yet been <code class="inline"><a class="l_k" href="functions/wait.html">wait</a></code>ed for.</p>
</li>
</ul>
<p>If you want the old signal behavior back despite possible
memory corruption, set the environment variable <code class="inline"><span class="w">PERL_SIGNALS</span></code>
 to
<code class="inline"><span class="q">&quot;unsafe&quot;</span></code>
.  This feature first appeared in Perl 5.8.1.</p>
<a name="Named-Pipes"></a><h1>Named Pipes</h1>
<p>A named pipe (often referred to as a FIFO) is an old Unix IPC
mechanism for processes communicating on the same machine.  It works
just like regular anonymous pipes, except that the
processes rendezvous using a filename and need not be related.</p>
<p>To create a named pipe, use the <code class="inline"><span class="i">POSIX::mkfifo</span><span class="s">(</span><span class="s">)</span></code>
 function.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="q">qw(mkfifo)</span><span class="sc">;</span></li><li>    <span class="i">mkfifo</span><span class="s">(</span><span class="i">$path</span><span class="cm">,</span> <span class="n">0700</span><span class="s">)</span>     ||  <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;mkfifo $path failed: $!&quot;</span><span class="sc">;</span></li></ol></pre><p>You can also use the Unix command mknod(1), or on some
systems, mkfifo(1).  These may not be in your normal path, though.</p>
<pre class="verbatim"><ol><li>    <span class="c"># system return val is backwards, so &amp;&amp; not ||</span></li><li>    <span class="c">#</span></li><li>    <span class="i">$ENV</span>{<span class="w">PATH</span>} .= <span class="q">&quot;:/etc:/usr/etc&quot;</span><span class="sc">;</span></li><li>    if  <span class="s">(</span>      <a class="l_k" href="functions/system.html">system</a><span class="s">(</span><span class="q">&quot;mknod&quot;</span><span class="cm">,</span>  <span class="i">$path</span><span class="cm">,</span> <span class="q">&quot;p&quot;</span><span class="s">)</span></li><li>            &amp;&amp; <a class="l_k" href="functions/system.html">system</a><span class="s">(</span><span class="q">&quot;mkfifo&quot;</span><span class="cm">,</span> <span class="i">$path</span><span class="s">)</span> <span class="s">)</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;mk{nod,fifo} $path failed&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>A fifo is convenient when you want to connect a process to an unrelated
one.  When you open a fifo, the program will block until there's something
on the other end.</p>
<p>For example, let's say you'd like to have your <i>.signature</i> file be a
named pipe that has a Perl program on the other end.  Now every time any
program (like a mailer, news reader, finger program, etc.) tries to read
from that file, the reading program will read the new signature from your
program.  We'll use the pipe-checking file-test operator, <b>-p</b>, to find
out whether anyone (or anything) has accidentally removed our fifo.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/chdir.html">chdir</a><span class="s">(</span><span class="s">)</span><span class="sc">;</span>    <span class="c"># go home</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$FIFO</span> = <span class="q">&quot;.signature&quot;</span><span class="sc">;</span></li><li></li><li>    while <span class="s">(</span><span class="n">1</span><span class="s">)</span> <span class="s">{</span></li><li>        unless <span class="s">(</span>-p <span class="i">$FIFO</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/unlink.html">unlink</a> <span class="i">$FIFO</span><span class="sc">;</span>   <span class="c"># discard any failure, will catch later</span></li><li>            <a class="l_k" href="functions/require.html">require</a> <span class="w">POSIX</span><span class="sc">;</span>  <span class="c"># delayed loading of heavy module</span></li><li>            <span class="i">POSIX::mkfifo</span><span class="s">(</span><span class="i">$FIFO</span><span class="cm">,</span> <span class="n">0700</span><span class="s">)</span></li><li>                                || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t mkfifo $FIFO: $!&quot;</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li></li><li>        <span class="c"># next line blocks till there&#39;s a reader</span></li><li>        <a class="l_k" href="functions/open.html">open</a> <span class="s">(</span><span class="w">FIFO</span><span class="cm">,</span> <span class="q">&quot;&gt; $FIFO&quot;</span><span class="s">)</span>  || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t open $FIFO: $!&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">FIFO</span> <span class="q">&quot;John Smith (smith\@host.org)\n&quot;</span><span class="cm">,</span> <span class="q">`fortune -s`</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">FIFO</span><span class="s">)</span>             || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t close $FIFO: $!&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/sleep.html">sleep</a> <span class="n">2</span><span class="sc">;</span>                <span class="c"># to avoid dup signals</span></li><li>    <span class="s">}</span></li></ol></pre><a name="Using-open()-for-IPC"></a><h1>Using open() for IPC</h1>
<p>Perl's basic open() statement can also be used for unidirectional
interprocess communication by either appending or prepending a pipe
symbol to the second argument to open().  Here's how to start
something up in a child process you intend to write to:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">SPOOLER</span><span class="cm">,</span> <span class="q">&quot;| cat -v | lpr -h 2&gt;/dev/null&quot;</span><span class="s">)</span></li><li>                        || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t fork: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/local.html">local</a> <span class="i">$SIG</span>{<span class="w">PIPE</span>} = <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;spooler pipe broke&quot;</span> <span class="s">}</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="i">SPOOLER</span> <span class="q">&quot;stuff\n&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/close.html">close</a> <span class="w">SPOOLER</span>       || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;bad spool: $! $?&quot;</span><span class="sc">;</span></li></ol></pre><p>And here's how to start up a child process you intend to read from:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">STATUS</span><span class="cm">,</span> <span class="q">&quot;netstat -an 2&gt;&amp;1 |&quot;</span><span class="s">)</span></li><li>                        || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t fork: $!&quot;</span><span class="sc">;</span></li><li>    while <span class="s">(</span><span class="q">&lt;STATUS&gt;</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/next.html">next</a> if <span class="q">/^(tcp|udp)/</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/print.html">print</a><span class="sc">;</span></li><li>    <span class="s">}</span></li><li>    <a class="l_k" href="functions/close.html">close</a> <span class="w">STATUS</span>        || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;bad netstat: $! $?&quot;</span><span class="sc">;</span></li></ol></pre><p>If one can be sure that a particular program is a Perl script expecting
filenames in @ARGV, the clever programmer can write something like this:</p>
<pre class="verbatim"><ol><li>    % program f1 "cmd1|" - f2 "cmd2|" f3 &lt; tmpfile</li></ol></pre><p>and no matter which sort of shell it's called from, the Perl program will
read from the file <i>f1</i>, the process <i>cmd1</i>, standard input (<i>tmpfile</i>
in this case), the <i>f2</i> file, the <i>cmd2</i> command, and finally the <i>f3</i>
file.  Pretty nifty, eh?</p>
<p>You might notice that you could use backticks for much the
same effect as opening a pipe for reading:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/grep.html">grep</a> <span class="s">{</span> !<span class="q">/^(tcp|udp)/</span> <span class="s">}</span> <span class="q">`netstat -an 2&gt;&amp;1`</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;bad netstatus ($?)&quot;</span> if <span class="i">$?</span><span class="sc">;</span></li></ol></pre><p>While this is true on the surface, it's much more efficient to process the
file one line or record at a time because then you don't have to read the
whole thing into memory at once.  It also gives you finer control of the
whole process, letting you kill off the child process early if you'd like.</p>
<p>Be careful to check the return values from both open() and close().  If
you're <i>writing</i> to a pipe, you should also trap SIGPIPE.  Otherwise,
think of what happens when you start up a pipe to a command that doesn't
exist: the open() will in all likelihood succeed (it only reflects the
fork()'s success), but then your output will fail--spectacularly.  Perl
can't know whether the command worked, because your command is actually
running in a separate process whose exec() might have failed.  Therefore,
while readers of bogus commands return just a quick EOF, writers
to bogus commands will get hit with a signal, which they'd best be prepared
to handle.  Consider:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">&quot;|bogus&quot;</span><span class="s">)</span>      || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t fork: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="i">FH</span> <span class="q">&quot;bang\n&quot;</span><span class="sc">;</span>      <span class="c">#  neither necessary nor sufficient</span></li><li>                            <span class="c">#  to check print retval!</span></li><li>    <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">FH</span><span class="s">)</span>               || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t close: $!&quot;</span><span class="sc">;</span></li></ol></pre><p>The reason for not checking the return value from print() is because of
pipe buffering; physical writes are delayed.  That won't blow up until the
close, and it will blow up with a SIGPIPE.  To catch it, you could use
this:</p>
<pre class="verbatim"><ol><li>    <span class="i">$SIG</span>{<span class="w">PIPE</span>} = <span class="q">&quot;IGNORE&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">&quot;|bogus&quot;</span><span class="s">)</span>  || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t fork: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="i">FH</span> <span class="q">&quot;bang\n&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">FH</span><span class="s">)</span>           || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t close: status=$?&quot;</span><span class="sc">;</span></li></ol></pre><a name="Filehandles"></a><h2>Filehandles</h2>
<p>Both the main process and any child processes it forks share the same
STDIN, STDOUT, and STDERR filehandles.  If both processes try to access
them at once, strange things can happen.  You may also want to close
or reopen the filehandles for the child.  You can get around this by
opening your pipe with open(), but on some systems this means that the
child process cannot outlive the parent.</p>
<a name="Background-Processes"></a><h2>Background Processes</h2>
<p>You can run a command in the background with:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/system.html">system</a><span class="s">(</span><span class="q">&quot;cmd &amp;&quot;</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The command's STDOUT and STDERR (and possibly STDIN, depending on your
shell) will be the same as the parent's.  You won't need to catch
SIGCHLD because of the double-fork taking place; see below for details.</p>
<a name="Complete-Dissociation-of-Child-from-Parent"></a><h2>Complete Dissociation of Child from Parent</h2>
<p>In some cases (starting server processes, for instance) you'll want to
completely dissociate the child process from the parent.  This is
often called daemonization.  A well-behaved daemon will also chdir()
to the root directory so it doesn't prevent unmounting the filesystem
containing the directory from which it was launched, and redirect its
standard file descriptors from and to <i>/dev/null</i> so that random
output doesn't wind up on the user's terminal.</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="q">&quot;setsid&quot;</span><span class="sc">;</span></li><li></li><li><a name="daemonize"></a> sub <span class="m">daemonize</span> <span class="s">{</span></li><li>     <a class="l_k" href="functions/chdir.html">chdir</a><span class="s">(</span><span class="q">&quot;/&quot;</span><span class="s">)</span>                  || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t chdir to /: $!&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">STDIN</span><span class="cm">,</span>  <span class="q">&quot;&lt; /dev/null&quot;</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t read /dev/null: $!&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">STDOUT</span><span class="cm">,</span> <span class="q">&quot;&gt; /dev/null&quot;</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t write to /dev/null: $!&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$pid</span> = <a class="l_k" href="functions/fork.html">fork</a><span class="s">(</span><span class="s">)</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t fork: $!&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/exit.html">exit</a> <a class="l_k" href="functions/if.html">if</a> <span class="i">$pid</span><span class="sc">;</span>               <span class="c"># non-zero now means I am the parent</span></li><li>     <span class="s">(</span><span class="i">setsid</span><span class="s">(</span><span class="s">)</span> != <span class="n">-1</span><span class="s">)</span>            || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;Can&#39;t start a new session: $!&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">STDERR</span><span class="cm">,</span> <span class="q">&quot;&gt;&amp;STDOUT&quot;</span><span class="s">)</span>    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t dup stdout: $!&quot;</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>The fork() has to come before the setsid() to ensure you aren't a
process group leader; the setsid() will fail if you are.  If your
system doesn't have the setsid() function, open <i>/dev/tty</i> and use the
<code class="inline"><span class="w">TIOCNOTTY</span></code>
 ioctl() on it instead.  See tty(4) for details.</p>
<p>Non-Unix users should check their <code class="inline"><i>Your_OS</i>::Process</code> module for
other possible solutions.</p>
<a name="Safe-Pipe-Opens"></a><h2>Safe Pipe Opens</h2>
<p>Another interesting approach to IPC is making your single program go
multiprocess and communicate between--or even amongst--yourselves.  The
open() function will accept a file argument of either <code class="inline"><span class="q">&quot;-|&quot;</span></code>
 or <code class="inline"><span class="q">&quot;|-&quot;</span></code>

to do a very interesting thing: it forks a child connected to the
filehandle you've opened.  The child is running the same program as the
parent.  This is useful for safely opening a file when running under an
assumed UID or GID, for example.  If you open a pipe <i>to</i> minus, you can
write to the filehandle you opened and your kid will find it in <i>his</i>
STDIN.  If you open a pipe <i>from</i> minus, you can read from the filehandle
you opened whatever your kid writes to <i>his</i> STDOUT.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">English</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$PRECIOUS</span> = <span class="q">&quot;/path/to/some/safe/file&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$sleep_count</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$pid</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/do.html">do</a> <span class="s">{</span></li><li>        <span class="i">$pid</span> = <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">KID_TO_WRITE</span><span class="cm">,</span> <span class="q">&quot;|-&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/unless.html">unless</a> <span class="s">(</span><a class="l_k" href="functions/defined.html">defined</a> <span class="i">$pid</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/warn.html">warn</a> <span class="q">&quot;cannot fork: $!&quot;</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;bailing out&quot;</span> <a class="l_k" href="functions/if.html">if</a> <span class="i">$sleep_count</span>++ &gt; <span class="n">6</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/sleep.html">sleep</a> <span class="n">10</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span> <a class="l_k" href="functions/until.html">until</a> <a class="l_k" href="functions/defined.html">defined</a> <span class="i">$pid</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$pid</span><span class="s">)</span> <span class="s">{</span>                 <span class="c"># I am the parent</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">KID_TO_WRITE</span> <span class="i">@some_data</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">KID_TO_WRITE</span><span class="s">)</span>     || <a class="l_k" href="functions/warn.html">warn</a> <span class="q">&quot;kid exited $?&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span> <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span>                    <span class="c"># I am the child</span></li><li>        <span class="c"># drop permissions in setuid and/or setgid programs:</span></li><li>        <span class="s">(</span><span class="i">$EUID</span><span class="cm">,</span> <span class="i">$EGID</span><span class="s">)</span> = <span class="s">(</span><span class="i">$UID</span><span class="cm">,</span> <span class="i">$GID</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/open.html">open</a> <span class="s">(</span><span class="w">OUTFILE</span><span class="cm">,</span> <span class="q">&quot;&gt; $PRECIOUS&quot;</span><span class="s">)</span></li><li>                                || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t open $PRECIOUS: $!&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="q">&lt;STDIN&gt;</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/print.html">print</a> <span class="i">OUTFILE</span><span class="sc">;</span>      <span class="c"># child&#39;s STDIN is parent&#39;s KID_TO_WRITE</span></li><li>        <span class="s">}</span></li><li>        <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">OUTFILE</span><span class="s">)</span>          || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t close $PRECIOUS: $!&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span>                <span class="c"># don&#39;t forget this!!</span></li><li>    <span class="s">}</span></li></ol></pre><p>Another common use for this construct is when you need to execute
something without the shell's interference.  With system(), it's
straightforward, but you can't use a pipe open or backticks safely.
That's because there's no way to stop the shell from getting its hands on
your arguments.   Instead, use lower-level control to call exec() directly.</p>
<p>Here's a safe backtick or pipe open for read:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$pid</span> = <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">KID_TO_READ</span><span class="cm">,</span> <span class="q">&quot;-|&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$pid</span><span class="s">)</span>           || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t fork: $!&quot;</span><span class="sc">;</span></li><li></li><li>    if <span class="s">(</span><span class="i">$pid</span><span class="s">)</span> <span class="s">{</span>             <span class="c"># parent</span></li><li>        while <span class="s">(</span><span class="q">&lt;KID_TO_READ&gt;</span><span class="s">)</span> <span class="s">{</span></li><li>                            <span class="c"># do something interesting</span></li><li>        <span class="s">}</span></li><li>        <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">KID_TO_READ</span><span class="s">)</span>  || <a class="l_k" href="functions/warn.html">warn</a> <span class="q">&quot;kid exited $?&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="s">}</span> else <span class="s">{</span>                <span class="c"># child</span></li><li>        <span class="s">(</span><span class="i">$EUID</span><span class="cm">,</span> <span class="i">$EGID</span><span class="s">)</span> = <span class="s">(</span><span class="i">$UID</span><span class="cm">,</span> <span class="i">$GID</span><span class="s">)</span><span class="sc">;</span> <span class="c"># suid only</span></li><li>        <a class="l_k" href="functions/exec.html">exec</a><span class="s">(</span><span class="i">$program</span><span class="cm">,</span> <span class="i">@options</span><span class="cm">,</span> <span class="i">@args</span><span class="s">)</span></li><li>                            || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t exec program: $!&quot;</span><span class="sc">;</span></li><li>        <span class="c"># NOTREACHED</span></li><li>    <span class="s">}</span></li></ol></pre><p>And here's a safe pipe open for writing:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$pid</span> = <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">KID_TO_WRITE</span><span class="cm">,</span> <span class="q">&quot;|-&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$pid</span><span class="s">)</span>           || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t fork: $!&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="i">$SIG</span>{<span class="w">PIPE</span>} = <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;whoops, $program pipe broke&quot;</span> <span class="s">}</span><span class="sc">;</span></li><li></li><li>    if <span class="s">(</span><span class="i">$pid</span><span class="s">)</span> <span class="s">{</span>             <span class="c"># parent</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">KID_TO_WRITE</span> <span class="i">@data</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">KID_TO_WRITE</span><span class="s">)</span> || <a class="l_k" href="functions/warn.html">warn</a> <span class="q">&quot;kid exited $?&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="s">}</span> else <span class="s">{</span>                <span class="c"># child</span></li><li>        <span class="s">(</span><span class="i">$EUID</span><span class="cm">,</span> <span class="i">$EGID</span><span class="s">)</span> = <span class="s">(</span><span class="i">$UID</span><span class="cm">,</span> <span class="i">$GID</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/exec.html">exec</a><span class="s">(</span><span class="i">$program</span><span class="cm">,</span> <span class="i">@options</span><span class="cm">,</span> <span class="i">@args</span><span class="s">)</span></li><li>                            || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t exec program: $!&quot;</span><span class="sc">;</span></li><li>        <span class="c"># NOTREACHED</span></li><li>    <span class="s">}</span></li></ol></pre><p>It is very easy to dead-lock a process using this form of open(), or
indeed with any use of pipe() with multiple subprocesses.  The
example above is "safe" because it is simple and calls exec().  See
<a href="#Avoiding-Pipe-Deadlocks">Avoiding Pipe Deadlocks</a> for general safety principles, but there
are extra gotchas with Safe Pipe Opens.</p>
<p>In particular, if you opened the pipe using <code class="inline"><a class="l_k" href="functions/open.html">open</a> <span class="w">FH</span><span class="cm">,</span> <span class="q">&quot;|-&quot;</span></code>
, then you
cannot simply use close() in the parent process to close an unwanted
writer.  Consider this code:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$pid</span> = <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">WRITER</span><span class="cm">,</span> <span class="q">&quot;|-&quot;</span><span class="s">)</span><span class="sc">;</span>        <span class="c"># fork open a kid</span></li><li>    <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$pid</span><span class="s">)</span>               || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;first fork failed: $!&quot;</span><span class="sc">;</span></li><li>    if <span class="s">(</span><span class="i">$pid</span><span class="s">)</span> <span class="s">{</span></li><li>        if <span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$sub_pid</span> = <a class="l_k" href="functions/fork.html">fork</a><span class="s">(</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$sub_pid</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;second fork failed: $!&quot;</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">WRITER</span><span class="s">)</span>       || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;couldn&#39;t close WRITER: $!&quot;</span><span class="sc">;</span></li><li>            <span class="c"># now do something else...</span></li><li>        <span class="s">}</span></li><li>        else <span class="s">{</span></li><li>            <span class="c"># first write to WRITER</span></li><li>            <span class="c"># ...</span></li><li>            <span class="c"># then when finished</span></li><li>            <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">WRITER</span><span class="s">)</span>       || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;couldn&#39;t close WRITER: $!&quot;</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li><li>    else <span class="s">{</span></li><li>        <span class="c"># first do something with STDIN, then</span></li><li>        <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>In the example above, the true parent does not want to write to the WRITER
filehandle, so it closes it.  However, because WRITER was opened using
<code class="inline"><a class="l_k" href="functions/open.html">open</a> <span class="w">FH</span><span class="cm">,</span> <span class="q">&quot;|-&quot;</span></code>
, it has a special behavior: closing it calls
waitpid() (see <a href="functions/waitpid.html">waitpid</a>), which waits for the subprocess
to exit.  If the child process ends up waiting for something happening
in the section marked "do something else", you have deadlock.</p>
<p>This can also be a problem with intermediate subprocesses in more
complicated code, which will call waitpid() on all open filehandles
during global destruction--in no predictable order.</p>
<p>To solve this, you must manually use pipe(), fork(), and the form of
open() which sets one file descriptor to another, as shown below:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/pipe.html">pipe</a><span class="s">(</span><span class="w">READER</span><span class="cm">,</span> <span class="w">WRITER</span><span class="s">)</span>        || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;pipe failed: $!&quot;</span><span class="sc">;</span></li><li>    <span class="i">$pid</span> = <a class="l_k" href="functions/fork.html">fork</a><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$pid</span><span class="s">)</span>               || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;first fork failed: $!&quot;</span><span class="sc">;</span></li><li>    if <span class="s">(</span><span class="i">$pid</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/close.html">close</a> <span class="w">READER</span><span class="sc">;</span></li><li>        if <span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$sub_pid</span> = <a class="l_k" href="functions/fork.html">fork</a><span class="s">(</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$sub_pid</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;first fork failed: $!&quot;</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">WRITER</span><span class="s">)</span>       || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t close WRITER: $!&quot;</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>        else <span class="s">{</span></li><li>            <span class="c"># write to WRITER...</span></li><li>            <span class="c"># ...</span></li><li>            <span class="c"># then  when finished</span></li><li>            <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">WRITER</span><span class="s">)</span>       || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t close WRITER: $!&quot;</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>        <span class="c"># write to WRITER...</span></li><li>    <span class="s">}</span></li><li>    else <span class="s">{</span></li><li>        <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">STDIN</span><span class="cm">,</span> <span class="q">&quot;&lt;&amp;READER&quot;</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t reopen STDIN: $!&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">WRITER</span><span class="s">)</span>           || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t close WRITER: $!&quot;</span><span class="sc">;</span></li><li>        <span class="c"># do something...</span></li><li>        <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Since Perl 5.8.0, you can also use the list form of <code class="inline"><a class="l_k" href="functions/open.html">open</a></code> for pipes.
This is preferred when you wish to avoid having the shell interpret
metacharacters that may be in your command string.</p>
<p>So for example, instead of using:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">PS_PIPE</span><span class="cm">,</span> <span class="q">&quot;ps aux|&quot;</span><span class="s">)</span>    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t open ps pipe: $!&quot;</span><span class="sc">;</span></li></ol></pre><p>One would use either of these:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">PS_PIPE</span><span class="cm">,</span> <span class="q">&quot;-|&quot;</span><span class="cm">,</span> <span class="q">&quot;ps&quot;</span><span class="cm">,</span> <span class="q">&quot;aux&quot;</span><span class="s">)</span></li><li>                                || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t open ps pipe: $!&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="i">@ps_args</span> = <span class="q">qw[ ps aux ]</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">PS_PIPE</span><span class="cm">,</span> <span class="q">&quot;-|&quot;</span><span class="cm">,</span> <span class="i">@ps_args</span><span class="s">)</span></li><li>                                || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t open @ps_args|: $!&quot;</span><span class="sc">;</span></li></ol></pre><p>Because there are more than three arguments to open(), forks the ps(1)
command <i>without</i> spawning a shell, and reads its standard output via the
<code class="inline"><span class="w">PS_PIPE</span></code>
 filehandle.  The corresponding syntax to <i>write</i> to command
pipes is to use <code class="inline"><span class="q">&quot;|-&quot;</span></code>
 in place of <code class="inline"><span class="q">&quot;-|&quot;</span></code>
.</p>
<p>This was admittedly a rather silly example, because you're using string
literals whose content is perfectly safe.  There is therefore no cause to
resort to the harder-to-read, multi-argument form of pipe open().  However,
whenever you cannot be assured that the program arguments are free of shell
metacharacters, the fancier form of open() should be used.  For example:</p>
<pre class="verbatim"><ol><li>    <span class="i">@grep_args</span> = <span class="s">(</span><span class="q">&quot;egrep&quot;</span><span class="cm">,</span> <span class="q">&quot;-i&quot;</span><span class="cm">,</span> <span class="i">$some_pattern</span><span class="cm">,</span> <span class="i">@many_files</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">GREP_PIPE</span><span class="cm">,</span> <span class="q">&quot;-|&quot;</span><span class="cm">,</span> <span class="i">@grep_args</span><span class="s">)</span></li><li>                        || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t open @grep_args|: $!&quot;</span><span class="sc">;</span></li></ol></pre><p>Here the multi-argument form of pipe open() is preferred because the
pattern and indeed even the filenames themselves might hold metacharacters.</p>
<p>Be aware that these operations are full Unix forks, which means they may
not be correctly implemented on all alien systems.</p>
<a name="Avoiding-Pipe-Deadlocks"></a><h2>Avoiding Pipe Deadlocks</h2>
<p>Whenever you have more than one subprocess, you must be careful that each
closes whichever half of any pipes created for interprocess communication
it is not using.  This is because any child process reading from the pipe
and expecting an EOF will never receive it, and therefore never exit. A
single process closing a pipe is not enough to close it; the last process
with the pipe open must close it for it to read EOF.</p>
<p>Certain built-in Unix features help prevent this most of the time.  For
instance, filehandles have a "close on exec" flag, which is set <i>en masse</i>
under control of the <code class="inline"><span class="i">$^F</span></code>
 variable.  This is so any filehandles you
didn't explicitly route to the STDIN, STDOUT or STDERR of a child
<i>program</i> will be automatically closed.</p>
<p>Always explicitly and immediately call close() on the writable end of any
pipe, unless that process is actually writing to it.  Even if you don't
explicitly call close(), Perl will still close() all filehandles during
global destruction.  As previously discussed, if those filehandles have
been opened with Safe Pipe Open, this will result in calling waitpid(),
which may again deadlock.</p>
<a name="Bidirectional-Communication-with-Another-Process"></a><h2>Bidirectional Communication with Another Process</h2>
<p>While this works reasonably well for unidirectional communication, what
about bidirectional communication?  The most obvious approach doesn't work:</p>
<pre class="verbatim"><ol><li>    <span class="c"># THIS DOES NOT WORK!!</span></li><li>    <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">PROG_FOR_READING_AND_WRITING</span><span class="cm">,</span> <span class="q">&quot;| some program |&quot;</span><span class="s">)</span></li></ol></pre><p>If you forget to <code class="inline"><a class="l_k" href="functions/use.html">use</a> <span class="w">warnings</span></code>
, you'll miss out entirely on the
helpful diagnostic message:</p>
<pre class="verbatim"><ol><li>    <span class="w">Can&#39;t</span> <a class="l_k" href="functions/do.html">do</a> <span class="w">bidirectional</span> <a class="l_k" href="functions/pipe.html">pipe</a> <span class="w">at</span> -e <span class="w">line</span> <span class="n">1.</span></li></ol></pre><p>If you really want to, you can use the standard open2() from the
<code class="inline"><span class="w">IPC::Open2</span></code>
 module to catch both ends.  There's also an open3() in
<code class="inline"><span class="w">IPC::Open3</span></code>
 for tridirectional I/O so you can also catch your child's
STDERR, but doing so would then require an awkward select() loop and
wouldn't allow you to use normal Perl input operations.</p>
<p>If you look at its source, you'll see that open2() uses low-level
primitives like the pipe() and exec() syscalls to create all the
connections.  Although it might have been more efficient by using
socketpair(), this would have been even less portable than it already
is. The open2() and open3() functions are unlikely to work anywhere
except on a Unix system, or at least one purporting POSIX compliance.</p>
<p>Here's an example of using open2():</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">FileHandle</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">IPC::Open2</span><span class="sc">;</span></li><li>    <span class="i">$pid</span> = <span class="i">open2</span><span class="s">(</span><span class="i">*Reader</span><span class="cm">,</span> <span class="i">*Writer</span><span class="cm">,</span> <span class="q">&quot;cat -un&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="i">Writer</span> <span class="q">&quot;stuff\n&quot;</span><span class="sc">;</span></li><li>    <span class="i">$got</span> = <span class="q">&lt;Reader&gt;</span><span class="sc">;</span></li></ol></pre><p>The problem with this is that buffering is really going to ruin your
day.  Even though your <code class="inline"><span class="w">Writer</span></code>
 filehandle is auto-flushed so the process
on the other end gets your data in a timely manner, you can't usually do
anything to force that process to give its data to you in a similarly quick
fashion.  In this special case, we could actually so, because we gave
<i>cat</i> a <b>-u</b> flag to make it unbuffered.  But very few commands are
designed to operate over pipes, so this seldom works unless you yourself
wrote the program on the other end of the double-ended pipe.</p>
<p>A solution to this is to use a library which uses pseudottys to make your
program behave more reasonably.  This way you don't have to have control
over the source code of the program you're using.  The <code class="inline"><span class="w">Expect</span></code>
 module
from CPAN also addresses this kind of thing.  This module requires two
other modules from CPAN, <code class="inline"><span class="w">IO::Pty</span></code>
 and <code class="inline"><span class="w">IO::Stty</span></code>
.  It sets up a pseudo
terminal to interact with programs that insist on talking to the terminal
device driver.  If your system is supported, this may be your best bet.</p>
<a name="Bidirectional-Communication-with-Yourself"></a><h2>Bidirectional Communication with Yourself</h2>
<p>If you want, you may make low-level pipe() and fork() syscalls to stitch
this together by hand.  This example only talks to itself, but you could
reopen the appropriate handles to STDIN and STDOUT and call other processes.
(The following example lacks proper error checking.)</p>
<pre class="verbatim"><ol><li> <span class="c">#!/usr/bin/perl -w</span></li><li> <span class="c"># pipe1 - bidirectional communication using two pipe pairs</span></li><li> <span class="c">#         designed for the socketpair-challenged</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">IO::Handle</span><span class="sc">;</span>             <span class="c"># thousands of lines just for autoflush :-(</span></li><li> <a class="l_k" href="functions/pipe.html">pipe</a><span class="s">(</span><span class="w">PARENT_RDR</span><span class="cm">,</span> <span class="w">CHILD_WTR</span><span class="s">)</span><span class="sc">;</span>  <span class="c"># XXX: check failure?</span></li><li> <a class="l_k" href="functions/pipe.html">pipe</a><span class="s">(</span><span class="w">CHILD_RDR</span><span class="cm">,</span>  <span class="w">PARENT_WTR</span><span class="s">)</span><span class="sc">;</span> <span class="c"># XXX: check failure?</span></li><li> <span class="w">CHILD_WTR</span><span class="w">-&gt;autoflush</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="w">PARENT_WTR</span><span class="w">-&gt;autoflush</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$pid</span> = <a class="l_k" href="functions/fork.html">fork</a><span class="s">(</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">PARENT_RDR</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">PARENT_WTR</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/print.html">print</a> <span class="i">CHILD_WTR</span> <span class="q">&quot;Parent Pid $$ is sending this\n&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/chomp.html">chomp</a><span class="s">(</span><span class="i">$line</span> = <span class="q">&lt;CHILD_RDR&gt;</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Parent Pid $$ just read this: &#39;$line&#39;\n&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">CHILD_RDR</span><span class="sc">;</span> <a class="l_k" href="functions/close.html">close</a> <span class="w">CHILD_WTR</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/waitpid.html">waitpid</a><span class="s">(</span><span class="i">$pid</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span> <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span></li><li>     <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;cannot fork: $!&quot;</span> <a class="l_k" href="functions/unless.html">unless</a> <a class="l_k" href="functions/defined.html">defined</a> <span class="i">$pid</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">CHILD_RDR</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">CHILD_WTR</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/chomp.html">chomp</a><span class="s">(</span><span class="i">$line</span> = <span class="q">&lt;PARENT_RDR&gt;</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Child Pid $$ just read this: &#39;$line&#39;\n&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/print.html">print</a> <span class="i">PARENT_WTR</span> <span class="q">&quot;Child Pid $$ is sending this\n&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">PARENT_RDR</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">PARENT_WTR</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>But you don't actually have to make two pipe calls.  If you
have the socketpair() system call, it will do this all for you.</p>
<pre class="verbatim"><ol><li> <span class="c">#!/usr/bin/perl -w</span></li><li> <span class="c"># pipe2 - bidirectional communication using socketpair</span></li><li> <span class="c">#   &quot;the best ones always go both ways&quot;</span></li><li></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Socket</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">IO::Handle</span><span class="sc">;</span>  <span class="c"># thousands of lines just for autoflush :-(</span></li><li></li><li> <span class="c"># We say AF_UNIX because although *_LOCAL is the</span></li><li> <span class="c"># POSIX 1003.1g form of the constant, many machines</span></li><li> <span class="c"># still don&#39;t have it.</span></li><li> <a class="l_k" href="functions/socketpair.html">socketpair</a><span class="s">(</span><span class="w">CHILD</span><span class="cm">,</span> <span class="w">PARENT</span><span class="cm">,</span> <span class="w">AF_UNIX</span><span class="cm">,</span> <span class="w">SOCK_STREAM</span><span class="cm">,</span> <span class="w">PF_UNSPEC</span><span class="s">)</span></li><li>                             ||  <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;socketpair: $!&quot;</span><span class="sc">;</span></li><li></li><li> <span class="w">CHILD</span><span class="w">-&gt;autoflush</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="w">PARENT</span><span class="w">-&gt;autoflush</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$pid</span> = <a class="l_k" href="functions/fork.html">fork</a><span class="s">(</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">PARENT</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/print.html">print</a> <span class="i">CHILD</span> <span class="q">&quot;Parent Pid $$ is sending this\n&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/chomp.html">chomp</a><span class="s">(</span><span class="i">$line</span> = <span class="q">&lt;CHILD&gt;</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Parent Pid $$ just read this: &#39;$line&#39;\n&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">CHILD</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/waitpid.html">waitpid</a><span class="s">(</span><span class="i">$pid</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span> <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span></li><li>     <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;cannot fork: $!&quot;</span> <a class="l_k" href="functions/unless.html">unless</a> <a class="l_k" href="functions/defined.html">defined</a> <span class="i">$pid</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">CHILD</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/chomp.html">chomp</a><span class="s">(</span><span class="i">$line</span> = <span class="q">&lt;PARENT&gt;</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Child Pid $$ just read this: &#39;$line&#39;\n&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/print.html">print</a> <span class="i">PARENT</span> <span class="q">&quot;Child Pid $$ is sending this\n&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">PARENT</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><a name="Sockets%3a-Client%2fServer-Communication"></a><h1>Sockets: Client/Server Communication</h1>
<p>While not entirely limited to Unix-derived operating systems (e.g., WinSock
on PCs provides socket support, as do some VMS libraries), you might not have
sockets on your system, in which case this section probably isn't going to
do you much good.  With sockets, you can do both virtual circuits like TCP
streams and datagrams like UDP packets.  You may be able to do even more
depending on your system.</p>
<p>The Perl functions for dealing with sockets have the same names as
the corresponding system calls in C, but their arguments tend to differ
for two reasons.  First, Perl filehandles work differently than C file
descriptors.  Second, Perl already knows the length of its strings, so you
don't need to pass that information.</p>
<p>One of the major problems with ancient, antemillennial socket code in Perl
was that it used hard-coded values for some of the constants, which
severely hurt portability.  If you ever see code that does anything like
explicitly setting <code class="inline"><span class="i">$AF_INET</span> = <span class="n">2</span></code>
, you know you're in for big trouble.
An immeasurably superior approach is to use the <code class="inline"><span class="w">Socket</span></code>
 module, which more
reliably grants access to the various constants and functions you'll need.</p>
<p>If you're not writing a server/client for an existing protocol like
NNTP or SMTP, you should give some thought to how your server will
know when the client has finished talking, and vice-versa.  Most
protocols are based on one-line messages and responses (so one party
knows the other has finished when a "\n" is received) or multi-line
messages and responses that end with a period on an empty line
("\n.\n" terminates a message/response).</p>
<a name="Internet-Line-Terminators"></a><h2>Internet Line Terminators</h2>
<p>The Internet line terminator is "\015\012".  Under ASCII variants of
Unix, that could usually be written as "\r\n", but under other systems,
"\r\n" might at times be "\015\015\012", "\012\012\015", or something
completely different.  The standards specify writing "\015\012" to be
conformant (be strict in what you provide), but they also recommend
accepting a lone "\012" on input (be lenient in what you require).
We haven't always been very good about that in the code in this manpage,
but unless you're on a Mac from way back in its pre-Unix dark ages, you'll
probably be ok.</p>
<a name="Internet-TCP-Clients-and-Servers"></a><h2>Internet TCP Clients and Servers</h2>
<p>Use Internet-domain sockets when you want to do client-server
communication that might extend to machines outside of your own system.</p>
<p>Here's a sample TCP client using Internet-domain sockets:</p>
<pre class="verbatim"><ol><li>    <span class="c">#!/usr/bin/perl -w</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Socket</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$remote</span><span class="cm">,</span> <span class="i">$port</span><span class="cm">,</span> <span class="i">$iaddr</span><span class="cm">,</span> <span class="i">$paddr</span><span class="cm">,</span> <span class="i">$proto</span><span class="cm">,</span> <span class="i">$line</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="i">$remote</span>  = <a class="l_k" href="functions/shift.html">shift</a> || <span class="q">&quot;localhost&quot;</span><span class="sc">;</span></li><li>    <span class="i">$port</span>    = <a class="l_k" href="functions/shift.html">shift</a> || <span class="n">2345</span><span class="sc">;</span>  <span class="c"># random port</span></li><li>    if <span class="s">(</span><span class="i">$port</span> =~ <span class="q">/\D/</span><span class="s">)</span> <span class="s">{</span> <span class="i">$port</span> = <a class="l_k" href="functions/getservbyname.html">getservbyname</a><span class="s">(</span><span class="i">$port</span><span class="cm">,</span> <span class="q">&quot;tcp&quot;</span><span class="s">)</span> <span class="s">}</span></li><li>    <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;No port&quot;</span> unless <span class="i">$port</span><span class="sc">;</span></li><li>    <span class="i">$iaddr</span>   = <span class="i">inet_aton</span><span class="s">(</span><span class="i">$remote</span><span class="s">)</span>       || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;no host: $remote&quot;</span><span class="sc">;</span></li><li>    <span class="i">$paddr</span>   = <span class="i">sockaddr_in</span><span class="s">(</span><span class="i">$port</span><span class="cm">,</span> <span class="i">$iaddr</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="i">$proto</span>   = <a class="l_k" href="functions/getprotobyname.html">getprotobyname</a><span class="s">(</span><span class="q">&quot;tcp&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/socket.html">socket</a><span class="s">(</span><span class="w">SOCK</span><span class="cm">,</span> <span class="w">PF_INET</span><span class="cm">,</span> <span class="w">SOCK_STREAM</span><span class="cm">,</span> <span class="i">$proto</span><span class="s">)</span>  || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;socket: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/connect.html">connect</a><span class="s">(</span><span class="w">SOCK</span><span class="cm">,</span> <span class="i">$paddr</span><span class="s">)</span>               || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;connect: $!&quot;</span><span class="sc">;</span></li><li>    while <span class="s">(</span><span class="i">$line</span> = <span class="q">&lt;SOCK&gt;</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">$line</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/close.html">close</a> <span class="s">(</span><span class="w">SOCK</span><span class="s">)</span>                        || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;close: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>And here's a corresponding server to go along with it.  We'll
leave the address as <code class="inline"><span class="w">INADDR_ANY</span></code>
 so that the kernel can choose
the appropriate interface on multihomed hosts.  If you want sit
on a particular interface (like the external side of a gateway
or firewall machine), fill this in with your real address instead.</p>
<pre class="verbatim"><ol><li> <span class="c">#!/usr/bin/perl -Tw</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/BEGIN.html">BEGIN</a> <span class="s">{</span> <span class="i">$ENV</span>{<span class="w">PATH</span>} = <span class="q">&quot;/usr/bin:/bin&quot;</span> <span class="s">}</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Socket</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Carp</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$EOL</span> = <span class="q">&quot;\015\012&quot;</span><span class="sc">;</span></li><li></li><li><a name="logmsg"></a> sub <span class="m">logmsg</span> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$0 $$: @_ at &quot;</span><span class="cm">,</span> <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span> <span class="s">}</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$port</span>  = <a class="l_k" href="functions/shift.html">shift</a> || <span class="n">2345</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;invalid port&quot;</span> <a class="l_k" href="functions/unless.html">unless</a> <span class="i">$port</span> =~ <span class="q">/^ \d+ $/x</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$proto</span> = <a class="l_k" href="functions/getprotobyname.html">getprotobyname</a><span class="s">(</span><span class="q">&quot;tcp&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/socket.html">socket</a><span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="w">PF_INET</span><span class="cm">,</span> <span class="w">SOCK_STREAM</span><span class="cm">,</span> <span class="i">$proto</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;socket: $!&quot;</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/setsockopt.html">setsockopt</a><span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="w">SOL_SOCKET</span><span class="cm">,</span> <span class="w">SO_REUSEADDR</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;l&quot;</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="s">)</span></li><li>                                                || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;setsockopt: $!&quot;</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/bind.html">bind</a><span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="i">sockaddr_in</span><span class="s">(</span><span class="i">$port</span><span class="cm">,</span> <span class="w">INADDR_ANY</span><span class="s">)</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;bind: $!&quot;</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/listen.html">listen</a><span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="w">SOMAXCONN</span><span class="s">)</span>                      || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;listen: $!&quot;</span><span class="sc">;</span></li><li></li><li> <span class="i">logmsg</span> <span class="q">&quot;server started on port $port&quot;</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$paddr</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/for.html">for</a> <span class="s">(</span> <span class="sc">;</span> <span class="i">$paddr</span> = <a class="l_k" href="functions/accept.html">accept</a><span class="s">(</span><span class="w">Client</span><span class="cm">,</span> <span class="w">Server</span><span class="s">)</span><span class="sc">;</span> <a class="l_k" href="functions/close.html">close</a> <span class="w">Client</span><span class="s">)</span> <span class="s">{</span></li><li>     <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$port</span><span class="cm">,</span> <span class="i">$iaddr</span><span class="s">)</span> = <span class="i">sockaddr_in</span><span class="s">(</span><span class="i">$paddr</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/my.html">my</a> <span class="i">$name</span> = <a class="l_k" href="functions/gethostbyaddr.html">gethostbyaddr</a><span class="s">(</span><span class="i">$iaddr</span><span class="cm">,</span> <span class="w">AF_INET</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="i">logmsg</span> <span class="q">&quot;connection from $name [&quot;</span><span class="cm">,</span></li><li>             <span class="i">inet_ntoa</span><span class="s">(</span><span class="i">$iaddr</span><span class="s">)</span><span class="cm">,</span> <span class="q">&quot;]</span></li><li>             <span class="q">             at port $port&quot;</span><span class="sc">;</span></li><li></li><li>     <a class="l_k" href="functions/print.html">print</a> <span class="i">Client</span> <span class="q">&quot;Hello there, $name, it&#39;s now &quot;</span><span class="cm">,</span></li><li>                     <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="s">)</span><span class="cm">,</span> <span class="i">$EOL</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>And here's a multitasking version.  It's multitasked in that
like most typical servers, it spawns (fork()s) a slave server to
handle the client request so that the master server can quickly
go back to service a new client.</p>
<pre class="verbatim"><ol><li> <span class="c">#!/usr/bin/perl -Tw</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/BEGIN.html">BEGIN</a> <span class="s">{</span> <span class="i">$ENV</span>{<span class="w">PATH</span>} = <span class="q">&quot;/usr/bin:/bin&quot;</span> <span class="s">}</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Socket</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Carp</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$EOL</span> = <span class="q">&quot;\015\012&quot;</span><span class="sc">;</span></li><li></li><li> sub <span class="m">spawn</span><span class="sc">;</span>  <span class="c"># forward declaration</span></li><li><a name="logmsg"></a> sub <span class="m">logmsg</span> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$0 $$: @_ at &quot;</span><span class="cm">,</span> <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span> <span class="s">}</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$port</span>  = <a class="l_k" href="functions/shift.html">shift</a> || <span class="n">2345</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;invalid port&quot;</span> <a class="l_k" href="functions/unless.html">unless</a> <span class="i">$port</span> =~ <span class="q">/^ \d+ $/x</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$proto</span> = <a class="l_k" href="functions/getprotobyname.html">getprotobyname</a><span class="s">(</span><span class="q">&quot;tcp&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/socket.html">socket</a><span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="w">PF_INET</span><span class="cm">,</span> <span class="w">SOCK_STREAM</span><span class="cm">,</span> <span class="i">$proto</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;socket: $!&quot;</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/setsockopt.html">setsockopt</a><span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="w">SOL_SOCKET</span><span class="cm">,</span> <span class="w">SO_REUSEADDR</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;l&quot;</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="s">)</span></li><li>                                                || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;setsockopt: $!&quot;</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/bind.html">bind</a><span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="i">sockaddr_in</span><span class="s">(</span><span class="i">$port</span><span class="cm">,</span> <span class="w">INADDR_ANY</span><span class="s">)</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;bind: $!&quot;</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/listen.html">listen</a><span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="w">SOMAXCONN</span><span class="s">)</span>                      || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;listen: $!&quot;</span><span class="sc">;</span></li><li></li><li> <span class="i">logmsg</span> <span class="q">&quot;server started on port $port&quot;</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$waitedpid</span> = <span class="n">0</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$paddr</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="q">&quot;:sys_wait_h&quot;</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Errno</span><span class="sc">;</span></li><li></li><li><a name="REAPER"></a> sub <span class="m">REAPER</span> <span class="s">{</span></li><li>     <a class="l_k" href="functions/local.html">local</a> <span class="i">$!</span><span class="sc">;</span>   <span class="c"># don&#39;t let waitpid() overwrite current error</span></li><li>     <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$pid</span> = <a class="l_k" href="functions/waitpid.html">waitpid</a><span class="s">(</span><span class="n">-1</span><span class="cm">,</span> <span class="w">WNOHANG</span><span class="s">)</span><span class="s">)</span> &gt; <span class="n">0</span> &amp;&amp; <span class="i">WIFEXITED</span><span class="s">(</span><span class="i">$?</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>         <span class="i">logmsg</span> <span class="q">&quot;reaped $waitedpid&quot;</span> . <span class="s">(</span><span class="i">$?</span> ? <span class="q">&quot; with exit $?&quot;</span> <span class="co">:</span> <span class="q">&quot;&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="s">}</span></li><li>     <span class="i">$SIG</span>{<span class="w">CHLD</span>} = \<span class="i">&amp;REAPER</span><span class="sc">;</span>  <span class="c"># loathe SysV</span></li><li> <span class="s">}</span></li><li></li><li> <span class="i">$SIG</span>{<span class="w">CHLD</span>} = \<span class="i">&amp;REAPER</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="n">1</span><span class="s">)</span> <span class="s">{</span></li><li>     <span class="i">$paddr</span> = <a class="l_k" href="functions/accept.html">accept</a><span class="s">(</span><span class="w">Client</span><span class="cm">,</span> <span class="w">Server</span><span class="s">)</span> || <a class="l_k" href="functions/do.html">do</a> <span class="s">{</span></li><li>         <span class="c"># try again if accept() returned because got a signal</span></li><li>         <a class="l_k" href="functions/next.html">next</a> <a class="l_k" href="functions/if.html">if</a> <span class="i">$!</span>{<span class="w">EINTR</span>}<span class="sc">;</span></li><li>         <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;accept: $!&quot;</span><span class="sc">;</span></li><li>     <span class="s">}</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$port</span><span class="cm">,</span> <span class="i">$iaddr</span><span class="s">)</span> = <span class="i">sockaddr_in</span><span class="s">(</span><span class="i">$paddr</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/my.html">my</a> <span class="i">$name</span> = <a class="l_k" href="functions/gethostbyaddr.html">gethostbyaddr</a><span class="s">(</span><span class="i">$iaddr</span><span class="cm">,</span> <span class="w">AF_INET</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="i">logmsg</span> <span class="q">&quot;connection from $name [&quot;</span><span class="cm">,</span></li><li>            <span class="i">inet_ntoa</span><span class="s">(</span><span class="i">$iaddr</span><span class="s">)</span><span class="cm">,</span></li><li>            <span class="q">&quot;] at port $port&quot;</span><span class="sc">;</span></li><li></li><li>     <span class="i">spawn</span> <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span></li><li>         <span class="i">$|</span> = <span class="n">1</span><span class="sc">;</span></li><li>         <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Hello there, $name, it&#39;s now &quot;</span><span class="cm">,</span></li><li>               <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="s">)</span><span class="cm">,</span></li><li>               <span class="i">$EOL</span><span class="sc">;</span></li><li>         <a class="l_k" href="functions/exec.html">exec</a> <span class="q">&quot;/usr/games/fortune&quot;</span>       <span class="c"># XXX: &quot;wrong&quot; line terminators</span></li><li>             <a class="l_k" href="functions/or.html">or</a> <span class="w">confess</span> <span class="q">&quot;can&#39;t exec fortune: $!&quot;</span><span class="sc">;</span></li><li>     <span class="s">}</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/close.html">close</a> <span class="w">Client</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li><a name="spawn"></a> sub <span class="m">spawn</span> <span class="s">{</span></li><li>     <a class="l_k" href="functions/my.html">my</a> <span class="i">$coderef</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="sc">;</span></li><li></li><li>     <a class="l_k" href="functions/unless.html">unless</a> <span class="s">(</span><span class="i">@_</span> == <span class="n">0</span> &amp;&amp; <span class="i">$coderef</span> &amp;&amp; <a class="l_k" href="functions/ref.html">ref</a><span class="s">(</span><span class="i">$coderef</span><span class="s">)</span> <a class="l_k" href="functions/eq.html">eq</a> <span class="q">&quot;CODE&quot;</span><span class="s">)</span> <span class="s">{</span></li><li>         <span class="w">confess</span> <span class="q">&quot;usage: spawn CODEREF&quot;</span><span class="sc">;</span></li><li>     <span class="s">}</span></li><li></li><li>     <a class="l_k" href="functions/my.html">my</a> <span class="i">$pid</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/unless.html">unless</a> <span class="s">(</span><a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$pid</span> = <a class="l_k" href="functions/fork.html">fork</a><span class="s">(</span><span class="s">)</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>         <span class="i">logmsg</span> <span class="q">&quot;cannot fork: $!&quot;</span><span class="sc">;</span></li><li>         <a class="l_k" href="functions/return.html">return</a><span class="sc">;</span></li><li>     <span class="s">}</span></li><li>     <a class="l_k" href="functions/elsif.html">elsif</a> <span class="s">(</span><span class="i">$pid</span><span class="s">)</span> <span class="s">{</span></li><li>         <span class="i">logmsg</span> <span class="q">&quot;begat $pid&quot;</span><span class="sc">;</span></li><li>         <a class="l_k" href="functions/return.html">return</a><span class="sc">;</span> <span class="c"># I&#39;m the parent</span></li><li>     <span class="s">}</span></li><li>     <span class="c"># else I&#39;m the child -- go spawn</span></li><li></li><li>     <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">STDIN</span><span class="cm">,</span>  <span class="q">&quot;&lt;&amp;Client&quot;</span><span class="s">)</span>    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t dup client to stdin&quot;</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">STDOUT</span><span class="cm">,</span> <span class="q">&quot;&gt;&amp;Client&quot;</span><span class="s">)</span>    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t dup client to stdout&quot;</span><span class="sc">;</span></li><li>     <span class="c">## open(STDERR, &quot;&gt;&amp;STDOUT&quot;) || die &quot;can&#39;t dup stdout to stderr&quot;;</span></li><li>     <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="i">$coderef</span>-&gt;<span class="s">(</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>This server takes the trouble to clone off a child version via fork()
for each incoming request.  That way it can handle many requests at
once, which you might not always want.  Even if you don't fork(), the
listen() will allow that many pending connections.  Forking servers
have to be particularly careful about cleaning up their dead children
(called "zombies" in Unix parlance), because otherwise you'll quickly
fill up your process table.  The REAPER subroutine is used here to
call waitpid() for any child processes that have finished, thereby
ensuring that they terminate cleanly and don't join the ranks of the
living dead.</p>
<p>Within the while loop we call accept() and check to see if it returns
a false value.  This would normally indicate a system error needs
to be reported.  However, the introduction of safe signals (see
<a href="#Deferred-Signals-(Safe-Signals)">Deferred Signals (Safe Signals)</a> above) in Perl 5.8.0 means that
accept() might also be interrupted when the process receives a signal.
This typically happens when one of the forked subprocesses exits and
notifies the parent process with a CHLD signal.</p>
<p>If accept() is interrupted by a signal, $! will be set to EINTR.
If this happens, we can safely continue to the next iteration of
the loop and another call to accept().  It is important that your
signal handling code not modify the value of $!, or else this test
will likely fail.  In the REAPER subroutine we create a local version
of $! before calling waitpid().  When waitpid() sets $! to ECHILD as
it inevitably does when it has no more children waiting, it
updates the local copy and leaves the original unchanged.</p>
<p>You should use the <b>-T</b> flag to enable taint checking (see <a href="perlsec.html">perlsec</a>)
even if we aren't running setuid or setgid.  This is always a good idea
for servers or any program run on behalf of someone else (like CGI
scripts), because it lessens the chances that people from the outside will
be able to compromise your system.</p>
<p>Let's look at another TCP client.  This one connects to the TCP "time"
service on a number of different machines and shows how far their clocks
differ from the system on which it's being run:</p>
<pre class="verbatim"><ol><li>    <span class="c">#!/usr/bin/perl  -w</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Socket</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$SECS_OF_70_YEARS</span> = <span class="n">2208988800</span><span class="sc">;</span></li><li><a name="ctime"></a>    sub <span class="m">ctime</span> <span class="s">{</span> <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><a class="l_k" href="functions/shift.html">shift</a><span class="s">(</span><span class="s">)</span> || <a class="l_k" href="functions/time.html">time</a><span class="s">(</span><span class="s">)</span><span class="s">)</span> <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$iaddr</span> = <a class="l_k" href="functions/gethostbyname.html">gethostbyname</a><span class="s">(</span><span class="q">&quot;localhost&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$proto</span> = <a class="l_k" href="functions/getprotobyname.html">getprotobyname</a><span class="s">(</span><span class="q">&quot;tcp&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$port</span> = <a class="l_k" href="functions/getservbyname.html">getservbyname</a><span class="s">(</span><span class="q">&quot;time&quot;</span><span class="cm">,</span> <span class="q">&quot;tcp&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$paddr</span> = <span class="i">sockaddr_in</span><span class="s">(</span><span class="n">0</span><span class="cm">,</span> <span class="i">$iaddr</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$host</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="i">$|</span> = <span class="n">1</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;%-24s %8s %s\n&quot;</span><span class="cm">,</span> <span class="q">&quot;localhost&quot;</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="i">ctime</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/foreach.html">foreach</a> <span class="i">$host</span> <span class="s">(</span><span class="i">@ARGV</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;%-24s &quot;</span><span class="cm">,</span> <span class="i">$host</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$hisiaddr</span> = <span class="i">inet_aton</span><span class="s">(</span><span class="i">$host</span><span class="s">)</span>     || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;unknown host&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$hispaddr</span> = <span class="i">sockaddr_in</span><span class="s">(</span><span class="i">$port</span><span class="cm">,</span> <span class="i">$hisiaddr</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/socket.html">socket</a><span class="s">(</span><span class="w">SOCKET</span><span class="cm">,</span> <span class="w">PF_INET</span><span class="cm">,</span> <span class="w">SOCK_STREAM</span><span class="cm">,</span> <span class="i">$proto</span><span class="s">)</span></li><li>                                            || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;socket: $!&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/connect.html">connect</a><span class="s">(</span><span class="w">SOCKET</span><span class="cm">,</span> <span class="i">$hispaddr</span><span class="s">)</span>          || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;connect: $!&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$rtime</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;C4&quot;</span><span class="cm">,</span> <span class="s">(</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/read.html">read</a><span class="s">(</span><span class="w">SOCKET</span><span class="cm">,</span> <span class="i">$rtime</span><span class="cm">,</span> <span class="n">4</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">SOCKET</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$histime</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;N&quot;</span><span class="cm">,</span> <span class="i">$rtime</span><span class="s">)</span> - <span class="i">$SECS_OF_70_YEARS</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;%8d %s\n&quot;</span><span class="cm">,</span> <span class="i">$histime</span> - <a class="l_k" href="functions/time.html">time</a><span class="s">(</span><span class="s">)</span><span class="cm">,</span> <span class="i">ctime</span><span class="s">(</span><span class="i">$histime</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><a name="Unix-Domain-TCP-Clients-and-Servers"></a><h2>Unix-Domain TCP Clients and Servers</h2>
<p>That's fine for Internet-domain clients and servers, but what about local
communications?  While you can use the same setup, sometimes you don't
want to.  Unix-domain sockets are local to the current host, and are often
used internally to implement pipes.  Unlike Internet domain sockets, Unix
domain sockets can show up in the file system with an ls(1) listing.</p>
<pre class="verbatim"><ol><li>    % ls -l /dev/log</li><li>    srw-rw-rw-  1 root            0 Oct 31 07:23 /dev/log</li></ol></pre><p>You can test for these with Perl's <b>-S</b> file test:</p>
<pre class="verbatim"><ol><li>    unless <span class="s">(</span>-S <span class="q">&quot;/dev/log&quot;</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;something&#39;s wicked with the log system&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Here's a sample Unix-domain client:</p>
<pre class="verbatim"><ol><li>    <span class="c">#!/usr/bin/perl -w</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Socket</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$rendezvous</span><span class="cm">,</span> <span class="i">$line</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="i">$rendezvous</span> = <a class="l_k" href="functions/shift.html">shift</a> || <span class="q">&quot;catsock&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/socket.html">socket</a><span class="s">(</span><span class="w">SOCK</span><span class="cm">,</span> <span class="w">PF_UNIX</span><span class="cm">,</span> <span class="w">SOCK_STREAM</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span>     || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;socket: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/connect.html">connect</a><span class="s">(</span><span class="w">SOCK</span><span class="cm">,</span> <span class="i">sockaddr_un</span><span class="s">(</span><span class="i">$rendezvous</span><span class="s">)</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;connect: $!&quot;</span><span class="sc">;</span></li><li>    while <span class="s">(</span><a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$line</span> = <span class="q">&lt;SOCK&gt;</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">$line</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li>    <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>And here's a corresponding server.  You don't have to worry about silly
network terminators here because Unix domain sockets are guaranteed
to be on the localhost, and thus everything works right.</p>
<pre class="verbatim"><ol><li>    <span class="c">#!/usr/bin/perl -Tw</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Socket</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Carp</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/BEGIN.html">BEGIN</a> <span class="s">{</span> <span class="i">$ENV</span>{<span class="w">PATH</span>} = <span class="q">&quot;/usr/bin:/bin&quot;</span> <span class="s">}</span></li><li>    sub <span class="m">spawn</span><span class="sc">;</span>  <span class="c"># forward declaration</span></li><li><a name="logmsg"></a>    sub <span class="m">logmsg</span> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$0 $$: @_ at &quot;</span><span class="cm">,</span> <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span> <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$NAME</span> = <span class="q">&quot;catsock&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$uaddr</span> = <span class="i">sockaddr_un</span><span class="s">(</span><span class="i">$NAME</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$proto</span> = <a class="l_k" href="functions/getprotobyname.html">getprotobyname</a><span class="s">(</span><span class="q">&quot;tcp&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/socket.html">socket</a><span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="w">PF_UNIX</span><span class="cm">,</span> <span class="w">SOCK_STREAM</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;socket: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/unlink.html">unlink</a><span class="s">(</span><span class="i">$NAME</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/bind.html">bind</a>  <span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="i">$uaddr</span><span class="s">)</span>                  || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;bind: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/listen.html">listen</a><span class="s">(</span><span class="w">Server</span><span class="cm">,</span> <span class="w">SOMAXCONN</span><span class="s">)</span>               || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;listen: $!&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="i">logmsg</span> <span class="q">&quot;server started on $NAME&quot;</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$waitedpid</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="q">&quot;:sys_wait_h&quot;</span><span class="sc">;</span></li><li><a name="REAPER"></a>    sub <span class="m">REAPER</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$child</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="s">(</span><span class="i">$waitedpid</span> = <a class="l_k" href="functions/waitpid.html">waitpid</a><span class="s">(</span><span class="n">-1</span><span class="cm">,</span> <span class="w">WNOHANG</span><span class="s">)</span><span class="s">)</span> &gt; <span class="n">0</span><span class="s">)</span> <span class="s">{</span></li><li>            <span class="i">logmsg</span> <span class="q">&quot;reaped $waitedpid&quot;</span> . <span class="s">(</span><span class="i">$?</span> ? <span class="q">&quot; with exit $?&quot;</span> <span class="co">:</span> <span class="q">&quot;&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>        <span class="i">$SIG</span>{<span class="w">CHLD</span>} = \<span class="i">&amp;REAPER</span><span class="sc">;</span>  <span class="c"># loathe SysV</span></li><li>    <span class="s">}</span></li><li></li><li>    <span class="i">$SIG</span>{<span class="w">CHLD</span>} = \<span class="i">&amp;REAPER</span><span class="sc">;</span></li><li></li><li></li><li>    <a class="l_k" href="functions/for.html">for</a> <span class="s">(</span> <span class="i">$waitedpid</span> = <span class="n">0</span><span class="sc">;</span></li><li>          <a class="l_k" href="functions/accept.html">accept</a><span class="s">(</span><span class="w">Client</span><span class="cm">,</span> <span class="w">Server</span><span class="s">)</span> || <span class="i">$waitedpid</span><span class="sc">;</span></li><li>          <span class="i">$waitedpid</span> = <span class="n">0</span><span class="cm">,</span> <a class="l_k" href="functions/close.html">close</a> <span class="w">Client</span><span class="s">)</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/next.html">next</a> <a class="l_k" href="functions/if.html">if</a> <span class="i">$waitedpid</span><span class="sc">;</span></li><li>        <span class="i">logmsg</span> <span class="q">&quot;connection on $NAME&quot;</span><span class="sc">;</span></li><li>        <span class="i">spawn</span> <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span></li><li>            <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Hello there, it&#39;s now &quot;</span><span class="cm">,</span> <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/exec.html">exec</a><span class="s">(</span><span class="q">&quot;/usr/games/fortune&quot;</span><span class="s">)</span>  || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t exec fortune: $!&quot;</span><span class="sc">;</span></li><li>        <span class="s">}</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li></li><li><a name="spawn"></a>    sub <span class="m">spawn</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$coderef</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/unless.html">unless</a> <span class="s">(</span><span class="i">@_</span> == <span class="n">0</span> &amp;&amp; <span class="i">$coderef</span> &amp;&amp; <a class="l_k" href="functions/ref.html">ref</a><span class="s">(</span><span class="i">$coderef</span><span class="s">)</span> <a class="l_k" href="functions/eq.html">eq</a> <span class="q">&quot;CODE&quot;</span><span class="s">)</span> <span class="s">{</span></li><li>            <span class="w">confess</span> <span class="q">&quot;usage: spawn CODEREF&quot;</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$pid</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/unless.html">unless</a> <span class="s">(</span><a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$pid</span> = <a class="l_k" href="functions/fork.html">fork</a><span class="s">(</span><span class="s">)</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>            <span class="i">logmsg</span> <span class="q">&quot;cannot fork: $!&quot;</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/return.html">return</a><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>        <a class="l_k" href="functions/elsif.html">elsif</a> <span class="s">(</span><span class="i">$pid</span><span class="s">)</span> <span class="s">{</span></li><li>            <span class="i">logmsg</span> <span class="q">&quot;begat $pid&quot;</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/return.html">return</a><span class="sc">;</span> <span class="c"># I&#39;m the parent</span></li><li>        <span class="s">}</span></li><li>        <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span></li><li>            <span class="c"># I&#39;m the child -- go spawn</span></li><li>        <span class="s">}</span></li><li></li><li>        <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">STDIN</span><span class="cm">,</span>  <span class="q">&quot;&lt;&amp;Client&quot;</span><span class="s">)</span>    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t dup client to stdin&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">STDOUT</span><span class="cm">,</span> <span class="q">&quot;&gt;&amp;Client&quot;</span><span class="s">)</span>    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t dup client to stdout&quot;</span><span class="sc">;</span></li><li>        <span class="c">## open(STDERR, &quot;&gt;&amp;STDOUT&quot;) || die &quot;can&#39;t dup stdout to stderr&quot;;</span></li><li>        <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="i">$coderef</span>-&gt;<span class="s">(</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>As you see, it's remarkably similar to the Internet domain TCP server, so
much so, in fact, that we've omitted several duplicate functions--spawn(),
logmsg(), ctime(), and REAPER()--which are the same as in the other server.</p>
<p>So why would you ever want to use a Unix domain socket instead of a
simpler named pipe?  Because a named pipe doesn't give you sessions.  You
can't tell one process's data from another's.  With socket programming,
you get a separate session for each client; that's why accept() takes two
arguments.</p>
<p>For example, let's say that you have a long-running database server daemon
that you want folks to be able to access from the Web, but only
if they go through a CGI interface.  You'd have a small, simple CGI
program that does whatever checks and logging you feel like, and then acts
as a Unix-domain client and connects to your private server.</p>
<a name="TCP-Clients-with-IO%3a%3aSocket"></a><h1>TCP Clients with IO::Socket</h1>
<p>For those preferring a higher-level interface to socket programming, the
IO::Socket module provides an object-oriented approach.  If for some reason
you lack this module, you can just fetch IO::Socket from CPAN, where you'll also
find modules providing easy interfaces to the following systems: DNS, FTP,
Ident (RFC 931), NIS and NISPlus, NNTP, Ping, POP3, SMTP, SNMP, SSLeay,
Telnet, and Time--to name just a few.</p>
<a name="A-Simple-Client"></a><h2>A Simple Client</h2>
<p>Here's a client that creates a TCP connection to the "daytime"
service at port 13 of the host name "localhost" and prints out everything
that the server there cares to provide.</p>
<pre class="verbatim"><ol><li>    <span class="c">#!/usr/bin/perl -w</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">IO::Socket</span><span class="sc">;</span></li><li>    <span class="i">$remote</span> = <span class="w">IO::Socket::INET</span><span class="w">-&gt;new</span><span class="s">(</span></li><li>                        <span class="w">Proto</span>    <span class="cm">=&gt;</span> <span class="q">&quot;tcp&quot;</span><span class="cm">,</span></li><li>                        <span class="w">PeerAddr</span> <span class="cm">=&gt;</span> <span class="q">&quot;localhost&quot;</span><span class="cm">,</span></li><li>                        <span class="w">PeerPort</span> <span class="cm">=&gt;</span> <span class="q">&quot;daytime(13)&quot;</span><span class="cm">,</span></li><li>                    <span class="s">)</span></li><li>                 || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t connect to daytime service on localhost&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="q">&lt;$remote&gt;</span><span class="s">)</span> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="s">}</span></li></ol></pre><p>When you run this program, you should get something back that
looks like this:</p>
<pre class="verbatim"><ol><li>    Wed May 14 08:40:46 MDT 1997</li></ol></pre><p>Here are what those parameters to the new() constructor mean:</p>
<ul>
<li><a name="Proto"></a><b><code class="inline"><span class="w">Proto</span></code>
</b>
<p>This is which protocol to use.  In this case, the socket handle returned
will be connected to a TCP socket, because we want a stream-oriented
connection, that is, one that acts pretty much like a plain old file.
Not all sockets are this of this type.  For example, the UDP protocol
can be used to make a datagram socket, used for message-passing.</p>
</li>
<li><a name="PeerAddr"></a><b><code class="inline"><span class="w">PeerAddr</span></code>
</b>
<p>This is the name or Internet address of the remote host the server is
running on.  We could have specified a longer name like <code class="inline"><span class="q">&quot;www.perl.com&quot;</span></code>
,
or an address like <code class="inline"><span class="q">&quot;207.171.7.72&quot;</span></code>
.  For demonstration purposes, we've
used the special hostname <code class="inline"><span class="q">&quot;localhost&quot;</span></code>
, which should always mean the
current machine you're running on.  The corresponding Internet address
for localhost is <code class="inline"><span class="q">&quot;127.0.0.1&quot;</span></code>
, if you'd rather use that.</p>
</li>
<li><a name="PeerPort"></a><b><code class="inline"><span class="w">PeerPort</span></code>
</b>
<p>This is the service name or port number we'd like to connect to.
We could have gotten away with using just <code class="inline"><span class="q">&quot;daytime&quot;</span></code>
 on systems with a
well-configured system services file,[FOOTNOTE: The system services file
is found in <i>/etc/services</i> under Unixy systems.] but here we've specified the
port number (13) in parentheses.  Using just the number would have also
worked, but numeric literals make careful programmers nervous.</p>
</li>
</ul>
<p>Notice how the return value from the <code class="inline"><span class="w">new</span></code>
 constructor is used as
a filehandle in the <code class="inline">while</code>
 loop?  That's what's called an <i>indirect
filehandle</i>, a scalar variable containing a filehandle.  You can use
it the same way you would a normal filehandle.  For example, you
can read one line from it this way:</p>
<pre class="verbatim"><ol><li>    <span class="i">$line</span> = <span class="q">&lt;$handle&gt;</span><span class="sc">;</span></li></ol></pre><p>all remaining lines from is this way:</p>
<pre class="verbatim"><ol><li>    <span class="i">@lines</span> = <span class="q">&lt;$handle&gt;</span><span class="sc">;</span></li></ol></pre><p>and send a line of data to it this way:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <span class="i">$handle</span> <span class="q">&quot;some data\n&quot;</span><span class="sc">;</span></li></ol></pre><a name="A-Webget-Client"></a><h2>A Webget Client</h2>
<p>Here's a simple client that takes a remote host to fetch a document
from, and then a list of files to get from that host.  This is a
more interesting client than the previous one because it first sends
something to the server before fetching the server's response.</p>
<pre class="verbatim"><ol><li>    <span class="c">#!/usr/bin/perl -w</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">IO::Socket</span><span class="sc">;</span></li><li>    unless <span class="s">(</span><span class="i">@ARGV</span> &gt; <span class="n">1</span><span class="s">)</span> <span class="s">{</span> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;usage: $0 host url ...&quot;</span> <span class="s">}</span></li><li>    <span class="i">$host</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="s">(</span><span class="i">@ARGV</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$EOL</span> = <span class="q">&quot;\015\012&quot;</span><span class="sc">;</span></li><li>    <span class="i">$BLANK</span> = <span class="i">$EOL</span> x <span class="n">2</span><span class="sc">;</span></li><li>    for <a class="l_k" href="functions/my.html">my</a> <span class="i">$document</span> <span class="s">(</span><span class="i">@ARGV</span><span class="s">)</span> <span class="s">{</span></li><li>        <span class="i">$remote</span> = <span class="w">IO::Socket::INET</span><span class="w">-&gt;new</span><span class="s">(</span> <span class="w">Proto</span>     <span class="cm">=&gt;</span> <span class="q">&quot;tcp&quot;</span><span class="cm">,</span></li><li>                                         <span class="w">PeerAddr</span>  <span class="cm">=&gt;</span> <span class="i">$host</span><span class="cm">,</span></li><li>                                         <span class="w">PeerPort</span>  <span class="cm">=&gt;</span> <span class="q">&quot;http(80)&quot;</span><span class="cm">,</span></li><li>                  <span class="s">)</span>     || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;cannot connect to httpd on $host&quot;</span><span class="sc">;</span></li><li>        <span class="i">$remote</span><span class="i">-&gt;autoflush</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">$remote</span> <span class="q">&quot;GET $document HTTP/1.0&quot;</span> . <span class="i">$BLANK</span><span class="sc">;</span></li><li>        while <span class="s">(</span> <span class="q">&lt;$remote&gt;</span> <span class="s">)</span> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="s">}</span></li><li>        <a class="l_k" href="functions/close.html">close</a> <span class="i">$remote</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>The web server handling the HTTP service is assumed to be at
its standard port, number 80.  If the server you're trying to
connect to is at a different port, like 1080 or 8080, you should specify it
as the named-parameter pair, <code class="inline"><span class="w">PeerPort</span> <span class="cm">=&gt;</span> <span class="n">8080</span></code>
.  The <code class="inline"><span class="w">autoflush</span></code>

method is used on the socket because otherwise the system would buffer
up the output we sent it.  (If you're on a prehistoric Mac, you'll also
need to change every <code class="inline"><span class="q">&quot;\n&quot;</span></code>
 in your code that sends data over the network
to be a <code class="inline"><span class="q">&quot;\015\012&quot;</span></code>
 instead.)</p>
<p>Connecting to the server is only the first part of the process: once you
have the connection, you have to use the server's language.  Each server
on the network has its own little command language that it expects as
input.  The string that we send to the server starting with "GET" is in
HTTP syntax.  In this case, we simply request each specified document.
Yes, we really are making a new connection for each document, even though
it's the same host.  That's the way you always used to have to speak HTTP.
Recent versions of web browsers may request that the remote server leave
the connection open a little while, but the server doesn't have to honor
such a request.</p>
<p>Here's an example of running that program, which we'll call <i>webget</i>:</p>
<pre class="verbatim"><ol><li>    % webget www.perl.com /guanaco.html</li><li>    HTTP/1.1 404 File Not Found</li><li>    Date: Thu, 08 May 1997 18:02:32 GMT</li><li>    Server: Apache/1.2b6</li><li>    Connection: close</li><li>    Content-type: text/html</li><li></li><li>    &lt;HEAD&gt;&lt;TITLE&gt;404 File Not Found&lt;/TITLE&gt;&lt;/HEAD&gt;</li><li>    &lt;BODY&gt;&lt;H1&gt;File Not Found&lt;/H1&gt;</li><li>    The requested URL /guanaco.html was not found on this server.&lt;P&gt;</li><li>    &lt;/BODY&gt;</li></ol></pre><p>Ok, so that's not very interesting, because it didn't find that
particular document.  But a long response wouldn't have fit on this page.</p>
<p>For a more featureful version of this program, you should look to
the <i>lwp-request</i> program included with the LWP modules from CPAN.</p>
<a name="Interactive-Client-with-IO%3a%3aSocket"></a><h2>Interactive Client with IO::Socket</h2>
<p>Well, that's all fine if you want to send one command and get one answer,
but what about setting up something fully interactive, somewhat like
the way <i>telnet</i> works?  That way you can type a line, get the answer,
type a line, get the answer, etc.</p>
<p>This client is more complicated than the two we've done so far, but if
you're on a system that supports the powerful <code class="inline"><a class="l_k" href="functions/fork.html">fork</a></code> call, the solution
isn't that rough.  Once you've made the connection to whatever service
you'd like to chat with, call <code class="inline"><a class="l_k" href="functions/fork.html">fork</a></code> to clone your process.  Each of
these two identical process has a very simple job to do: the parent
copies everything from the socket to standard output, while the child
simultaneously copies everything from standard input to the socket.
To accomplish the same thing using just one process would be <i>much</i>
harder, because it's easier to code two processes to do one thing than it
is to code one process to do two things.  (This keep-it-simple principle
a cornerstones of the Unix philosophy, and good software engineering as
well, which is probably why it's spread to other systems.)</p>
<p>Here's the code:</p>
<pre class="verbatim"><ol><li>    <span class="c">#!/usr/bin/perl -w</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">IO::Socket</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$host</span><span class="cm">,</span> <span class="i">$port</span><span class="cm">,</span> <span class="i">$kidpid</span><span class="cm">,</span> <span class="i">$handle</span><span class="cm">,</span> <span class="i">$line</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    unless <span class="s">(</span><span class="i">@ARGV</span> == <span class="n">2</span><span class="s">)</span> <span class="s">{</span> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;usage: $0 host port&quot;</span> <span class="s">}</span></li><li>    <span class="s">(</span><span class="i">$host</span><span class="cm">,</span> <span class="i">$port</span><span class="s">)</span> = <span class="i">@ARGV</span><span class="sc">;</span></li><li></li><li>    <span class="c"># create a tcp connection to the specified host and port</span></li><li>    <span class="i">$handle</span> = <span class="w">IO::Socket::INET</span><span class="w">-&gt;new</span><span class="s">(</span><span class="w">Proto</span>     <span class="cm">=&gt;</span> <span class="q">&quot;tcp&quot;</span><span class="cm">,</span></li><li>                                    <span class="w">PeerAddr</span>  <span class="cm">=&gt;</span> <span class="i">$host</span><span class="cm">,</span></li><li>                                    <span class="w">PeerPort</span>  <span class="cm">=&gt;</span> <span class="i">$port</span><span class="s">)</span></li><li>               || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t connect to port $port on $host: $!&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="i">$handle</span><span class="i">-&gt;autoflush</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span>       <span class="c"># so output gets there right away</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="i">STDERR</span> <span class="q">&quot;[Connected to $host:$port]\n&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="c"># split the program into two processes, identical twins</span></li><li>    <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t fork: $!&quot;</span> unless <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$kidpid</span> = <a class="l_k" href="functions/fork.html">fork</a><span class="s">(</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="c"># the if{} block runs only in the parent process</span></li><li>    if <span class="s">(</span><span class="i">$kidpid</span><span class="s">)</span> <span class="s">{</span></li><li>        <span class="c"># copy the socket to standard output</span></li><li>        while <span class="s">(</span><a class="l_k" href="functions/defined.html">defined</a> <span class="s">(</span><span class="i">$line</span> = <span class="q">&lt;$handle&gt;</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/print.html">print</a> <span class="i">STDOUT</span> <span class="i">$line</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>        <a class="l_k" href="functions/kill.html">kill</a><span class="s">(</span><span class="q">&quot;TERM&quot;</span><span class="cm">,</span> <span class="i">$kidpid</span><span class="s">)</span><span class="sc">;</span>   <span class="c"># send SIGTERM to child</span></li><li>    <span class="s">}</span></li><li>    <span class="c"># the else{} block runs only in the child process</span></li><li>    else <span class="s">{</span></li><li>        <span class="c"># copy standard input to the socket</span></li><li>        while <span class="s">(</span><a class="l_k" href="functions/defined.html">defined</a> <span class="s">(</span><span class="i">$line</span> = <span class="q">&lt;STDIN&gt;</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/print.html">print</a> <span class="i">$handle</span> <span class="i">$line</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>        <a class="l_k" href="functions/exit.html">exit</a><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span>                <span class="c"># just in case</span></li><li>    <span class="s">}</span></li></ol></pre><p>The <code class="inline"><a class="l_k" href="functions/kill.html">kill</a></code> function in the parent's <code class="inline">if</code>
 block is there to send a
signal to our child process, currently running in the <code class="inline">else</code>
 block,
as soon as the remote server has closed its end of the connection.</p>
<p>If the remote server sends data a byte at time, and you need that
data immediately without waiting for a newline (which might not happen),
you may wish to replace the <code class="inline">while</code>
 loop in the parent with the
following:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$byte</span><span class="sc">;</span></li><li>    while <span class="s">(</span><a class="l_k" href="functions/sysread.html">sysread</a><span class="s">(</span><span class="i">$handle</span><span class="cm">,</span> <span class="i">$byte</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span> == <span class="n">1</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">STDOUT</span> <span class="i">$byte</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Making a system call for each byte you want to read is not very efficient
(to put it mildly) but is the simplest to explain and works reasonably
well.</p>
<a name="TCP-Servers-with-IO%3a%3aSocket"></a><h1>TCP Servers with IO::Socket</h1>
<p>As always, setting up a server is little bit more involved than running a client.
The model is that the server creates a special kind of socket that
does nothing but listen on a particular port for incoming connections.
It does this by calling the <code class="inline"><span class="w">IO::Socket::INET</span><span class="w">-&gt;new</span><span class="s">(</span><span class="s">)</span></code>
 method with
slightly different arguments than the client did.</p>
<ul>
<li><a name="Proto"></a><b>Proto</b>
<p>This is which protocol to use.  Like our clients, we'll
still specify <code class="inline"><span class="q">&quot;tcp&quot;</span></code>
 here.</p>
</li>
<li><a name="LocalPort"></a><b>LocalPort</b>
<p>We specify a local
port in the <code class="inline"><span class="w">LocalPort</span></code>
 argument, which we didn't do for the client.
This is service name or port number for which you want to be the
server. (Under Unix, ports under 1024 are restricted to the
superuser.)  In our sample, we'll use port 9000, but you can use
any port that's not currently in use on your system.  If you try
to use one already in used, you'll get an "Address already in use"
message.  Under Unix, the <code class="inline"><span class="w">netstat</span> -<span class="w">a</span></code>
 command will show
which services current have servers.</p>
</li>
<li><a name="Listen"></a><b>Listen</b>
<p>The <code class="inline"><span class="w">Listen</span></code>
 parameter is set to the maximum number of
pending connections we can accept until we turn away incoming clients.
Think of it as a call-waiting queue for your telephone.
The low-level Socket module has a special symbol for the system maximum, which
is SOMAXCONN.</p>
</li>
<li><a name="Reuse"></a><b>Reuse</b>
<p>The <code class="inline"><span class="w">Reuse</span></code>
 parameter is needed so that we restart our server
manually without waiting a few minutes to allow system buffers to
clear out.</p>
</li>
</ul>
<p>Once the generic server socket has been created using the parameters
listed above, the server then waits for a new client to connect
to it.  The server blocks in the <code class="inline"><a class="l_k" href="functions/accept.html">accept</a></code> method, which eventually accepts a
bidirectional connection from the remote client.  (Make sure to autoflush
this handle to circumvent buffering.)</p>
<p>To add to user-friendliness, our server prompts the user for commands.
Most servers don't do this.  Because of the prompt without a newline,
you'll have to use the <code class="inline"><a class="l_k" href="functions/sysread.html">sysread</a></code> variant of the interactive client above.</p>
<p>This server accepts one of five different commands, sending output back to
the client.  Unlike most network servers, this one handles only one
incoming client at a time.  Multitasking servers are covered in
Chapter 16 of the Camel.</p>
<p>Here's the code.  We'll</p>
<pre class="verbatim"><ol><li> <span class="c">#!/usr/bin/perl -w</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">IO::Socket</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Net::hostent</span><span class="sc">;</span>      <span class="c"># for OOish version of gethostbyaddr</span></li><li></li><li> <span class="i">$PORT</span> = <span class="n">9000</span><span class="sc">;</span>          <span class="c"># pick something not in use</span></li><li></li><li> <span class="i">$server</span> = <span class="w">IO::Socket::INET</span><span class="w">-&gt;new</span><span class="s">(</span> <span class="w">Proto</span>     <span class="cm">=&gt;</span> <span class="q">&quot;tcp&quot;</span><span class="cm">,</span></li><li>                                  <span class="w">LocalPort</span> <span class="cm">=&gt;</span> <span class="i">$PORT</span><span class="cm">,</span></li><li>                                  <span class="w">Listen</span>    <span class="cm">=&gt;</span> <span class="w">SOMAXCONN</span><span class="cm">,</span></li><li>                                  <span class="w">Reuse</span>     <span class="cm">=&gt;</span> <span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;can&#39;t setup server&quot;</span> <a class="l_k" href="functions/unless.html">unless</a> <span class="i">$server</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;[Server $0 accepting clients]\n&quot;</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="i">$client</span> = <span class="i">$server</span><span class="i">-&gt;accept</span><span class="s">(</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>   <span class="i">$client</span><span class="i">-&gt;autoflush</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/print.html">print</a> <span class="i">$client</span> <span class="q">&quot;Welcome to $0; type help for command list.\n&quot;</span><span class="sc">;</span></li><li>   <span class="i">$hostinfo</span> = <a class="l_k" href="functions/gethostbyaddr.html">gethostbyaddr</a><span class="s">(</span><span class="i">$client</span><span class="i">-&gt;peeraddr</span><span class="s">)</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;[Connect from %s]\n&quot;</span><span class="cm">,</span></li><li>          <span class="i">$hostinfo</span> ? <span class="i">$hostinfo</span><span class="i">-&gt;name</span> <span class="co">:</span> <span class="i">$client</span><span class="i">-&gt;peerhost</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/print.html">print</a> <span class="i">$client</span> <span class="q">&quot;Command? &quot;</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> <span class="q">&lt;$client&gt;</span><span class="s">)</span> <span class="s">{</span></li><li>     <a class="l_k" href="functions/next.html">next</a> <a class="l_k" href="functions/unless.html">unless</a> <span class="q">/\S/</span><span class="sc">;</span>     <span class="c"># blank line</span></li><li>     <a class="l_k" href="functions/if.html">if</a>    <span class="s">(</span><span class="q">/quit|exit/i</span><span class="s">)</span>  <span class="s">{</span> <a class="l_k" href="functions/last.html">last</a>                                      <span class="s">}</span></li><li>     <a class="l_k" href="functions/elsif.html">elsif</a> <span class="s">(</span><span class="q">/date|time/i</span><span class="s">)</span>  <span class="s">{</span> <a class="l_k" href="functions/printf.html">printf</a> <span class="i">$client</span> <span class="q">&quot;%s\n&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="s">)</span> <span class="s">}</span></li><li>     <a class="l_k" href="functions/elsif.html">elsif</a> <span class="s">(</span><span class="q">/who/i</span> <span class="s">)</span>       <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a>  <span class="i">$client</span> <span class="q">`who 2&gt;&amp;1`</span>                 <span class="s">}</span></li><li>     <a class="l_k" href="functions/elsif.html">elsif</a> <span class="s">(</span><span class="q">/cookie/i</span> <span class="s">)</span>    <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a>  <span class="i">$client</span> <span class="q">`/usr/games/fortune 2&gt;&amp;1`</span>  <span class="s">}</span></li><li>     <a class="l_k" href="functions/elsif.html">elsif</a> <span class="s">(</span><span class="q">/motd/i</span> <span class="s">)</span>      <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a>  <span class="i">$client</span> <span class="q">`cat /etc/motd 2&gt;&amp;1`</span>       <span class="s">}</span></li><li>     <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span></li><li>       <a class="l_k" href="functions/print.html">print</a> <span class="i">$client</span> <span class="q">&quot;Commands: quit date who cookie motd\n&quot;</span><span class="sc">;</span></li><li>     <span class="s">}</span></li><li>   <span class="s">}</span> <a class="l_k" href="functions/continue.html">continue</a> <span class="s">{</span></li><li>      <a class="l_k" href="functions/print.html">print</a> <span class="i">$client</span> <span class="q">&quot;Command? &quot;</span><span class="sc">;</span></li><li>   <span class="s">}</span></li><li>   <a class="l_k" href="functions/close.html">close</a> <span class="i">$client</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><a name="UDP%3a-Message-Passing"></a><h1>UDP: Message Passing</h1>
<p>Another kind of client-server setup is one that uses not connections, but
messages.  UDP communications involve much lower overhead but also provide
less reliability, as there are no promises that messages will arrive at
all, let alone in order and unmangled.  Still, UDP offers some advantages
over TCP, including being able to "broadcast" or "multicast" to a whole
bunch of destination hosts at once (usually on your local subnet).  If you
find yourself overly concerned about reliability and start building checks
into your message system, then you probably should use just TCP to start
with.</p>
<p>UDP datagrams are <i>not</i> a bytestream and should not be treated as such.
This makes using I/O mechanisms with internal buffering like stdio (i.e.
print() and friends) especially cumbersome. Use syswrite(), or better
send(), like in the example below.</p>
<p>Here's a UDP program similar to the sample Internet TCP client given
earlier.  However, instead of checking one host at a time, the UDP version
will check many of them asynchronously by simulating a multicast and then
using select() to do a timed-out wait for I/O.  To do something similar
with TCP, you'd have to use a different socket handle for each host.</p>
<pre class="verbatim"><ol><li> <span class="c">#!/usr/bin/perl -w</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Socket</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Sys::Hostname</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span> <span class="i">$count</span><span class="cm">,</span> <span class="i">$hisiaddr</span><span class="cm">,</span> <span class="i">$hispaddr</span><span class="cm">,</span> <span class="i">$histime</span><span class="cm">,</span></li><li>      <span class="i">$host</span><span class="cm">,</span> <span class="i">$iaddr</span><span class="cm">,</span> <span class="i">$paddr</span><span class="cm">,</span> <span class="i">$port</span><span class="cm">,</span> <span class="i">$proto</span><span class="cm">,</span></li><li>      <span class="i">$rin</span><span class="cm">,</span> <span class="i">$rout</span><span class="cm">,</span> <span class="i">$rtime</span><span class="cm">,</span> <span class="i">$SECS_OF_70_YEARS</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <span class="i">$SECS_OF_70_YEARS</span> = <span class="n">2_208_988_800</span><span class="sc">;</span></li><li></li><li> <span class="i">$iaddr</span> = <a class="l_k" href="functions/gethostbyname.html">gethostbyname</a><span class="s">(</span><span class="i">hostname</span><span class="s">(</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$proto</span> = <a class="l_k" href="functions/getprotobyname.html">getprotobyname</a><span class="s">(</span><span class="q">&quot;udp&quot;</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$port</span> = <a class="l_k" href="functions/getservbyname.html">getservbyname</a><span class="s">(</span><span class="q">&quot;time&quot;</span><span class="cm">,</span> <span class="q">&quot;udp&quot;</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$paddr</span> = <span class="i">sockaddr_in</span><span class="s">(</span><span class="n">0</span><span class="cm">,</span> <span class="i">$iaddr</span><span class="s">)</span><span class="sc">;</span> <span class="c"># 0 means let kernel pick</span></li><li></li><li> <a class="l_k" href="functions/socket.html">socket</a><span class="s">(</span><span class="w">SOCKET</span><span class="cm">,</span> <span class="w">PF_INET</span><span class="cm">,</span> <span class="w">SOCK_DGRAM</span><span class="cm">,</span> <span class="i">$proto</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;socket: $!&quot;</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/bind.html">bind</a><span class="s">(</span><span class="w">SOCKET</span><span class="cm">,</span> <span class="i">$paddr</span><span class="s">)</span>                          || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;bind: $!&quot;</span><span class="sc">;</span></li><li></li><li> <span class="i">$|</span> = <span class="n">1</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;%-12s %8s %s\n&quot;</span><span class="cm">,</span>  <span class="q">&quot;localhost&quot;</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$count</span> = <span class="n">0</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/for.html">for</a> <span class="i">$host</span> <span class="s">(</span><span class="i">@ARGV</span><span class="s">)</span> <span class="s">{</span></li><li>     <span class="i">$count</span>++<span class="sc">;</span></li><li>     <span class="i">$hisiaddr</span> = <span class="i">inet_aton</span><span class="s">(</span><span class="i">$host</span><span class="s">)</span>              || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;unknown host&quot;</span><span class="sc">;</span></li><li>     <span class="i">$hispaddr</span> = <span class="i">sockaddr_in</span><span class="s">(</span><span class="i">$port</span><span class="cm">,</span> <span class="i">$hisiaddr</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><a class="l_k" href="functions/send.html">send</a><span class="s">(</span><span class="w">SOCKET</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="i">$hispaddr</span><span class="s">)</span><span class="s">)</span>    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;send $host: $!&quot;</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li> <span class="i">$rin</span> = <span class="q">&quot;&quot;</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/vec.html">vec</a><span class="s">(</span><span class="i">$rin</span><span class="cm">,</span> <a class="l_k" href="functions/fileno.html">fileno</a><span class="s">(</span><span class="w">SOCKET</span><span class="s">)</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span> = <span class="n">1</span><span class="sc">;</span></li><li></li><li> <span class="c"># timeout after 10.0 seconds</span></li><li> <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="i">$count</span> &amp;&amp; <a class="l_k" href="functions/select.html">select</a><span class="s">(</span><span class="i">$rout</span> = <span class="i">$rin</span><span class="cm">,</span> <a class="l_k" href="functions/undef.html">undef</a><span class="cm">,</span> <a class="l_k" href="functions/undef.html">undef</a><span class="cm">,</span> <span class="n">10.0</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>     <span class="i">$rtime</span> = <span class="q">&quot;&quot;</span><span class="sc">;</span></li><li>     <span class="i">$hispaddr</span> = <a class="l_k" href="functions/recv.html">recv</a><span class="s">(</span><span class="w">SOCKET</span><span class="cm">,</span> <span class="i">$rtime</span><span class="cm">,</span> <span class="n">4</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span>    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;recv: $!&quot;</span><span class="sc">;</span></li><li>     <span class="s">(</span><span class="i">$port</span><span class="cm">,</span> <span class="i">$hisiaddr</span><span class="s">)</span> = <span class="i">sockaddr_in</span><span class="s">(</span><span class="i">$hispaddr</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">$host</span> = <a class="l_k" href="functions/gethostbyaddr.html">gethostbyaddr</a><span class="s">(</span><span class="i">$hisiaddr</span><span class="cm">,</span> <span class="w">AF_INET</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">$histime</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;N&quot;</span><span class="cm">,</span> <span class="i">$rtime</span><span class="s">)</span> - <span class="i">$SECS_OF_70_YEARS</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;%-12s &quot;</span><span class="cm">,</span> <span class="i">$host</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;%8d %s\n&quot;</span><span class="cm">,</span> <span class="i">$histime</span> - <a class="l_k" href="functions/time.html">time</a><span class="s">(</span><span class="s">)</span><span class="cm">,</span> <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="i">$histime</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">$count</span>--<span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>This example does not include any retries and may consequently fail to
contact a reachable host. The most prominent reason for this is congestion
of the queues on the sending host if the number of hosts to contact is
sufficiently large.</p>
<a name="SysV-IPC"></a><h1>SysV IPC</h1>
<p>While System V IPC isn't so widely used as sockets, it still has some
interesting uses.  However, you cannot use SysV IPC or Berkeley mmap() to
have a variable shared amongst several processes.  That's because Perl
would reallocate your string when you weren't wanting it to.  You might
look into the <code class="inline"><span class="w">IPC::Shareable</span></code>
 or <code class="inline"><span class="w">threads::shared</span></code>
 modules for that.</p>
<p>Here's a small example showing shared memory usage.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">IPC::SysV</span> <span class="q">qw(IPC_PRIVATE IPC_RMID S_IRUSR S_IWUSR)</span><span class="sc">;</span></li><li></li><li>    <span class="i">$size</span> = <span class="n">2000</span><span class="sc">;</span></li><li>    <span class="i">$id</span> = <a class="l_k" href="functions/shmget.html">shmget</a><span class="s">(</span><span class="w">IPC_PRIVATE</span><span class="cm">,</span> <span class="i">$size</span><span class="cm">,</span> <span class="w">S_IRUSR</span> | <span class="w">S_IWUSR</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$id</span><span class="s">)</span>                    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;shmget: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;shm key $id\n&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="i">$message</span> = <span class="q">&quot;Message #1&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/shmwrite.html">shmwrite</a><span class="s">(</span><span class="i">$id</span><span class="cm">,</span> <span class="i">$message</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">60</span><span class="s">)</span>  || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;shmwrite: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;wrote: &#39;$message&#39;\n&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/shmread.html">shmread</a><span class="s">(</span><span class="i">$id</span><span class="cm">,</span> <span class="i">$buff</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">60</span><span class="s">)</span>      || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;shmread: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;read : &#39;$buff&#39;\n&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="c"># the buffer of shmread is zero-character end-padded.</span></li><li>    <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$buff</span><span class="cm">,</span> <a class="l_k" href="functions/index.html">index</a><span class="s">(</span><span class="i">$buff</span><span class="cm">,</span> <span class="q">&quot;\0&quot;</span><span class="s">)</span><span class="s">)</span> = <span class="q">&quot;&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;un&quot;</span> <a class="l_k" href="functions/unless.html">unless</a> <span class="i">$buff</span> <a class="l_k" href="functions/eq.html">eq</a> <span class="i">$message</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;swell\n&quot;</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;deleting shm $id\n&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/shmctl.html">shmctl</a><span class="s">(</span><span class="i">$id</span><span class="cm">,</span> <span class="w">IPC_RMID</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span>        || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;shmctl: $!&quot;</span><span class="sc">;</span></li></ol></pre><p>Here's an example of a semaphore:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">IPC::SysV</span> <span class="q">qw(IPC_CREAT)</span><span class="sc">;</span></li><li></li><li>    <span class="i">$IPC_KEY</span> = <span class="n">1234</span><span class="sc">;</span></li><li>    <span class="i">$id</span> = <a class="l_k" href="functions/semget.html">semget</a><span class="s">(</span><span class="i">$IPC_KEY</span><span class="cm">,</span> <span class="n">10</span><span class="cm">,</span> <span class="n">0666</span> | <span class="w">IPC_CREAT</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$id</span><span class="s">)</span>                    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;semget: $!&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;sem id $id\n&quot;</span><span class="sc">;</span></li></ol></pre><p>Put this code in a separate file to be run in more than one process.
Call the file <i>take</i>:</p>
<pre class="verbatim"><ol><li>    <span class="c"># create a semaphore</span></li><li></li><li>    <span class="i">$IPC_KEY</span> = <span class="n">1234</span><span class="sc">;</span></li><li>    <span class="i">$id</span> = <a class="l_k" href="functions/semget.html">semget</a><span class="s">(</span><span class="i">$IPC_KEY</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$id</span><span class="s">)</span>                    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;semget: $!&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="i">$semnum</span>  = <span class="n">0</span><span class="sc">;</span></li><li>    <span class="i">$semflag</span> = <span class="n">0</span><span class="sc">;</span></li><li></li><li>    <span class="c"># &quot;take&quot; semaphore</span></li><li>    <span class="c"># wait for semaphore to be zero</span></li><li>    <span class="i">$semop</span> = <span class="n">0</span><span class="sc">;</span></li><li>    <span class="i">$opstring1</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;s!s!s!&quot;</span><span class="cm">,</span> <span class="i">$semnum</span><span class="cm">,</span> <span class="i">$semop</span><span class="cm">,</span> <span class="i">$semflag</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="c"># Increment the semaphore count</span></li><li>    <span class="i">$semop</span> = <span class="n">1</span><span class="sc">;</span></li><li>    <span class="i">$opstring2</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;s!s!s!&quot;</span><span class="cm">,</span> <span class="i">$semnum</span><span class="cm">,</span> <span class="i">$semop</span><span class="cm">,</span>  <span class="i">$semflag</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$opstring</span>  = <span class="i">$opstring1</span> . <span class="i">$opstring2</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/semop.html">semop</a><span class="s">(</span><span class="i">$id</span><span class="cm">,</span> <span class="i">$opstring</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;semop: $!&quot;</span><span class="sc">;</span></li></ol></pre><p>Put this code in a separate file to be run in more than one process.
Call this file <i>give</i>:</p>
<pre class="verbatim"><ol><li>    <span class="c"># &quot;give&quot; the semaphore</span></li><li>    <span class="c"># run this in the original process and you will see</span></li><li>    <span class="c"># that the second process continues</span></li><li></li><li>    <span class="i">$IPC_KEY</span> = <span class="n">1234</span><span class="sc">;</span></li><li>    <span class="i">$id</span> = <a class="l_k" href="functions/semget.html">semget</a><span class="s">(</span><span class="i">$IPC_KEY</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/die.html">die</a> unless <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$id</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="i">$semnum</span>  = <span class="n">0</span><span class="sc">;</span></li><li>    <span class="i">$semflag</span> = <span class="n">0</span><span class="sc">;</span></li><li></li><li>    <span class="c"># Decrement the semaphore count</span></li><li>    <span class="i">$semop</span> = <span class="n">-1</span><span class="sc">;</span></li><li>    <span class="i">$opstring</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;s!s!s!&quot;</span><span class="cm">,</span> <span class="i">$semnum</span><span class="cm">,</span> <span class="i">$semop</span><span class="cm">,</span> <span class="i">$semflag</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/semop.html">semop</a><span class="s">(</span><span class="i">$id</span><span class="cm">,</span> <span class="i">$opstring</span><span class="s">)</span>   || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;semop: $!&quot;</span><span class="sc">;</span></li></ol></pre><p>The SysV IPC code above was written long ago, and it's definitely
clunky looking.  For a more modern look, see the IPC::SysV module.</p>
<p>A small example demonstrating SysV message queues:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">IPC::SysV</span> <span class="q">qw(IPC_PRIVATE IPC_RMID IPC_CREAT S_IRUSR S_IWUSR)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$id</span> = <a class="l_k" href="functions/msgget.html">msgget</a><span class="s">(</span><span class="w">IPC_PRIVATE</span><span class="cm">,</span> <span class="w">IPC_CREAT</span> | <span class="w">S_IRUSR</span> | <span class="w">S_IWUSR</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><span class="i">$id</span><span class="s">)</span>                || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;msgget failed: $!&quot;</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$sent</span>      = <span class="q">&quot;message&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$type_sent</span> = <span class="n">1234</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/msgsnd.html">msgsnd</a><span class="s">(</span><span class="i">$id</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;l! a*&quot;</span><span class="cm">,</span> <span class="i">$type_sent</span><span class="cm">,</span> <span class="i">$sent</span><span class="s">)</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span></li><li>                                || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;msgsnd failed: $!&quot;</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/msgrcv.html">msgrcv</a><span class="s">(</span><span class="i">$id</span><span class="cm">,</span> <a class="l_k" href="functions/my.html">my</a> <span class="i">$rcvd_buf</span><span class="cm">,</span> <span class="n">60</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span></li><li>                                || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;msgrcv failed: $!&quot;</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$type_rcvd</span><span class="cm">,</span> <span class="i">$rcvd</span><span class="s">)</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;l! a*&quot;</span><span class="cm">,</span> <span class="i">$rcvd_buf</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    if <span class="s">(</span><span class="i">$rcvd</span> eq <span class="i">$sent</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;okay\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span> else <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;not okay\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/msgctl.html">msgctl</a><span class="s">(</span><span class="i">$id</span><span class="cm">,</span> <span class="w">IPC_RMID</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span>    || <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;msgctl failed: $!\n&quot;</span><span class="sc">;</span></li></ol></pre><a name="NOTES"></a><h1>NOTES</h1>
<p>Most of these routines quietly but politely return <code class="inline"><a class="l_k" href="functions/undef.html">undef</a></code> when they
fail instead of causing your program to die right then and there due to
an uncaught exception.  (Actually, some of the new <i>Socket</i> conversion
functions do croak() on bad arguments.)  It is therefore essential to
check return values from these functions.  Always begin your socket
programs this way for optimal success, and don't forget to add the <b>-T</b>
taint-checking flag to the <code class="inline"><span class="c">#!</span></code>
 line for servers:</p>
<pre class="verbatim"><ol><li>    <span class="c">#!/usr/bin/perl -Tw</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">sigtrap</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Socket</span><span class="sc">;</span></li></ol></pre><a name="BUGS"></a><h1>BUGS</h1>
<p>These routines all create system-specific portability problems.  As noted
elsewhere, Perl is at the mercy of your C libraries for much of its system
behavior.  It's probably safest to assume broken SysV semantics for
signals and to stick with simple TCP and UDP socket operations; e.g., don't
try to pass open file descriptors over a local UDP datagram socket if you
want your code to stand a chance of being portable.</p>
<a name="AUTHOR"></a><h1>AUTHOR</h1>
<p>Tom Christiansen, with occasional vestiges of Larry Wall's original
version and suggestions from the Perl Porters.</p>
<a name="SEE-ALSO"></a><h1>SEE ALSO</h1>
<p>There's a lot more to networking than this, but this should get you
started.</p>
<p>For intrepid programmers, the indispensable textbook is <i>Unix Network
Programming, 2nd Edition, Volume 1</i> by W. Richard Stevens (published by
Prentice-Hall).  Most books on networking address the subject from the
perspective of a C programmer; translation to Perl is left as an exercise
for the reader.</p>
<p>The IO::Socket(3) manpage describes the object library, and the Socket(3)
manpage describes the low-level interface to sockets.  Besides the obvious
functions in <a href="perlfunc.html">perlfunc</a>, you should also check out the <i>modules</i> file at
your nearest CPAN site, especially
<a href="http://www.cpan.org/modules/00modlist.long.html#ID5_Networking_">http://www.cpan.org/modules/00modlist.long.html#ID5_Networking_</a>.
See <a href="perlmodlib.html">perlmodlib</a> or best yet, the <i>Perl FAQ</i> for a description
of what CPAN is and where to get it if the previous link doesn't work
for you.</p>
<p>Section 5 of CPAN's <i>modules</i> file is devoted to "Networking, Device
Control (modems), and Interprocess Communication", and contains numerous
unbundled modules numerous networking modules, Chat and Expect operations,
CGI programming, DCE, FTP, IPC, NNTP, Proxy, Ptty, RPC, SNMP, SMTP, Telnet,
Threads, and ToolTalk--to name just a few.</p>




  <div id="page_index" class="hud_container">
    <div id="page_index_header" class="hud_header">
      <div id="page_index_close" class="hud_close"><a href="#" onClick="pageIndex.hide();return false;"></a></div>
      <div id="page_index_title" class="hud_title"><span class="hud_span_top">Page index</span></div>
      <div id="page_index_topright" class="hud_topright"></div>
    </div>
    <div id="page_index_content" class="hud_content">
      <ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><li><a href="#Signals">Signals</a><ul><li><a href="#Handling-the-SIGHUP-Signal-in-Daemons">Handling the SIGHUP Signal in Daemons</a><li><a href="#Deferred-Signals-(Safe-Signals)">Deferred Signals (Safe Signals)</a></ul><li><a href="#Named-Pipes">Named Pipes</a><li><a href="#Using-open()-for-IPC">Using open() for IPC</a><ul><li><a href="#Filehandles">Filehandles</a><li><a href="#Background-Processes">Background Processes</a><li><a href="#Complete-Dissociation-of-Child-from-Parent">Complete Dissociation of Child from Parent</a><li><a href="#Safe-Pipe-Opens">Safe Pipe Opens</a><li><a href="#Avoiding-Pipe-Deadlocks">Avoiding Pipe Deadlocks</a><li><a href="#Bidirectional-Communication-with-Another-Process">Bidirectional Communication with Another Process</a><li><a href="#Bidirectional-Communication-with-Yourself">Bidirectional Communication with Yourself</a></ul><li><a href="#Sockets%3a-Client%2fServer-Communication">Sockets: Client/Server Communication</a><ul><li><a href="#Internet-Line-Terminators">Internet Line Terminators</a><li><a href="#Internet-TCP-Clients-and-Servers">Internet TCP Clients and Servers</a><li><a href="#Unix-Domain-TCP-Clients-and-Servers">Unix-Domain TCP Clients and Servers</a></ul><li><a href="#TCP-Clients-with-IO%3a%3aSocket">TCP Clients with IO::Socket</a><ul><li><a href="#A-Simple-Client">A Simple Client</a><li><a href="#A-Webget-Client">A Webget Client</a><li><a href="#Interactive-Client-with-IO%3a%3aSocket">Interactive Client with IO::Socket</a></ul><li><a href="#TCP-Servers-with-IO%3a%3aSocket">TCP Servers with IO::Socket</a><li><a href="#UDP%3a-Message-Passing">UDP: Message Passing</a><li><a href="#SysV-IPC">SysV IPC</a><li><a href="#NOTES">NOTES</a><li><a href="#BUGS">BUGS</a><li><a href="#AUTHOR">AUTHOR</a><li><a href="#SEE-ALSO">SEE ALSO</a></ul>
    </div>
    <div id="page_index_footer" class="hud_footer">
      <div id="page_index_bottomleft" class="hud_bottomleft"></div>
      <div id="page_index_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
      <div id="page_index_resize" class="hud_resize"></div>
    </div>
  </div>


	    &nbsp;
          </div>
          <div id="content_footer">
          </div>
        </div>
        <div class="clear"></div>
      </div>
      
    <div id="footer">
      <div id="footer_content">
        <div id="footer_strapline">
          perldoc.perl.org - Official documentation for the Perl programming language
        </div>
        <div id="footer_links">
          <div id="address">
            <p class="name">Contact details</p>
            <p class="address">
	      Site maintained by <a href="mailto:jj@jonallen.info">Jon Allen (JJ)</a><br>
	    </p>
            <p class="contact">
              Documentation maintained by the <a href="http://lists.cpan.org/showlist.cgi?name=perl5-porters">Perl 5 Porters</a>
            </p>
          </div>
          <ul class="f1">
            <li>Manual
              <ul class="f2">
                <li><a href="index-overview.html">Overview</a>
                <li><a href="index-tutorials.html">Tutorials</a>
                <li><a href="index-faq.html">FAQs</a>
                <li><a href="index-history.html">Changes</a>
              </ul>
            <li>Reference
              <ul class="f2">
                <li><a href="index-language.html">Language</a>
                <li><a href="index-functions.html">Functions</a>
                <li><a href="perlop.html">Operators</a>
                <li><a href="perlvar.html">Variables</a>
              </ul>
            <li>Modules
              <ul class="f2">
                <li><a href="index-modules-A.html">Modules</a>
                <li><a href="index-pragmas.html">Pragmas</a>
                <li><a href="index-utilities.html">Utilities</a>
              </ul>
            <li>Misc
              <ul class="f2">
                <li><a href="index-licence.html">License</a>
                <li><a href="index-internals.html">Internals</a>
                <li><a href="index-platforms.html">Platforms</a>
              </ul>          </ul>
          <div class="clear"></div>
        </div>
      </div>
      <div id="footer_end">
      </div>
    </div>
      
    </div>
      <script language="JavaScript" type="text/javascript" src="static/exploreperl.js"></script>
      <script language="JavaScript" src="static/combined-20100403.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
  perldoc.setPath(0);
  perldoc.pageName    = 'perlipc';
  perldoc.pageAddress = 'perlipc.html';
  perldoc.contentPage = 1;
  explorePerl.render();
  explorePerl.addEvents('explore_anchor');
</script>
    
  </body>
</html>