Debian Codegraph @

upstream/debian-unstable/man1/perlipc.1

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