{
    "mode": "perldoc",
    "parameter": "perlipc",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/perlipc/json",
    "generated": "2026-06-12T05:20:12Z",
    "sections": {
        "NAME": {
            "content": "perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets,\nand semaphores)\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "The basic IPC facilities of Perl are built out of the good old Unix signals, named pipes, pipe\nopens, the Berkeley socket routines, and SysV IPC calls. Each is used in slightly different\nsituations.\n",
            "subsections": []
        },
        "Signals": {
            "content": "Perl uses a simple signal handling model: the %SIG hash contains names or references of\nuser-installed signal handlers. These handlers will be called with an argument which is the name\nof the signal that triggered it. A signal may be generated intentionally from a particular\nkeyboard sequence like control-C or control-Z, sent to you from another process, or triggered\nautomatically by the kernel when special events transpire, like a child process exiting, your\nown process running out of stack space, or hitting a process file-size limit.\n\nFor example, to trap an interrupt signal, set up a handler like this:\n\nour $shucks;\n\nsub catchzap {\nmy $signame = shift;\n$shucks++;\ndie \"Somebody sent me a SIG$signame\";\n}\n$SIG{INT} = PACKAGE . \"::catchzap\";\n$SIG{INT} = \\&catchzap;  # best strategy\n\nPrior to Perl 5.8.0 it was necessary to do as little as you possibly could in your handler;\nnotice how all we do is set a global variable and then raise an exception. That's because on\nmost systems, libraries are not re-entrant; particularly, memory allocation and I/O routines are\nnot. That meant that doing nearly *anything* in your handler could in theory trigger a memory\nfault and subsequent core dump - see \"Deferred Signals (Safe Signals)\" below.\n\nThe names of the signals are the ones listed out by \"kill -l\" on your system, or you can\nretrieve them using the CPAN module IPC::Signal.\n\nYou may also choose to assign the strings \"IGNORE\" or \"DEFAULT\" as the handler, in which case\nPerl will try to discard the signal or do the default thing.\n\nOn most Unix platforms, the \"CHLD\" (sometimes also known as \"CLD\") signal has special behavior\nwith respect to a value of \"IGNORE\". Setting $SIG{CHLD} to \"IGNORE\" on such a platform has the\neffect of not creating zombie processes when the parent process fails to \"wait()\" on its child\nprocesses (i.e., child processes are automatically reaped). Calling \"wait()\" with $SIG{CHLD} set\nto \"IGNORE\" usually returns -1 on such platforms.\n\nSome signals can be neither trapped nor ignored, such as the KILL and STOP (but not the TSTP)\nsignals. Note that ignoring signals makes them disappear. If you only want them blocked\ntemporarily without them getting lost you'll have to use the \"POSIX\" module's sigprocmask.\n\nSending a signal to a negative process ID means that you send the signal to the entire Unix\nprocess group. This code sends a hang-up signal to all processes in the current process group,\nand also sets $SIG{HUP} to \"IGNORE\" so it doesn't kill itself:\n\n# block scope for local\n{\nlocal $SIG{HUP} = \"IGNORE\";\nkill HUP => -getpgrp();\n# snazzy writing of: kill(\"HUP\", -getpgrp())\n}\n\nAnother interesting signal to send is signal number zero. This doesn't actually affect a child\nprocess, but instead checks whether it's alive or has changed its UIDs.\n\nunless (kill 0 => $kidpid) {\nwarn \"something wicked happened to $kidpid\";\n}\n\nSignal number zero may fail because you lack permission to send the signal when directed at a\nprocess whose real or saved UID is not identical to the real or effective UID of the sending\nprocess, even though the process is alive. You may be able to determine the cause of failure\nusing $! or \"%!\".\n\nunless (kill(0 => $pid) || $!{EPERM}) {\nwarn \"$pid looks dead\";\n}\n\nYou might also want to employ anonymous functions for simple signal handlers:\n\n$SIG{INT} = sub { die \"\\nOutta here!\\n\" };\n\nSIGCHLD handlers require some special care. If a second child dies while in the signal handler\ncaused by the first death, we won't get another signal. So must loop here else we will leave the\nunreaped child as a zombie. And the next time two children die we get another zombie. And so on.\n\nuse POSIX \":syswaith\";\n$SIG{CHLD} = sub {\nwhile ((my $child = waitpid(-1, WNOHANG)) > 0) {\n$KidStatus{$child} = $?;\n}\n};\n# do something that forks...\n\nBe careful: qx(), system(), and some modules for calling external commands do a fork(), then",
            "subsections": [
                {
                    "name": "wait",
                    "content": "called by system() or qx(), the wait() in the signal handler will see no more zombies and will\ntherefore block.\n\nThe best way to prevent this issue is to use waitpid(), as in the following example:\n\nuse POSIX \":syswaith\"; # for nonblocking read\n\nmy %children;\n\n$SIG{CHLD} = sub {\n# don't change $! and $? outside handler\nlocal ($!, $?);\nwhile ( (my $pid = waitpid(-1, WNOHANG)) > 0 ) {\ndelete $children{$pid};\ncleanupchild($pid, $?);\n}\n};\n\nwhile (1) {\nmy $pid = fork();\ndie \"cannot fork\" unless defined $pid;\nif ($pid == 0) {\n# ...\nexit 0;\n} else {\n$children{$pid}=1;\n# ...\nsystem($command);\n# ...\n}\n}\n\nSignal handling is also used for timeouts in Unix. While safely protected within an \"eval{}\"\nblock, you set a signal handler to trap alarm signals and then schedule to have one delivered to\nyou in some number of seconds. Then try your blocking operation, clearing the alarm when it's\ndone but not before you've exited your \"eval{}\" block. If it goes off, you'll use die() to jump\nout of the block.\n\nHere's an example:\n\nmy $ALARMEXCEPTION = \"alarm clock restart\";\neval {\nlocal $SIG{ALRM} = sub { die $ALARMEXCEPTION };\nalarm 10;\nflock($fh, 2)    # blocking write lock\n|| die \"cannot flock: $!\";\nalarm 0;\n};\nif ($@ && $@ !~ quotemeta($ALARMEXCEPTION)) { die }\n\nIf the operation being timed out is system() or qx(), this technique is liable to generate\nzombies. If this matters to you, you'll need to do your own fork() and exec(), and kill the\nerrant child process.\n\nFor more complex signal handling, you might see the standard POSIX module. Lamentably, this is\nalmost entirely undocumented, but the ext/POSIX/t/sigaction.t file from the Perl source\ndistribution has some examples in it.\n"
                },
                {
                    "name": "Handling the SIGHUP Signal in Daemons",
                    "content": "A process that usually starts when the system boots and shuts down when the system is shut down\nis called a daemon (Disk And Execution MONitor). If a daemon process has a configuration file\nwhich is modified after the process has been started, there should be a way to tell that process\nto reread its configuration file without stopping the process. Many daemons provide this\nmechanism using a \"SIGHUP\" signal handler. When you want to tell the daemon to reread the file,\nsimply send it the \"SIGHUP\" signal.\n\nThe following example implements a simple daemon, which restarts itself every time the \"SIGHUP\"\nsignal is received. The actual code is located in the subroutine \"code()\", which just prints\nsome debugging info to show that it works; it should be replaced with the real code.\n\n#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse POSIX ();\nuse FindBin ();\nuse File::Basename ();\nuse File::Spec::Functions qw(catfile);\n\n$| = 1;\n\n# make the daemon cross-platform, so exec always calls the script\n# itself with the right path, no matter how the script was invoked.\nmy $script = File::Basename::basename($0);\nmy $SELF  = catfile($FindBin::Bin, $script);\n\n# POSIX unmasks the sigprocmask properly\n$SIG{HUP} = sub {\nprint \"got SIGHUP\\n\";\nexec($SELF, @ARGV)        || die \"$0: couldn't restart: $!\";\n};\n\ncode();\n\nsub code {\nprint \"PID: $$\\n\";\nprint \"ARGV: @ARGV\\n\";\nmy $count = 0;\nwhile (1) {\nsleep 2;\nprint ++$count, \"\\n\";\n}\n}\n\nDeferred Signals (Safe Signals)\nBefore Perl 5.8.0, installing Perl code to deal with signals exposed you to danger from two\nthings. First, few system library functions are re-entrant. If the signal interrupts while Perl\nis executing one function (like malloc(3) or printf(3)), and your signal handler then calls the\nsame function again, you could get unpredictable behavior--often, a core dump. Second, Perl\nisn't itself re-entrant at the lowest levels. If the signal interrupts Perl while Perl is\nchanging its own internal data structures, similarly unpredictable behavior may result.\n\nThere were two things you could do, knowing this: be paranoid or be pragmatic. The paranoid\napproach was to do as little as possible in your signal handler. Set an existing integer\nvariable that already has a value, and return. This doesn't help you if you're in a slow system\ncall, which will just restart. That means you have to \"die\" to longjmp(3) out of the handler.\nEven this is a little cavalier for the true paranoiac, who avoids \"die\" in a handler because the\nsystem *is* out to get you. The pragmatic approach was to say \"I know the risks, but prefer the\nconvenience\", and to do anything you wanted in your signal handler, and be prepared to clean up\ncore dumps now and again.\n\nPerl 5.8.0 and later avoid these problems by \"deferring\" signals. That is, when the signal is\ndelivered to the process by the system (to the C code that implements Perl) a flag is set, and\nthe handler returns immediately. Then at strategic \"safe\" points in the Perl interpreter (e.g.\nwhen it is about to execute a new opcode) the flags are checked and the Perl level handler from\n%SIG is executed. The \"deferred\" scheme allows much more flexibility in the coding of signal\nhandlers as we know the Perl interpreter is in a safe state, and that we are not in a system\nlibrary function when the handler is called. However the implementation does differ from\nprevious Perls in the following ways:\n\nLong-running opcodes\nAs the Perl interpreter looks at signal flags only when it is about to execute a new opcode,\na signal that arrives during a long-running opcode (e.g. a regular expression operation on a\nvery large string) will not be seen until the current opcode completes.\n\nIf a signal of any given type fires multiple times during an opcode (such as from a\nfine-grained timer), the handler for that signal will be called only once, after the opcode\ncompletes; all other instances will be discarded. Furthermore, if your system's signal queue\ngets flooded to the point that there are signals that have been raised but not yet caught\n(and thus not deferred) at the time an opcode completes, those signals may well be caught\nand deferred during subsequent opcodes, with sometimes surprising results. For example, you\nmay see alarms delivered even after calling alarm(0) as the latter stops the raising of\nalarms but does not cancel the delivery of alarms raised but not yet caught. Do not depend\non the behaviors described in this paragraph as they are side effects of the current\nimplementation and may change in future versions of Perl.\n\nInterrupting IO\nWhen a signal is delivered (e.g., SIGINT from a control-C) the operating system breaks into\nIO operations like *read*(2), which is used to implement Perl's readline() function, the\n\"<>\" operator. On older Perls the handler was called immediately (and as \"read\" is not\n\"unsafe\", this worked well). With the \"deferred\" scheme the handler is *not* called\nimmediately, and if Perl is using the system's \"stdio\" library that library may restart the\n\"read\" without returning to Perl to give it a chance to call the %SIG handler. If this\nhappens on your system the solution is to use the \":perlio\" layer to do IO--at least on\nthose handles that you want to be able to break into with signals. (The \":perlio\" layer\nchecks the signal flags and calls %SIG handlers before resuming IO operation.)\n\nThe default in Perl 5.8.0 and later is to automatically use the \":perlio\" layer.\n\nNote that it is not advisable to access a file handle within a signal handler where that\nsignal has interrupted an I/O operation on that same handle. While perl will at least try\nhard not to crash, there are no guarantees of data integrity; for example, some data might\nget dropped or written twice.\n\nSome networking library functions like gethostbyname() are known to have their own\nimplementations of timeouts which may conflict with your timeouts. If you have problems with\nsuch functions, try using the POSIX sigaction() function, which bypasses Perl safe signals.\nBe warned that this does subject you to possible memory corruption, as described above.\n\nInstead of setting $SIG{ALRM}:\n\nlocal $SIG{ALRM} = sub { die \"alarm\" };\n\ntry something like the following:\n\nuse POSIX qw(SIGALRM);\nPOSIX::sigaction(SIGALRM,\nPOSIX::SigAction->new(sub { die \"alarm\" }))\n|| die \"Error setting SIGALRM handler: $!\\n\";\n\nAnother way to disable the safe signal behavior locally is to use the\n\"Perl::Unsafe::Signals\" module from CPAN, which affects all signals.\n\nRestartable system calls\nOn systems that supported it, older versions of Perl used the SARESTART flag when\ninstalling %SIG handlers. This meant that restartable system calls would continue rather\nthan returning when a signal arrived. In order to deliver deferred signals promptly, Perl\n5.8.0 and later do *not* use SARESTART. Consequently, restartable system calls can fail\n(with $! set to \"EINTR\") in places where they previously would have succeeded.\n\nThe default \":perlio\" layer retries \"read\", \"write\" and \"close\" as described above;\ninterrupted \"wait\" and \"waitpid\" calls will always be retried.\n\nSignals as \"faults\"\nCertain signals like SEGV, ILL, and BUS are generated by virtual memory addressing errors\nand similar \"faults\". These are normally fatal: there is little a Perl-level handler can do\nwith them. So Perl delivers them immediately rather than attempting to defer them.\n\nSignals triggered by operating system state\nOn some operating systems certain signal handlers are supposed to \"do something\" before\nreturning. One example can be CHLD or CLD, which indicates a child process has completed. On\nsome operating systems the signal handler is expected to \"wait\" for the completed child\nprocess. On such systems the deferred signal scheme will not work for those signals: it does\nnot do the \"wait\". Again the failure will look like a loop as the operating system will\nreissue the signal because there are completed child processes that have not yet been\n\"wait\"ed for.\n\nIf you want the old signal behavior back despite possible memory corruption, set the environment\nvariable \"PERLSIGNALS\" to \"unsafe\". This feature first appeared in Perl 5.8.1.\n"
                }
            ]
        },
        "Named Pipes": {
            "content": "A named pipe (often referred to as a FIFO) is an old Unix IPC mechanism for processes\ncommunicating on the same machine. It works just like regular anonymous pipes, except that the\nprocesses rendezvous using a filename and need not be related.\n\nTo create a named pipe, use the \"POSIX::mkfifo()\" function.\n\nuse POSIX qw(mkfifo);\nmkfifo($path, 0700)     ||  die \"mkfifo $path failed: $!\";\n\nYou can also use the Unix command mknod(1), or on some systems, mkfifo(1). These may not be in\nyour normal path, though.\n\n# system return val is backwards, so && not ||\n#\n$ENV{PATH} .= \":/etc:/usr/etc\";\nif  (      system(\"mknod\",  $path, \"p\")\n&& system(\"mkfifo\", $path) )\n{\ndie \"mk{nod,fifo} $path failed\";\n}\n\nA fifo is convenient when you want to connect a process to an unrelated one. When you open a\nfifo, the program will block until there's something on the other end.\n\nFor example, let's say you'd like to have your .signature file be a named pipe that has a Perl\nprogram on the other end. Now every time any program (like a mailer, news reader, finger\nprogram, etc.) tries to read from that file, the reading program will read the new signature\nfrom your program. We'll use the pipe-checking file-test operator, -p, to find out whether\nanyone (or anything) has accidentally removed our fifo.\n\nchdir();    # go home\nmy $FIFO = \".signature\";\n\nwhile (1) {\nunless (-p $FIFO) {\nunlink $FIFO;   # discard any failure, will catch later\nrequire POSIX;  # delayed loading of heavy module\nPOSIX::mkfifo($FIFO, 0700)\n|| die \"can't mkfifo $FIFO: $!\";\n}\n\n# next line blocks till there's a reader\nopen (my $fh, \">\", $FIFO) || die \"can't open $FIFO: $!\";\nprint $fh \"John Smith (smith\\@host.org)\\n\", `fortune -s`;\nclose($fh)                || die \"can't close $FIFO: $!\";\nsleep 2;                # to avoid dup signals\n}\n",
            "subsections": []
        },
        "Using open() for IPC": {
            "content": "Perl's basic open() statement can also be used for unidirectional interprocess communication by\nspecifying the open mode as \"|-\" or \"-|\". Here's how to start something up in a child process\nyou intend to write to:\n\nopen(my $spooler, \"|-\", \"cat -v | lpr -h 2>/dev/null\")\n|| die \"can't fork: $!\";\nlocal $SIG{PIPE} = sub { die \"spooler pipe broke\" };\nprint $spooler \"stuff\\n\";\nclose $spooler      || die \"bad spool: $! $?\";\n\nAnd here's how to start up a child process you intend to read from:\n\nopen(my $status, \"-|\", \"netstat -an 2>&1\")\n|| die \"can't fork: $!\";\nwhile (<$status>) {\nnext if /^(tcp|udp)/;\nprint;\n}\nclose $status       || die \"bad netstat: $! $?\";\n\nBe aware that these operations are full Unix forks, which means they may not be correctly\nimplemented on all alien systems. See \"open\" in perlport for portability details.\n\nIn the two-argument form of open(), a pipe open can be achieved by either appending or\nprepending a pipe symbol to the second argument:\n\nopen(my $spooler, \"| cat -v | lpr -h 2>/dev/null\")\n|| die \"can't fork: $!\";\nopen(my $status, \"netstat -an 2>&1 |\")\n|| die \"can't fork: $!\";\n\nThis can be used even on systems that do not support forking, but this possibly allows code\nintended to read files to unexpectedly execute programs. If one can be sure that a particular\nprogram is a Perl script expecting filenames in @ARGV using the two-argument form of open() or\nthe \"<>\" operator, the clever programmer can write something like this:\n\n% program f1 \"cmd1|\" - f2 \"cmd2|\" f3 < tmpfile\n\nand no matter which sort of shell it's called from, the Perl program will read from the file f1,\nthe process cmd1, standard input (tmpfile in this case), the f2 file, the cmd2 command, and\nfinally the f3 file. Pretty nifty, eh?\n\nYou might notice that you could use backticks for much the same effect as opening a pipe for\nreading:\n\nprint grep { !/^(tcp|udp)/ } `netstat -an 2>&1`;\ndie \"bad netstatus ($?)\" if $?;\n\nWhile this is true on the surface, it's much more efficient to process the file one line or\nrecord at a time because then you don't have to read the whole thing into memory at once. It\nalso gives you finer control of the whole process, letting you kill off the child process early\nif you'd like.\n\nBe careful to check the return values from both open() and close(). If you're *writing* to a\npipe, you should also trap SIGPIPE. Otherwise, think of what happens when you start up a pipe to\na command that doesn't exist: the open() will in all likelihood succeed (it only reflects the",
            "subsections": [
                {
                    "name": "fork",
                    "content": "command worked, because your command is actually running in a separate process whose exec()\nmight have failed. Therefore, while readers of bogus commands return just a quick EOF, writers\nto bogus commands will get hit with a signal, which they'd best be prepared to handle. Consider:\n\nopen(my $fh, \"|-\", \"bogus\") || die \"can't fork: $!\";\nprint $fh \"bang\\n\";         #  neither necessary nor sufficient\n#  to check print retval!\nclose($fh)                  || die \"can't close: $!\";\n\nThe reason for not checking the return value from print() is because of pipe buffering; physical\nwrites are delayed. That won't blow up until the close, and it will blow up with a SIGPIPE. To\ncatch it, you could use this:\n\n$SIG{PIPE} = \"IGNORE\";\nopen(my $fh, \"|-\", \"bogus\") || die \"can't fork: $!\";\nprint $fh \"bang\\n\";\nclose($fh)                  || die \"can't close: status=$?\";\n"
                },
                {
                    "name": "Filehandles",
                    "content": "Both the main process and any child processes it forks share the same STDIN, STDOUT, and STDERR\nfilehandles. If both processes try to access them at once, strange things can happen. You may\nalso want to close or reopen the filehandles for the child. You can get around this by opening\nyour pipe with open(), but on some systems this means that the child process cannot outlive the\nparent.\n"
                },
                {
                    "name": "Background Processes",
                    "content": "You can run a command in the background with:\n\nsystem(\"cmd &\");\n\nThe command's STDOUT and STDERR (and possibly STDIN, depending on your shell) will be the same\nas the parent's. You won't need to catch SIGCHLD because of the double-fork taking place; see\nbelow for details.\n"
                },
                {
                    "name": "Complete Dissociation of Child from Parent",
                    "content": "In some cases (starting server processes, for instance) you'll want to completely dissociate the\nchild process from the parent. This is often called daemonization. A well-behaved daemon will\nalso chdir() to the root directory so it doesn't prevent unmounting the filesystem containing\nthe directory from which it was launched, and redirect its standard file descriptors from and to\n/dev/null so that random output doesn't wind up on the user's terminal.\n\nuse POSIX \"setsid\";\n\nsub daemonize {\nchdir(\"/\")                     || die \"can't chdir to /: $!\";\nopen(STDIN,  \"<\", \"/dev/null\") || die \"can't read /dev/null: $!\";\nopen(STDOUT, \">\", \"/dev/null\") || die \"can't write /dev/null: $!\";\ndefined(my $pid = fork())      || die \"can't fork: $!\";\nexit if $pid;              # non-zero now means I am the parent\n(setsid() != -1)           || die \"Can't start a new session: $!\";\nopen(STDERR, \">&\", STDOUT) || die \"can't dup stdout: $!\";\n}\n\nThe fork() has to come before the setsid() to ensure you aren't a process group leader; the"
                },
                {
                    "name": "setsid",
                    "content": "and use the \"TIOCNOTTY\" ioctl() on it instead. See tty(4) for details.\n\nNon-Unix users should check their \"*YourOS*::Process\" module for other possible solutions.\n"
                },
                {
                    "name": "Safe Pipe Opens",
                    "content": "Another interesting approach to IPC is making your single program go multiprocess and\ncommunicate between--or even amongst--yourselves. The two-argument form of the open() function\nwill accept a file argument of either \"-|\" or \"|-\" to do a very interesting thing: it forks a\nchild connected to the filehandle you've opened. The child is running the same program as the\nparent. This is useful for safely opening a file when running under an assumed UID or GID, for\nexample. If you open a pipe *to* minus, you can write to the filehandle you opened and your kid\nwill find it in *his* STDIN. If you open a pipe *from* minus, you can read from the filehandle\nyou opened whatever your kid writes to *his* STDOUT.\n\nmy $PRECIOUS = \"/path/to/some/safe/file\";\nmy $sleepcount;\nmy $pid;\nmy $kidtowrite;\n\ndo {\n$pid = open($kidtowrite, \"|-\");\nunless (defined $pid) {\nwarn \"cannot fork: $!\";\ndie \"bailing out\" if $sleepcount++ > 6;\nsleep 10;\n}\n} until defined $pid;\n\nif ($pid) {                 # I am the parent\nprint $kidtowrite @somedata;\nclose($kidtowrite)    || warn \"kid exited $?\";\n} else {                    # I am the child\n# drop permissions in setuid and/or setgid programs:\n($>, $)) = ($<, $();\nopen (my $outfile, \">\", $PRECIOUS)\n|| die \"can't open $PRECIOUS: $!\";\nwhile (<STDIN>) {\nprint $outfile;     # child STDIN is parent $kidtowrite\n}\nclose($outfile)         || die \"can't close $PRECIOUS: $!\";\nexit(0);                # don't forget this!!\n}\n\nAnother common use for this construct is when you need to execute something without the shell's\ninterference. With system(), it's straightforward, but you can't use a pipe open or backticks\nsafely. That's because there's no way to stop the shell from getting its hands on your\narguments. Instead, use lower-level control to call exec() directly.\n\nHere's a safe backtick or pipe open for read:\n\nmy $pid = open(my $kidtoread, \"-|\");\ndefined($pid)            || die \"can't fork: $!\";\n\nif ($pid) {             # parent\nwhile (<$kidtoread>) {\n# do something interesting\n}\nclose($kidtoread)  || warn \"kid exited $?\";\n\n} else {                # child\n($>, $)) = ($<, $(); # suid only\nexec($program, @options, @args)\n|| die \"can't exec program: $!\";\n# NOTREACHED\n}\n\nAnd here's a safe pipe open for writing:\n\nmy $pid = open(my $kidtowrite, \"|-\");\ndefined($pid)            || die \"can't fork: $!\";\n\n$SIG{PIPE} = sub { die \"whoops, $program pipe broke\" };\n\nif ($pid) {             # parent\nprint $kidtowrite @data;\nclose($kidtowrite) || warn \"kid exited $?\";\n\n} else {                # child\n($>, $)) = ($<, $();\nexec($program, @options, @args)\n|| die \"can't exec program: $!\";\n# NOTREACHED\n}\n\nIt is very easy to dead-lock a process using this form of open(), or indeed with any use of"
                },
                {
                    "name": "pipe",
                    "content": ""
                },
                {
                    "name": "exec",
                    "content": "with Safe Pipe Opens.\n\nIn particular, if you opened the pipe using \"open $fh, \"|-\"\", then you cannot simply use close()\nin the parent process to close an unwanted writer. Consider this code:\n\nmy $pid = open(my $writer, \"|-\");        # fork open a kid\ndefined($pid)               || die \"first fork failed: $!\";\nif ($pid) {\nif (my $subpid = fork()) {\ndefined($subpid)   || die \"second fork failed: $!\";\nclose($writer)      || die \"couldn't close writer: $!\";\n# now do something else...\n}\nelse {\n# first write to $writer\n# ...\n# then when finished\nclose($writer)      || die \"couldn't close writer: $!\";\nexit(0);\n}\n}\nelse {\n# first do something with STDIN, then\nexit(0);\n}\n\nIn the example above, the true parent does not want to write to the $writer filehandle, so it\ncloses it. However, because $writer was opened using \"open $fh, \"|-\"\", it has a special\nbehavior: closing it calls waitpid() (see \"waitpid\" in perlfunc), which waits for the subprocess\nto exit. If the child process ends up waiting for something happening in the section marked \"do\nsomething else\", you have deadlock.\n\nThis can also be a problem with intermediate subprocesses in more complicated code, which will\ncall waitpid() on all open filehandles during global destruction--in no predictable order.\n\nTo solve this, you must manually use pipe(), fork(), and the form of open() which sets one file\ndescriptor to another, as shown below:\n\npipe(my $reader, my $writer)   || die \"pipe failed: $!\";\nmy $pid = fork();\ndefined($pid)                  || die \"first fork failed: $!\";\nif ($pid) {\nclose $reader;\nif (my $subpid = fork()) {\ndefined($subpid)      || die \"first fork failed: $!\";\nclose($writer)         || die \"can't close writer: $!\";\n}\nelse {\n# write to $writer...\n# ...\n# then  when finished\nclose($writer)         || die \"can't close writer: $!\";\nexit(0);\n}\n# write to $writer...\n}\nelse {\nopen(STDIN, \"<&\", $reader) || die \"can't reopen STDIN: $!\";\nclose($writer)             || die \"can't close writer: $!\";\n# do something...\nexit(0);\n}\n\nSince Perl 5.8.0, you can also use the list form of \"open\" for pipes. This is preferred when you\nwish to avoid having the shell interpret metacharacters that may be in your command string.\n\nSo for example, instead of using:\n\nopen(my $pspipe, \"-|\", \"ps aux\") || die \"can't open ps pipe: $!\";\n\nOne would use either of these:\n\nopen(my $pspipe, \"-|\", \"ps\", \"aux\")\n|| die \"can't open ps pipe: $!\";\n\nmy @psargs = qw[ ps aux ];\nopen(my $pspipe, \"-|\", @psargs)\n|| die \"can't open @psargs|: $!\";\n\nBecause there are more than three arguments to open(), it forks the ps(1) command *without*\nspawning a shell, and reads its standard output via the $pspipe filehandle. The corresponding\nsyntax to *write* to command pipes is to use \"|-\" in place of \"-|\".\n\nThis was admittedly a rather silly example, because you're using string literals whose content\nis perfectly safe. There is therefore no cause to resort to the harder-to-read, multi-argument\nform of pipe open(). However, whenever you cannot be assured that the program arguments are free\nof shell metacharacters, the fancier form of open() should be used. For example:\n\nmy @grepargs = (\"egrep\", \"-i\", $somepattern, @manyfiles);\nopen(my $greppipe, \"-|\", @grepargs)\n|| die \"can't open @grepargs|: $!\";\n\nHere the multi-argument form of pipe open() is preferred because the pattern and indeed even the\nfilenames themselves might hold metacharacters.\n"
                },
                {
                    "name": "Avoiding Pipe Deadlocks",
                    "content": "Whenever you have more than one subprocess, you must be careful that each closes whichever half\nof any pipes created for interprocess communication it is not using. This is because any child\nprocess reading from the pipe and expecting an EOF will never receive it, and therefore never\nexit. A single process closing a pipe is not enough to close it; the last process with the pipe\nopen must close it for it to read EOF.\n\nCertain built-in Unix features help prevent this most of the time. For instance, filehandles\nhave a \"close on exec\" flag, which is set *en masse* under control of the $^F variable. This is\nso any filehandles you didn't explicitly route to the STDIN, STDOUT or STDERR of a child\n*program* will be automatically closed.\n\nAlways explicitly and immediately call close() on the writable end of any pipe, unless that\nprocess is actually writing to it. Even if you don't explicitly call close(), Perl will still"
                },
                {
                    "name": "close",
                    "content": "have been opened with Safe Pipe Open, this will result in calling waitpid(), which may again\ndeadlock.\n"
                },
                {
                    "name": "Bidirectional Communication with Another Process",
                    "content": "While this works reasonably well for unidirectional communication, what about bidirectional\ncommunication? The most obvious approach doesn't work:\n\n# THIS DOES NOT WORK!!\nopen(my $progforreadingandwriting, \"| some program |\")\n\nIf you forget to \"use warnings\", you'll miss out entirely on the helpful diagnostic message:\n\nCan't do bidirectional pipe at -e line 1.\n\nIf you really want to, you can use the standard open2() from the IPC::Open2 module to catch both\nends. There's also an open3() in IPC::Open3 for tridirectional I/O so you can also catch your\nchild's STDERR, but doing so would then require an awkward select() loop and wouldn't allow you\nto use normal Perl input operations.\n\nIf you look at its source, you'll see that open2() uses low-level primitives like the pipe() and"
                },
                {
                    "name": "exec",
                    "content": "using socketpair(), this would have been even less portable than it already is. The open2() and"
                },
                {
                    "name": "open3",
                    "content": "purporting POSIX compliance.\n\nHere's an example of using open2():\n\nuse IPC::Open2;\nmy $pid = open2(my $reader, my $writer, \"cat -un\");\nprint $writer \"stuff\\n\";\nmy $got = <$reader>;\nwaitpid $pid, 0;\n\nThe problem with this is that buffering is really going to ruin your day. Even though your\n$writer filehandle is auto-flushed so the process on the other end gets your data in a timely\nmanner, you can't usually do anything to force that process to give its data to you in a\nsimilarly quick fashion. In this special case, we could actually so, because we gave *cat* a -u\nflag to make it unbuffered. But very few commands are designed to operate over pipes, so this\nseldom works unless you yourself wrote the program on the other end of the double-ended pipe.\n\nA solution to this is to use a library which uses pseudottys to make your program behave more\nreasonably. This way you don't have to have control over the source code of the program you're\nusing. The \"Expect\" module from CPAN also addresses this kind of thing. This module requires two\nother modules from CPAN, \"IO::Pty\" and \"IO::Stty\". It sets up a pseudo terminal to interact with\nprograms that insist on talking to the terminal device driver. If your system is supported, this\nmay be your best bet.\n"
                },
                {
                    "name": "Bidirectional Communication with Yourself",
                    "content": "If you want, you may make low-level pipe() and fork() syscalls to stitch this together by hand.\nThis example only talks to itself, but you could reopen the appropriate handles to STDIN and\nSTDOUT and call other processes. (The following example lacks proper error checking.)\n\n#!/usr/bin/perl\n# pipe1 - bidirectional communication using two pipe pairs\n#         designed for the socketpair-challenged\nuse strict;\nuse warnings;\nuse IO::Handle;  # enable autoflush method before Perl 5.14\npipe(my $parentrdr, my $childwtr);  # XXX: check failure?\npipe(my $childrdr,  my $parentwtr); # XXX: check failure?\n$childwtr->autoflush(1);\n$parentwtr->autoflush(1);\n\nif ($pid = fork()) {\nclose $parentrdr;\nclose $parentwtr;\nprint $childwtr \"Parent Pid $$ is sending this\\n\";\nchomp(my $line = <$childrdr>);\nprint \"Parent Pid $$ just read this: '$line'\\n\";\nclose $childrdr; close $childwtr;\nwaitpid($pid, 0);\n} else {\ndie \"cannot fork: $!\" unless defined $pid;\nclose $childrdr;\nclose $childwtr;\nchomp(my $line = <$parentrdr>);\nprint \"Child Pid $$ just read this: '$line'\\n\";\nprint $parentwtr \"Child Pid $$ is sending this\\n\";\nclose $parentrdr;\nclose $parentwtr;\nexit(0);\n}\n\nBut you don't actually have to make two pipe calls. If you have the socketpair() system call, it\nwill do this all for you.\n\n#!/usr/bin/perl\n# pipe2 - bidirectional communication using socketpair\n#   \"the best ones always go both ways\"\n\nuse strict;\nuse warnings;\nuse Socket;\nuse IO::Handle;  # enable autoflush method before Perl 5.14\n\n# We say AFUNIX because although *LOCAL is the\n# POSIX 1003.1g form of the constant, many machines\n# still don't have it.\nsocketpair(my $child, my $parent, AFUNIX, SOCKSTREAM, PFUNSPEC)\n||  die \"socketpair: $!\";\n\n$child->autoflush(1);\n$parent->autoflush(1);\n\nif ($pid = fork()) {\nclose $parent;\nprint $child \"Parent Pid $$ is sending this\\n\";\nchomp(my $line = <$child>);\nprint \"Parent Pid $$ just read this: '$line'\\n\";\nclose $child;\nwaitpid($pid, 0);\n} else {\ndie \"cannot fork: $!\" unless defined $pid;\nclose $child;\nchomp(my $line = <$parent>);\nprint \"Child Pid $$ just read this: '$line'\\n\";\nprint $parent \"Child Pid $$ is sending this\\n\";\nclose $parent;\nexit(0);\n}\n"
                }
            ]
        },
        "Sockets: Client/Server Communication": {
            "content": "While not entirely limited to Unix-derived operating systems (e.g., WinSock on PCs provides\nsocket support, as do some VMS libraries), you might not have sockets on your system, in which\ncase this section probably isn't going to do you much good. With sockets, you can do both\nvirtual circuits like TCP streams and datagrams like UDP packets. You may be able to do even\nmore depending on your system.\n\nThe Perl functions for dealing with sockets have the same names as the corresponding system\ncalls in C, but their arguments tend to differ for two reasons. First, Perl filehandles work\ndifferently than C file descriptors. Second, Perl already knows the length of its strings, so\nyou don't need to pass that information.\n\nOne of the major problems with ancient, antemillennial socket code in Perl was that it used\nhard-coded values for some of the constants, which severely hurt portability. If you ever see\ncode that does anything like explicitly setting \"$AFINET = 2\", you know you're in for big\ntrouble. An immeasurably superior approach is to use the Socket module, which more reliably\ngrants access to the various constants and functions you'll need.\n\nIf you're not writing a server/client for an existing protocol like NNTP or SMTP, you should\ngive some thought to how your server will know when the client has finished talking, and\nvice-versa. Most protocols are based on one-line messages and responses (so one party knows the\nother has finished when a \"\\n\" is received) or multi-line messages and responses that end with a\nperiod on an empty line (\"\\n.\\n\" terminates a message/response).\n",
            "subsections": [
                {
                    "name": "Internet Line Terminators",
                    "content": "The Internet line terminator is \"\\015\\012\". Under ASCII variants of Unix, that could usually be\nwritten as \"\\r\\n\", but under other systems, \"\\r\\n\" might at times be \"\\015\\015\\012\",\n\"\\012\\012\\015\", or something completely different. The standards specify writing \"\\015\\012\" to\nbe conformant (be strict in what you provide), but they also recommend accepting a lone \"\\012\"\non input (be lenient in what you require). We haven't always been very good about that in the\ncode in this manpage, but unless you're on a Mac from way back in its pre-Unix dark ages, you'll\nprobably be ok.\n"
                },
                {
                    "name": "Internet TCP Clients and Servers",
                    "content": "Use Internet-domain sockets when you want to do client-server communication that might extend to\nmachines outside of your own system.\n\nHere's a sample TCP client using Internet-domain sockets:\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse Socket;\n\nmy $remote  = shift || \"localhost\";\nmy $port    = shift || 2345;  # random port\nif ($port =~ /\\D/) { $port = getservbyname($port, \"tcp\") }\ndie \"No port\" unless $port;\nmy $iaddr   = inetaton($remote)       || die \"no host: $remote\";\nmy $paddr   = sockaddrin($port, $iaddr);\n\nmy $proto   = getprotobyname(\"tcp\");\nsocket(my $sock, PFINET, SOCKSTREAM, $proto)  || die \"socket: $!\";\nconnect($sock, $paddr)              || die \"connect: $!\";\nwhile (my $line = <$sock>) {\nprint $line;\n}\n\nclose ($sock)                        || die \"close: $!\";\nexit(0);\n\nAnd here's a corresponding server to go along with it. We'll leave the address as \"INADDRANY\"\nso that the kernel can choose the appropriate interface on multihomed hosts. If you want sit on\na particular interface (like the external side of a gateway or firewall machine), fill this in\nwith your real address instead.\n\n#!/usr/bin/perl -T\nuse strict;\nuse warnings;\nBEGIN { $ENV{PATH} = \"/usr/bin:/bin\" }\nuse Socket;\nuse Carp;\nmy $EOL = \"\\015\\012\";\n\nsub logmsg { print \"$0 $$: @ at \", scalar localtime(), \"\\n\" }\n\nmy $port  = shift || 2345;\ndie \"invalid port\" unless $port =~ /^ \\d+ $/x;\n\nmy $proto = getprotobyname(\"tcp\");\n\nsocket(my $server, PFINET, SOCKSTREAM, $proto) || die \"socket: $!\";\nsetsockopt($server, SOLSOCKET, SOREUSEADDR, pack(\"l\", 1))\n|| die \"setsockopt: $!\";\nbind($server, sockaddrin($port, INADDRANY)) || die \"bind: $!\";\nlisten($server, SOMAXCONN)                    || die \"listen: $!\";\n\nlogmsg \"server started on port $port\";\n\nfor (my $paddr; $paddr = accept(my $client, $server); close $client) {\nmy($port, $iaddr) = sockaddrin($paddr);\nmy $name = gethostbyaddr($iaddr, AFINET);\n\nlogmsg \"connection from $name [\",\ninetntoa($iaddr), \"]\nat port $port\";\n\nprint $client \"Hello there, $name, it's now \",\nscalar localtime(), $EOL;\n}\n\nAnd here's a multitasking version. It's multitasked in that like most typical servers, it spawns\n(fork()s) a slave server to handle the client request so that the master server can quickly go\nback to service a new client.\n\n#!/usr/bin/perl -T\nuse strict;\nuse warnings;\nBEGIN { $ENV{PATH} = \"/usr/bin:/bin\" }\nuse Socket;\nuse Carp;\nmy $EOL = \"\\015\\012\";\n\nsub spawn;  # forward declaration\nsub logmsg { print \"$0 $$: @ at \", scalar localtime(), \"\\n\" }\n\nmy $port  = shift || 2345;\ndie \"invalid port\" unless $port =~ /^ \\d+ $/x;\n\nmy $proto = getprotobyname(\"tcp\");\n\nsocket(my $server, PFINET, SOCKSTREAM, $proto) || die \"socket: $!\";\nsetsockopt($server, SOLSOCKET, SOREUSEADDR, pack(\"l\", 1))\n|| die \"setsockopt: $!\";\nbind($server, sockaddrin($port, INADDRANY)) || die \"bind: $!\";\nlisten($server, SOMAXCONN)                    || die \"listen: $!\";\n\nlogmsg \"server started on port $port\";\n\nmy $waitedpid = 0;\n\nuse POSIX \":syswaith\";\nuse Errno;\n\nsub REAPER {\nlocal $!;   # don't let waitpid() overwrite current error\nwhile ((my $pid = waitpid(-1, WNOHANG)) > 0 && WIFEXITED($?)) {\nlogmsg \"reaped $waitedpid\" . ($? ? \" with exit $?\" : \"\");\n}\n$SIG{CHLD} = \\&REAPER;  # loathe SysV\n}\n\n$SIG{CHLD} = \\&REAPER;\n\nwhile (1) {\nmy $paddr = accept(my $client, $server) || do {\n# try again if accept() returned because got a signal\nnext if $!{EINTR};\ndie \"accept: $!\";\n};\nmy ($port, $iaddr) = sockaddrin($paddr);\nmy $name = gethostbyaddr($iaddr, AFINET);\n\nlogmsg \"connection from $name [\",\ninetntoa($iaddr),\n\"] at port $port\";\n\nspawn $client, sub {\n$| = 1;\nprint \"Hello there, $name, it's now \",\nscalar localtime(),\n$EOL;\nexec \"/usr/games/fortune\"       # XXX: \"wrong\" line terminators\nor confess \"can't exec fortune: $!\";\n};\nclose $client;\n}\n\nsub spawn {\nmy $client = shift;\nmy $coderef = shift;\n\nunless (@ == 0 && $coderef && ref($coderef) eq \"CODE\") {\nconfess \"usage: spawn CLIENT CODEREF\";\n}\n\nmy $pid;\nunless (defined($pid = fork())) {\nlogmsg \"cannot fork: $!\";\nreturn;\n}\nelsif ($pid) {\nlogmsg \"begat $pid\";\nreturn; # I'm the parent\n}\n# else I'm the child -- go spawn\n\nopen(STDIN,  \"<&\", $client)   || die \"can't dup client to stdin\";\nopen(STDOUT, \">&\", $client)   || die \"can't dup client to stdout\";\n## open(STDERR, \">&\", STDOUT) || die \"can't dup stdout to stderr\";\nexit($coderef->());\n}\n\nThis server takes the trouble to clone off a child version via fork() for each incoming request.\nThat way it can handle many requests at once, which you might not always want. Even if you don't"
                },
                {
                    "name": "fork",
                    "content": "particularly careful about cleaning up their dead children (called \"zombies\" in Unix parlance),\nbecause otherwise you'll quickly fill up your process table. The REAPER subroutine is used here\nto call waitpid() for any child processes that have finished, thereby ensuring that they\nterminate cleanly and don't join the ranks of the living dead.\n\nWithin the while loop we call accept() and check to see if it returns a false value. This would\nnormally indicate a system error needs to be reported. However, the introduction of safe signals\n(see \"Deferred Signals (Safe Signals)\" above) in Perl 5.8.0 means that accept() might also be\ninterrupted when the process receives a signal. This typically happens when one of the forked\nsubprocesses exits and notifies the parent process with a CHLD signal.\n\nIf accept() is interrupted by a signal, $! will be set to EINTR. If this happens, we can safely\ncontinue to the next iteration of the loop and another call to accept(). It is important that\nyour signal handling code not modify the value of $!, or else this test will likely fail. In the\nREAPER subroutine we create a local version of $! before calling waitpid(). When waitpid() sets\n$! to ECHILD as it inevitably does when it has no more children waiting, it updates the local\ncopy and leaves the original unchanged.\n\nYou should use the -T flag to enable taint checking (see perlsec) even if we aren't running\nsetuid or setgid. This is always a good idea for servers or any program run on behalf of someone\nelse (like CGI scripts), because it lessens the chances that people from the outside will be\nable to compromise your system.\n\nLet's look at another TCP client. This one connects to the TCP \"time\" service on a number of\ndifferent machines and shows how far their clocks differ from the system on which it's being\nrun:\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse Socket;\n\nmy $SECSOF70YEARS = 2208988800;\nsub ctime { scalar localtime(shift() || time()) }\n\nmy $iaddr = gethostbyname(\"localhost\");\nmy $proto = getprotobyname(\"tcp\");\nmy $port = getservbyname(\"time\", \"tcp\");\nmy $paddr = sockaddrin(0, $iaddr);\n\n$| = 1;\nprintf \"%-24s %8s %s\\n\", \"localhost\", 0, ctime();\n\nforeach my $host (@ARGV) {\nprintf \"%-24s \", $host;\nmy $hisiaddr = inetaton($host)     || die \"unknown host\";\nmy $hispaddr = sockaddrin($port, $hisiaddr);\nsocket(my $socket, PFINET, SOCKSTREAM, $proto)\n|| die \"socket: $!\";\nconnect($socket, $hispaddr)         || die \"connect: $!\";\nmy $rtime = pack(\"C4\", ());\nread($socket, $rtime, 4);\nclose($socket);\nmy $histime = unpack(\"N\", $rtime) - $SECSOF70YEARS;\nprintf \"%8d %s\\n\", $histime - time(), ctime($histime);\n}\n"
                },
                {
                    "name": "Unix-Domain TCP Clients and Servers",
                    "content": "That's fine for Internet-domain clients and servers, but what about local communications? While\nyou can use the same setup, sometimes you don't want to. Unix-domain sockets are local to the\ncurrent host, and are often used internally to implement pipes. Unlike Internet domain sockets,\nUnix domain sockets can show up in the file system with an ls(1) listing.\n\n% ls -l /dev/log\nsrw-rw-rw-  1 root            0 Oct 31 07:23 /dev/log\n\nYou can test for these with Perl's -S file test:\n\nunless (-S \"/dev/log\") {\ndie \"something's wicked with the log system\";\n}\n\nHere's a sample Unix-domain client:\n\n#!/usr/bin/perl\nuse Socket;\nuse strict;\nuse warnings;\n\nmy $rendezvous = shift || \"catsock\";\nsocket(my $sock, PFUNIX, SOCKSTREAM, 0) || die \"socket: $!\";\nconnect($sock, sockaddrun($rendezvous))  || die \"connect: $!\";\nwhile (defined(my $line = <$sock>)) {\nprint $line;\n}\nexit(0);\n\nAnd here's a corresponding server. You don't have to worry about silly network terminators here\nbecause Unix domain sockets are guaranteed to be on the localhost, and thus everything works\nright.\n\n#!/usr/bin/perl -T\nuse strict;\nuse warnings;\nuse Socket;\nuse Carp;\n\nBEGIN { $ENV{PATH} = \"/usr/bin:/bin\" }\nsub spawn;  # forward declaration\nsub logmsg { print \"$0 $$: @ at \", scalar localtime(), \"\\n\" }\n\nmy $NAME = \"catsock\";\nmy $uaddr = sockaddrun($NAME);\nmy $proto = getprotobyname(\"tcp\");\n\nsocket(my $server, PFUNIX, SOCKSTREAM, 0) || die \"socket: $!\";\nunlink($NAME);\nbind  ($server, $uaddr)                     || die \"bind: $!\";\nlisten($server, SOMAXCONN)                  || die \"listen: $!\";\n\nlogmsg \"server started on $NAME\";\n\nmy $waitedpid;\n\nuse POSIX \":syswaith\";\nsub REAPER {\nmy $child;\nwhile (($waitedpid = waitpid(-1, WNOHANG)) > 0) {\nlogmsg \"reaped $waitedpid\" . ($? ? \" with exit $?\" : \"\");\n}\n$SIG{CHLD} = \\&REAPER;  # loathe SysV\n}\n\n$SIG{CHLD} = \\&REAPER;\n\n\nfor ( $waitedpid = 0;\naccept(my $client, $server) || $waitedpid;\n$waitedpid = 0, close $client)\n{\nnext if $waitedpid;\nlogmsg \"connection on $NAME\";\nspawn $client, sub {\nprint \"Hello there, it's now \", scalar localtime(), \"\\n\";\nexec(\"/usr/games/fortune\")  || die \"can't exec fortune: $!\";\n};\n}\n\nsub spawn {\nmy $client = shift();\nmy $coderef = shift();\n\nunless (@ == 0 && $coderef && ref($coderef) eq \"CODE\") {\nconfess \"usage: spawn CLIENT CODEREF\";\n}\n\nmy $pid;\nunless (defined($pid = fork())) {\nlogmsg \"cannot fork: $!\";\nreturn;\n}\nelsif ($pid) {\nlogmsg \"begat $pid\";\nreturn; # I'm the parent\n}\nelse {\n# I'm the child -- go spawn\n}\n\nopen(STDIN,  \"<&\", $client)\n|| die \"can't dup client to stdin\";\nopen(STDOUT, \">&\", $client)\n|| die \"can't dup client to stdout\";\n## open(STDERR, \">&\", STDOUT)\n##  || die \"can't dup stdout to stderr\";\nexit($coderef->());\n}\n\nAs you see, it's remarkably similar to the Internet domain TCP server, so much so, in fact, that\nwe've omitted several duplicate functions--spawn(), logmsg(), ctime(), and REAPER()--which are\nthe same as in the other server.\n\nSo why would you ever want to use a Unix domain socket instead of a simpler named pipe? Because\na named pipe doesn't give you sessions. You can't tell one process's data from another's. With\nsocket programming, you get a separate session for each client; that's why accept() takes two\narguments.\n\nFor example, let's say that you have a long-running database server daemon that you want folks\nto be able to access from the Web, but only if they go through a CGI interface. You'd have a\nsmall, simple CGI program that does whatever checks and logging you feel like, and then acts as\na Unix-domain client and connects to your private server.\n\nTCP Clients with IO::Socket\nFor those preferring a higher-level interface to socket programming, the IO::Socket module\nprovides an object-oriented approach. If for some reason you lack this module, you can just\nfetch IO::Socket from CPAN, where you'll also find modules providing easy interfaces to the\nfollowing systems: DNS, FTP, Ident (RFC 931), NIS and NISPlus, NNTP, Ping, POP3, SMTP, SNMP,\nSSLeay, Telnet, and Time--to name just a few.\n\nA Simple Client\nHere's a client that creates a TCP connection to the \"daytime\" service at port 13 of the host\nname \"localhost\" and prints out everything that the server there cares to provide.\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse IO::Socket;\nmy $remote = IO::Socket::INET->new(\nProto    => \"tcp\",\nPeerAddr => \"localhost\",\nPeerPort => \"daytime(13)\",\n)\n|| die \"can't connect to daytime service on localhost\";\nwhile (<$remote>) { print }\n\nWhen you run this program, you should get something back that looks like this:\n\nWed May 14 08:40:46 MDT 1997\n\nHere are what those parameters to the new() constructor mean:\n\n\"Proto\"\nThis is which protocol to use. In this case, the socket handle returned will be connected to\na TCP socket, because we want a stream-oriented connection, that is, one that acts pretty\nmuch like a plain old file. Not all sockets are this of this type. For example, the UDP\nprotocol can be used to make a datagram socket, used for message-passing.\n\n\"PeerAddr\"\nThis is the name or Internet address of the remote host the server is running on. We could\nhave specified a longer name like \"www.perl.com\", or an address like \"207.171.7.72\". For\ndemonstration purposes, we've used the special hostname \"localhost\", which should always\nmean the current machine you're running on. The corresponding Internet address for localhost\nis \"127.0.0.1\", if you'd rather use that.\n\n\"PeerPort\"\nThis is the service name or port number we'd like to connect to. We could have gotten away\nwith using just \"daytime\" on systems with a well-configured system services file,[FOOTNOTE:\nThe system services file is found in */etc/services* under Unixy systems.] but here we've\nspecified the port number (13) in parentheses. Using just the number would have also worked,\nbut numeric literals make careful programmers nervous.\n\nA Webget Client\nHere's a simple client that takes a remote host to fetch a document from, and then a list of\nfiles to get from that host. This is a more interesting client than the previous one because it\nfirst sends something to the server before fetching the server's response.\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse IO::Socket;\nunless (@ARGV > 1) { die \"usage: $0 host url ...\" }\nmy $host = shift(@ARGV);\nmy $EOL = \"\\015\\012\";\nmy $BLANK = $EOL x 2;\nfor my $document (@ARGV) {\nmy $remote = IO::Socket::INET->new( Proto     => \"tcp\",\nPeerAddr  => $host,\nPeerPort  => \"http(80)\",\n)     || die \"cannot connect to httpd on $host\";\n$remote->autoflush(1);\nprint $remote \"GET $document HTTP/1.0\" . $BLANK;\nwhile ( <$remote> ) { print }\nclose $remote;\n}\n\nThe web server handling the HTTP service is assumed to be at its standard port, number 80. If\nthe server you're trying to connect to is at a different port, like 1080 or 8080, you should\nspecify it as the named-parameter pair, \"PeerPort => 8080\". The \"autoflush\" method is used on\nthe socket because otherwise the system would buffer up the output we sent it. (If you're on a\nprehistoric Mac, you'll also need to change every \"\\n\" in your code that sends data over the\nnetwork to be a \"\\015\\012\" instead.)\n\nConnecting to the server is only the first part of the process: once you have the connection,\nyou have to use the server's language. Each server on the network has its own little command\nlanguage that it expects as input. The string that we send to the server starting with \"GET\" is\nin HTTP syntax. In this case, we simply request each specified document. Yes, we really are\nmaking a new connection for each document, even though it's the same host. That's the way you\nalways used to have to speak HTTP. Recent versions of web browsers may request that the remote\nserver leave the connection open a little while, but the server doesn't have to honor such a\nrequest.\n\nHere's an example of running that program, which we'll call *webget*:\n\n% webget www.perl.com /guanaco.html\nHTTP/1.1 404 File Not Found\nDate: Thu, 08 May 1997 18:02:32 GMT\nServer: Apache/1.2b6\nConnection: close\nContent-type: text/html\n\n<HEAD><TITLE>404 File Not Found</TITLE></HEAD>\n<BODY><H1>File Not Found</H1>\nThe requested URL /guanaco.html was not found on this server.<P>\n</BODY>\n\nOk, so that's not very interesting, because it didn't find that particular document. But a long\nresponse wouldn't have fit on this page.\n\nFor a more featureful version of this program, you should look to the *lwp-request* program\nincluded with the LWP modules from CPAN.\n"
                },
                {
                    "name": "Interactive Client with IO::Socket",
                    "content": "Well, that's all fine if you want to send one command and get one answer, but what about setting\nup something fully interactive, somewhat like the way *telnet* works? That way you can type a\nline, get the answer, type a line, get the answer, etc.\n\nThis client is more complicated than the two we've done so far, but if you're on a system that\nsupports the powerful \"fork\" call, the solution isn't that rough. Once you've made the\nconnection to whatever service you'd like to chat with, call \"fork\" to clone your process. Each\nof these two identical process has a very simple job to do: the parent copies everything from\nthe socket to standard output, while the child simultaneously copies everything from standard\ninput to the socket. To accomplish the same thing using just one process would be *much* harder,\nbecause it's easier to code two processes to do one thing than it is to code one process to do\ntwo things. (This keep-it-simple principle a cornerstones of the Unix philosophy, and good\nsoftware engineering as well, which is probably why it's spread to other systems.)\n\nHere's the code:\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse IO::Socket;\n\nunless (@ARGV == 2) { die \"usage: $0 host port\" }\nmy ($host, $port) = @ARGV;\n\n# create a tcp connection to the specified host and port\nmy $handle = IO::Socket::INET->new(Proto     => \"tcp\",\nPeerAddr  => $host,\nPeerPort  => $port)\n|| die \"can't connect to port $port on $host: $!\";\n\n$handle->autoflush(1);       # so output gets there right away\nprint STDERR \"[Connected to $host:$port]\\n\";\n\n# split the program into two processes, identical twins\ndie \"can't fork: $!\" unless defined(my $kidpid = fork());\n\n# the if{} block runs only in the parent process\nif ($kidpid) {\n# copy the socket to standard output\nwhile (defined (my $line = <$handle>)) {\nprint STDOUT $line;\n}\nkill(\"TERM\", $kidpid);   # send SIGTERM to child\n}\n# the else{} block runs only in the child process\nelse {\n# copy standard input to the socket\nwhile (defined (my $line = <STDIN>)) {\nprint $handle $line;\n}\nexit(0);                # just in case\n}\n\nThe \"kill\" function in the parent's \"if\" block is there to send a signal to our child process,\ncurrently running in the \"else\" block, as soon as the remote server has closed its end of the\nconnection.\n\nIf the remote server sends data a byte at time, and you need that data immediately without\nwaiting for a newline (which might not happen), you may wish to replace the \"while\" loop in the\nparent with the following:\n\nmy $byte;\nwhile (sysread($handle, $byte, 1) == 1) {\nprint STDOUT $byte;\n}\n\nMaking a system call for each byte you want to read is not very efficient (to put it mildly) but\nis the simplest to explain and works reasonably well.\n\nTCP Servers with IO::Socket\nAs always, setting up a server is little bit more involved than running a client. The model is\nthat the server creates a special kind of socket that does nothing but listen on a particular\nport for incoming connections. It does this by calling the \"IO::Socket::INET->new()\" method with\nslightly different arguments than the client did.\n\nProto\nThis is which protocol to use. Like our clients, we'll still specify \"tcp\" here.\n\nLocalPort\nWe specify a local port in the \"LocalPort\" argument, which we didn't do for the client. This\nis service name or port number for which you want to be the server. (Under Unix, ports under\n1024 are restricted to the superuser.) In our sample, we'll use port 9000, but you can use\nany port that's not currently in use on your system. If you try to use one already in used,\nyou'll get an \"Address already in use\" message. Under Unix, the \"netstat -a\" command will\nshow which services current have servers.\n\nListen\nThe \"Listen\" parameter is set to the maximum number of pending connections we can accept\nuntil we turn away incoming clients. Think of it as a call-waiting queue for your telephone.\nThe low-level Socket module has a special symbol for the system maximum, which is SOMAXCONN.\n\nReuse\nThe \"Reuse\" parameter is needed so that we restart our server manually without waiting a few\nminutes to allow system buffers to clear out.\n\nOnce the generic server socket has been created using the parameters listed above, the server\nthen waits for a new client to connect to it. The server blocks in the \"accept\" method, which\neventually accepts a bidirectional connection from the remote client. (Make sure to autoflush\nthis handle to circumvent buffering.)\n\nTo add to user-friendliness, our server prompts the user for commands. Most servers don't do\nthis. Because of the prompt without a newline, you'll have to use the \"sysread\" variant of the\ninteractive client above.\n\nThis server accepts one of five different commands, sending output back to the client. Unlike\nmost network servers, this one handles only one incoming client at a time. Multitasking servers\nare covered in Chapter 16 of the Camel.\n\nHere's the code.\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse IO::Socket;\nuse Net::hostent;      # for OOish version of gethostbyaddr\n\nmy $PORT = 9000;       # pick something not in use\n\nmy $server = IO::Socket::INET->new( Proto     => \"tcp\",\nLocalPort => $PORT,\nListen    => SOMAXCONN,\nReuse     => 1);\n\ndie \"can't setup server\" unless $server;\nprint \"[Server $0 accepting clients]\\n\";\n\nwhile (my $client = $server->accept()) {\n$client->autoflush(1);\nprint $client \"Welcome to $0; type help for command list.\\n\";\nmy $hostinfo = gethostbyaddr($client->peeraddr);\nprintf \"[Connect from %s]\\n\",\n$hostinfo ? $hostinfo->name : $client->peerhost;\nprint $client \"Command? \";\nwhile ( <$client>) {\nnext unless /\\S/;     # blank line\nif    (/quit|exit/i)  { last                                      }\nelsif (/date|time/i)  { printf $client \"%s\\n\", scalar localtime() }\nelsif (/who/i )       { print  $client `who 2>&1`                 }\nelsif (/cookie/i )    { print  $client `/usr/games/fortune 2>&1`  }\nelsif (/motd/i )      { print  $client `cat /etc/motd 2>&1`       }\nelse {\nprint $client \"Commands: quit date who cookie motd\\n\";\n}\n} continue {\nprint $client \"Command? \";\n}\nclose $client;\n}\n\nUDP: Message Passing\nAnother kind of client-server setup is one that uses not connections, but messages. UDP\ncommunications involve much lower overhead but also provide less reliability, as there are no\npromises that messages will arrive at all, let alone in order and unmangled. Still, UDP offers\nsome advantages over TCP, including being able to \"broadcast\" or \"multicast\" to a whole bunch of\ndestination hosts at once (usually on your local subnet). If you find yourself overly concerned\nabout reliability and start building checks into your message system, then you probably should\nuse just TCP to start with.\n\nUDP datagrams are *not* a bytestream and should not be treated as such. This makes using I/O\nmechanisms with internal buffering like stdio (i.e. print() and friends) especially cumbersome.\nUse syswrite(), or better send(), like in the example below.\n\nHere's a UDP program similar to the sample Internet TCP client given earlier. However, instead\nof checking one host at a time, the UDP version will check many of them asynchronously by\nsimulating a multicast and then using select() to do a timed-out wait for I/O. To do something\nsimilar with TCP, you'd have to use a different socket handle for each host.\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse Socket;\nuse Sys::Hostname;\n\nmy $SECSOF70YEARS = 2208988800;\n\nmy $iaddr = gethostbyname(hostname());\nmy $proto = getprotobyname(\"udp\");\nmy $port = getservbyname(\"time\", \"udp\");\nmy $paddr = sockaddrin(0, $iaddr); # 0 means let kernel pick\n\nsocket(my $socket, PFINET, SOCKDGRAM, $proto) || die \"socket: $!\";\nbind($socket, $paddr)                           || die \"bind: $!\";\n\n$| = 1;\nprintf \"%-12s %8s %s\\n\",  \"localhost\", 0, scalar localtime();\nmy $count = 0;\nfor my $host (@ARGV) {\n$count++;\nmy $hisiaddr = inetaton($host)         || die \"unknown host\";\nmy $hispaddr = sockaddrin($port, $hisiaddr);\ndefined(send($socket, 0, 0, $hispaddr)) || die \"send $host: $!\";\n}\n\nmy $rout = my $rin = \"\";\nvec($rin, fileno($socket), 1) = 1;\n\n# timeout after 10.0 seconds\nwhile ($count && select($rout = $rin, undef, undef, 10.0)) {\nmy $rtime = \"\";\nmy $hispaddr = recv($socket, $rtime, 4, 0) || die \"recv: $!\";\nmy ($port, $hisiaddr) = sockaddrin($hispaddr);\nmy $host = gethostbyaddr($hisiaddr, AFINET);\nmy $histime = unpack(\"N\", $rtime) - $SECSOF70YEARS;\nprintf \"%-12s \", $host;\nprintf \"%8d %s\\n\", $histime - time(), scalar localtime($histime);\n$count--;\n}\n\nThis example does not include any retries and may consequently fail to contact a reachable host.\nThe most prominent reason for this is congestion of the queues on the sending host if the number\nof hosts to contact is sufficiently large.\n\nSysV IPC\nWhile System V IPC isn't so widely used as sockets, it still has some interesting uses. However,\nyou cannot use SysV IPC or Berkeley mmap() to have a variable shared amongst several processes.\nThat's because Perl would reallocate your string when you weren't wanting it to. You might look\ninto the \"IPC::Shareable\" or \"threads::shared\" modules for that.\n\nHere's a small example showing shared memory usage.\n\nuse IPC::SysV qw(IPCPRIVATE IPCRMID SIRUSR SIWUSR);\n\nmy $size = 2000;\nmy $id = shmget(IPCPRIVATE, $size, SIRUSR | SIWUSR);\ndefined($id)                    || die \"shmget: $!\";\nprint \"shm key $id\\n\";\n\nmy $message = \"Message #1\";\nshmwrite($id, $message, 0, 60)  || die \"shmwrite: $!\";\nprint \"wrote: '$message'\\n\";\nshmread($id, my $buff, 0, 60)      || die \"shmread: $!\";\nprint \"read : '$buff'\\n\";\n\n# the buffer of shmread is zero-character end-padded.\nsubstr($buff, index($buff, \"\\0\")) = \"\";\nprint \"un\" unless $buff eq $message;\nprint \"swell\\n\";\n\nprint \"deleting shm $id\\n\";\nshmctl($id, IPCRMID, 0)        || die \"shmctl: $!\";\n\nHere's an example of a semaphore:\n\nuse IPC::SysV qw(IPCCREAT);\n\nmy $IPCKEY = 1234;\nmy $id = semget($IPCKEY, 10, 0666 | IPCCREAT);\ndefined($id)                    || die \"semget: $!\";\nprint \"sem id $id\\n\";\n\nPut this code in a separate file to be run in more than one process. Call the file take:\n\n# create a semaphore\n\nmy $IPCKEY = 1234;\nmy $id = semget($IPCKEY, 0, 0);\ndefined($id)                    || die \"semget: $!\";\n\nmy $semnum  = 0;\nmy $semflag = 0;\n\n# \"take\" semaphore\n# wait for semaphore to be zero\nmy $semop = 0;\nmy $opstring1 = pack(\"s!s!s!\", $semnum, $semop, $semflag);\n\n# Increment the semaphore count\n$semop = 1;\nmy $opstring2 = pack(\"s!s!s!\", $semnum, $semop,  $semflag);\nmy $opstring  = $opstring1 . $opstring2;\n\nsemop($id, $opstring)   || die \"semop: $!\";\n\nPut this code in a separate file to be run in more than one process. Call this file give:\n\n# \"give\" the semaphore\n# run this in the original process and you will see\n# that the second process continues\n\nmy $IPCKEY = 1234;\nmy $id = semget($IPCKEY, 0, 0);\ndie unless defined($id);\n\nmy $semnum  = 0;\nmy $semflag = 0;\n\n# Decrement the semaphore count\nmy $semop = -1;\nmy $opstring = pack(\"s!s!s!\", $semnum, $semop, $semflag);\n\nsemop($id, $opstring)   || die \"semop: $!\";\n\nThe SysV IPC code above was written long ago, and it's definitely clunky looking. For a more\nmodern look, see the IPC::SysV module.\n\nA small example demonstrating SysV message queues:\n\nuse IPC::SysV qw(IPCPRIVATE IPCRMID IPCCREAT SIRUSR SIWUSR);\n\nmy $id = msgget(IPCPRIVATE, IPCCREAT | SIRUSR | SIWUSR);\ndefined($id)                || die \"msgget failed: $!\";\n\nmy $sent      = \"message\";\nmy $typesent = 1234;\n\nmsgsnd($id, pack(\"l! a*\", $typesent, $sent), 0)\n|| die \"msgsnd failed: $!\";\n\nmsgrcv($id, my $rcvdbuf, 60, 0, 0)\n|| die \"msgrcv failed: $!\";\n\nmy($typercvd, $rcvd) = unpack(\"l! a*\", $rcvdbuf);\n\nif ($rcvd eq $sent) {\nprint \"okay\\n\";\n} else {\nprint \"not okay\\n\";\n}\n\nmsgctl($id, IPCRMID, 0)    || die \"msgctl failed: $!\\n\";\n"
                }
            ]
        },
        "NOTES": {
            "content": "Most of these routines quietly but politely return \"undef\" when they fail instead of causing\nyour program to die right then and there due to an uncaught exception. (Actually, some of the\nnew *Socket* conversion functions do croak() on bad arguments.) It is therefore essential to\ncheck return values from these functions. Always begin your socket programs this way for optimal\nsuccess, and don't forget to add the -T taint-checking flag to the \"#!\" line for servers:\n\n#!/usr/bin/perl -T\nuse strict;\nuse warnings;\nuse sigtrap;\nuse Socket;\n",
            "subsections": []
        },
        "BUGS": {
            "content": "These routines all create system-specific portability problems. As noted elsewhere, Perl is at\nthe mercy of your C libraries for much of its system behavior. It's probably safest to assume\nbroken SysV semantics for signals and to stick with simple TCP and UDP socket operations; e.g.,\ndon't try to pass open file descriptors over a local UDP datagram socket if you want your code\nto stand a chance of being portable.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Tom Christiansen, with occasional vestiges of Larry Wall's original version and suggestions from\nthe Perl Porters.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "There's a lot more to networking than this, but this should get you started.\n\nFor intrepid programmers, the indispensable textbook is *Unix Network Programming, 2nd Edition,\nVolume 1* by W. Richard Stevens (published by Prentice-Hall). Most books on networking address\nthe subject from the perspective of a C programmer; translation to Perl is left as an exercise\nfor the reader.\n\nThe IO::Socket(3) manpage describes the object library, and the Socket(3) manpage describes the\nlow-level interface to sockets. Besides the obvious functions in perlfunc, you should also check\nout the modules file at your nearest CPAN site, especially\n<http://www.cpan.org/modules/00modlist.long.html#ID5Networking>. See perlmodlib or best yet,\nthe Perl FAQ for a description of what CPAN is and where to get it if the previous link doesn't\nwork for you.\n\nSection 5 of CPAN's modules file is devoted to \"Networking, Device Control (modems), and\nInterprocess Communication\", and contains numerous unbundled modules numerous networking\nmodules, Chat and Expect operations, CGI programming, DCE, FTP, IPC, NNTP, Proxy, Ptty, RPC,\nSNMP, SMTP, Telnet, Threads, and ToolTalk--to name just a few.\n",
            "subsections": []
        }
    },
    "summary": "perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets, and semaphores)",
    "flags": [],
    "examples": [],
    "see_also": [
        {
            "name": "Socket",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/Socket/3/json"
        },
        {
            "name": "Socket",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/Socket/3/json"
        }
    ]
}