3 perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets, and semaphores)
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.
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.
22 For example, to trap an interrupt signal, set up a handler like this:
29 die "Somebody sent me a SIG$signame";
31 $SIG{INT} = __PACKAGE__ . "::catch_zap";
32 $SIG{INT} = \&catch_zap; # best strategy
34 Prior to Perl 5.7.3 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.
42 The names of the signals are the ones listed out by C<kill -l> on your
43 system, or you can retrieve them from the Config module. Set up an
44 @signame list indexed by number to get the name and a %signo hash table
45 indexed by name to get the number:
48 defined($Config{sig_name}) || die "No sigs?";
49 foreach $name (split(" ", $Config{sig_name})) {
55 So to check whether signal 17 and SIGALRM were the same, do just this:
57 print "signal #17 = $signame[17]\n";
59 print "SIGALRM is $signo{ALRM}\n";
62 You may also choose to assign the strings C<"IGNORE"> or C<"DEFAULT"> as
63 the handler, in which case Perl will try to discard the signal or do the
66 On most Unix platforms, the C<CHLD> (sometimes also known as C<CLD>) signal
67 has special behavior with respect to a value of C<"IGNORE">.
68 Setting C<$SIG{CHLD}> to C<"IGNORE"> on such a platform has the effect of
69 not creating zombie processes when the parent process fails to C<wait()>
70 on its child processes (i.e., child processes are automatically reaped).
71 Calling C<wait()> with C<$SIG{CHLD}> set to C<"IGNORE"> usually returns
72 C<-1> on such platforms.
74 Some signals can be neither trapped nor ignored, such as the KILL and STOP
75 (but not the TSTP) signals. One strategy for temporarily ignoring signals
76 is to use a local() on that hash element, automatically restoring a
77 previous value once your block is exited. Remember that values created by
78 the dynamically-scoped local() are "inherited" by functions called from
79 within their caller's scope.
82 local $SIG{INT} = "IGNORE";
86 # interrupts still ignored, for now...
89 Sending a signal to a negative process ID means that you send the signal
90 to the entire Unix process group. This code sends a hang-up signal to all
91 processes in the current process group, and also sets $SIG{HUP} to C<"IGNORE">
92 so it doesn't kill itself:
94 # block scope for local
96 local $SIG{HUP} = "IGNORE";
98 # snazzy writing of: kill("HUP", -$$)
101 Another interesting signal to send is signal number zero. This doesn't
102 actually affect a child process, but instead checks whether it's alive
103 or has changed its UID.
105 unless (kill 0 => $kid_pid) {
106 warn "something wicked happened to $kid_pid";
109 When directed at a process whose UID is not identical to that
110 of the sending process, signal number zero may fail because
111 you lack permission to send the signal, even though the process is alive.
112 You may be able to determine the cause of failure using C<%!>.
114 unless (kill(0 => $pid) || $!{EPERM}) {
115 warn "$pid looks dead";
118 You might also want to employ anonymous functions for simple signal
121 $SIG{INT} = sub { die "\nOutta here!\n" };
123 But that will be problematic for the more complicated handlers that need
124 to reinstall themselves. Because Perl's signal mechanism is currently
125 based on the signal(3) function from the C library, you may sometimes be so
126 unfortunate as to run on systems where that function is "broken"; that
127 is, it behaves in the old unreliable SysV way rather than the newer, more
128 reasonable BSD and POSIX fashion. So you'll see defensive people writing
129 signal handlers like this:
133 # loathe SysV: it makes us not only reinstate
134 # the handler, but place it after the wait
135 $SIG{CHLD} = \&REAPER;
137 $SIG{CHLD} = \&REAPER;
138 # now do something that forks...
142 use POSIX ":sys_wait_h";
145 # If a second child dies while in the signal handler caused by the
146 # first death, we won't get another signal. So must loop here else
147 # we will leave the unreaped child as a zombie. And the next time
148 # two children die we get another zombie. And so on.
149 while (($child = waitpid(-1, WNOHANG)) > 0) {
150 $Kid_Status{$child} = $?;
152 $SIG{CHLD} = \&REAPER; # still loathe SysV
154 $SIG{CHLD} = \&REAPER;
155 # do something that forks...
157 Be careful: qx(), system(), and some modules for calling external commands
158 do a fork(), then wait() for the result. Thus, your signal handler
159 (C<&REAPER> in the example) will be called. Because wait() was already
160 called by system() or qx(), the wait() in the signal handler will see no
161 more zombies and will therefore block.
163 The best way to prevent this issue is to use waitpid(), as in the following
166 use POSIX ":sys_wait_h"; # for nonblocking read
171 # don't change $! and $? outside handler
173 my $pid = waitpid(-1, WNOHANG);
174 return if $pid == -1;
175 return unless defined $children{$pid};
176 delete $children{$pid};
177 cleanup_child($pid, $?);
182 die "cannot fork" unless defined $pid;
194 Signal handling is also used for timeouts in Unix. While safely
195 protected within an C<eval{}> block, you set a signal handler to trap
196 alarm signals and then schedule to have one delivered to you in some
197 number of seconds. Then try your blocking operation, clearing the alarm
198 when it's done but not before you've exited your C<eval{}> block. If it
199 goes off, you'll use die() to jump out of the block, much as you might
200 using longjmp() or throw() in other languages.
204 my $ALARM_EXCEPTION = "alarm clock restart";
206 local $SIG{ALRM} = sub { die $ALARM_EXCEPTION };
208 flock(FH, 2) # blocking write lock
209 || die "cannot flock: $!";
212 if ($@ && $@ !~ quotemeta($ALARM_EXCEPTION)) { die }
214 If the operation being timed out is system() or qx(), this technique
215 is liable to generate zombies. If this matters to you, you'll
216 need to do your own fork() and exec(), and kill the errant child process.
218 For more complex signal handling, you might see the standard POSIX
219 module. Lamentably, this is almost entirely undocumented, but
220 the F<t/lib/posix.t> file from the Perl source distribution has some
223 =head2 Handling the SIGHUP Signal in Daemons
225 A process that usually starts when the system boots and shuts down
226 when the system is shut down is called a daemon (Disk And Execution
227 MONitor). If a daemon process has a configuration file which is
228 modified after the process has been started, there should be a way to
229 tell that process to reread its configuration file without stopping
230 the process. Many daemons provide this mechanism using a C<SIGHUP>
231 signal handler. When you want to tell the daemon to reread the file,
232 simply send it the C<SIGHUP> signal.
234 Not all platforms automatically reinstall their (native) signal
235 handlers after a signal delivery. This means that the handler works
236 the first time the signal is sent, only. The solution to this problem
237 is to use C<POSIX> signal handlers if available; their behavior
240 The following example implements a simple daemon, which restarts
241 itself every time the C<SIGHUP> signal is received. The actual code is
242 located in the subroutine C<code()>, which just prints some debugging
243 info to show that it works; it should be replaced with the real code.
249 use File::Basename ();
250 use File::Spec::Functions;
254 # make the daemon cross-platform, so exec always calls the script
255 # itself with the right path, no matter how the script was invoked.
256 my $script = File::Basename::basename($0);
257 my $SELF = catfile($FindBin::Bin, $script);
259 # POSIX unmasks the sigprocmask properly
260 my $sigset = POSIX::SigSet->new();
261 my $action = POSIX::SigAction->new("sigHUP_handler",
264 POSIX::sigaction(&POSIX::SIGHUP, $action);
267 print "got SIGHUP\n";
268 exec($SELF, @ARGV) || die "$0: couldn't restart: $!";
275 print "ARGV: @ARGV\n";
284 =head2 Deferred Signals (Safe Signals)
286 Before Perl 5.7.3, installing Perl code to deal with signals exposed you to
287 danger from two things. First, few system library functions are
288 re-entrant. If the signal interrupts while Perl is executing one function
289 (like malloc(3) or printf(3)), and your signal handler then calls the same
290 function again, you could get unpredictable behavior--often, a core dump.
291 Second, Perl isn't itself re-entrant at the lowest levels. If the signal
292 interrupts Perl while Perl is changing its own internal data structures,
293 similarly unpredictable behavior may result.
295 There were two things you could do, knowing this: be paranoid or be
296 pragmatic. The paranoid approach was to do as little as possible in your
297 signal handler. Set an existing integer variable that already has a
298 value, and return. This doesn't help you if you're in a slow system call,
299 which will just restart. That means you have to C<die> to longjmp(3) out
300 of the handler. Even this is a little cavalier for the true paranoiac,
301 who avoids C<die> in a handler because the system I<is> out to get you.
302 The pragmatic approach was to say "I know the risks, but prefer the
303 convenience", and to do anything you wanted in your signal handler,
304 and be prepared to clean up core dumps now and again.
306 Perl 5.7.3 and later avoid these problems by "deferring" signals. That is,
307 when the signal is delivered to the process by the system (to the C code
308 that implements Perl) a flag is set, and the handler returns immediately.
309 Then at strategic "safe" points in the Perl interpreter (e.g. when it is
310 about to execute a new opcode) the flags are checked and the Perl level
311 handler from %SIG is executed. The "deferred" scheme allows much more
312 flexibility in the coding of signal handlers as we know the Perl
313 interpreter is in a safe state, and that we are not in a system library function when the handler is called. However the implementation does
314 differ from previous Perls in the following ways:
318 =item Long-running opcodes
320 As the Perl interpreter looks at signal flags only when it is about
321 to execute a new opcode, a signal that arrives during a long-running
322 opcode (e.g. a regular expression operation on a very large string) will
323 not be seen until the current opcode completes.
325 If a signal of any given type fires multiple times during an opcode
326 (such as from a fine-grained timer), the handler for that signal will
327 be called only once, after the opcode completes; all other
328 instances will be discarded. Furthermore, if your system's signal queue
329 gets flooded to the point that there are signals that have been raised
330 but not yet caught (and thus not deferred) at the time an opcode
331 completes, those signals may well be caught and deferred during
332 subsequent opcodes, with sometimes surprising results. For example, you
333 may see alarms delivered even after calling C<alarm(0)> as the latter
334 stops the raising of alarms but does not cancel the delivery of alarms
335 raised but not yet caught. Do not depend on the behaviors described in
336 this paragraph as they are side effects of the current implementation and
337 may change in future versions of Perl.
339 =item Interrupting IO
341 When a signal is delivered (e.g., SIGINT from a control-C) the operating
342 system breaks into IO operations like I<read>(2), which is used to
343 implement Perl's readline() function, the C<< <> >> operator. On older
344 Perls the handler was called immediately (and as C<read> is not "unsafe",
345 this worked well). With the "deferred" scheme the handler is I<not> called
346 immediately, and if Perl is using the system's C<stdio> library that
347 library may restart the C<read> without returning to Perl to give it a
348 chance to call the %SIG handler. If this happens on your system the
349 solution is to use the C<:perlio> layer to do IO--at least on those handles
350 that you want to be able to break into with signals. (The C<:perlio> layer
351 checks the signal flags and calls %SIG handlers before resuming IO
354 The default in Perl 5.7.3 and later is to automatically use
355 the C<:perlio> layer.
357 Note that it is not advisable to access a file handle within a signal
358 handler where that signal has interrupted an I/O operation on that same
359 handle. While perl will at least try hard not to crash, there are no
360 guarantees of data integrity; for example, some data might get dropped or
363 Some networking library functions like gethostbyname() are known to have
364 their own implementations of timeouts which may conflict with your
365 timeouts. If you have problems with such functions, try using the POSIX
366 sigaction() function, which bypasses Perl safe signals. Be warned that
367 this does subject you to possible memory corruption, as described above.
369 Instead of setting C<$SIG{ALRM}>:
371 local $SIG{ALRM} = sub { die "alarm" };
373 try something like the following:
375 use POSIX qw(SIGALRM);
376 POSIX::sigaction(SIGALRM,
377 POSIX::SigAction->new(sub { die "alarm" }))
378 || die "Error setting SIGALRM handler: $!\n";
380 Another way to disable the safe signal behavior locally is to use
381 the C<Perl::Unsafe::Signals> module from CPAN, which affects
384 =item Restartable system calls
386 On systems that supported it, older versions of Perl used the
387 SA_RESTART flag when installing %SIG handlers. This meant that
388 restartable system calls would continue rather than returning when
389 a signal arrived. In order to deliver deferred signals promptly,
390 Perl 5.7.3 and later do I<not> use SA_RESTART. Consequently,
391 restartable system calls can fail (with $! set to C<EINTR>) in places
392 where they previously would have succeeded.
394 The default C<:perlio> layer retries C<read>, C<write>
395 and C<close> as described above; interrupted C<wait> and
396 C<waitpid> calls will always be retried.
398 =item Signals as "faults"
400 Certain signals like SEGV, ILL, and BUS are generated by virtual memory
401 addressing errors and similiar "faults". These are normally fatal: there is
402 little a Perl-level handler can do with them. So Perl now delivers them
403 immediately rather than attempting to defer them.
405 =item Signals triggered by operating system state
407 On some operating systems certain signal handlers are supposed to "do
408 something" before returning. One example can be CHLD or CLD, which
409 indicates a child process has completed. On some operating systems the
410 signal handler is expected to C<wait> for the completed child
411 process. On such systems the deferred signal scheme will not work for
412 those signals: it does not do the C<wait>. Again the failure will
413 look like a loop as the operating system will reissue the signal because
414 there are completed child processes that have not yet been C<wait>ed for.
418 If you want the old signal behavior back despite possible
419 memory corruption, set the environment variable C<PERL_SIGNALS> to
420 C<"unsafe">. This feature first appeared in Perl 5.8.1.
424 A named pipe (often referred to as a FIFO) is an old Unix IPC
425 mechanism for processes communicating on the same machine. It works
426 just like regular anonymous pipes, except that the
427 processes rendezvous using a filename and need not be related.
429 To create a named pipe, use the C<POSIX::mkfifo()> function.
431 use POSIX qw(mkfifo);
432 mkfifo($path, 0700) || die "mkfifo $path failed: $!";
434 You can also use the Unix command mknod(1), or on some
435 systems, mkfifo(1). These may not be in your normal path, though.
437 # system return val is backwards, so && not ||
439 $ENV{PATH} .= ":/etc:/usr/etc";
440 if ( system("mknod", $path, "p")
441 && system("mkfifo", $path) )
443 die "mk{nod,fifo} $path failed";
447 A fifo is convenient when you want to connect a process to an unrelated
448 one. When you open a fifo, the program will block until there's something
451 For example, let's say you'd like to have your F<.signature> file be a
452 named pipe that has a Perl program on the other end. Now every time any
453 program (like a mailer, news reader, finger program, etc.) tries to read
454 from that file, the reading program will read the new signature from your
455 program. We'll use the pipe-checking file-test operator, B<-p>, to find
456 out whether anyone (or anything) has accidentally removed our fifo.
459 my $FIFO = ".signature";
463 unlink $FIFO; # discard any failure, will catch later
464 require POSIX; # delayed loading of heavy module
465 POSIX::mkfifo($FIFO, 0700)
466 || die "can't mkfifo $FIFO: $!";
469 # next line blocks till there's a reader
470 open (FIFO, "> $FIFO") || die "can't open $FIFO: $!";
471 print FIFO "John Smith (smith\@host.org)\n", `fortune -s`;
472 close(FIFO) || die "can't close $FIFO: $!";
473 sleep 2; # to avoid dup signals
476 =head1 Using open() for IPC
478 Perl's basic open() statement can also be used for unidirectional
479 interprocess communication by either appending or prepending a pipe
480 symbol to the second argument to open(). Here's how to start
481 something up in a child process you intend to write to:
483 open(SPOOLER, "| cat -v | lpr -h 2>/dev/null")
484 || die "can't fork: $!";
485 local $SIG{PIPE} = sub { die "spooler pipe broke" };
486 print SPOOLER "stuff\n";
487 close SPOOLER || die "bad spool: $! $?";
489 And here's how to start up a child process you intend to read from:
491 open(STATUS, "netstat -an 2>&1 |")
492 || die "can't fork: $!";
494 next if /^(tcp|udp)/;
497 close STATUS || die "bad netstat: $! $?";
499 If one can be sure that a particular program is a Perl script expecting
500 filenames in @ARGV, the clever programmer can write something like this:
502 % program f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile
504 and no matter which sort of shell it's called from, the Perl program will
505 read from the file F<f1>, the process F<cmd1>, standard input (F<tmpfile>
506 in this case), the F<f2> file, the F<cmd2> command, and finally the F<f3>
507 file. Pretty nifty, eh?
509 You might notice that you could use backticks for much the
510 same effect as opening a pipe for reading:
512 print grep { !/^(tcp|udp)/ } `netstat -an 2>&1`;
513 die "bad netstatus ($?)" if $?;
515 While this is true on the surface, it's much more efficient to process the
516 file one line or record at a time because then you don't have to read the
517 whole thing into memory at once. It also gives you finer control of the
518 whole process, letting you kill off the child process early if you'd like.
520 Be careful to check the return values from both open() and close(). If
521 you're I<writing> to a pipe, you should also trap SIGPIPE. Otherwise,
522 think of what happens when you start up a pipe to a command that doesn't
523 exist: the open() will in all likelihood succeed (it only reflects the
524 fork()'s success), but then your output will fail--spectacularly. Perl
525 can't know whether the command worked, because your command is actually
526 running in a separate process whose exec() might have failed. Therefore,
527 while readers of bogus commands return just a quick EOF, writers
528 to bogus commands will get hit with a signal, which they'd best be prepared
531 open(FH, "|bogus") || die "can't fork: $!";
532 print FH "bang\n"; # neither necessary nor sufficient
533 # to check print retval!
534 close(FH) || die "can't close: $!";
536 The reason for not checking the return value from print() is because of
537 pipe buffering; physical writes are delayed. That won't blow up until the
538 close, and it will blow up with a SIGPIPE. To catch it, you could use
541 $SIG{PIPE} = "IGNORE";
542 open(FH, "|bogus") || die "can't fork: $!";
544 close(FH) || die "can't close: status=$?";
548 Both the main process and any child processes it forks share the same
549 STDIN, STDOUT, and STDERR filehandles. If both processes try to access
550 them at once, strange things can happen. You may also want to close
551 or reopen the filehandles for the child. You can get around this by
552 opening your pipe with open(), but on some systems this means that the
553 child process cannot outlive the parent.
555 =head2 Background Processes
557 You can run a command in the background with:
561 The command's STDOUT and STDERR (and possibly STDIN, depending on your
562 shell) will be the same as the parent's. You won't need to catch
563 SIGCHLD because of the double-fork taking place; see below for details.
565 =head2 Complete Dissociation of Child from Parent
567 In some cases (starting server processes, for instance) you'll want to
568 completely dissociate the child process from the parent. This is
569 often called daemonization. A well-behaved daemon will also chdir()
570 to the root directory so it doesn't prevent unmounting the filesystem
571 containing the directory from which it was launched, and redirect its
572 standard file descriptors from and to F</dev/null> so that random
573 output doesn't wind up on the user's terminal.
578 chdir("/") || die "can't chdir to /: $!";
579 open(STDIN, "< /dev/null") || die "can't read /dev/null: $!";
580 open(STDOUT, "> /dev/null") || die "can't write to /dev/null: $!";
581 defined(my $pid = fork()) || die "can't fork: $!";
582 exit if $pid; # non-zero now means I am the parent
583 (setsid() != -1) || die "Can't start a new session: $!"
584 open(STDERR, ">&STDOUT") || die "can't dup stdout: $!";
587 The fork() has to come before the setsid() to ensure you aren't a
588 process group leader; the setsid() will fail if you are. If your
589 system doesn't have the setsid() function, open F</dev/tty> and use the
590 C<TIOCNOTTY> ioctl() on it instead. See tty(4) for details.
592 Non-Unix users should check their C<< I<Your_OS>::Process >> module for
593 other possible solutions.
595 =head2 Safe Pipe Opens
597 Another interesting approach to IPC is making your single program go
598 multiprocess and communicate between--or even amongst--yourselves. The
599 open() function will accept a file argument of either C<"-|"> or C<"|-">
600 to do a very interesting thing: it forks a child connected to the
601 filehandle you've opened. The child is running the same program as the
602 parent. This is useful for safely opening a file when running under an
603 assumed UID or GID, for example. If you open a pipe I<to> minus, you can
604 write to the filehandle you opened and your kid will find it in I<his>
605 STDIN. If you open a pipe I<from> minus, you can read from the filehandle
606 you opened whatever your kid writes to I<his> STDOUT.
608 use English qw[ -no_match_vars ];
609 my $PRECIOUS = "/path/to/some/safe/file";
614 $pid = open(KID_TO_WRITE, "|-");
615 unless (defined $pid) {
616 warn "cannot fork: $!";
617 die "bailing out" if $sleep_count++ > 6;
620 } until defined $pid;
622 if ($pid) { # I am the parent
623 print KID_TO_WRITE @some_data;
624 close(KID_TO_WRITE) || warn "kid exited $?";
625 } else { # I am the child
626 # drop permissions in setuid and/or setgid programs:
627 ($EUID, $EGID) = ($UID, $GID);
628 open (OUTFILE, "> $PRECIOUS")
629 || die "can't open $PRECIOUS: $!";
631 print OUTFILE; # child's STDIN is parent's KID_TO_WRITE
633 close(OUTFILE) || die "can't close $PRECIOUS: $!";
634 exit(0); # don't forget this!!
637 Another common use for this construct is when you need to execute
638 something without the shell's interference. With system(), it's
639 straightforward, but you can't use a pipe open or backticks safely.
640 That's because there's no way to stop the shell from getting its hands on
641 your arguments. Instead, use lower-level control to call exec() directly.
643 Here's a safe backtick or pipe open for read:
645 my $pid = open(KID_TO_READ, "-|");
646 defined($pid) || die "can't fork: $!";
649 while (<KID_TO_READ>) {
650 # do something interesting
652 close(KID_TO_READ) || warn "kid exited $?";
655 ($EUID, $EGID) = ($UID, $GID); # suid only
656 exec($program, @options, @args)
657 || die "can't exec program: $!";
661 And here's a safe pipe open for writing:
663 my $pid = open(KID_TO_WRITE, "|-");
664 defined($pid) || die "can't fork: $!";
666 $SIG{PIPE} = sub { die "whoops, $program pipe broke" };
669 print KID_TO_WRITE @data;
670 close(KID_TO_WRITE) || warn "kid exited $?";
673 ($EUID, $EGID) = ($UID, $GID);
674 exec($program, @options, @args)
675 || die "can't exec program: $!";
679 It is very easy to dead-lock a process using this form of open(), or
680 indeed with any use of pipe() with multiple subprocesses. The
681 example above is "safe" because it is simple and calls exec(). See
682 L</"Avoiding Pipe Deadlocks"> for general safety principles, but there
683 are extra gotchas with Safe Pipe Opens.
685 In particular, if you opened the pipe using C<open FH, "|-">, then you
686 cannot simply use close() in the parent process to close an unwanted
687 writer. Consider this code:
689 my $pid = open(WRITER, "|-"); # fork open a kid
690 defined($pid) || die "first fork failed: $!";
692 if (my $sub_pid = fork()) {
693 defined($sub_pid) || die "second fork failed: $!";
694 close(WRITER) || die "couldn't close WRITER: $!";
695 # now do something else...
698 # first write to WRITER
701 close(WRITER) || die "couldn't close WRITER: $!";
706 # first do something with STDIN, then
710 In the example above, the true parent does not want to write to the WRITER
711 filehandle, so it closes it. However, because WRITER was opened using
712 C<open FH, "|-">, it has a special behavior: closing it calls
713 waitpid() (see L<perlfunc/waitpid>), which waits for the subprocess
714 to exit. If the child process ends up waiting for something happening
715 in the section marked "do something else", you have deadlock.
717 This can also be a problem with intermediate subprocesses in more
718 complicated code, which will call waitpid() on all open filehandles
719 during global destruction--in no predictable order.
721 To solve this, you must manually use pipe(), fork(), and the form of
722 open() which sets one file descriptor to another, as shown below:
724 pipe(READER, WRITER) || die "pipe failed: $!";
726 defined($pid) || die "first fork failed: $!";
729 if (my $sub_pid = fork()) {
730 defined($sub_pid) || die "first fork failed: $!";
731 close(WRITER) || die "can't close WRITER: $!";
737 close(WRITER) || die "can't close WRITER: $!";
743 open(STDIN, "<&READER") || die "can't reopen STDIN: $!";
744 close(WRITER) || die "can't close WRITER: $!";
749 Since Perl 5.8.0, you can also use the list form of C<open> for pipes.
750 This is preferred when you wish to avoid having the shell interpret
751 metacharacters that may be in your command string.
753 So for example, instead of using:
755 open(PS_PIPE, "ps aux|") || die "can't open ps pipe: $!";
757 One would use either of these:
759 open(PS_PIPE, "-|", "ps", "aux")
760 || die "can't open ps pipe: $!";
762 @ps_args = qw[ ps aux ];
763 open(PS_PIPE, "-|", @ps_args)
764 || die "can't open @ps_args|: $!";
766 Because there are more than three arguments to open(), forks the ps(1)
767 command I<without> spawning a shell, and reads its standard output via the
768 C<PS_PIPE> filehandle. The corresponding syntax to I<write> to command
769 pipes is to use C<"|-"> in place of C<"-|">.
771 This was admittedly a rather silly example, because you're using string
772 literals whose content is perfectly safe. There is therefore no cause to
773 resort to the harder-to-read, multi-argument form of pipe open(). However,
774 whenever you cannot be assured that the program arguments are free of shell
775 metacharacters, the fancier form of open() should be used. For example:
777 @grep_args = ("egrep", "-i", $some_pattern, @many_files);
778 open(GREP_PIPE, "-|", @grep_args)
779 || die "can't open @grep_args|: $!";
781 Here the multi-argument form of pipe open() is preferred because the
782 pattern and indeed even the filenames themselves might hold metacharacters.
784 Be aware that these operations are full Unix forks, which means they may
785 not be correctly implemented on all alien systems. Additionally, these are
786 not true multithreading. To learn more about threading, see the F<modules>
787 file mentioned below in the SEE ALSO section.
789 =head2 Avoiding Pipe Deadlocks
791 Whenever you have more than one subprocess, you must be careful that each
792 closes whichever half of any pipes created for interprocess communication
793 it is not using. This is because any child process reading from the pipe
794 and expecting an EOF will never receive it, and therefore never exit. A
795 single process closing a pipe is not enough to close it; the last process
796 with the pipe open must close it for it to read EOF.
798 Certain built-in Unix features help prevent this most of the time. For
799 instance, filehandles have a "close on exec" flag, which is set I<en masse>
800 under control of the C<$^F> variable. This is so any filehandles you
801 didn't explicitly route to the STDIN, STDOUT or STDERR of a child
802 I<program> will be automatically closed.
804 Always explicitly and immediately call close() on the writable end of any
805 pipe, unless that process is actually writing to it. Even if you don't
806 explicitly call close(), Perl will still close() all filehandles during
807 global destruction. As previously discussed, if those filehandles have
808 been opened with Safe Pipe Open, this will result in calling waitpid(),
809 which may again deadlock.
811 =head2 Bidirectional Communication with Another Process
813 While this works reasonably well for unidirectional communication, what
814 about bidirectional communication? The most obvious approach doesn't work:
816 # THIS DOES NOT WORK!!
817 open(PROG_FOR_READING_AND_WRITING, "| some program |")
819 If you forget to C<use warnings>, you'll miss out entirely on the
820 helpful diagnostic message:
822 Can't do bidirectional pipe at -e line 1.
824 If you really want to, you can use the standard open2() from the
825 C<IPC::Open2> module to catch both ends. There's also an open3() in
826 C<IPC::Open3> for tridirectional I/O so you can also catch your child's
827 STDERR, but doing so would then require an awkward select() loop and
828 wouldn't allow you to use normal Perl input operations.
830 If you look at its source, you'll see that open2() uses low-level
831 primitives like the pipe() and exec() syscalls to create all the
832 connections. Although it might have been more efficient by using
833 socketpair(), this would have been even less portable than it already
834 is. The open2() and open3() functions are unlikely to work anywhere
835 except on a Unix system, or at least one purporting POSIX compliance.
838 Hold on, is this even true? First it says that socketpair() is avoided
839 for portability, but then it says it probably won't work except on
840 Unixy systems anyway. Which one of those is true?
842 Here's an example of using open2():
846 $pid = open2(*Reader, *Writer, "cat -un");
847 print Writer "stuff\n";
850 The problem with this is that buffering is really going to ruin your
851 day. Even though your C<Writer> filehandle is auto-flushed so the process
852 on the other end gets your data in a timely manner, you can't usually do
853 anything to force that process to give its data to you in a similarly quick
854 fashion. In this special case, we could actually so, because we gave
855 I<cat> a B<-u> flag to make it unbuffered. But very few commands are
856 designed to operate over pipes, so this seldom works unless you yourself
857 wrote the program on the other end of the double-ended pipe.
859 A solution to this is to use a library which uses pseudottys to make your
860 program behave more reasonably. This way you don't have to have control
861 over the source code of the program you're using. The C<Expect> module
862 from CPAN also addresses this kind of thing. This module requires two
863 other modules from CPAN, C<IO::Pty> and C<IO::Stty>. It sets up a pseudo
864 terminal to interact with programs that insist on talking to the terminal
865 device driver. If your system is supported, this may be your best bet.
867 =head2 Bidirectional Communication with Yourself
869 If you want, you may make low-level pipe() and fork() syscalls to stitch
870 this together by hand. This example only talks to itself, but you could
871 reopen the appropriate handles to STDIN and STDOUT and call other processes.
872 (The following example lacks proper error checking.)
875 # pipe1 - bidirectional communication using two pipe pairs
876 # designed for the socketpair-challenged
877 use IO::Handle; # thousands of lines just for autoflush :-(
878 pipe(PARENT_RDR, CHILD_WTR); # XXX: check failure?
879 pipe(CHILD_RDR, PARENT_WTR); # XXX: check failure?
880 CHILD_WTR->autoflush(1);
881 PARENT_WTR->autoflush(1);
886 print CHILD_WTR "Parent Pid $$ is sending this\n";
887 chomp($line = <CHILD_RDR>);
888 print "Parent Pid $$ just read this: `$line'\n";
889 close CHILD_RDR; close CHILD_WTR;
892 die "cannot fork: $!" unless defined $pid;
895 chomp($line = <PARENT_RDR>);
896 print "Child Pid $$ just read this: `$line'\n";
897 print PARENT_WTR "Child Pid $$ is sending this\n";
903 But you don't actually have to make two pipe calls. If you
904 have the socketpair() system call, it will do this all for you.
907 # pipe2 - bidirectional communication using socketpair
908 # "the best ones always go both ways"
911 use IO::Handle; # thousands of lines just for autoflush :-(
913 # We say AF_UNIX because although *_LOCAL is the
914 # POSIX 1003.1g form of the constant, many machines
915 # still don't have it.
916 socketpair(CHILD, PARENT, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
917 || die "socketpair: $!";
920 PARENT->autoflush(1);
924 print CHILD "Parent Pid $$ is sending this\n";
925 chomp($line = <CHILD>);
926 print "Parent Pid $$ just read this: `$line'\n";
930 die "cannot fork: $!" unless defined $pid;
932 chomp($line = <PARENT>);
933 print "Child Pid $$ just read this: '$line'\n";
934 print PARENT "Child Pid $$ is sending this\n";
939 =head1 Sockets: Client/Server Communication
941 While not entirely limited to Unix-derived operating systems (e.g., WinSock
942 on PCs provides socket support, as do some VMS libraries), you might not have
943 sockets on your system, in which case this section probably isn't going to
944 do you much good. With sockets, you can do both virtual circuits like TCP
945 streams and datagrams like UDP packets. You may be able to do even more
946 depending on your system.
948 The Perl functions for dealing with sockets have the same names as
949 the corresponding system calls in C, but their arguments tend to differ
950 for two reasons. First, Perl filehandles work differently than C file
951 descriptors. Second, Perl already knows the length of its strings, so you
952 don't need to pass that information.
954 One of the major problems with ancient, antemillennial socket code in Perl
955 was that it used hard-coded values for some of the constants, which
956 severely hurt portability. If you ever see code that does anything like
957 explicitly setting C<$AF_INET = 2>, you know you're in for big trouble.
958 An immeasurably superior approach is to use the C<Socket> module, which more
959 reliably grants access to the various constants and functions you'll need.
961 If you're not writing a server/client for an existing protocol like
962 NNTP or SMTP, you should give some thought to how your server will
963 know when the client has finished talking, and vice-versa. Most
964 protocols are based on one-line messages and responses (so one party
965 knows the other has finished when a "\n" is received) or multi-line
966 messages and responses that end with a period on an empty line
967 ("\n.\n" terminates a message/response).
969 =head2 Internet Line Terminators
971 The Internet line terminator is "\015\012". Under ASCII variants of
972 Unix, that could usually be written as "\r\n", but under other systems,
973 "\r\n" might at times be "\015\015\012", "\012\012\015", or something
974 completely different. The standards specify writing "\015\012" to be
975 conformant (be strict in what you provide), but they also recommend
976 accepting a lone "\012" on input (be lenient in what you require).
977 We haven't always been very good about that in the code in this manpage,
978 but unless you're on a Mac from way back in its pre-Unix dark ages, you'll
981 =head2 Internet TCP Clients and Servers
983 Use Internet-domain sockets when you want to do client-server
984 communication that might extend to machines outside of your own system.
986 Here's a sample TCP client using Internet-domain sockets:
991 my ($remote, $port, $iaddr, $paddr, $proto, $line);
993 $remote = shift || "localhost";
994 $port = shift || 2345; # random port
995 if ($port =~ /\D/) { $port = getservbyname($port, "tcp") }
996 die "No port" unless $port;
997 $iaddr = inet_aton($remote) || die "no host: $remote";
998 $paddr = sockaddr_in($port, $iaddr);
1000 $proto = getprotobyname("tcp");
1001 socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
1002 connect(SOCK, $paddr) || die "connect: $!";
1003 while ($line = <SOCK>) {
1007 close (SOCK) || die "close: $!";
1010 And here's a corresponding server to go along with it. We'll
1011 leave the address as C<INADDR_ANY> so that the kernel can choose
1012 the appropriate interface on multihomed hosts. If you want sit
1013 on a particular interface (like the external side of a gateway
1014 or firewall machine), fill this in with your real address instead.
1018 BEGIN { $ENV{PATH} = "/usr/bin:/bin" }
1021 my $EOL = "\015\012";
1023 sub logmsg { print "$0 $$: @_ at ", scalar localtime(), "\n" }
1025 my $port = shift || 2345;
1026 die "invalid port" unless if $port =~ /^ \d+ $/x;
1028 my $proto = getprotobyname("tcp");
1030 socket(Server, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
1031 setsockopt(Server, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))
1032 || die "setsockopt: $!";
1033 bind(Server, sockaddr_in($port, INADDR_ANY)) || die "bind: $!";
1034 listen(Server, SOMAXCONN) || die "listen: $!";
1036 logmsg "server started on port $port";
1040 $SIG{CHLD} = \&REAPER;
1042 for ( ; $paddr = accept(Client, Server); close Client) {
1043 my($port, $iaddr) = sockaddr_in($paddr);
1044 my $name = gethostbyaddr($iaddr, AF_INET);
1046 logmsg "connection from $name [",
1047 inet_ntoa($iaddr), "]
1050 print Client "Hello there, $name, it's now ",
1051 scalar localtime(), $EOL;
1054 And here's a multithreaded version. It's multithreaded in that
1055 like most typical servers, it spawns (fork()s) a slave server to
1056 handle the client request so that the master server can quickly
1057 go back to service a new client.
1061 BEGIN { $ENV{PATH} = "/usr/bin:/bin" }
1064 my $EOL = "\015\012";
1066 sub spawn; # forward declaration
1067 sub logmsg { print "$0 $$: @_ at ", scalar localtime(), "\n" }
1069 my $port = shift || 2345;
1070 die "invalid port" unless if $port =~ /^ \d+ $/x;
1072 my $proto = getprotobyname("tcp");
1074 socket(Server, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
1075 setsockopt(Server, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))
1076 || die "setsockopt: $!";
1077 bind(Server, sockaddr_in($port, INADDR_ANY)) || die "bind: $!";
1078 listen(Server, SOMAXCONN) || die "listen: $!";
1080 logmsg "server started on port $port";
1085 use POSIX ":sys_wait_h";
1089 local $!; # don't let waitpid() overwrite current error
1090 while ((my $pid = waitpid(-1, WNOHANG)) > 0 && WIFEXITED($?)) {
1091 logmsg "reaped $waitedpid" . ($? ? " with exit $?" : "");
1093 $SIG{CHLD} = \&REAPER; # loathe SysV
1096 $SIG{CHLD} = \&REAPER;
1099 $paddr = accept(Client, Server) || do {
1100 # try again if accept() returned because got a signal
1104 my ($port, $iaddr) = sockaddr_in($paddr);
1105 my $name = gethostbyaddr($iaddr, AF_INET);
1107 logmsg "connection from $name [",
1113 print "Hello there, $name, it's now ", scalar localtime(), $EOL;
1114 exec "/usr/games/fortune" # XXX: "wrong" line terminators
1115 or confess "can't exec fortune: $!";
1121 my $coderef = shift;
1123 unless (@_ == 0 && $coderef && ref($coderef) eq "CODE") {
1124 confess "usage: spawn CODEREF";
1128 unless (defined($pid = fork())) {
1129 logmsg "cannot fork: $!";
1133 logmsg "begat $pid";
1134 return; # I'm the parent
1136 # else I'm the child -- go spawn
1138 open(STDIN, "<&Client") || die "can't dup client to stdin";
1139 open(STDOUT, ">&Client") || die "can't dup client to stdout";
1140 ## open(STDERR, ">&STDOUT") || die "can't dup stdout to stderr";
1144 This server takes the trouble to clone off a child version via fork()
1145 for each incoming request. That way it can handle many requests at
1146 once, which you might not always want. Even if you don't fork(), the
1147 listen() will allow that many pending connections. Forking servers
1148 have to be particularly careful about cleaning up their dead children
1149 (called "zombies" in Unix parlance), because otherwise you'll quickly
1150 fill up your process table. The REAPER subroutine is used here to
1151 call waitpid() for any child processes that have finished, thereby
1152 ensuring that they terminate cleanly and don't join the ranks of the
1155 Within the while loop we call accept() and check to see if it returns
1156 a false value. This would normally indicate a system error needs
1157 to be reported. However, the introduction of safe signals (see
1158 L</Deferred Signals (Safe Signals)> above) in Perl 5.7.3 means that
1159 accept() might also be interrupted when the process receives a signal.
1160 This typically happens when one of the forked subprocesses exits and
1161 notifies the parent process with a CHLD signal.
1163 If accept() is interrupted by a signal, $! will be set to EINTR.
1164 If this happens, we can safely continue to the next iteration of
1165 the loop and another call to accept(). It is important that your
1166 signal handling code not modify the value of $!, or else this test
1167 will likely fail. In the REAPER subroutine we create a local version
1168 of $! before calling waitpid(). When waitpid() sets $! to ECHILD as
1169 it inevitably does when it has no more children waiting, it
1170 updates the local copy and leaves the original unchanged.
1172 You should use the B<-T> flag to enable taint checking (see L<perlsec>)
1173 even if we aren't running setuid or setgid. This is always a good idea
1174 for servers or any program run on behalf of someone else (like CGI
1175 scripts), because it lessens the chances that people from the outside will
1176 be able to compromise your system.
1178 Let's look at another TCP client. This one connects to the TCP "time"
1179 service on a number of different machines and shows how far their clocks
1180 differ from the system on which it's being run:
1186 my $SECS_OF_70_YEARS = 2208988800;
1187 sub ctime { scalar localtime(shift() || time()) }
1189 my $iaddr = gethostbyname("localhost");
1190 my $proto = getprotobyname("tcp");
1191 my $port = getservbyname("time", "tcp");
1192 my $paddr = sockaddr_in(0, $iaddr);
1196 printf "%-24s %8s %s\n", "localhost", 0, ctime();
1198 foreach $host (@ARGV) {
1199 printf "%-24s ", $host;
1200 my $hisiaddr = inet_aton($host) || die "unknown host";
1201 my $hispaddr = sockaddr_in($port, $hisiaddr);
1202 socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
1203 || die "socket: $!";
1204 connect(SOCKET, $hispaddr) || die "connect: $!";
1205 my $rtime = pack("C4", ());
1206 read(SOCKET, $rtime, 4);
1208 my $histime = unpack("N", $rtime) - $SECS_OF_70_YEARS;
1209 printf "%8d %s\n", $histime - time(), ctime($histime);
1212 =head2 Unix-Domain TCP Clients and Servers
1214 That's fine for Internet-domain clients and servers, but what about local
1215 communications? While you can use the same setup, sometimes you don't
1216 want to. Unix-domain sockets are local to the current host, and are often
1217 used internally to implement pipes. Unlike Internet domain sockets, Unix
1218 domain sockets can show up in the file system with an ls(1) listing.
1221 srw-rw-rw- 1 root 0 Oct 31 07:23 /dev/log
1223 You can test for these with Perl's B<-S> file test:
1225 unless (-S "/dev/log") {
1226 die "something's wicked with the log system";
1229 Here's a sample Unix-domain client:
1234 my ($rendezvous, $line);
1236 $rendezvous = shift || "catsock";
1237 socket(SOCK, PF_UNIX, SOCK_STREAM, 0) || die "socket: $!";
1238 connect(SOCK, sockaddr_un($rendezvous)) || die "connect: $!";
1239 while (defined($line = <SOCK>)) {
1244 And here's a corresponding server. You don't have to worry about silly
1245 network terminators here because Unix domain sockets are guaranteed
1246 to be on the localhost, and thus everything works right.
1253 BEGIN { $ENV{PATH} = "/usr/bin:/bin" }
1254 sub spawn; # forward declaration
1255 sub logmsg { print "$0 $$: @_ at ", scalar localtime(), "\n" }
1257 my $NAME = "catsock";
1258 my $uaddr = sockaddr_un($NAME);
1259 my $proto = getprotobyname("tcp");
1261 socket(Server, PF_UNIX, SOCK_STREAM, 0) || die "socket: $!";
1263 bind (Server, $uaddr) || die "bind: $!";
1264 listen(Server, SOMAXCONN) || die "listen: $!";
1266 logmsg "server started on $NAME";
1270 use POSIX ":sys_wait_h";
1273 while (($waitedpid = waitpid(-1, WNOHANG)) > 0) {
1274 logmsg "reaped $waitedpid" . ($? ? " with exit $?" : "");
1276 $SIG{CHLD} = \&REAPER; # loathe SysV
1279 $SIG{CHLD} = \&REAPER;
1282 for ( $waitedpid = 0;
1283 accept(Client, Server) || $waitedpid;
1284 $waitedpid = 0, close Client)
1287 logmsg "connection on $NAME";
1289 print "Hello there, it's now ", scalar localtime(), "\n";
1290 exec("/usr/games/fortune") || die "can't exec fortune: $!";
1295 my $coderef = shift();
1297 unless (@_ == 0 && $coderef && ref($coderef) eq "CODE") {
1298 confess "usage: spawn CODEREF";
1302 unless (defined($pid = fork())) {
1303 logmsg "cannot fork: $!";
1307 logmsg "begat $pid";
1308 return; # I'm the parent
1311 # I'm the child -- go spawn
1314 open(STDIN, "<&Client") || die "can't dup client to stdin";
1315 open(STDOUT, ">&Client") || die "can't dup client to stdout";
1316 ## open(STDERR, ">&STDOUT") || die "can't dup stdout to stderr";
1320 As you see, it's remarkably similar to the Internet domain TCP server, so
1321 much so, in fact, that we've omitted several duplicate functions--spawn(),
1322 logmsg(), ctime(), and REAPER()--which are the same as in the other server.
1324 So why would you ever want to use a Unix domain socket instead of a
1325 simpler named pipe? Because a named pipe doesn't give you sessions. You
1326 can't tell one process's data from another's. With socket programming,
1327 you get a separate session for each client; that's why accept() takes two
1330 For example, let's say that you have a long-running database server daemon
1331 that you want folks to be able to access from the Web, but only
1332 if they go through a CGI interface. You'd have a small, simple CGI
1333 program that does whatever checks and logging you feel like, and then acts
1334 as a Unix-domain client and connects to your private server.
1336 =head1 TCP Clients with IO::Socket
1338 For those preferring a higher-level interface to socket programming, the
1339 IO::Socket module provides an object-oriented approach. IO::Socket has
1340 been included in the standard Perl distribution ever since Perl 5.004. If
1341 you're running an earlier version of Perl (in which case, how are you
1342 reading this manpage?), just fetch IO::Socket from CPAN, where you'll also
1343 find modules providing easy interfaces to the following systems: DNS, FTP,
1344 Ident (RFC 931), NIS and NISPlus, NNTP, Ping, POP3, SMTP, SNMP, SSLeay,
1345 Telnet, and Time--to name just a few.
1347 =head2 A Simple Client
1349 Here's a client that creates a TCP connection to the "daytime"
1350 service at port 13 of the host name "localhost" and prints out everything
1351 that the server there cares to provide.
1355 $remote = IO::Socket::INET->new(
1357 PeerAddr => "localhost",
1358 PeerPort => "daytime(13)",
1360 || die "can't connect to daytime service on localhost";
1361 while (<$remote>) { print }
1363 When you run this program, you should get something back that
1366 Wed May 14 08:40:46 MDT 1997
1368 Here are what those parameters to the new() constructor mean:
1374 This is which protocol to use. In this case, the socket handle returned
1375 will be connected to a TCP socket, because we want a stream-oriented
1376 connection, that is, one that acts pretty much like a plain old file.
1377 Not all sockets are this of this type. For example, the UDP protocol
1378 can be used to make a datagram socket, used for message-passing.
1382 This is the name or Internet address of the remote host the server is
1383 running on. We could have specified a longer name like C<"www.perl.com">,
1384 or an address like C<"207.171.7.72">. For demonstration purposes, we've
1385 used the special hostname C<"localhost">, which should always mean the
1386 current machine you're running on. The corresponding Internet address
1387 for localhost is C<"127.0.0.1">, if you'd rather use that.
1391 This is the service name or port number we'd like to connect to.
1392 We could have gotten away with using just C<"daytime"> on systems with a
1393 well-configured system services file,[FOOTNOTE: The system services file
1394 is found in I</etc/services> under Unixy systems.] but here we've specified the
1395 port number (13) in parentheses. Using just the number would have also
1396 worked, but numeric literals make careful programmers nervous.
1400 Notice how the return value from the C<new> constructor is used as
1401 a filehandle in the C<while> loop? That's what's called an I<indirect
1402 filehandle>, a scalar variable containing a filehandle. You can use
1403 it the same way you would a normal filehandle. For example, you
1404 can read one line from it this way:
1408 all remaining lines from is this way:
1412 and send a line of data to it this way:
1414 print $handle "some data\n";
1416 =head2 A Webget Client
1418 Here's a simple client that takes a remote host to fetch a document
1419 from, and then a list of files to get from that host. This is a
1420 more interesting client than the previous one because it first sends
1421 something to the server before fetching the server's response.
1425 unless (@ARGV > 1) { die "usage: $0 host url ..." }
1426 $host = shift(@ARGV);
1429 for my $document (@ARGV) {
1430 $remote = IO::Socket::INET->new( Proto => "tcp",
1432 PeerPort => "http(80)",
1433 ) || die "cannot connect to httpd on $host";
1434 $remote->autoflush(1);
1435 print $remote "GET $document HTTP/1.0" . $BLANK;
1436 while ( <$remote> ) { print }
1440 The web server handling the HTTP service is assumed to be at
1441 its standard port, number 80. If the server you're trying to
1442 connect to is at a different port, like 1080 or 8080, you should specify it
1443 as the named-parameter pair, C<< PeerPort => 8080 >>. The C<autoflush>
1444 method is used on the socket because otherwise the system would buffer
1445 up the output we sent it. (If you're on a prehistoric Mac, you'll also
1446 need to change every C<"\n"> in your code that sends data over the network
1447 to be a C<"\015\012"> instead.)
1449 Connecting to the server is only the first part of the process: once you
1450 have the connection, you have to use the server's language. Each server
1451 on the network has its own little command language that it expects as
1452 input. The string that we send to the server starting with "GET" is in
1453 HTTP syntax. In this case, we simply request each specified document.
1454 Yes, we really are making a new connection for each document, even though
1455 it's the same host. That's the way you always used to have to speak HTTP.
1456 Recent versions of web browsers may request that the remote server leave
1457 the connection open a little while, but the server doesn't have to honor
1460 Here's an example of running that program, which we'll call I<webget>:
1462 % webget www.perl.com /guanaco.html
1463 HTTP/1.1 404 File Not Found
1464 Date: Thu, 08 May 1997 18:02:32 GMT
1465 Server: Apache/1.2b6
1467 Content-type: text/html
1469 <HEAD><TITLE>404 File Not Found</TITLE></HEAD>
1470 <BODY><H1>File Not Found</H1>
1471 The requested URL /guanaco.html was not found on this server.<P>
1474 Ok, so that's not very interesting, because it didn't find that
1475 particular document. But a long response wouldn't have fit on this page.
1477 For a more featureful version of this program, you should look to
1478 the I<lwp-request> program included with the LWP modules from CPAN.
1480 =head2 Interactive Client with IO::Socket
1482 Well, that's all fine if you want to send one command and get one answer,
1483 but what about setting up something fully interactive, somewhat like
1484 the way I<telnet> works? That way you can type a line, get the answer,
1485 type a line, get the answer, etc.
1487 This client is more complicated than the two we've done so far, but if
1488 you're on a system that supports the powerful C<fork> call, the solution
1489 isn't that rough. Once you've made the connection to whatever service
1490 you'd like to chat with, call C<fork> to clone your process. Each of
1491 these two identical process has a very simple job to do: the parent
1492 copies everything from the socket to standard output, while the child
1493 simultaneously copies everything from standard input to the socket.
1494 To accomplish the same thing using just one process would be I<much>
1495 harder, because it's easier to code two processes to do one thing than it
1496 is to code one process to do two things. (This keep-it-simple principle
1497 a cornerstones of the Unix philosophy, and good software engineering as
1498 well, which is probably why it's spread to other systems.)
1505 my ($host, $port, $kidpid, $handle, $line);
1507 unless (@ARGV == 2) { die "usage: $0 host port" }
1508 ($host, $port) = @ARGV;
1510 # create a tcp connection to the specified host and port
1511 $handle = IO::Socket::INET->new(Proto => "tcp",
1514 || die "can't connect to port $port on $host: $!";
1516 $handle->autoflush(1); # so output gets there right away
1517 print STDERR "[Connected to $host:$port]\n";
1519 # split the program into two processes, identical twins
1520 die "can't fork: $!" unless defined($kidpid = fork());
1522 # the if{} block runs only in the parent process
1524 # copy the socket to standard output
1525 while (defined ($line = <$handle>)) {
1528 kill("TERM", $kidpid); # send SIGTERM to child
1530 # the else{} block runs only in the child process
1532 # copy standard input to the socket
1533 while (defined ($line = <STDIN>)) {
1534 print $handle $line;
1536 exit(0); # just in case
1539 The C<kill> function in the parent's C<if> block is there to send a
1540 signal to our child process, currently running in the C<else> block,
1541 as soon as the remote server has closed its end of the connection.
1543 If the remote server sends data a byte at time, and you need that
1544 data immediately without waiting for a newline (which might not happen),
1545 you may wish to replace the C<while> loop in the parent with the
1549 while (sysread($handle, $byte, 1) == 1) {
1553 Making a system call for each byte you want to read is not very efficient
1554 (to put it mildly) but is the simplest to explain and works reasonably
1557 =head1 TCP Servers with IO::Socket
1559 As always, setting up a server is little bit more involved than running a client.
1560 The model is that the server creates a special kind of socket that
1561 does nothing but listen on a particular port for incoming connections.
1562 It does this by calling the C<< IO::Socket::INET->new() >> method with
1563 slightly different arguments than the client did.
1569 This is which protocol to use. Like our clients, we'll
1570 still specify C<"tcp"> here.
1575 port in the C<LocalPort> argument, which we didn't do for the client.
1576 This is service name or port number for which you want to be the
1577 server. (Under Unix, ports under 1024 are restricted to the
1578 superuser.) In our sample, we'll use port 9000, but you can use
1579 any port that's not currently in use on your system. If you try
1580 to use one already in used, you'll get an "Address already in use"
1581 message. Under Unix, the C<netstat -a> command will show
1582 which services current have servers.
1586 The C<Listen> parameter is set to the maximum number of
1587 pending connections we can accept until we turn away incoming clients.
1588 Think of it as a call-waiting queue for your telephone.
1589 The low-level Socket module has a special symbol for the system maximum, which
1594 The C<Reuse> parameter is needed so that we restart our server
1595 manually without waiting a few minutes to allow system buffers to
1600 Once the generic server socket has been created using the parameters
1601 listed above, the server then waits for a new client to connect
1602 to it. The server blocks in the C<accept> method, which eventually accepts a
1603 bidirectional connection from the remote client. (Make sure to autoflush
1604 this handle to circumvent buffering.)
1606 To add to user-friendliness, our server prompts the user for commands.
1607 Most servers don't do this. Because of the prompt without a newline,
1608 you'll have to use the C<sysread> variant of the interactive client above.
1610 This server accepts one of five different commands, sending output back to
1611 the client. Unlike most network servers, this one handles only one
1612 incoming client at a time. Multithreaded servers are covered in
1613 Chapter 16 of the Camel.
1615 Here's the code. We'll
1619 use Net::hostent; # for OOish version of gethostbyaddr
1621 $PORT = 9000; # pick something not in use
1623 $server = IO::Socket::INET->new( Proto => "tcp",
1625 Listen => SOMAXCONN,
1628 die "can't setup server" unless $server;
1629 print "[Server $0 accepting clients]\n";
1631 while ($client = $server->accept()) {
1632 $client->autoflush(1);
1633 print $client "Welcome to $0; type help for command list.\n";
1634 $hostinfo = gethostbyaddr($client->peeraddr);
1635 printf "[Connect from %s]\n", $hostinfo ? $hostinfo->name : $client->peerhost;
1636 print $client "Command? ";
1637 while ( <$client>) {
1638 next unless /\S/; # blank line
1639 if (/quit|exit/i) { last }
1640 elsif (/date|time/i) { printf $client "%s\n", scalar localtime() }
1641 elsif (/who/i ) { print $client `who 2>&1` }
1642 elsif (/cookie/i ) { print $client `/usr/games/fortune 2>&1` }
1643 elsif (/motd/i ) { print $client `cat /etc/motd 2>&1` }
1645 print $client "Commands: quit date who cookie motd\n";
1648 print $client "Command? ";
1653 =head1 UDP: Message Passing
1655 Another kind of client-server setup is one that uses not connections, but
1656 messages. UDP communications involve much lower overhead but also provide
1657 less reliability, as there are no promises that messages will arrive at
1658 all, let alone in order and unmangled. Still, UDP offers some advantages
1659 over TCP, including being able to "broadcast" or "multicast" to a whole
1660 bunch of destination hosts at once (usually on your local subnet). If you
1661 find yourself overly concerned about reliability and start building checks
1662 into your message system, then you probably should use just TCP to start
1665 UDP datagrams are I<not> a bytestream and should not be treated as such.
1666 This makes using I/O mechanisms with internal buffering like stdio (i.e.
1667 print() and friends) especially cumbersome. Use syswrite(), or better
1668 send(), like in the example below.
1670 Here's a UDP program similar to the sample Internet TCP client given
1671 earlier. However, instead of checking one host at a time, the UDP version
1672 will check many of them asynchronously by simulating a multicast and then
1673 using select() to do a timed-out wait for I/O. To do something similar
1674 with TCP, you'd have to use a different socket handle for each host.
1681 my ( $count, $hisiaddr, $hispaddr, $histime,
1682 $host, $iaddr, $paddr, $port, $proto,
1683 $rin, $rout, $rtime, $SECS_OF_70_YEARS);
1685 $SECS_OF_70_YEARS = 2_208_988_800;
1687 $iaddr = gethostbyname(hostname());
1688 $proto = getprotobyname("udp");
1689 $port = getservbyname("time", "udp");
1690 $paddr = sockaddr_in(0, $iaddr); # 0 means let kernel pick
1692 socket(SOCKET, PF_INET, SOCK_DGRAM, $proto) || die "socket: $!";
1693 bind(SOCKET, $paddr) || die "bind: $!";
1696 printf "%-12s %8s %s\n", "localhost", 0, scalar localtime();
1700 $hisiaddr = inet_aton($host) || die "unknown host";
1701 $hispaddr = sockaddr_in($port, $hisiaddr);
1702 defined(send(SOCKET, 0, 0, $hispaddr)) || die "send $host: $!";
1706 vec($rin, fileno(SOCKET), 1) = 1;
1708 # timeout after 10.0 seconds
1709 while ($count && select($rout = $rin, undef, undef, 10.0)) {
1711 $hispaddr = recv(SOCKET, $rtime, 4, 0) || die "recv: $!";
1712 ($port, $hisiaddr) = sockaddr_in($hispaddr);
1713 $host = gethostbyaddr($hisiaddr, AF_INET);
1714 $histime = unpack("N", $rtime) - $SECS_OF_70_YEARS;
1715 printf "%-12s ", $host;
1716 printf "%8d %s\n", $histime - time(), scalar localtime($histime);
1720 This example does not include any retries and may consequently fail to
1721 contact a reachable host. The most prominent reason for this is congestion
1722 of the queues on the sending host if the number of hosts to contact is
1727 While System V IPC isn't so widely used as sockets, it still has some
1728 interesting uses. However, you cannot use SysV IPC or Berkeley mmap() to
1729 have a variable shared amongst several processes. That's because Perl
1730 would reallocate your string when you weren't wanting it to. You might
1731 look into the C<IPC::Shareable> or C<threads::shared> modules for that.
1733 Here's a small example showing shared memory usage.
1735 use IPC::SysV qw(IPC_PRIVATE IPC_RMID S_IRUSR S_IWUSR);
1738 $id = shmget(IPC_PRIVATE, $size, S_IRUSR | S_IWUSR);
1739 defined($id) || die "shmget: $!";
1740 print "shm key $id\n";
1742 $message = "Message #1";
1743 shmwrite($id, $message, 0, 60) || die "shmwrite: $!";
1744 print "wrote: '$message'\n";
1745 shmread($id, $buff, 0, 60) || die "shmread: $!";
1746 print "read : '$buff'\n";
1748 # the buffer of shmread is zero-character end-padded.
1749 substr($buff, index($buff, "\0")) = "":
1750 print "un" unless $buff eq $message;
1753 print "deleting shm $id\n";
1754 shmctl($id, IPC_RMID, 0) || die "shmctl: $!";
1756 Here's an example of a semaphore:
1758 use IPC::SysV qw(IPC_CREAT);
1761 $id = semget($IPC_KEY, 10, 0666 | IPC_CREAT);
1762 defined($id) || die "shmget: $!";
1763 print "shm key $id\n";
1765 Put this code in a separate file to be run in more than one process.
1766 Call the file F<take>:
1768 # create a semaphore
1771 $id = semget($IPC_KEY, 0, 0);
1772 defined($id) || die "shmget: $!";
1778 # wait for semaphore to be zero
1780 $opstring1 = pack("s!s!s!", $semnum, $semop, $semflag);
1782 # Increment the semaphore count
1784 $opstring2 = pack("s!s!s!", $semnum, $semop, $semflag);
1785 $opstring = $opstring1 . $opstring2;
1787 semop($id, $opstring) || die "semop: $!";
1789 Put this code in a separate file to be run in more than one process.
1790 Call this file F<give>:
1792 # "give" the semaphore
1793 # run this in the original process and you will see
1794 # that the second process continues
1797 $id = semget($IPC_KEY, 0, 0);
1798 die unless defined($id);
1803 # Decrement the semaphore count
1805 $opstring = pack("s!s!s!", $semnum, $semop, $semflag);
1807 semop($id, $opstring) || die "semop: $!";
1809 The SysV IPC code above was written long ago, and it's definitely
1810 clunky looking. For a more modern look, see the IPC::SysV module
1811 which is included with Perl starting from Perl 5.005.
1813 A small example demonstrating SysV message queues:
1815 use IPC::SysV qw(IPC_PRIVATE IPC_RMID IPC_CREAT S_IRUSR S_IWUSR);
1817 my $id = msgget(IPC_PRIVATE, IPC_CREAT | S_IRUSR | S_IWUSR);
1818 defined($id) || die "msgget failed: $!";
1820 my $sent = "message";
1821 my $type_sent = 1234;
1823 msgsnd($id, pack("l! a*", $type_sent, $sent), 0)
1824 || die "msgsnd failed: $!";
1826 msgrcv($id, my $rcvd_buf, 60, 0, 0)
1827 || die "msgrcv failed: $!";
1829 my($type_rcvd, $rcvd) = unpack("l! a*", $rcvd_buf);
1831 if ($rcvd eq $sent) {
1837 msgctl($id, IPC_RMID, 0) || die "msgctl failed: $!\n";
1841 Most of these routines quietly but politely return C<undef> when they
1842 fail instead of causing your program to die right then and there due to
1843 an uncaught exception. (Actually, some of the new I<Socket> conversion
1844 functions do croak() on bad arguments.) It is therefore essential to
1845 check return values from these functions. Always begin your socket
1846 programs this way for optimal success, and don't forget to add the B<-T>
1847 taint-checking flag to the C<#!> line for servers:
1856 These routines all create system-specific portability problems. As noted
1857 elsewhere, Perl is at the mercy of your C libraries for much of its system
1858 behavior. It's probably safest to assume broken SysV semantics for
1859 signals and to stick with simple TCP and UDP socket operations; e.g., don't
1860 try to pass open file descriptors over a local UDP datagram socket if you
1861 want your code to stand a chance of being portable.
1865 Tom Christiansen, with occasional vestiges of Larry Wall's original
1866 version and suggestions from the Perl Porters.
1870 There's a lot more to networking than this, but this should get you
1873 For intrepid programmers, the indispensable textbook is I<Unix Network
1874 Programming, 2nd Edition, Volume 1> by W. Richard Stevens (published by
1875 Prentice-Hall). Most books on networking address the subject from the
1876 perspective of a C programmer; translation to Perl is left as an exercise
1879 The IO::Socket(3) manpage describes the object library, and the Socket(3)
1880 manpage describes the low-level interface to sockets. Besides the obvious
1881 functions in L<perlfunc>, you should also check out the F<modules> file at
1882 your nearest CPAN site, especially
1883 L<http://www.cpan.org/modules/00modlist.long.html#ID5_Networking_>.
1884 See L<perlmodlib> or best yet, the F<Perl FAQ> for a description
1885 of what CPAN is and where to get it if the previous link doesn't work
1888 Section 5 of CPAN's F<modules> file is devoted to "Networking, Device
1889 Control (modems), and Interprocess Communication", and contains numerous
1890 unbundled modules numerous networking modules, Chat and Expect operations,
1891 CGI programming, DCE, FTP, IPC, NNTP, Proxy, Ptty, RPC, SNMP, SMTP, Telnet,
1892 Threads, and ToolTalk--to name just a few.