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