{
    "mode": "man",
    "parameter": "PERLIPC",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/PERLIPC/1/json",
    "generated": "2026-11-15T14:41:17Z",
    "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,\npipe opens, the Berkeley socket routines, and SysV IPC calls.  Each is used in slightly\ndifferent situations.\n",
            "subsections": []
        },
        "Signals": {
            "content": "Perl uses a simple signal handling model: the %SIG hash contains names or references of user-\ninstalled 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\nare not.  That meant that doing nearly anything in your handler could in theory trigger a\nmemory fault 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\nbehavior with respect to a value of \"IGNORE\".  Setting $SIG{CHLD} to \"IGNORE\" on such a\nplatform has the effect of not creating zombie processes when the parent process fails to\nwait() on its child processes (i.e., child processes are automatically reaped).  Calling\nwait() with $SIG{CHLD} set to \"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\ngroup, and 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\nchild process, 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\nhandler caused by the first death, we won't get another signal. So must loop here else we\nwill leave the unreaped child as a zombie. And the next time two children die we get another\nzombie.  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\nwait() for the result. Thus, your signal handler will be called. Because wait() was already\ncalled by system() or qx(), the wait() in the signal handler will see no more zombies and\nwill therefore 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\nto you in some number of seconds.  Then try your blocking operation, clearing the alarm when\nit's done but not before you've exited your \"eval{}\" block.  If it goes off, you'll use die()\nto jump out 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\nthe errant child process.\n\nFor more complex signal handling, you might see the standard POSIX module.  Lamentably, this\nis almost entirely undocumented, but the ext/POSIX/t/sigaction.t file from the Perl source\ndistribution has some examples in it.\n",
            "subsections": [
                {
                    "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\ndown is called a daemon (Disk And Execution MONitor). If a daemon process has a configuration\nfile which is modified after the process has been started, there should be a way to tell that\nprocess to reread its configuration file without stopping the process. Many daemons provide\nthis mechanism using a \"SIGHUP\" signal handler. When you want to tell the daemon to reread\nthe file, simply send it the \"SIGHUP\" signal.\n\nThe following example implements a simple daemon, which restarts itself every time the\n\"SIGHUP\" signal is received. The actual code is located in the subroutine code(), which just\nprints some debugging info to show that it works; it should be replaced with the real code.\n\n#!/usr/bin/perl\n\nuse v5.36;\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"
                },
                {
                    "name": "Deferred Signals (Safe Signals)",
                    "content": "Before 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\nPerl is executing one function (like malloc(3) or printf(3)), and your signal handler then\ncalls the same function again, you could get unpredictable behavior--often, a core dump.\nSecond, Perl isn't itself re-entrant at the lowest levels.  If the signal interrupts Perl\nwhile Perl is changing its own internal data structures, similarly unpredictable behavior may\nresult.\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\nsystem call, which will just restart.  That means you have to \"die\" to longjmp(3) out of the\nhandler.  Even this is a little cavalier for the true paranoiac, who avoids \"die\" in a\nhandler because the system is out to get you.  The pragmatic approach was to say \"I know the\nrisks, but prefer the convenience\", and to do anything you wanted in your signal handler, and\nbe prepared to clean up core dumps now and again.\n\nPerl 5.8.0 and later avoid these problems by \"deferring\" signals.  That is, when the signal\nis delivered to the process by the system (to the C code that implements Perl) a flag is set,\nand the handler returns immediately.  Then at strategic \"safe\" points in the Perl interpreter\n(e.g. when it is about to execute a new opcode) the flags are checked and the Perl level\nhandler from %SIG is executed. The \"deferred\" scheme allows much more flexibility in the\ncoding of signal handlers as we know the Perl interpreter is in a safe state, and that we are\nnot in a system library function when the handler is called.  However the implementation does\ndiffer from previous 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\nopcode, a signal that arrives during a long-running opcode  (e.g.  a  regular  expression\noperation on a very 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 fine-\ngrained  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\nqueue  gets flooded to the point that there are signals that have been raised but not yet\ncaught (and thus not deferred) at the time an opcode completes, those signals may well be\ncaught and deferred during subsequent opcodes, with sometimes  surprising  results.   For\nexample, you may see alarms delivered even after calling alarm(0) as the latter stops the\nraising  of  alarms but does not cancel the delivery of alarms raised but not yet caught.\nDo not depend on the behaviors described in this paragraph as they are  side  effects  of\nthe current implementation 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\ninto IO operations like read(2), which is used to implement Perl's  readline()  function,\nthe  \"<>\"  operator.  On older Perls the handler was called immediately (and as \"read\" is\nnot \"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\nthe \"read\" without returning to Perl to give it a chance to call  the  %SIG  handler.  If\nthis happens on your system the solution is to use the \":perlio\" layer to do IO--at least\non  those  handles  that  you  want to be able to break into with signals. (The \":perlio\"\nlayer checks 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\nmight get 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\nwith such functions, try using the POSIX sigaction() function, which bypasses  Perl  safe\nsignals.   Be  warned  that  this  does  subject  you  to  possible memory corruption, as\ndescribed 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,\nPerl  5.8.0  and later do not use SARESTART.  Consequently, restartable system calls can\nfail (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, BUS and FPE are generated by virtual memory addressing\nerrors and similar \"faults\". These are normally  fatal:  there  is  little  a  Perl-level\nhandler  can  do  with them.  So Perl delivers them immediately rather than attempting to\ndefer them.\n\nIt is possible to catch these with a %SIG handler (see perlvar), but on top of the  usual\nproblems  of  \"unsafe\" signals the signal is likely to get rethrown immediately on return\nfrom the signal handler, so such a handler should \"die\" or \"exit\" instead.\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.\nOn  some  operating  systems  the  signal handler is expected to \"wait\" for the completed\nchild process. On such systems the  deferred  signal  scheme  will  not  work  for  those\nsignals:  it  does  not  do  the  \"wait\".  Again the failure will look like a loop as the\noperating system will reissue the signal because there are completed child processes that\nhave not yet been \"wait\"ed for.\n\nIf you want the old  signal  behavior  back  despite  possible  memory  corruption,  set  the\nenvironment variable \"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\nthe processes 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\nin your 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\nPerl  program  on  the  other  end.   Now every time any program (like a mailer, news reader,\nfinger program, etc.) tries to read from that file, the reading program  will  read  the  new\nsignature from your program.  We'll use the pipe-checking file-test operator, -p, to find out\nwhether anyone (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\nby specifying the open mode as \"|-\" or \"-|\".  Here's how to start something  up  in  a  child\nprocess you 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\nparticular  program is a Perl script expecting filenames in @ARGV using the two-argument form\nof open() or the \"<>\" 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\nf1,  the  process cmd1, standard input (tmpfile in this case), the f2 file, the cmd2 command,\nand finally 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\nearly if 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\npipe  to  a  command  that  doesn't exist: the open() will in all likelihood succeed (it only\nreflects the fork()'s success), but then your output will  fail--spectacularly.   Perl  can't\nknow  whether  the  command  worked,  because  your command is actually running in a separate\nprocess whose exec() might have failed.  Therefore, while readers of  bogus  commands  return\njust  a quick EOF, writers to bogus commands will get hit with a signal, which they'd best be\nprepared 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;\nphysical  writes are delayed.  That won't blow up until the close, and it will blow up with a\nSIGPIPE.  To catch 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",
            "subsections": [
                {
                    "name": "Filehandles",
                    "content": "Both the main process and any child processes it forks share  the  same  STDIN,  STDOUT,  and\nSTDERR filehandles.  If both processes try to access them at once, strange things can happen.\nYou  may also want to close or reopen the filehandles for the child.  You can get around this\nby opening your pipe with open(), but on some systems  this  means  that  the  child  process\ncannot outlive the parent.\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\nsame as the parent's.  You won't need to catch SIGCHLD  because  of  the  double-fork  taking\nplace; see below 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\nthe child process from the parent.  This  is  often  called  daemonization.   A  well-behaved\ndaemon  will  also  chdir()  to  the  root  directory  so  it  doesn't prevent unmounting the\nfilesystem containing the directory from which it was launched,  and  redirect  its  standard\nfile  descriptors  from  and to /dev/null so that random output doesn't wind up on the user's\nterminal.\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\nsetsid()  will  fail  if  you  are.   If your system doesn't have the setsid() function, open\n/dev/tty 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()\nfunction will accept a file argument of either \"-|\" or \"|-\" to do a very  interesting  thing:\nit  forks  a  child connected to the filehandle you've opened.  The child is running the same\nprogram as the parent.  This is useful for safely  opening  a  file  when  running  under  an\nassumed  UID  or  GID,  for  example.   If  you  open  a  pipe to minus, you can write to the\nfilehandle you opened and your kid will find it in his STDIN.  If you open a pipe from minus,\nyou can read from the filehandle you 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\nshell's  interference.  With system(), it's straightforward, but you can't use a pipe open or\nbackticks safely.  That's because there's no way to stop the shell from getting its hands  on\nyour arguments.   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\npipe() with multiple subprocesses.  The example above is \"safe\"  because  it  is  simple  and\ncalls  exec().   See  \"Avoiding  Pipe Deadlocks\" for general safety principles, but there are\nextra gotchas with Safe Pipe Opens.\n\nIn particular, if you opened the pipe using \"open $fh, \"|-\"\",  then  you  cannot  simply  use\nclose() in 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\nsubprocess  to  exit.   If  the  child process ends up waiting for something happening in the\nsection marked \"do something else\", you have deadlock.\n\nThis can also be a problem with intermediate subprocesses in  more  complicated  code,  which\nwill  call  waitpid()  on  all  open filehandles during global destruction--in no predictable\norder.\n\nTo solve this, you must manually use pipe(), fork(), and the form of open()  which  sets  one\nfile descriptor 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\nyou  wish  to  avoid  having  the  shell interpret metacharacters that may be in your command\nstring.\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\ncorresponding syntax 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\ncontent  is  perfectly  safe.   There  is therefore no cause to resort to the harder-to-read,\nmulti-argument form of pipe open().  However, whenever you cannot be assured that the program\narguments are free of shell metacharacters, the fancier form of open() should be  used.   For\nexample:\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\nthe filenames 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\nhalf  of  any  pipes created for interprocess communication it is not using.  This is because\nany child process reading from the pipe and expecting an  EOF  will  never  receive  it,  and\ntherefore  never  exit.  A  single process closing a pipe is not enough to close it; the last\nprocess with the pipe open 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\nis  so  any filehandles you didn't explicitly route to the STDIN, STDOUT or STDERR of a child\nprogram 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\nstill close() all filehandles during global destruction.  As previously discussed,  if  those\nfilehandles  have  been  opened  with  Safe Pipe Open, this will result in calling waitpid(),\nwhich may again deadlock.\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\nboth ends.  There's also an open3() in IPC::Open3 for tridirectional  I/O  so  you  can  also\ncatch  your  child's  STDERR,  but  doing  so would then require an awkward select() loop and\nwouldn't allow you to use normal Perl input operations.\n\nIf you look at its source, you'll see that open2() uses low-level primitives like the  pipe()\nand  exec()  syscalls  to  create  all  the  connections.   Although  it might have been more\nefficient by using socketpair(), this would have been even less portable than it already  is.\nThe  open2()  and open3() functions are unlikely to work anywhere except on a Unix system, or\nat least one 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"
                },
                {
                    "name": "-u",
                    "content": "this seldom works unless you yourself wrote the program on the other end of the  double-ended\npipe.\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\nyou're using.  The \"Expect\" module from CPAN also addresses this kind of thing.  This  module\nrequires two other modules from CPAN, \"IO::Pty\" and \"IO::Stty\".  It sets up a pseudo terminal\nto  interact  with  programs  that  insist on talking to the terminal device driver.  If your\nsystem is supported, this may be your best bet.\n",
                    "flag": "-u"
                },
                {
                    "name": "Bidirectional Communication with Yourself",
                    "content": "If you want, you may make low-level pipe() and fork() syscalls to  stitch  this  together  by\nhand.   This  example  only  talks to itself, but you could reopen the appropriate handles to\nSTDIN and STDOUT and call  other  processes.   (The  following  example  lacks  proper  error\nchecking.)\n\n#!/usr/bin/perl\n# pipe1 - bidirectional communication using two pipe pairs\n#         designed for the socketpair-challenged\nuse v5.36;\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\ncall, it will 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 v5.36;\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\nwhich case this section probably isn't going to do you much good.  With sockets, you  can  do\nboth virtual circuits like TCP streams and datagrams like UDP packets.  You may be able to do\neven more 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,\nso you 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\nsee  code  that  does anything like explicitly setting \"$AFINET = 2\", you know you're in for\nbig trouble.  An immeasurably superior approach is to  use  the  Socket  module,  which  more\nreliably grants 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\nthe other has finished when a \"\\n\" is received) or multi-line messages and responses that end\nwith a period 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\nbe written 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\"\nto be conformant (be strict in what you provide), but they also recommend  accepting  a  lone\n\"\\012\"  on  input  (be  lenient in what you require).  We haven't always been very good about\nthat in the code in this manpage, but unless you're on a Mac from way back  in  its  pre-Unix\ndark ages, you'll probably 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\nto machines outside of your own system.\n\nHere's a sample TCP client using Internet-domain sockets:\n\n#!/usr/bin/perl\nuse v5.36;\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\n\"INADDRANY\" so that the kernel can choose the appropriate interface on multihomed hosts.  If\nyou want sit on a particular interface (like the external  side  of  a  gateway  or  firewall\nmachine), fill this in with your real address instead.\n\n#!/usr/bin/perl -T\nuse v5.36;\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\nspawns (fork()s) a child server to handle the client request so that the  master  server  can\nquickly go back to service a new client.\n\n#!/usr/bin/perl -T\nuse v5.36;\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\nrequest.  That way it can handle many requests at once, which  you  might  not  always  want.\nEven  if  you  don't  fork(), the listen() will allow that many pending connections.  Forking\nservers have to be particularly  careful  about  cleaning  up  their  dead  children  (called\n\"zombies\"  in  Unix  parlance),  because otherwise you'll quickly fill up your process table.\nThe REAPER subroutine is used here to call  waitpid()  for  any  child  processes  that  have\nfinished, thereby ensuring that they terminate cleanly and don't join the ranks of the living\ndead.\n\nWithin  the  while  loop we call accept() and check to see if it returns a false value.  This\nwould normally indicate a system error needs to be reported.  However,  the  introduction  of\nsafe  signals (see \"Deferred Signals (Safe Signals)\" above) in Perl 5.8.0 means that accept()\nmight also be interrupted when the process receives a signal.  This  typically  happens  when\none of the forked subprocesses 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\nsafely continue to the next iteration of the loop  and  another  call  to  accept().   It  is\nimportant  that  your signal handling code not modify the value of $!, or else this test will\nlikely fail.  In the REAPER subroutine we  create  a  local  version  of  $!  before  calling\nwaitpid().   When  waitpid()  sets  $!  to  ECHILD  as it inevitably does when it has no more\nchildren waiting, it updates the local copy 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\nsomeone else (like CGI scripts), because it lessens the chances that people from the  outside\nwill  be  able to compromise your system.  Note that perl can be built without taint support.\nThere are two different modes: in one, -T will silently do nothing.  In  the  other  mode  -T\nresults in a fatal error.\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 v5.36;\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?\nWhile you can use the same setup, sometimes you don't want to.  Unix-domain sockets are local\nto  the  current  host,  and  are  often used internally to implement pipes.  Unlike Internet\ndomain sockets, Unix 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 v5.36;\nuse Socket;\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\nhere  because  Unix domain sockets are guaranteed to be on the localhost, and thus everything\nworks right.\n\n#!/usr/bin/perl -T\nuse v5.36;\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,\nthat   we've   omitted   several   duplicate   functions--spawn(),   logmsg(),  ctime(),  and\nREAPER()--which are the 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?\nBecause  a  named  pipe  doesn't  give  you sessions.  You can't tell one process's data from\nanother's.  With socket programming, you get a separate session for each client;  that's  why\naccept() takes two arguments.\n\nFor  example,  let's  say  that  you have a long-running database server daemon that you want\nfolks to be able to access from the Web, but only if they go through a CGI interface.   You'd\nhave  a  small,  simple  CGI program that does whatever checks and logging you feel like, and\nthen acts as a 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"
                },
                {
                    "name": "A Simple Client",
                    "content": "Here'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 v5.36;\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\nconnected  to  a  TCP  socket, because we want a stream-oriented connection, that is, one\nthat acts pretty much like a plain old file.  Not all sockets are this of this type.  For\nexample, the UDP protocol can be used to  make  a  datagram  socket,  used  for  message-\npassing.\n\n\"PeerAddr\"\nThis  is  the  name  or Internet address of the remote host the server is running on.  We\ncould  have  specified  a  longer  name  like  \"www.perl.com\",   or   an   address   like\n\"207.171.7.72\".  For demonstration purposes, we've used the special hostname \"localhost\",\nwhich  should  always  mean  the  current  machine  you're running on.  The corresponding\nInternet address for localhost is \"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\naway  with  using  just  \"daytime\"  on  systems  with  a  well-configured system services\nfile,[FOOTNOTE: The system services file is found in /etc/services under Unixy  systems.]\nbut  here  we've  specified  the  port number (13) in parentheses.  Using just the number\nwould have also worked, but numeric literals make careful programmers nervous.\n"
                },
                {
                    "name": "A Webget Client",
                    "content": "Here'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\nit first sends something to the server before fetching the server's response.\n\n#!/usr/bin/perl\nuse v5.36;\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.\nIf the server you're trying to connect to is at a different port,  like  1080  or  8080,  you\nshould specify it as the named-parameter pair, \"PeerPort => 8080\".  The \"autoflush\" method is\nused  on  the socket because otherwise the system would buffer up the output we sent it.  (If\nyou're on a prehistoric Mac, you'll also need to change every \"\\n\" in your  code  that  sends\ndata over the network 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\"\nis  in HTTP syntax.  In this case, we simply request each specified document.  Yes, we really\nare making a new connection for each document, even though it's the same  host.   That's  the\nway  you always used to have to speak HTTP.  Recent versions of web browsers may request that\nthe remote server leave the connection open a little while, but the server  doesn't  have  to\nhonor such a request.\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\nlong response 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\nsetting up something fully interactive, somewhat like the way telnet works?  That way you can\ntype a line, 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\nthat  supports 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.\nEach of these two identical process has a very simple job to do: the parent copies everything\nfrom  the  socket  to  standard output, while the child simultaneously copies everything from\nstandard input to the socket.  To accomplish the same thing using just one process  would  be\nmuch harder, because it's easier to code two processes to do one thing than it is to code one\nprocess  to  do  two  things.   (This  keep-it-simple  principle  a  cornerstones of the Unix\nphilosophy, and good software engineering as well, which is probably why it's spread to other\nsystems.)\n\nHere's the code:\n\n#!/usr/bin/perl\nuse v5.36;\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\nprocess,  currently  running in the \"else\" block, as soon as the remote server has closed its\nend of the connection.\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\nthe parent 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)\nbut is 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\nis that the server creates a special kind of  socket  that  does  nothing  but  listen  on  a\nparticular    port    for    incoming   connections.    It   does   this   by   calling   the\n\"IO::Socket::INET->new()\" method with slightly 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.\nThis  is  service  name  or port number for which you want to be the server. (Under Unix,\nports under 1024 are restricted to the superuser.)  In our sample, we'll use  port  9000,\nbut  you  can use any port that's not currently in use on your system.  If you try to use\none already in used, you'll get an \"Address already in use\"  message.   Under  Unix,  the\n\"netstat -a\" command will show 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\ntelephone.   The  low-level  Socket  module  has a special symbol for the system maximum,\nwhich is SOMAXCONN.\n\nReuse\nThe \"Reuse\" parameter is needed so that we restart our server manually without waiting  a\nfew minutes 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,\nwhich eventually accepts a bidirectional connection from the remote client.   (Make  sure  to\nautoflush this 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\nthe interactive client above.\n\nThis server accepts one of five different  commands,  sending  output  back  to  the  client.\nUnlike  most  network  servers,  this  one  handles  only  one  incoming  client  at  a time.\nMultitasking servers are covered in Chapter 16 of the Camel.\n\nHere's the code.\n\n#!/usr/bin/perl\nuse v5.36;\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\noffers some advantages over TCP, including being able to  \"broadcast\"  or  \"multicast\"  to  a\nwhole  bunch  of  destination  hosts  at  once  (usually  on your local subnet).  If you find\nyourself overly concerned about reliability and  start  building  checks  into  your  message\nsystem, then you probably should use 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\ncumbersome. Use 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,\ninstead of  checking  one  host  at  a  time,  the  UDP  version  will  check  many  of  them\nasynchronously  by  simulating a multicast and then using select() to do a timed-out wait for\nI/O.  To do something similar with TCP, you'd have to use a different socket handle for  each\nhost.\n\n#!/usr/bin/perl\nuse v5.36;\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\nhost. The most prominent reason for this is congestion of the queues on the sending  host  if\nthe number of 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.\nHowever, you cannot use SysV IPC or Berkeley mmap() to have a variable shared amongst several\nprocesses.  That's because Perl would reallocate your string when you weren't wanting it  to.\nYou might look into 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\nthe  new Socket conversion functions do croak() on bad arguments.)  It is therefore essential\nto check return values from these functions.  Always begin your socket programs this way  for\noptimal  success,  and  don't  forget  to add the -T taint-checking flag to the \"#!\" line for\nservers:\n\n#!/usr/bin/perl -T\nuse v5.36;\nuse sigtrap;\nuse Socket;\n",
            "subsections": []
        },
        "BUGS": {
            "content": "These routines all create system-specific portability problems.  As noted elsewhere, Perl  is\nat  the  mercy  of your C libraries for much of its system behavior.  It's probably safest to\nassume broken SysV semantics for signals  and  to  stick  with  simple  TCP  and  UDP  socket\noperations; e.g., don't try to pass open file descriptors over a local UDP datagram socket if\nyou want your code to stand a chance of being portable.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Tom  Christiansen,  with occasional vestiges of Larry Wall's original version and suggestions\nfrom the 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\nEdition,  Volume  1  by  W.  Richard  Stevens  (published  by  Prentice-Hall).  Most books on\nnetworking address the subject from the perspective of a C programmer; translation to Perl is\nleft as an exercise for the reader.\n\nThe IO::Socket(3) manpage describes the object library, and the Socket(3)  manpage  describes\nthe  low-level  interface  to sockets.  Besides the obvious functions in perlfunc, you should\nalso   check   out   the   modules   file   at   your   nearest   CPAN    site,    especially\n<http://www.cpan.org/modules/00modlist.long.html#ID5Networking>.   See  perlmodlib  or best\nyet, the Perl FAQ for a description of what CPAN is and where to get it if the previous  link\ndoesn't work 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\nperl v5.38.2                                 2026-08-18                                   PERLIPC(1)",
            "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"
        }
    ]
}