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