Debian Codegraph @

upstream/opensuse-tumbleweed/man1/perlipc.1

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