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