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