Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perlipc.html
blob22e7d68d036fee03548773341218fa05986bf11a
1 <?xml version="1.0" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title>perlipc - Perl interprocess communication</title>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7 <link rev="made" href="mailto:" />
8 </head>
10 <body style="background-color: white">
11 <table border="0" width="100%" cellspacing="0" cellpadding="3">
12 <tr><td class="block" style="background-color: #cccccc" valign="middle">
13 <big><strong><span class="block">&nbsp;perlipc - Perl interprocess communication</span></strong></big>
14 </td></tr>
15 </table>
17 <p><a name="__index__"></a></p>
18 <!-- INDEX BEGIN -->
20 <ul>
22 <li><a href="#name">NAME</a></li>
23 <li><a href="#description">DESCRIPTION</a></li>
24 <li><a href="#signals">Signals</a></li>
25 <ul>
27 <li><a href="#handling_the_sighup_signal_in_daemons">Handling the SIGHUP Signal in Daemons</a></li>
28 </ul>
30 <li><a href="#named_pipes">Named Pipes</a></li>
31 <ul>
33 <li><a href="#deferred_signals__safe_signals_">Deferred Signals (Safe Signals)</a></li>
34 </ul>
36 <li><a href="#using_open___for_ipc">Using <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open()</code></a> for IPC</a></li>
37 <ul>
39 <li><a href="#filehandles">Filehandles</a></li>
40 <li><a href="#background_processes">Background Processes</a></li>
41 <li><a href="#complete_dissociation_of_child_from_parent">Complete Dissociation of Child from Parent</a></li>
42 <li><a href="#safe_pipe_opens">Safe Pipe Opens</a></li>
43 <li><a href="#bidirectional_communication_with_another_process">Bidirectional Communication with Another Process</a></li>
44 <li><a href="#bidirectional_communication_with_yourself">Bidirectional Communication with Yourself</a></li>
45 </ul>
47 <li><a href="#sockets__client_server_communication">Sockets: Client/Server Communication</a></li>
48 <ul>
50 <li><a href="#internet_line_terminators">Internet Line Terminators</a></li>
51 <li><a href="#internet_tcp_clients_and_servers">Internet TCP Clients and Servers</a></li>
52 <li><a href="#unixdomain_tcp_clients_and_servers">Unix-Domain TCP Clients and Servers</a></li>
53 </ul>
55 <li><a href="#tcp_clients_with_io__socket">TCP Clients with IO::Socket</a></li>
56 <ul>
58 <li><a href="#a_simple_client">A Simple Client</a></li>
59 <li><a href="#a_webget_client">A Webget Client</a></li>
60 <li><a href="#interactive_client_with_io__socket">Interactive Client with IO::Socket</a></li>
61 </ul>
63 <li><a href="#tcp_servers_with_io__socket">TCP Servers with IO::Socket</a></li>
64 <li><a href="#udp__message_passing">UDP: Message Passing</a></li>
65 <li><a href="#sysv_ipc">SysV IPC</a></li>
66 <li><a href="#notes">NOTES</a></li>
67 <li><a href="#bugs">BUGS</a></li>
68 <li><a href="#author">AUTHOR</a></li>
69 <li><a href="#see_also">SEE ALSO</a></li>
70 </ul>
71 <!-- INDEX END -->
73 <hr />
74 <p>
75 </p>
76 <h1><a name="name">NAME</a></h1>
77 <p>perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets, and semaphores)</p>
78 <p>
79 </p>
80 <hr />
81 <h1><a name="description">DESCRIPTION</a></h1>
82 <p>The basic IPC facilities of Perl are built out of the good old Unix
83 signals, named pipes, pipe opens, the Berkeley socket routines, and SysV
84 IPC calls. Each is used in slightly different situations.</p>
85 <p>
86 </p>
87 <hr />
88 <h1><a name="signals">Signals</a></h1>
89 <p>Perl uses a simple signal handling model: the %SIG hash contains names
90 or references of user-installed signal handlers. These handlers will
91 be called with an argument which is the name of the signal that
92 triggered it. A signal may be generated intentionally from a
93 particular keyboard sequence like control-C or control-Z, sent to you
94 from another process, or triggered automatically by the kernel when
95 special events transpire, like a child process exiting, your process
96 running out of stack space, or hitting file size limit.</p>
97 <p>For example, to trap an interrupt signal, set up a handler like this:</p>
98 <pre>
99 sub catch_zap {
100 my $signame = shift;
101 $shucks++;
102 die &quot;Somebody sent me a SIG$signame&quot;;
104 $SIG{INT} = 'catch_zap'; # could fail in modules
105 $SIG{INT} = \&amp;catch_zap; # best strategy</pre>
106 <p>Prior to Perl 5.7.3 it was necessary to do as little as you possibly
107 could in your handler; notice how all we do is set a global variable
108 and then raise an exception. That's because on most systems,
109 libraries are not re-entrant; particularly, memory allocation and I/O
110 routines are not. That meant that doing nearly <em>anything</em> in your
111 handler could in theory trigger a memory fault and subsequent core
112 dump - see <a href="#deferred_signals__safe_signals_">Deferred Signals (Safe Signals)</a> below.</p>
113 <p>The names of the signals are the ones listed out by <code>kill -l</code> on your
114 system, or you can retrieve them from the Config module. Set up an
115 @signame list indexed by number to get the name and a %signo table
116 indexed by name to get the number:</p>
117 <pre>
118 use Config;
119 defined $Config{sig_name} || die &quot;No sigs?&quot;;
120 foreach $name (split(' ', $Config{sig_name})) {
121 $signo{$name} = $i;
122 $signame[$i] = $name;
123 $i++;
124 }</pre>
125 <p>So to check whether signal 17 and SIGALRM were the same, do just this:</p>
126 <pre>
127 print &quot;signal #17 = $signame[17]\n&quot;;
128 if ($signo{ALRM}) {
129 print &quot;SIGALRM is $signo{ALRM}\n&quot;;
130 }</pre>
131 <p>You may also choose to assign the strings <code>'IGNORE'</code> or <code>'DEFAULT'</code> as
132 the handler, in which case Perl will try to discard the signal or do the
133 default thing.</p>
134 <p>On most Unix platforms, the <code>CHLD</code> (sometimes also known as <code>CLD</code>) signal
135 has special behavior with respect to a value of <code>'IGNORE'</code>.
136 Setting <code>$SIG{CHLD}</code> to <code>'IGNORE'</code> on such a platform has the effect of
137 not creating zombie processes when the parent process fails to <code>wait()</code>
138 on its child processes (i.e. child processes are automatically reaped).
139 Calling <code>wait()</code> with <code>$SIG{CHLD}</code> set to <code>'IGNORE'</code> usually returns
140 <code>-1</code> on such platforms.</p>
141 <p>Some signals can be neither trapped nor ignored, such as
142 the KILL and STOP (but not the TSTP) signals. One strategy for
143 temporarily ignoring signals is to use a <code>local()</code> statement, which will be
144 automatically restored once your block is exited. (Remember that <code>local()</code>
145 values are ``inherited'' by functions called from within that block.)</p>
146 <pre>
147 sub precious {
148 local $SIG{INT} = 'IGNORE';
149 &amp;more_functions;
151 sub more_functions {
152 # interrupts still ignored, for now...
153 }</pre>
154 <p>Sending a signal to a negative process ID means that you send the signal
155 to the entire Unix process-group. This code sends a hang-up signal to all
156 processes in the current process group (and sets $SIG{HUP} to IGNORE so
157 it doesn't kill itself):</p>
158 <pre>
160 local $SIG{HUP} = 'IGNORE';
161 kill HUP =&gt; -$$;
162 # snazzy writing of: kill('HUP', -$$)
163 }</pre>
164 <p>Another interesting signal to send is signal number zero. This doesn't
165 actually affect a child process, but instead checks whether it's alive
166 or has changed its UID.</p>
167 <pre>
168 unless (kill 0 =&gt; $kid_pid) {
169 warn &quot;something wicked happened to $kid_pid&quot;;
170 }</pre>
171 <p>When directed at a process whose UID is not identical to that
172 of the sending process, signal number zero may fail because
173 you lack permission to send the signal, even though the process is alive.
174 You may be able to determine the cause of failure using <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>%!</code></a>.</p>
175 <pre>
176 unless (kill 0 =&gt; $pid or $!{EPERM}) {
177 warn &quot;$pid looks dead&quot;;
178 }</pre>
179 <p>You might also want to employ anonymous functions for simple signal
180 handlers:</p>
181 <pre>
182 $SIG{INT} = sub { die &quot;\nOutta here!\n&quot; };</pre>
183 <p>But that will be problematic for the more complicated handlers that need
184 to reinstall themselves. Because Perl's signal mechanism is currently
185 based on the <code>signal(3)</code> function from the C library, you may sometimes be so
186 misfortunate as to run on systems where that function is ``broken'', that
187 is, it behaves in the old unreliable SysV way rather than the newer, more
188 reasonable BSD and POSIX fashion. So you'll see defensive people writing
189 signal handlers like this:</p>
190 <pre>
191 sub REAPER {
192 $waitedpid = wait;
193 # loathe sysV: it makes us not only reinstate
194 # the handler, but place it after the wait
195 $SIG{CHLD} = \&amp;REAPER;
197 $SIG{CHLD} = \&amp;REAPER;
198 # now do something that forks...</pre>
199 <p>or better still:</p>
200 <pre>
201 use POSIX &quot;:sys_wait_h&quot;;
202 sub REAPER {
203 my $child;
204 # If a second child dies while in the signal handler caused by the
205 # first death, we won't get another signal. So must loop here else
206 # we will leave the unreaped child as a zombie. And the next time
207 # two children die we get another zombie. And so on.
208 while (($child = waitpid(-1,WNOHANG)) &gt; 0) {
209 $Kid_Status{$child} = $?;
211 $SIG{CHLD} = \&amp;REAPER; # still loathe sysV
213 $SIG{CHLD} = \&amp;REAPER;
214 # do something that forks...</pre>
215 <p>Signal handling is also used for timeouts in Unix, While safely
216 protected within an <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_eval"><code>eval{}</code></a> block, you set a signal handler to trap
217 alarm signals and then schedule to have one delivered to you in some
218 number of seconds. Then try your blocking operation, clearing the alarm
219 when it's done but not before you've exited your <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_eval"><code>eval{}</code></a> block. If it
220 goes off, you'll use <code>die()</code> to jump out of the block, much as you might
221 using <code>longjmp()</code> or <code>throw()</code> in other languages.</p>
222 <p>Here's an example:</p>
223 <pre>
224 eval {
225 local $SIG{ALRM} = sub { die &quot;alarm clock restart&quot; };
226 alarm 10;
227 flock(FH, 2); # blocking write lock
228 alarm 0;
230 if ($@ and $@ !~ /alarm clock restart/) { die }</pre>
231 <p>If the operation being timed out is <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_system"><code>system()</code></a> or qx(), this technique
232 is liable to generate zombies. If this matters to you, you'll
233 need to do your own <code>fork()</code> and exec(), and kill the errant child process.</p>
234 <p>For more complex signal handling, you might see the standard POSIX
235 module. Lamentably, this is almost entirely undocumented, but
236 the <em>t/lib/posix.t</em> file from the Perl source distribution has some
237 examples in it.</p>
239 </p>
240 <h2><a name="handling_the_sighup_signal_in_daemons">Handling the SIGHUP Signal in Daemons</a></h2>
241 <p>A process that usually starts when the system boots and shuts down
242 when the system is shut down is called a daemon (Disk And Execution
243 MONitor). If a daemon process has a configuration file which is
244 modified after the process has been started, there should be a way to
245 tell that process to re-read its configuration file, without stopping
246 the process. Many daemons provide this mechanism using the <code>SIGHUP</code>
247 signal handler. When you want to tell the daemon to re-read the file
248 you simply send it the <code>SIGHUP</code> signal.</p>
249 <p>Not all platforms automatically reinstall their (native) signal
250 handlers after a signal delivery. This means that the handler works
251 only the first time the signal is sent. The solution to this problem
252 is to use <code>POSIX</code> signal handlers if available, their behaviour
253 is well-defined.</p>
254 <p>The following example implements a simple daemon, which restarts
255 itself every time the <code>SIGHUP</code> signal is received. The actual code is
256 located in the subroutine <code>code()</code>, which simply prints some debug
257 info to show that it works and should be replaced with the real code.</p>
258 <pre>
259 #!/usr/bin/perl -w</pre>
260 <pre>
261 use POSIX ();
262 use FindBin ();
263 use File::Basename ();
264 use File::Spec::Functions;</pre>
265 <pre>
266 $|=1;</pre>
267 <pre>
268 # make the daemon cross-platform, so exec always calls the script
269 # itself with the right path, no matter how the script was invoked.
270 my $script = File::Basename::basename($0);
271 my $SELF = catfile $FindBin::Bin, $script;</pre>
272 <pre>
273 # POSIX unmasks the sigprocmask properly
274 my $sigset = POSIX::SigSet-&gt;new();
275 my $action = POSIX::SigAction-&gt;new('sigHUP_handler',
276 $sigset,
277 &amp;POSIX::SA_NODEFER);
278 POSIX::sigaction(&amp;POSIX::SIGHUP, $action);</pre>
279 <pre>
280 sub sigHUP_handler {
281 print &quot;got SIGHUP\n&quot;;
282 exec($SELF, @ARGV) or die &quot;Couldn't restart: $!\n&quot;;
283 }</pre>
284 <pre>
285 code();</pre>
286 <pre>
287 sub code {
288 print &quot;PID: $$\n&quot;;
289 print &quot;ARGV: @ARGV\n&quot;;
290 my $c = 0;
291 while (++$c) {
292 sleep 2;
293 print &quot;$c\n&quot;;
296 __END__</pre>
298 </p>
299 <hr />
300 <h1><a name="named_pipes">Named Pipes</a></h1>
301 <p>A named pipe (often referred to as a FIFO) is an old Unix IPC
302 mechanism for processes communicating on the same machine. It works
303 just like a regular, connected anonymous pipes, except that the
304 processes rendezvous using a filename and don't have to be related.</p>
305 <p>To create a named pipe, use the <code>POSIX::mkfifo()</code> function.</p>
306 <pre>
307 use POSIX qw(mkfifo);
308 mkfifo($path, 0700) or die &quot;mkfifo $path failed: $!&quot;;</pre>
309 <p>You can also use the Unix command <code>mknod(1)</code> or on some
310 systems, mkfifo(1). These may not be in your normal path.</p>
311 <pre>
312 # system return val is backwards, so &amp;&amp; not ||
314 $ENV{PATH} .= &quot;:/etc:/usr/etc&quot;;
315 if ( system('mknod', $path, 'p')
316 &amp;&amp; system('mkfifo', $path) )
318 die &quot;mk{nod,fifo} $path failed&quot;;
319 }</pre>
320 <p>A fifo is convenient when you want to connect a process to an unrelated
321 one. When you open a fifo, the program will block until there's something
322 on the other end.</p>
323 <p>For example, let's say you'd like to have your <em>.signature</em> file be a
324 named pipe that has a Perl program on the other end. Now every time any
325 program (like a mailer, news reader, finger program, etc.) tries to read
326 from that file, the reading program will block and your program will
327 supply the new signature. We'll use the pipe-checking file test <strong>-p</strong>
328 to find out whether anyone (or anything) has accidentally removed our fifo.</p>
329 <pre>
330 chdir; # go home
331 $FIFO = '.signature';</pre>
332 <pre>
333 while (1) {
334 unless (-p $FIFO) {
335 unlink $FIFO;
336 require POSIX;
337 POSIX::mkfifo($FIFO, 0700)
338 or die &quot;can't mkfifo $FIFO: $!&quot;;
339 }</pre>
340 <pre>
341 # next line blocks until there's a reader
342 open (FIFO, &quot;&gt; $FIFO&quot;) || die &quot;can't write $FIFO: $!&quot;;
343 print FIFO &quot;John Smith (smith\@host.org)\n&quot;, `fortune -s`;
344 close FIFO;
345 sleep 2; # to avoid dup signals
346 }</pre>
348 </p>
349 <h2><a name="deferred_signals__safe_signals_">Deferred Signals (Safe Signals)</a></h2>
350 <p>In Perls before Perl 5.7.3 by installing Perl code to deal with
351 signals, you were exposing yourself to danger from two things. First,
352 few system library functions are re-entrant. If the signal interrupts
353 while Perl is executing one function (like <code>malloc(3)</code> or printf(3)),
354 and your signal handler then calls the same function again, you could
355 get unpredictable behavior--often, a core dump. Second, Perl isn't
356 itself re-entrant at the lowest levels. If the signal interrupts Perl
357 while Perl is changing its own internal data structures, similarly
358 unpredictable behaviour may result.</p>
359 <p>There were two things you could do, knowing this: be paranoid or be
360 pragmatic. The paranoid approach was to do as little as possible in your
361 signal handler. Set an existing integer variable that already has a
362 value, and return. This doesn't help you if you're in a slow system call,
363 which will just restart. That means you have to <code>die</code> to <code>longjump(3)</code> out
364 of the handler. Even this is a little cavalier for the true paranoiac,
365 who avoids <code>die</code> in a handler because the system <em>is</em> out to get you.
366 The pragmatic approach was to say ``I know the risks, but prefer the
367 convenience'', and to do anything you wanted in your signal handler,
368 and be prepared to clean up core dumps now and again.</p>
369 <p>In Perl 5.7.3 and later to avoid these problems signals are
370 ``deferred''-- that is when the signal is delivered to the process by
371 the system (to the C code that implements Perl) a flag is set, and the
372 handler returns immediately. Then at strategic ``safe'' points in the
373 Perl interpreter (e.g. when it is about to execute a new opcode) the
374 flags are checked and the Perl level handler from %SIG is
375 executed. The ``deferred'' scheme allows much more flexibility in the
376 coding of signal handler as we know Perl interpreter is in a safe
377 state, and that we are not in a system library function when the
378 handler is called. However the implementation does differ from
379 previous Perls in the following ways:</p>
380 <dl>
381 <dt><strong><a name="item_long_running_opcodes">Long running opcodes</a></strong>
383 <dd>
384 <p>As Perl interpreter only looks at the signal flags when it about to
385 execute a new opcode if a signal arrives during a long running opcode
386 (e.g. a regular expression operation on a very large string) then
387 signal will not be seen until operation completes.</p>
388 </dd>
389 </li>
390 <dt><strong><a name="item_interrupting_io">Interrupting IO</a></strong>
392 <dd>
393 <p>When a signal is delivered (e.g. INT control-C) the operating system
394 breaks into IO operations like <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_read"><code>read</code></a> (used to implement Perls
395 &lt;&gt; operator). On older Perls the handler was called
396 immediately (and as <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_read"><code>read</code></a> is not ``unsafe'' this worked well). With
397 the ``deferred'' scheme the handler is not called immediately, and if
398 Perl is using system's <code>stdio</code> library that library may re-start the
399 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_read"><code>read</code></a> without returning to Perl and giving it a chance to call the
400 %SIG handler. If this happens on your system the solution is to use
401 <code>:perlio</code> layer to do IO - at least on those handles which you want
402 to be able to break into with signals. (The <code>:perlio</code> layer checks
403 the signal flags and calls %SIG handlers before resuming IO operation.)</p>
404 </dd>
405 <dd>
406 <p>Note that the default in Perl 5.7.3 and later is to automatically use
407 the <code>:perlio</code> layer.</p>
408 </dd>
409 <dd>
410 <p>Note that some networking library functions like <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_gethostbyname"><code>gethostbyname()</code></a> are
411 known to have their own implementations of timeouts which may conflict
412 with your timeouts. If you are having problems with such functions,
413 you can try using the POSIX <code>sigaction()</code> function, which bypasses the
414 Perl safe signals (note that this means subjecting yourself to
415 possible memory corruption, as described above). Instead of setting
416 <code>$SIG{ALRM}</code>:</p>
417 </dd>
418 <dd>
419 <pre>
420 local $SIG{ALRM} = sub { die &quot;alarm&quot; };</pre>
421 </dd>
422 <dd>
423 <p>try something like the following:</p>
424 </dd>
425 <dd>
426 <pre>
427 use POSIX qw(SIGALRM);
428 POSIX::sigaction(SIGALRM,
429 POSIX::SigAction-&gt;new(sub { die &quot;alarm&quot; }))
430 or die &quot;Error setting SIGALRM handler: $!\n&quot;;</pre>
431 </dd>
432 </li>
433 <dt><strong><a name="item_restartable_system_calls">Restartable system calls</a></strong>
435 <dd>
436 <p>On systems that supported it, older versions of Perl used the
437 SA_RESTART flag when installing %SIG handlers. This meant that
438 restartable system calls would continue rather than returning when
439 a signal arrived. In order to deliver deferred signals promptly,
440 Perl 5.7.3 and later do <em>not</em> use SA_RESTART. Consequently,
441 restartable system calls can fail (with $! set to <code>EINTR</code>) in places
442 where they previously would have succeeded.</p>
443 </dd>
444 <dd>
445 <p>Note that the default <code>:perlio</code> layer will retry <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_read"><code>read</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_write"><code>write</code></a>
446 and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_close"><code>close</code></a> as described above and that interrupted <code>wait</code> and
447 <code>waitpid</code> calls will always be retried.</p>
448 </dd>
449 </li>
450 <dt><strong><a name="item_signals_as__22faults_22">Signals as ``faults''</a></strong>
452 <dd>
453 <p>Certain signals e.g. SEGV, ILL, BUS are generated as a result of
454 virtual memory or other ``faults''. These are normally fatal and there
455 is little a Perl-level handler can do with them. (In particular the
456 old signal scheme was particularly unsafe in such cases.) However if
457 a %SIG handler is set the new scheme simply sets a flag and returns as
458 described above. This may cause the operating system to try the
459 offending machine instruction again and - as nothing has changed - it
460 will generate the signal again. The result of this is a rather odd
461 ``loop''. In future Perl's signal mechanism may be changed to avoid this
462 - perhaps by simply disallowing %SIG handlers on signals of that
463 type. Until then the work-round is not to set a %SIG handler on those
464 signals. (Which signals they are is operating system dependent.)</p>
465 </dd>
466 </li>
467 <dt><strong><a name="item_signals_triggered_by_operating_system_state">Signals triggered by operating system state</a></strong>
469 <dd>
470 <p>On some operating systems certain signal handlers are supposed to ``do
471 something'' before returning. One example can be CHLD or CLD which
472 indicates a child process has completed. On some operating systems the
473 signal handler is expected to <code>wait</code> for the completed child
474 process. On such systems the deferred signal scheme will not work for
475 those signals (it does not do the <code>wait</code>). Again the failure will
476 look like a loop as the operating system will re-issue the signal as
477 there are un-waited-for completed child processes.</p>
478 </dd>
479 </li>
480 </dl>
481 <p>If you want the old signal behaviour back regardless of possible
482 memory corruption, set the environment variable <code>PERL_SIGNALS</code> to
483 <code>&quot;unsafe&quot;</code> (a new feature since Perl 5.8.1).</p>
485 </p>
486 <hr />
487 <h1><a name="using_open___for_ipc">Using <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open()</code></a> for IPC</a></h1>
488 <p>Perl's basic <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open()</code></a> statement can also be used for unidirectional
489 interprocess communication by either appending or prepending a pipe
490 symbol to the second argument to open(). Here's how to start
491 something up in a child process you intend to write to:</p>
492 <pre>
493 open(SPOOLER, &quot;| cat -v | lpr -h 2&gt;/dev/null&quot;)
494 || die &quot;can't fork: $!&quot;;
495 local $SIG{PIPE} = sub { die &quot;spooler pipe broke&quot; };
496 print SPOOLER &quot;stuff\n&quot;;
497 close SPOOLER || die &quot;bad spool: $! $?&quot;;</pre>
498 <p>And here's how to start up a child process you intend to read from:</p>
499 <pre>
500 open(STATUS, &quot;netstat -an 2&gt;&amp;1 |&quot;)
501 || die &quot;can't fork: $!&quot;;
502 while (&lt;STATUS&gt;) {
503 next if /^(tcp|udp)/;
504 print;
506 close STATUS || die &quot;bad netstat: $! $?&quot;;</pre>
507 <p>If one can be sure that a particular program is a Perl script that is
508 expecting filenames in @ARGV, the clever programmer can write something
509 like this:</p>
510 <pre>
511 % program f1 &quot;cmd1|&quot; - f2 &quot;cmd2|&quot; f3 &lt; tmpfile</pre>
512 <p>and irrespective of which shell it's called from, the Perl program will
513 read from the file <em>f1</em>, the process <em>cmd1</em>, standard input (<em>tmpfile</em>
514 in this case), the <em>f2</em> file, the <em>cmd2</em> command, and finally the <em>f3</em>
515 file. Pretty nifty, eh?</p>
516 <p>You might notice that you could use backticks for much the
517 same effect as opening a pipe for reading:</p>
518 <pre>
519 print grep { !/^(tcp|udp)/ } `netstat -an 2&gt;&amp;1`;
520 die &quot;bad netstat&quot; if $?;</pre>
521 <p>While this is true on the surface, it's much more efficient to process the
522 file one line or record at a time because then you don't have to read the
523 whole thing into memory at once. It also gives you finer control of the
524 whole process, letting you to kill off the child process early if you'd
525 like.</p>
526 <p>Be careful to check both the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open()</code></a> and the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_close"><code>close()</code></a> return values. If
527 you're <em>writing</em> to a pipe, you should also trap SIGPIPE. Otherwise,
528 think of what happens when you start up a pipe to a command that doesn't
529 exist: the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open()</code></a> will in all likelihood succeed (it only reflects the
530 fork()'s success), but then your output will fail--spectacularly. Perl
531 can't know whether the command worked because your command is actually
532 running in a separate process whose <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_exec"><code>exec()</code></a> might have failed. Therefore,
533 while readers of bogus commands return just a quick end of file, writers
534 to bogus command will trigger a signal they'd better be prepared to
535 handle. Consider:</p>
536 <pre>
537 open(FH, &quot;|bogus&quot;) or die &quot;can't fork: $!&quot;;
538 print FH &quot;bang\n&quot; or die &quot;can't write: $!&quot;;
539 close FH or die &quot;can't close: $!&quot;;</pre>
540 <p>That won't blow up until the close, and it will blow up with a SIGPIPE.
541 To catch it, you could use this:</p>
542 <pre>
543 $SIG{PIPE} = 'IGNORE';
544 open(FH, &quot;|bogus&quot;) or die &quot;can't fork: $!&quot;;
545 print FH &quot;bang\n&quot; or die &quot;can't write: $!&quot;;
546 close FH or die &quot;can't close: status=$?&quot;;</pre>
548 </p>
549 <h2><a name="filehandles">Filehandles</a></h2>
550 <p>Both the main process and any child processes it forks share the same
551 STDIN, STDOUT, and STDERR filehandles. If both processes try to access
552 them at once, strange things can happen. You may also want to close
553 or reopen the filehandles for the child. You can get around this by
554 opening your pipe with open(), but on some systems this means that the
555 child process cannot outlive the parent.</p>
557 </p>
558 <h2><a name="background_processes">Background Processes</a></h2>
559 <p>You can run a command in the background with:</p>
560 <pre>
561 system(&quot;cmd &amp;&quot;);</pre>
562 <p>The command's STDOUT and STDERR (and possibly STDIN, depending on your
563 shell) will be the same as the parent's. You won't need to catch
564 SIGCHLD because of the double-fork taking place (see below for more
565 details).</p>
567 </p>
568 <h2><a name="complete_dissociation_of_child_from_parent">Complete Dissociation of Child from Parent</a></h2>
569 <p>In some cases (starting server processes, for instance) you'll want to
570 completely dissociate the child process from the parent. This is
571 often called daemonization. A well behaved daemon will also <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_chdir"><code>chdir()</code></a>
572 to the root directory (so it doesn't prevent unmounting the filesystem
573 containing the directory from which it was launched) and redirect its
574 standard file descriptors from and to <em>/dev/null</em> (so that random
575 output doesn't wind up on the user's terminal).</p>
576 <pre>
577 use POSIX 'setsid';</pre>
578 <pre>
579 sub daemonize {
580 chdir '/' or die &quot;Can't chdir to /: $!&quot;;
581 open STDIN, '/dev/null' or die &quot;Can't read /dev/null: $!&quot;;
582 open STDOUT, '&gt;/dev/null'
583 or die &quot;Can't write to /dev/null: $!&quot;;
584 defined(my $pid = fork) or die &quot;Can't fork: $!&quot;;
585 exit if $pid;
586 setsid or die &quot;Can't start a new session: $!&quot;;
587 open STDERR, '&gt;&amp;STDOUT' or die &quot;Can't dup stdout: $!&quot;;
588 }</pre>
589 <p>The <code>fork()</code> has to come before the <code>setsid()</code> to ensure that you aren't a
590 process group leader (the <code>setsid()</code> will fail if you are). If your
591 system doesn't have the <code>setsid()</code> function, open <em>/dev/tty</em> and use the
592 <code>TIOCNOTTY</code> <code>ioctl()</code> on it instead. See <em>tty(4)</em> for details.</p>
593 <p>Non-Unix users should check their Your_OS::Process module for other
594 solutions.</p>
596 </p>
597 <h2><a name="safe_pipe_opens">Safe Pipe Opens</a></h2>
598 <p>Another interesting approach to IPC is making your single program go
599 multiprocess and communicate between (or even amongst) yourselves. The
600 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open()</code></a> function will accept a file argument of either <code>&quot;-|&quot;</code> or <code>&quot;|-&quot;</code>
601 to do a very interesting thing: it forks a child connected to the
602 filehandle you've opened. The child is running the same program as the
603 parent. This is useful for safely opening a file when running under an
604 assumed UID or GID, for example. If you open a pipe <em>to</em> minus, you can
605 write to the filehandle you opened and your kid will find it in his
606 STDIN. If you open a pipe <em>from</em> minus, you can read from the filehandle
607 you opened whatever your kid writes to his STDOUT.</p>
608 <pre>
609 use English '-no_match_vars';
610 my $sleep_count = 0;</pre>
611 <pre>
612 do {
613 $pid = open(KID_TO_WRITE, &quot;|-&quot;);
614 unless (defined $pid) {
615 warn &quot;cannot fork: $!&quot;;
616 die &quot;bailing out&quot; if $sleep_count++ &gt; 6;
617 sleep 10;
619 } until defined $pid;</pre>
620 <pre>
621 if ($pid) { # parent
622 print KID_TO_WRITE @some_data;
623 close(KID_TO_WRITE) || warn &quot;kid exited $?&quot;;
624 } else { # child
625 ($EUID, $EGID) = ($UID, $GID); # suid progs only
626 open (FILE, &quot;&gt; /safe/file&quot;)
627 || die &quot;can't open /safe/file: $!&quot;;
628 while (&lt;STDIN&gt;) {
629 print FILE; # child's STDIN is parent's KID
631 exit; # don't forget this
632 }</pre>
633 <p>Another common use for this construct is when you need to execute
634 something without the shell's interference. With system(), it's
635 straightforward, but you can't use a pipe open or backticks safely.
636 That's because there's no way to stop the shell from getting its hands on
637 your arguments. Instead, use lower-level control to call <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_exec"><code>exec()</code></a> directly.</p>
638 <p>Here's a safe backtick or pipe open for read:</p>
639 <pre>
640 # add error processing as above
641 $pid = open(KID_TO_READ, &quot;-|&quot;);</pre>
642 <pre>
643 if ($pid) { # parent
644 while (&lt;KID_TO_READ&gt;) {
645 # do something interesting
647 close(KID_TO_READ) || warn &quot;kid exited $?&quot;;</pre>
648 <pre>
649 } else { # child
650 ($EUID, $EGID) = ($UID, $GID); # suid only
651 exec($program, @options, @args)
652 || die &quot;can't exec program: $!&quot;;
653 # NOTREACHED
654 }</pre>
655 <p>And here's a safe pipe open for writing:</p>
656 <pre>
657 # add error processing as above
658 $pid = open(KID_TO_WRITE, &quot;|-&quot;);
659 $SIG{PIPE} = sub { die &quot;whoops, $program pipe broke&quot; };</pre>
660 <pre>
661 if ($pid) { # parent
662 for (@data) {
663 print KID_TO_WRITE;
665 close(KID_TO_WRITE) || warn &quot;kid exited $?&quot;;</pre>
666 <pre>
667 } else { # child
668 ($EUID, $EGID) = ($UID, $GID);
669 exec($program, @options, @args)
670 || die &quot;can't exec program: $!&quot;;
671 # NOTREACHED
672 }</pre>
673 <p>Since Perl 5.8.0, you can also use the list form of <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open</code></a> for pipes :
674 the syntax</p>
675 <pre>
676 open KID_PS, &quot;-|&quot;, &quot;ps&quot;, &quot;aux&quot; or die $!;</pre>
677 <p>forks the <code>ps(1)</code> command (without spawning a shell, as there are more than
678 three arguments to open()), and reads its standard output via the
679 <code>KID_PS</code> filehandle. The corresponding syntax to write to command
680 pipes (with <code>&quot;|-&quot;</code> in place of <code>&quot;-|&quot;</code>) is also implemented.</p>
681 <p>Note that these operations are full Unix forks, which means they may not be
682 correctly implemented on alien systems. Additionally, these are not true
683 multithreading. If you'd like to learn more about threading, see the
684 <em>modules</em> file mentioned below in the SEE ALSO section.</p>
686 </p>
687 <h2><a name="bidirectional_communication_with_another_process">Bidirectional Communication with Another Process</a></h2>
688 <p>While this works reasonably well for unidirectional communication, what
689 about bidirectional communication? The obvious thing you'd like to do
690 doesn't actually work:</p>
691 <pre>
692 open(PROG_FOR_READING_AND_WRITING, &quot;| some program |&quot;)</pre>
693 <p>and if you forget to use the <code>use warnings</code> pragma or the <strong>-w</strong> flag,
694 then you'll miss out entirely on the diagnostic message:</p>
695 <pre>
696 Can't do bidirectional pipe at -e line 1.</pre>
697 <p>If you really want to, you can use the standard <code>open2()</code> library function
698 to catch both ends. There's also an <code>open3()</code> for tridirectional I/O so you
699 can also catch your child's STDERR, but doing so would then require an
700 awkward <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_select"><code>select()</code></a> loop and wouldn't allow you to use normal Perl input
701 operations.</p>
702 <p>If you look at its source, you'll see that <code>open2()</code> uses low-level
703 primitives like Unix <code>pipe()</code> and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_exec"><code>exec()</code></a> calls to create all the connections.
704 While it might have been slightly more efficient by using socketpair(), it
705 would have then been even less portable than it already is. The <code>open2()</code>
706 and <code>open3()</code> functions are unlikely to work anywhere except on a Unix
707 system or some other one purporting to be POSIX compliant.</p>
708 <p>Here's an example of using open2():</p>
709 <pre>
710 use FileHandle;
711 use IPC::Open2;
712 $pid = open2(*Reader, *Writer, &quot;cat -u -n&quot; );
713 print Writer &quot;stuff\n&quot;;
714 $got = &lt;Reader&gt;;</pre>
715 <p>The problem with this is that Unix buffering is really going to
716 ruin your day. Even though your <code>Writer</code> filehandle is auto-flushed,
717 and the process on the other end will get your data in a timely manner,
718 you can't usually do anything to force it to give it back to you
719 in a similarly quick fashion. In this case, we could, because we
720 gave <em>cat</em> a <strong>-u</strong> flag to make it unbuffered. But very few Unix
721 commands are designed to operate over pipes, so this seldom works
722 unless you yourself wrote the program on the other end of the
723 double-ended pipe.</p>
724 <p>A solution to this is the nonstandard <em>Comm.pl</em> library. It uses
725 pseudo-ttys to make your program behave more reasonably:</p>
726 <pre>
727 require 'Comm.pl';
728 $ph = open_proc('cat -n');
729 for (1..10) {
730 print $ph &quot;a line\n&quot;;
731 print &quot;got back &quot;, scalar &lt;$ph&gt;;
732 }</pre>
733 <p>This way you don't have to have control over the source code of the
734 program you're using. The <em>Comm</em> library also has <code>expect()</code>
735 and <code>interact()</code> functions. Find the library (and we hope its
736 successor <em>IPC::Chat</em>) at your nearest CPAN archive as detailed
737 in the SEE ALSO section below.</p>
738 <p>The newer Expect.pm module from CPAN also addresses this kind of thing.
739 This module requires two other modules from CPAN: IO::Pty and IO::Stty.
740 It sets up a pseudo-terminal to interact with programs that insist on
741 using talking to the terminal device driver. If your system is
742 amongst those supported, this may be your best bet.</p>
744 </p>
745 <h2><a name="bidirectional_communication_with_yourself">Bidirectional Communication with Yourself</a></h2>
746 <p>If you want, you may make low-level <code>pipe()</code> and <code>fork()</code>
747 to stitch this together by hand. This example only
748 talks to itself, but you could reopen the appropriate
749 handles to STDIN and STDOUT and call other processes.</p>
750 <pre>
751 #!/usr/bin/perl -w
752 # pipe1 - bidirectional communication using two pipe pairs
753 # designed for the socketpair-challenged
754 use IO::Handle; # thousands of lines just for autoflush :-(
755 pipe(PARENT_RDR, CHILD_WTR); # XXX: failure?
756 pipe(CHILD_RDR, PARENT_WTR); # XXX: failure?
757 CHILD_WTR-&gt;autoflush(1);
758 PARENT_WTR-&gt;autoflush(1);</pre>
759 <pre>
760 if ($pid = fork) {
761 close PARENT_RDR; close PARENT_WTR;
762 print CHILD_WTR &quot;Parent Pid $$ is sending this\n&quot;;
763 chomp($line = &lt;CHILD_RDR&gt;);
764 print &quot;Parent Pid $$ just read this: `$line'\n&quot;;
765 close CHILD_RDR; close CHILD_WTR;
766 waitpid($pid,0);
767 } else {
768 die &quot;cannot fork: $!&quot; unless defined $pid;
769 close CHILD_RDR; close CHILD_WTR;
770 chomp($line = &lt;PARENT_RDR&gt;);
771 print &quot;Child Pid $$ just read this: `$line'\n&quot;;
772 print PARENT_WTR &quot;Child Pid $$ is sending this\n&quot;;
773 close PARENT_RDR; close PARENT_WTR;
774 exit;
775 }</pre>
776 <p>But you don't actually have to make two pipe calls. If you
777 have the <code>socketpair()</code> system call, it will do this all for you.</p>
778 <pre>
779 #!/usr/bin/perl -w
780 # pipe2 - bidirectional communication using socketpair
781 # &quot;the best ones always go both ways&quot;</pre>
782 <pre>
783 use Socket;
784 use IO::Handle; # thousands of lines just for autoflush :-(
785 # We say AF_UNIX because although *_LOCAL is the
786 # POSIX 1003.1g form of the constant, many machines
787 # still don't have it.
788 socketpair(CHILD, PARENT, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
789 or die &quot;socketpair: $!&quot;;</pre>
790 <pre>
791 CHILD-&gt;autoflush(1);
792 PARENT-&gt;autoflush(1);</pre>
793 <pre>
794 if ($pid = fork) {
795 close PARENT;
796 print CHILD &quot;Parent Pid $$ is sending this\n&quot;;
797 chomp($line = &lt;CHILD&gt;);
798 print &quot;Parent Pid $$ just read this: `$line'\n&quot;;
799 close CHILD;
800 waitpid($pid,0);
801 } else {
802 die &quot;cannot fork: $!&quot; unless defined $pid;
803 close CHILD;
804 chomp($line = &lt;PARENT&gt;);
805 print &quot;Child Pid $$ just read this: `$line'\n&quot;;
806 print PARENT &quot;Child Pid $$ is sending this\n&quot;;
807 close PARENT;
808 exit;
809 }</pre>
811 </p>
812 <hr />
813 <h1><a name="sockets__client_server_communication">Sockets: Client/Server Communication</a></h1>
814 <p>While not limited to Unix-derived operating systems (e.g., WinSock on PCs
815 provides socket support, as do some VMS libraries), you may not have
816 sockets on your system, in which case this section probably isn't going to do
817 you much good. With sockets, you can do both virtual circuits (i.e., TCP
818 streams) and datagrams (i.e., UDP packets). You may be able to do even more
819 depending on your system.</p>
820 <p>The Perl function calls for dealing with sockets have the same names as
821 the corresponding system calls in C, but their arguments tend to differ
822 for two reasons: first, Perl filehandles work differently than C file
823 descriptors. Second, Perl already knows the length of its strings, so you
824 don't need to pass that information.</p>
825 <p>One of the major problems with old socket code in Perl was that it used
826 hard-coded values for some of the constants, which severely hurt
827 portability. If you ever see code that does anything like explicitly
828 setting <code>$AF_INET = 2</code>, you know you're in for big trouble: An
829 immeasurably superior approach is to use the <code>Socket</code> module, which more
830 reliably grants access to various constants and functions you'll need.</p>
831 <p>If you're not writing a server/client for an existing protocol like
832 NNTP or SMTP, you should give some thought to how your server will
833 know when the client has finished talking, and vice-versa. Most
834 protocols are based on one-line messages and responses (so one party
835 knows the other has finished when a ``\n'' is received) or multi-line
836 messages and responses that end with a period on an empty line
837 (``\n.\n'' terminates a message/response).</p>
839 </p>
840 <h2><a name="internet_line_terminators">Internet Line Terminators</a></h2>
841 <p>The Internet line terminator is ``\015\012''. Under ASCII variants of
842 Unix, that could usually be written as ``\r\n'', but under other systems,
843 ``\r\n'' might at times be ``\015\015\012'', ``\012\012\015'', or something
844 completely different. The standards specify writing ``\015\012'' to be
845 conformant (be strict in what you provide), but they also recommend
846 accepting a lone ``\012'' on input (but be lenient in what you require).
847 We haven't always been very good about that in the code in this manpage,
848 but unless you're on a Mac, you'll probably be ok.</p>
850 </p>
851 <h2><a name="internet_tcp_clients_and_servers">Internet TCP Clients and Servers</a></h2>
852 <p>Use Internet-domain sockets when you want to do client-server
853 communication that might extend to machines outside of your own system.</p>
854 <p>Here's a sample TCP client using Internet-domain sockets:</p>
855 <pre>
856 #!/usr/bin/perl -w
857 use strict;
858 use Socket;
859 my ($remote,$port, $iaddr, $paddr, $proto, $line);</pre>
860 <pre>
861 $remote = shift || 'localhost';
862 $port = shift || 2345; # random port
863 if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }
864 die &quot;No port&quot; unless $port;
865 $iaddr = inet_aton($remote) || die &quot;no host: $remote&quot;;
866 $paddr = sockaddr_in($port, $iaddr);</pre>
867 <pre>
868 $proto = getprotobyname('tcp');
869 socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die &quot;socket: $!&quot;;
870 connect(SOCK, $paddr) || die &quot;connect: $!&quot;;
871 while (defined($line = &lt;SOCK&gt;)) {
872 print $line;
873 }</pre>
874 <pre>
875 close (SOCK) || die &quot;close: $!&quot;;
876 exit;</pre>
877 <p>And here's a corresponding server to go along with it. We'll
878 leave the address as INADDR_ANY so that the kernel can choose
879 the appropriate interface on multihomed hosts. If you want sit
880 on a particular interface (like the external side of a gateway
881 or firewall machine), you should fill this in with your real address
882 instead.</p>
883 <pre>
884 #!/usr/bin/perl -Tw
885 use strict;
886 BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
887 use Socket;
888 use Carp;
889 my $EOL = &quot;\015\012&quot;;</pre>
890 <pre>
891 sub logmsg { print &quot;$0 $$: @_ at &quot;, scalar localtime, &quot;\n&quot; }</pre>
892 <pre>
893 my $port = shift || 2345;
894 my $proto = getprotobyname('tcp');</pre>
895 <pre>
896 ($port) = $port =~ /^(\d+)$/ or die &quot;invalid port&quot;;</pre>
897 <pre>
898 socket(Server, PF_INET, SOCK_STREAM, $proto) || die &quot;socket: $!&quot;;
899 setsockopt(Server, SOL_SOCKET, SO_REUSEADDR,
900 pack(&quot;l&quot;, 1)) || die &quot;setsockopt: $!&quot;;
901 bind(Server, sockaddr_in($port, INADDR_ANY)) || die &quot;bind: $!&quot;;
902 listen(Server,SOMAXCONN) || die &quot;listen: $!&quot;;</pre>
903 <pre>
904 logmsg &quot;server started on port $port&quot;;</pre>
905 <pre>
906 my $paddr;</pre>
907 <pre>
908 $SIG{CHLD} = \&amp;REAPER;</pre>
909 <pre>
910 for ( ; $paddr = accept(Client,Server); close Client) {
911 my($port,$iaddr) = sockaddr_in($paddr);
912 my $name = gethostbyaddr($iaddr,AF_INET);</pre>
913 <pre>
914 logmsg &quot;connection from $name [&quot;,
915 inet_ntoa($iaddr), &quot;]
916 at port $port&quot;;</pre>
917 <pre>
918 print Client &quot;Hello there, $name, it's now &quot;,
919 scalar localtime, $EOL;
920 }</pre>
921 <p>And here's a multithreaded version. It's multithreaded in that
922 like most typical servers, it spawns (forks) a slave server to
923 handle the client request so that the master server can quickly
924 go back to service a new client.</p>
925 <pre>
926 #!/usr/bin/perl -Tw
927 use strict;
928 BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
929 use Socket;
930 use Carp;
931 my $EOL = &quot;\015\012&quot;;</pre>
932 <pre>
933 sub spawn; # forward declaration
934 sub logmsg { print &quot;$0 $$: @_ at &quot;, scalar localtime, &quot;\n&quot; }</pre>
935 <pre>
936 my $port = shift || 2345;
937 my $proto = getprotobyname('tcp');</pre>
938 <pre>
939 ($port) = $port =~ /^(\d+)$/ or die &quot;invalid port&quot;;</pre>
940 <pre>
941 socket(Server, PF_INET, SOCK_STREAM, $proto) || die &quot;socket: $!&quot;;
942 setsockopt(Server, SOL_SOCKET, SO_REUSEADDR,
943 pack(&quot;l&quot;, 1)) || die &quot;setsockopt: $!&quot;;
944 bind(Server, sockaddr_in($port, INADDR_ANY)) || die &quot;bind: $!&quot;;
945 listen(Server,SOMAXCONN) || die &quot;listen: $!&quot;;</pre>
946 <pre>
947 logmsg &quot;server started on port $port&quot;;</pre>
948 <pre>
949 my $waitedpid = 0;
950 my $paddr;</pre>
951 <pre>
952 use POSIX &quot;:sys_wait_h&quot;;
953 sub REAPER {
954 my $child;
955 while (($waitedpid = waitpid(-1,WNOHANG)) &gt; 0) {
956 logmsg &quot;reaped $waitedpid&quot; . ($? ? &quot; with exit $?&quot; : '');
958 $SIG{CHLD} = \&amp;REAPER; # loathe sysV
959 }</pre>
960 <pre>
961 $SIG{CHLD} = \&amp;REAPER;</pre>
962 <pre>
963 for ( $waitedpid = 0;
964 ($paddr = accept(Client,Server)) || $waitedpid;
965 $waitedpid = 0, close Client)
967 next if $waitedpid and not $paddr;
968 my($port,$iaddr) = sockaddr_in($paddr);
969 my $name = gethostbyaddr($iaddr,AF_INET);</pre>
970 <pre>
971 logmsg &quot;connection from $name [&quot;,
972 inet_ntoa($iaddr), &quot;]
973 at port $port&quot;;</pre>
974 <pre>
975 spawn sub {
976 $|=1;
977 print &quot;Hello there, $name, it's now &quot;, scalar localtime, $EOL;
978 exec '/usr/games/fortune' # XXX: `wrong' line terminators
979 or confess &quot;can't exec fortune: $!&quot;;
980 };</pre>
981 <pre>
982 }</pre>
983 <pre>
984 sub spawn {
985 my $coderef = shift;</pre>
986 <pre>
987 unless (@_ == 0 &amp;&amp; $coderef &amp;&amp; ref($coderef) eq 'CODE') {
988 confess &quot;usage: spawn CODEREF&quot;;
989 }</pre>
990 <pre>
991 my $pid;
992 if (!defined($pid = fork)) {
993 logmsg &quot;cannot fork: $!&quot;;
994 return;
995 } elsif ($pid) {
996 logmsg &quot;begat $pid&quot;;
997 return; # I'm the parent
999 # else I'm the child -- go spawn</pre>
1000 <pre>
1001 open(STDIN, &quot;&lt;&amp;Client&quot;) || die &quot;can't dup client to stdin&quot;;
1002 open(STDOUT, &quot;&gt;&amp;Client&quot;) || die &quot;can't dup client to stdout&quot;;
1003 ## open(STDERR, &quot;&gt;&amp;STDOUT&quot;) || die &quot;can't dup stdout to stderr&quot;;
1004 exit &amp;$coderef();
1005 }</pre>
1006 <p>This server takes the trouble to clone off a child version via <code>fork()</code> for
1007 each incoming request. That way it can handle many requests at once,
1008 which you might not always want. Even if you don't fork(), the <code>listen()</code>
1009 will allow that many pending connections. Forking servers have to be
1010 particularly careful about cleaning up their dead children (called
1011 ``zombies'' in Unix parlance), because otherwise you'll quickly fill up your
1012 process table.</p>
1013 <p>We suggest that you use the <strong>-T</strong> flag to use taint checking (see <a href="file://C|\msysgit\mingw\html/pod/perlsec.html">the perlsec manpage</a>)
1014 even if we aren't running setuid or setgid. This is always a good idea
1015 for servers and other programs run on behalf of someone else (like CGI
1016 scripts), because it lessens the chances that people from the outside will
1017 be able to compromise your system.</p>
1018 <p>Let's look at another TCP client. This one connects to the TCP ``time''
1019 service on a number of different machines and shows how far their clocks
1020 differ from the system on which it's being run:</p>
1021 <pre>
1022 #!/usr/bin/perl -w
1023 use strict;
1024 use Socket;</pre>
1025 <pre>
1026 my $SECS_of_70_YEARS = 2208988800;
1027 sub ctime { scalar localtime(shift) }</pre>
1028 <pre>
1029 my $iaddr = gethostbyname('localhost');
1030 my $proto = getprotobyname('tcp');
1031 my $port = getservbyname('time', 'tcp');
1032 my $paddr = sockaddr_in(0, $iaddr);
1033 my($host);</pre>
1034 <pre>
1035 $| = 1;
1036 printf &quot;%-24s %8s %s\n&quot;, &quot;localhost&quot;, 0, ctime(time());</pre>
1037 <pre>
1038 foreach $host (@ARGV) {
1039 printf &quot;%-24s &quot;, $host;
1040 my $hisiaddr = inet_aton($host) || die &quot;unknown host&quot;;
1041 my $hispaddr = sockaddr_in($port, $hisiaddr);
1042 socket(SOCKET, PF_INET, SOCK_STREAM, $proto) || die &quot;socket: $!&quot;;
1043 connect(SOCKET, $hispaddr) || die &quot;bind: $!&quot;;
1044 my $rtime = ' ';
1045 read(SOCKET, $rtime, 4);
1046 close(SOCKET);
1047 my $histime = unpack(&quot;N&quot;, $rtime) - $SECS_of_70_YEARS;
1048 printf &quot;%8d %s\n&quot;, $histime - time, ctime($histime);
1049 }</pre>
1051 </p>
1052 <h2><a name="unixdomain_tcp_clients_and_servers">Unix-Domain TCP Clients and Servers</a></h2>
1053 <p>That's fine for Internet-domain clients and servers, but what about local
1054 communications? While you can use the same setup, sometimes you don't
1055 want to. Unix-domain sockets are local to the current host, and are often
1056 used internally to implement pipes. Unlike Internet domain sockets, Unix
1057 domain sockets can show up in the file system with an <code>ls(1)</code> listing.</p>
1058 <pre>
1059 % ls -l /dev/log
1060 srw-rw-rw- 1 root 0 Oct 31 07:23 /dev/log</pre>
1061 <p>You can test for these with Perl's <strong>-S</strong> file test:</p>
1062 <pre>
1063 unless ( -S '/dev/log' ) {
1064 die &quot;something's wicked with the log system&quot;;
1065 }</pre>
1066 <p>Here's a sample Unix-domain client:</p>
1067 <pre>
1068 #!/usr/bin/perl -w
1069 use Socket;
1070 use strict;
1071 my ($rendezvous, $line);</pre>
1072 <pre>
1073 $rendezvous = shift || 'catsock';
1074 socket(SOCK, PF_UNIX, SOCK_STREAM, 0) || die &quot;socket: $!&quot;;
1075 connect(SOCK, sockaddr_un($rendezvous)) || die &quot;connect: $!&quot;;
1076 while (defined($line = &lt;SOCK&gt;)) {
1077 print $line;
1079 exit;</pre>
1080 <p>And here's a corresponding server. You don't have to worry about silly
1081 network terminators here because Unix domain sockets are guaranteed
1082 to be on the localhost, and thus everything works right.</p>
1083 <pre>
1084 #!/usr/bin/perl -Tw
1085 use strict;
1086 use Socket;
1087 use Carp;</pre>
1088 <pre>
1089 BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
1090 sub spawn; # forward declaration
1091 sub logmsg { print &quot;$0 $$: @_ at &quot;, scalar localtime, &quot;\n&quot; }</pre>
1092 <pre>
1093 my $NAME = 'catsock';
1094 my $uaddr = sockaddr_un($NAME);
1095 my $proto = getprotobyname('tcp');</pre>
1096 <pre>
1097 socket(Server,PF_UNIX,SOCK_STREAM,0) || die &quot;socket: $!&quot;;
1098 unlink($NAME);
1099 bind (Server, $uaddr) || die &quot;bind: $!&quot;;
1100 listen(Server,SOMAXCONN) || die &quot;listen: $!&quot;;</pre>
1101 <pre>
1102 logmsg &quot;server started on $NAME&quot;;</pre>
1103 <pre>
1104 my $waitedpid;</pre>
1105 <pre>
1106 use POSIX &quot;:sys_wait_h&quot;;
1107 sub REAPER {
1108 my $child;
1109 while (($waitedpid = waitpid(-1,WNOHANG)) &gt; 0) {
1110 logmsg &quot;reaped $waitedpid&quot; . ($? ? &quot; with exit $?&quot; : '');
1112 $SIG{CHLD} = \&amp;REAPER; # loathe sysV
1113 }</pre>
1114 <pre>
1115 $SIG{CHLD} = \&amp;REAPER;</pre>
1116 <pre>
1117 for ( $waitedpid = 0;
1118 accept(Client,Server) || $waitedpid;
1119 $waitedpid = 0, close Client)
1121 next if $waitedpid;
1122 logmsg &quot;connection on $NAME&quot;;
1123 spawn sub {
1124 print &quot;Hello there, it's now &quot;, scalar localtime, &quot;\n&quot;;
1125 exec '/usr/games/fortune' or die &quot;can't exec fortune: $!&quot;;
1127 }</pre>
1128 <pre>
1129 sub spawn {
1130 my $coderef = shift;</pre>
1131 <pre>
1132 unless (@_ == 0 &amp;&amp; $coderef &amp;&amp; ref($coderef) eq 'CODE') {
1133 confess &quot;usage: spawn CODEREF&quot;;
1134 }</pre>
1135 <pre>
1136 my $pid;
1137 if (!defined($pid = fork)) {
1138 logmsg &quot;cannot fork: $!&quot;;
1139 return;
1140 } elsif ($pid) {
1141 logmsg &quot;begat $pid&quot;;
1142 return; # I'm the parent
1144 # else I'm the child -- go spawn</pre>
1145 <pre>
1146 open(STDIN, &quot;&lt;&amp;Client&quot;) || die &quot;can't dup client to stdin&quot;;
1147 open(STDOUT, &quot;&gt;&amp;Client&quot;) || die &quot;can't dup client to stdout&quot;;
1148 ## open(STDERR, &quot;&gt;&amp;STDOUT&quot;) || die &quot;can't dup stdout to stderr&quot;;
1149 exit &amp;$coderef();
1150 }</pre>
1151 <p>As you see, it's remarkably similar to the Internet domain TCP server, so
1152 much so, in fact, that we've omitted several duplicate functions--spawn(),
1153 logmsg(), ctime(), and REAPER()--which are exactly the same as in the
1154 other server.</p>
1155 <p>So why would you ever want to use a Unix domain socket instead of a
1156 simpler named pipe? Because a named pipe doesn't give you sessions. You
1157 can't tell one process's data from another's. With socket programming,
1158 you get a separate session for each client: that's why <code>accept()</code> takes two
1159 arguments.</p>
1160 <p>For example, let's say that you have a long running database server daemon
1161 that you want folks from the World Wide Web to be able to access, but only
1162 if they go through a CGI interface. You'd have a small, simple CGI
1163 program that does whatever checks and logging you feel like, and then acts
1164 as a Unix-domain client and connects to your private server.</p>
1166 </p>
1167 <hr />
1168 <h1><a name="tcp_clients_with_io__socket">TCP Clients with IO::Socket</a></h1>
1169 <p>For those preferring a higher-level interface to socket programming, the
1170 IO::Socket module provides an object-oriented approach. IO::Socket is
1171 included as part of the standard Perl distribution as of the 5.004
1172 release. If you're running an earlier version of Perl, just fetch
1173 IO::Socket from CPAN, where you'll also find modules providing easy
1174 interfaces to the following systems: DNS, FTP, Ident (RFC 931), NIS and
1175 NISPlus, NNTP, Ping, POP3, SMTP, SNMP, SSLeay, Telnet, and Time--just
1176 to name a few.</p>
1178 </p>
1179 <h2><a name="a_simple_client">A Simple Client</a></h2>
1180 <p>Here's a client that creates a TCP connection to the ``daytime''
1181 service at port 13 of the host name ``localhost'' and prints out everything
1182 that the server there cares to provide.</p>
1183 <pre>
1184 #!/usr/bin/perl -w
1185 use IO::Socket;
1186 $remote = IO::Socket::INET-&gt;new(
1187 Proto =&gt; &quot;tcp&quot;,
1188 PeerAddr =&gt; &quot;localhost&quot;,
1189 PeerPort =&gt; &quot;daytime(13)&quot;,
1191 or die &quot;cannot connect to daytime port at localhost&quot;;
1192 while ( &lt;$remote&gt; ) { print }</pre>
1193 <p>When you run this program, you should get something back that
1194 looks like this:</p>
1195 <pre>
1196 Wed May 14 08:40:46 MDT 1997</pre>
1197 <p>Here are what those parameters to the <code>new</code> constructor mean:</p>
1198 <dl>
1199 <dt><strong><a name="item_proto"><code>Proto</code></a></strong>
1201 <dd>
1202 <p>This is which protocol to use. In this case, the socket handle returned
1203 will be connected to a TCP socket, because we want a stream-oriented
1204 connection, that is, one that acts pretty much like a plain old file.
1205 Not all sockets are this of this type. For example, the UDP protocol
1206 can be used to make a datagram socket, used for message-passing.</p>
1207 </dd>
1208 </li>
1209 <dt><strong><a name="item_peeraddr"><code>PeerAddr</code></a></strong>
1211 <dd>
1212 <p>This is the name or Internet address of the remote host the server is
1213 running on. We could have specified a longer name like <code>&quot;www.perl.com&quot;</code>,
1214 or an address like <code>&quot;204.148.40.9&quot;</code>. For demonstration purposes, we've
1215 used the special hostname <code>&quot;localhost&quot;</code>, which should always mean the
1216 current machine you're running on. The corresponding Internet address
1217 for localhost is <code>&quot;127.1&quot;</code>, if you'd rather use that.</p>
1218 </dd>
1219 </li>
1220 <dt><strong><a name="item_peerport"><code>PeerPort</code></a></strong>
1222 <dd>
1223 <p>This is the service name or port number we'd like to connect to.
1224 We could have gotten away with using just <code>&quot;daytime&quot;</code> on systems with a
1225 well-configured system services file,[FOOTNOTE: The system services file
1226 is in <em>/etc/services</em> under Unix] but just in case, we've specified the
1227 port number (13) in parentheses. Using just the number would also have
1228 worked, but constant numbers make careful programmers nervous.</p>
1229 </dd>
1230 </li>
1231 </dl>
1232 <p>Notice how the return value from the <code>new</code> constructor is used as
1233 a filehandle in the <code>while</code> loop? That's what's called an indirect
1234 filehandle, a scalar variable containing a filehandle. You can use
1235 it the same way you would a normal filehandle. For example, you
1236 can read one line from it this way:</p>
1237 <pre>
1238 $line = &lt;$handle&gt;;</pre>
1239 <p>all remaining lines from is this way:</p>
1240 <pre>
1241 @lines = &lt;$handle&gt;;</pre>
1242 <p>and send a line of data to it this way:</p>
1243 <pre>
1244 print $handle &quot;some data\n&quot;;</pre>
1246 </p>
1247 <h2><a name="a_webget_client">A Webget Client</a></h2>
1248 <p>Here's a simple client that takes a remote host to fetch a document
1249 from, and then a list of documents to get from that host. This is a
1250 more interesting client than the previous one because it first sends
1251 something to the server before fetching the server's response.</p>
1252 <pre>
1253 #!/usr/bin/perl -w
1254 use IO::Socket;
1255 unless (@ARGV &gt; 1) { die &quot;usage: $0 host document ...&quot; }
1256 $host = shift(@ARGV);
1257 $EOL = &quot;\015\012&quot;;
1258 $BLANK = $EOL x 2;
1259 foreach $document ( @ARGV ) {
1260 $remote = IO::Socket::INET-&gt;new( Proto =&gt; &quot;tcp&quot;,
1261 PeerAddr =&gt; $host,
1262 PeerPort =&gt; &quot;http(80)&quot;,
1264 unless ($remote) { die &quot;cannot connect to http daemon on $host&quot; }
1265 $remote-&gt;autoflush(1);
1266 print $remote &quot;GET $document HTTP/1.0&quot; . $BLANK;
1267 while ( &lt;$remote&gt; ) { print }
1268 close $remote;
1269 }</pre>
1270 <p>The web server handing the ``http'' service, which is assumed to be at
1271 its standard port, number 80. If the web server you're trying to
1272 connect to is at a different port (like 1080 or 8080), you should specify
1273 as the named-parameter pair, <code>PeerPort =&gt; 8080</code>. The <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item_autoflush"><code>autoflush</code></a>
1274 method is used on the socket because otherwise the system would buffer
1275 up the output we sent it. (If you're on a Mac, you'll also need to
1276 change every <code>&quot;\n&quot;</code> in your code that sends data over the network to
1277 be a <code>&quot;\015\012&quot;</code> instead.)</p>
1278 <p>Connecting to the server is only the first part of the process: once you
1279 have the connection, you have to use the server's language. Each server
1280 on the network has its own little command language that it expects as
1281 input. The string that we send to the server starting with ``GET'' is in
1282 HTTP syntax. In this case, we simply request each specified document.
1283 Yes, we really are making a new connection for each document, even though
1284 it's the same host. That's the way you always used to have to speak HTTP.
1285 Recent versions of web browsers may request that the remote server leave
1286 the connection open a little while, but the server doesn't have to honor
1287 such a request.</p>
1288 <p>Here's an example of running that program, which we'll call <em>webget</em>:</p>
1289 <pre>
1290 % webget www.perl.com /guanaco.html
1291 HTTP/1.1 404 File Not Found
1292 Date: Thu, 08 May 1997 18:02:32 GMT
1293 Server: Apache/1.2b6
1294 Connection: close
1295 Content-type: text/html</pre>
1296 <pre>
1297 &lt;HEAD&gt;&lt;TITLE&gt;404 File Not Found&lt;/TITLE&gt;&lt;/HEAD&gt;
1298 &lt;BODY&gt;&lt;H1&gt;File Not Found&lt;/H1&gt;
1299 The requested URL /guanaco.html was not found on this server.&lt;P&gt;
1300 &lt;/BODY&gt;</pre>
1301 <p>Ok, so that's not very interesting, because it didn't find that
1302 particular document. But a long response wouldn't have fit on this page.</p>
1303 <p>For a more fully-featured version of this program, you should look to
1304 the <em>lwp-request</em> program included with the LWP modules from CPAN.</p>
1306 </p>
1307 <h2><a name="interactive_client_with_io__socket">Interactive Client with IO::Socket</a></h2>
1308 <p>Well, that's all fine if you want to send one command and get one answer,
1309 but what about setting up something fully interactive, somewhat like
1310 the way <em>telnet</em> works? That way you can type a line, get the answer,
1311 type a line, get the answer, etc.</p>
1312 <p>This client is more complicated than the two we've done so far, but if
1313 you're on a system that supports the powerful <code>fork</code> call, the solution
1314 isn't that rough. Once you've made the connection to whatever service
1315 you'd like to chat with, call <code>fork</code> to clone your process. Each of
1316 these two identical process has a very simple job to do: the parent
1317 copies everything from the socket to standard output, while the child
1318 simultaneously copies everything from standard input to the socket.
1319 To accomplish the same thing using just one process would be <em>much</em>
1320 harder, because it's easier to code two processes to do one thing than it
1321 is to code one process to do two things. (This keep-it-simple principle
1322 a cornerstones of the Unix philosophy, and good software engineering as
1323 well, which is probably why it's spread to other systems.)</p>
1324 <p>Here's the code:</p>
1325 <pre>
1326 #!/usr/bin/perl -w
1327 use strict;
1328 use IO::Socket;
1329 my ($host, $port, $kidpid, $handle, $line);</pre>
1330 <pre>
1331 unless (@ARGV == 2) { die &quot;usage: $0 host port&quot; }
1332 ($host, $port) = @ARGV;</pre>
1333 <pre>
1334 # create a tcp connection to the specified host and port
1335 $handle = IO::Socket::INET-&gt;new(Proto =&gt; &quot;tcp&quot;,
1336 PeerAddr =&gt; $host,
1337 PeerPort =&gt; $port)
1338 or die &quot;can't connect to port $port on $host: $!&quot;;</pre>
1339 <pre>
1340 $handle-&gt;autoflush(1); # so output gets there right away
1341 print STDERR &quot;[Connected to $host:$port]\n&quot;;</pre>
1342 <pre>
1343 # split the program into two processes, identical twins
1344 die &quot;can't fork: $!&quot; unless defined($kidpid = fork());</pre>
1345 <pre>
1346 # the if{} block runs only in the parent process
1347 if ($kidpid) {
1348 # copy the socket to standard output
1349 while (defined ($line = &lt;$handle&gt;)) {
1350 print STDOUT $line;
1352 kill(&quot;TERM&quot;, $kidpid); # send SIGTERM to child
1354 # the else{} block runs only in the child process
1355 else {
1356 # copy standard input to the socket
1357 while (defined ($line = &lt;STDIN&gt;)) {
1358 print $handle $line;
1360 }</pre>
1361 <p>The <code>kill</code> function in the parent's <code>if</code> block is there to send a
1362 signal to our child process (current running in the <code>else</code> block)
1363 as soon as the remote server has closed its end of the connection.</p>
1364 <p>If the remote server sends data a byte at time, and you need that
1365 data immediately without waiting for a newline (which might not happen),
1366 you may wish to replace the <code>while</code> loop in the parent with the
1367 following:</p>
1368 <pre>
1369 my $byte;
1370 while (sysread($handle, $byte, 1) == 1) {
1371 print STDOUT $byte;
1372 }</pre>
1373 <p>Making a system call for each byte you want to read is not very efficient
1374 (to put it mildly) but is the simplest to explain and works reasonably
1375 well.</p>
1377 </p>
1378 <hr />
1379 <h1><a name="tcp_servers_with_io__socket">TCP Servers with IO::Socket</a></h1>
1380 <p>As always, setting up a server is little bit more involved than running a client.
1381 The model is that the server creates a special kind of socket that
1382 does nothing but listen on a particular port for incoming connections.
1383 It does this by calling the <code>IO::Socket::INET-&gt;new()</code> method with
1384 slightly different arguments than the client did.</p>
1385 <dl>
1386 <dt><strong>Proto</strong>
1388 <dd>
1389 <p>This is which protocol to use. Like our clients, we'll
1390 still specify <code>&quot;tcp&quot;</code> here.</p>
1391 </dd>
1392 </li>
1393 <dt><strong><a name="item_localport">LocalPort</a></strong>
1395 <dd>
1396 <p>We specify a local
1397 port in the <a href="#item_localport"><code>LocalPort</code></a> argument, which we didn't do for the client.
1398 This is service name or port number for which you want to be the
1399 server. (Under Unix, ports under 1024 are restricted to the
1400 superuser.) In our sample, we'll use port 9000, but you can use
1401 any port that's not currently in use on your system. If you try
1402 to use one already in used, you'll get an ``Address already in use''
1403 message. Under Unix, the <code>netstat -a</code> command will show
1404 which services current have servers.</p>
1405 </dd>
1406 </li>
1407 <dt><strong><a name="item_listen">Listen</a></strong>
1409 <dd>
1410 <p>The <a href="#item_listen"><code>Listen</code></a> parameter is set to the maximum number of
1411 pending connections we can accept until we turn away incoming clients.
1412 Think of it as a call-waiting queue for your telephone.
1413 The low-level Socket module has a special symbol for the system maximum, which
1414 is SOMAXCONN.</p>
1415 </dd>
1416 </li>
1417 <dt><strong><a name="item_reuse">Reuse</a></strong>
1419 <dd>
1420 <p>The <a href="#item_reuse"><code>Reuse</code></a> parameter is needed so that we restart our server
1421 manually without waiting a few minutes to allow system buffers to
1422 clear out.</p>
1423 </dd>
1424 </li>
1425 </dl>
1426 <p>Once the generic server socket has been created using the parameters
1427 listed above, the server then waits for a new client to connect
1428 to it. The server blocks in the <code>accept</code> method, which eventually accepts a
1429 bidirectional connection from the remote client. (Make sure to autoflush
1430 this handle to circumvent buffering.)</p>
1431 <p>To add to user-friendliness, our server prompts the user for commands.
1432 Most servers don't do this. Because of the prompt without a newline,
1433 you'll have to use the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_sysread"><code>sysread</code></a> variant of the interactive client above.</p>
1434 <p>This server accepts one of five different commands, sending output
1435 back to the client. Note that unlike most network servers, this one
1436 only handles one incoming client at a time. Multithreaded servers are
1437 covered in Chapter 6 of the Camel.</p>
1438 <p>Here's the code. We'll</p>
1439 <pre>
1440 #!/usr/bin/perl -w
1441 use IO::Socket;
1442 use Net::hostent; # for OO version of gethostbyaddr</pre>
1443 <pre>
1444 $PORT = 9000; # pick something not in use</pre>
1445 <pre>
1446 $server = IO::Socket::INET-&gt;new( Proto =&gt; 'tcp',
1447 LocalPort =&gt; $PORT,
1448 Listen =&gt; SOMAXCONN,
1449 Reuse =&gt; 1);</pre>
1450 <pre>
1451 die &quot;can't setup server&quot; unless $server;
1452 print &quot;[Server $0 accepting clients]\n&quot;;</pre>
1453 <pre>
1454 while ($client = $server-&gt;accept()) {
1455 $client-&gt;autoflush(1);
1456 print $client &quot;Welcome to $0; type help for command list.\n&quot;;
1457 $hostinfo = gethostbyaddr($client-&gt;peeraddr);
1458 printf &quot;[Connect from %s]\n&quot;, $hostinfo ? $hostinfo-&gt;name : $client-&gt;peerhost;
1459 print $client &quot;Command? &quot;;
1460 while ( &lt;$client&gt;) {
1461 next unless /\S/; # blank line
1462 if (/quit|exit/i) { last; }
1463 elsif (/date|time/i) { printf $client &quot;%s\n&quot;, scalar localtime; }
1464 elsif (/who/i ) { print $client `who 2&gt;&amp;1`; }
1465 elsif (/cookie/i ) { print $client `/usr/games/fortune 2&gt;&amp;1`; }
1466 elsif (/motd/i ) { print $client `cat /etc/motd 2&gt;&amp;1`; }
1467 else {
1468 print $client &quot;Commands: quit date who cookie motd\n&quot;;
1470 } continue {
1471 print $client &quot;Command? &quot;;
1473 close $client;
1474 }</pre>
1476 </p>
1477 <hr />
1478 <h1><a name="udp__message_passing">UDP: Message Passing</a></h1>
1479 <p>Another kind of client-server setup is one that uses not connections, but
1480 messages. UDP communications involve much lower overhead but also provide
1481 less reliability, as there are no promises that messages will arrive at
1482 all, let alone in order and unmangled. Still, UDP offers some advantages
1483 over TCP, including being able to ``broadcast'' or ``multicast'' to a whole
1484 bunch of destination hosts at once (usually on your local subnet). If you
1485 find yourself overly concerned about reliability and start building checks
1486 into your message system, then you probably should use just TCP to start
1487 with.</p>
1488 <p>Note that UDP datagrams are <em>not</em> a bytestream and should not be treated
1489 as such. This makes using I/O mechanisms with internal buffering
1490 like stdio (i.e. <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_print"><code>print()</code></a> and friends) especially cumbersome. Use syswrite(),
1491 or better send(), like in the example below.</p>
1492 <p>Here's a UDP program similar to the sample Internet TCP client given
1493 earlier. However, instead of checking one host at a time, the UDP version
1494 will check many of them asynchronously by simulating a multicast and then
1495 using <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_select"><code>select()</code></a> to do a timed-out wait for I/O. To do something similar
1496 with TCP, you'd have to use a different socket handle for each host.</p>
1497 <pre>
1498 #!/usr/bin/perl -w
1499 use strict;
1500 use Socket;
1501 use Sys::Hostname;</pre>
1502 <pre>
1503 my ( $count, $hisiaddr, $hispaddr, $histime,
1504 $host, $iaddr, $paddr, $port, $proto,
1505 $rin, $rout, $rtime, $SECS_of_70_YEARS);</pre>
1506 <pre>
1507 $SECS_of_70_YEARS = 2208988800;</pre>
1508 <pre>
1509 $iaddr = gethostbyname(hostname());
1510 $proto = getprotobyname('udp');
1511 $port = getservbyname('time', 'udp');
1512 $paddr = sockaddr_in(0, $iaddr); # 0 means let kernel pick</pre>
1513 <pre>
1514 socket(SOCKET, PF_INET, SOCK_DGRAM, $proto) || die &quot;socket: $!&quot;;
1515 bind(SOCKET, $paddr) || die &quot;bind: $!&quot;;</pre>
1516 <pre>
1517 $| = 1;
1518 printf &quot;%-12s %8s %s\n&quot;, &quot;localhost&quot;, 0, scalar localtime time;
1519 $count = 0;
1520 for $host (@ARGV) {
1521 $count++;
1522 $hisiaddr = inet_aton($host) || die &quot;unknown host&quot;;
1523 $hispaddr = sockaddr_in($port, $hisiaddr);
1524 defined(send(SOCKET, 0, 0, $hispaddr)) || die &quot;send $host: $!&quot;;
1525 }</pre>
1526 <pre>
1527 $rin = '';
1528 vec($rin, fileno(SOCKET), 1) = 1;</pre>
1529 <pre>
1530 # timeout after 10.0 seconds
1531 while ($count &amp;&amp; select($rout = $rin, undef, undef, 10.0)) {
1532 $rtime = '';
1533 ($hispaddr = recv(SOCKET, $rtime, 4, 0)) || die &quot;recv: $!&quot;;
1534 ($port, $hisiaddr) = sockaddr_in($hispaddr);
1535 $host = gethostbyaddr($hisiaddr, AF_INET);
1536 $histime = unpack(&quot;N&quot;, $rtime) - $SECS_of_70_YEARS;
1537 printf &quot;%-12s &quot;, $host;
1538 printf &quot;%8d %s\n&quot;, $histime - time, scalar localtime($histime);
1539 $count--;
1540 }</pre>
1541 <p>Note that this example does not include any retries and may consequently
1542 fail to contact a reachable host. The most prominent reason for this
1543 is congestion of the queues on the sending host if the number of
1544 list of hosts to contact is sufficiently large.</p>
1546 </p>
1547 <hr />
1548 <h1><a name="sysv_ipc">SysV IPC</a></h1>
1549 <p>While System V IPC isn't so widely used as sockets, it still has some
1550 interesting uses. You can't, however, effectively use SysV IPC or
1551 Berkeley <code>mmap()</code> to have shared memory so as to share a variable amongst
1552 several processes. That's because Perl would reallocate your string when
1553 you weren't wanting it to.</p>
1554 <p>Here's a small example showing shared memory usage.</p>
1555 <pre>
1556 use IPC::SysV qw(IPC_PRIVATE IPC_RMID S_IRWXU);</pre>
1557 <pre>
1558 $size = 2000;
1559 $id = shmget(IPC_PRIVATE, $size, S_IRWXU) || die &quot;$!&quot;;
1560 print &quot;shm key $id\n&quot;;</pre>
1561 <pre>
1562 $message = &quot;Message #1&quot;;
1563 shmwrite($id, $message, 0, 60) || die &quot;$!&quot;;
1564 print &quot;wrote: '$message'\n&quot;;
1565 shmread($id, $buff, 0, 60) || die &quot;$!&quot;;
1566 print &quot;read : '$buff'\n&quot;;</pre>
1567 <pre>
1568 # the buffer of shmread is zero-character end-padded.
1569 substr($buff, index($buff, &quot;\0&quot;)) = '';
1570 print &quot;un&quot; unless $buff eq $message;
1571 print &quot;swell\n&quot;;</pre>
1572 <pre>
1573 print &quot;deleting shm $id\n&quot;;
1574 shmctl($id, IPC_RMID, 0) || die &quot;$!&quot;;</pre>
1575 <p>Here's an example of a semaphore:</p>
1576 <pre>
1577 use IPC::SysV qw(IPC_CREAT);</pre>
1578 <pre>
1579 $IPC_KEY = 1234;
1580 $id = semget($IPC_KEY, 10, 0666 | IPC_CREAT ) || die &quot;$!&quot;;
1581 print &quot;shm key $id\n&quot;;</pre>
1582 <p>Put this code in a separate file to be run in more than one process.
1583 Call the file <em>take</em>:</p>
1584 <pre>
1585 # create a semaphore</pre>
1586 <pre>
1587 $IPC_KEY = 1234;
1588 $id = semget($IPC_KEY, 0 , 0 );
1589 die if !defined($id);</pre>
1590 <pre>
1591 $semnum = 0;
1592 $semflag = 0;</pre>
1593 <pre>
1594 # 'take' semaphore
1595 # wait for semaphore to be zero
1596 $semop = 0;
1597 $opstring1 = pack(&quot;s!s!s!&quot;, $semnum, $semop, $semflag);</pre>
1598 <pre>
1599 # Increment the semaphore count
1600 $semop = 1;
1601 $opstring2 = pack(&quot;s!s!s!&quot;, $semnum, $semop, $semflag);
1602 $opstring = $opstring1 . $opstring2;</pre>
1603 <pre>
1604 semop($id,$opstring) || die &quot;$!&quot;;</pre>
1605 <p>Put this code in a separate file to be run in more than one process.
1606 Call this file <em>give</em>:</p>
1607 <pre>
1608 # 'give' the semaphore
1609 # run this in the original process and you will see
1610 # that the second process continues</pre>
1611 <pre>
1612 $IPC_KEY = 1234;
1613 $id = semget($IPC_KEY, 0, 0);
1614 die if !defined($id);</pre>
1615 <pre>
1616 $semnum = 0;
1617 $semflag = 0;</pre>
1618 <pre>
1619 # Decrement the semaphore count
1620 $semop = -1;
1621 $opstring = pack(&quot;s!s!s!&quot;, $semnum, $semop, $semflag);</pre>
1622 <pre>
1623 semop($id,$opstring) || die &quot;$!&quot;;</pre>
1624 <p>The SysV IPC code above was written long ago, and it's definitely
1625 clunky looking. For a more modern look, see the IPC::SysV module
1626 which is included with Perl starting from Perl 5.005.</p>
1627 <p>A small example demonstrating SysV message queues:</p>
1628 <pre>
1629 use IPC::SysV qw(IPC_PRIVATE IPC_RMID IPC_CREAT S_IRWXU);</pre>
1630 <pre>
1631 my $id = msgget(IPC_PRIVATE, IPC_CREAT | S_IRWXU);</pre>
1632 <pre>
1633 my $sent = &quot;message&quot;;
1634 my $type_sent = 1234;
1635 my $rcvd;
1636 my $type_rcvd;</pre>
1637 <pre>
1638 if (defined $id) {
1639 if (msgsnd($id, pack(&quot;l! a*&quot;, $type_sent, $sent), 0)) {
1640 if (msgrcv($id, $rcvd, 60, 0, 0)) {
1641 ($type_rcvd, $rcvd) = unpack(&quot;l! a*&quot;, $rcvd);
1642 if ($rcvd eq $sent) {
1643 print &quot;okay\n&quot;;
1644 } else {
1645 print &quot;not okay\n&quot;;
1647 } else {
1648 die &quot;# msgrcv failed\n&quot;;
1650 } else {
1651 die &quot;# msgsnd failed\n&quot;;
1653 msgctl($id, IPC_RMID, 0) || die &quot;# msgctl failed: $!\n&quot;;
1654 } else {
1655 die &quot;# msgget failed\n&quot;;
1656 }</pre>
1658 </p>
1659 <hr />
1660 <h1><a name="notes">NOTES</a></h1>
1661 <p>Most of these routines quietly but politely return <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef</code></a> when they
1662 fail instead of causing your program to die right then and there due to
1663 an uncaught exception. (Actually, some of the new <em>Socket</em> conversion
1664 functions <code>croak()</code> on bad arguments.) It is therefore essential to
1665 check return values from these functions. Always begin your socket
1666 programs this way for optimal success, and don't forget to add <strong>-T</strong>
1667 taint checking flag to the #! line for servers:</p>
1668 <pre>
1669 #!/usr/bin/perl -Tw
1670 use strict;
1671 use sigtrap;
1672 use Socket;</pre>
1674 </p>
1675 <hr />
1676 <h1><a name="bugs">BUGS</a></h1>
1677 <p>All these routines create system-specific portability problems. As noted
1678 elsewhere, Perl is at the mercy of your C libraries for much of its system
1679 behaviour. It's probably safest to assume broken SysV semantics for
1680 signals and to stick with simple TCP and UDP socket operations; e.g., don't
1681 try to pass open file descriptors over a local UDP datagram socket if you
1682 want your code to stand a chance of being portable.</p>
1684 </p>
1685 <hr />
1686 <h1><a name="author">AUTHOR</a></h1>
1687 <p>Tom Christiansen, with occasional vestiges of Larry Wall's original
1688 version and suggestions from the Perl Porters.</p>
1690 </p>
1691 <hr />
1692 <h1><a name="see_also">SEE ALSO</a></h1>
1693 <p>There's a lot more to networking than this, but this should get you
1694 started.</p>
1695 <p>For intrepid programmers, the indispensable textbook is <em>Unix
1696 Network Programming, 2nd Edition, Volume 1</em> by W. Richard Stevens
1697 (published by Prentice-Hall). Note that most books on networking
1698 address the subject from the perspective of a C programmer; translation
1699 to Perl is left as an exercise for the reader.</p>
1700 <p>The IO::Socket(3) manpage describes the object library, and the <code>Socket(3)</code>
1701 manpage describes the low-level interface to sockets. Besides the obvious
1702 functions in <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html">the perlfunc manpage</a>, you should also check out the <em>modules</em> file
1703 at your nearest CPAN site. (See <a href="file://C|\msysgit\mingw\html/pod/perlmodlib.html">the perlmodlib manpage</a> or best yet, the <em>Perl
1704 FAQ</em> for a description of what CPAN is and where to get it.)</p>
1705 <p>Section 5 of the <em>modules</em> file is devoted to ``Networking, Device Control
1706 (modems), and Interprocess Communication'', and contains numerous unbundled
1707 modules numerous networking modules, Chat and Expect operations, CGI
1708 programming, DCE, FTP, IPC, NNTP, Proxy, Ptty, RPC, SNMP, SMTP, Telnet,
1709 Threads, and ToolTalk--just to name a few.</p>
1710 <table border="0" width="100%" cellspacing="0" cellpadding="3">
1711 <tr><td class="block" style="background-color: #cccccc" valign="middle">
1712 <big><strong><span class="block">&nbsp;perlipc - Perl interprocess communication</span></strong></big>
1713 </td></tr>
1714 </table>
1716 </body>
1718 </html>