Plan 9 from Bell Labs’s /usr/web/sources/contrib/gabidiaz/root/sys/man/1perl/perlfork

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  | will give a
.\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
.\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
.    de IX
.    tm Index:\\$1\t\\n%\t"\\$2"
..
.    nr % 0
.    rr F
.\}
.\"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLFORK 1"
.TH PERLFORK 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlfork \- Perl's fork() emulation
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 4
\&    NOTE:  As of the 5.8.0 release, fork() emulation has considerably
\&    matured.  However, there are still a few known bugs and differences
\&    from real fork() that might affect you.  See the "BUGS" and
\&    "CAVEATS AND LIMITATIONS" sections below.
.Ve
.PP
Perl provides a \fIfork()\fR keyword that corresponds to the Unix system call
of the same name.  On most Unix-like platforms where the \fIfork()\fR system
call is available, Perl's \fIfork()\fR simply calls it.
.PP
On some platforms such as Windows where the \fIfork()\fR system call is not
available, Perl can be built to emulate \fIfork()\fR at the interpreter level.
While the emulation is designed to be as compatible as possible with the
real \fIfork()\fR at the level of the Perl program, there are certain
important differences that stem from the fact that all the pseudo child
\&\*(L"processes\*(R" created this way live in the same real process as far as the
operating system is concerned.
.PP
This document provides a general overview of the capabilities and
limitations of the \fIfork()\fR emulation.  Note that the issues discussed here
are not applicable to platforms where a real \fIfork()\fR is available and Perl
has been configured to use it.
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
The \fIfork()\fR emulation is implemented at the level of the Perl interpreter.
What this means in general is that running \fIfork()\fR will actually clone the
running interpreter and all its state, and run the cloned interpreter in
a separate thread, beginning execution in the new thread just after the
point where the \fIfork()\fR was called in the parent.  We will refer to the
thread that implements this child \*(L"process\*(R" as the pseudo\-process.
.PP
To the Perl program that called \fIfork()\fR, all this is designed to be
transparent.  The parent returns from the \fIfork()\fR with a pseudo-process
\&\s-1ID\s0 that can be subsequently used in any process manipulation functions;
the child returns from the \fIfork()\fR with a value of \f(CW0\fR to signify that
it is the child pseudo\-process.
.Sh "Behavior of other Perl features in forked pseudo-processes"
.IX Subsection "Behavior of other Perl features in forked pseudo-processes"
Most Perl features behave in a natural way within pseudo\-processes.
.ie n .IP "$$ or $PROCESS_ID" 8
.el .IP "$$ or \f(CW$PROCESS_ID\fR" 8
.IX Item "$$ or $PROCESS_ID"
This special variable is correctly set to the pseudo-process \s-1ID\s0.
It can be used to identify pseudo-processes within a particular
session.  Note that this value is subject to recycling if any
pseudo-processes are launched after others have been \fIwait()\fR\-ed on.
.IP "%ENV" 8
.IX Item "%ENV"
Each pseudo-process maintains its own virtual environment.  Modifications
to \f(CW%ENV\fR affect the virtual environment, and are only visible within that
pseudo\-process, and in any processes (or pseudo\-processes) launched from
it.
.IP "\fIchdir()\fR and all other builtins that accept filenames" 8
.IX Item "chdir() and all other builtins that accept filenames"
Each pseudo-process maintains its own virtual idea of the current directory.
Modifications to the current directory using \fIchdir()\fR are only visible within
that pseudo\-process, and in any processes (or pseudo\-processes) launched from
it.  All file and directory accesses from the pseudo-process will correctly
map the virtual working directory to the real working directory appropriately.
.IP "\fIwait()\fR and \fIwaitpid()\fR" 8
.IX Item "wait() and waitpid()"
\&\fIwait()\fR and \fIwaitpid()\fR can be passed a pseudo-process \s-1ID\s0 returned by \fIfork()\fR.
These calls will properly wait for the termination of the pseudo-process
and return its status.
.IP "\fIkill()\fR" 8
.IX Item "kill()"
\&\fIkill()\fR can be used to terminate a pseudo-process by passing it the \s-1ID\s0 returned
by \fIfork()\fR.  This should not be used except under dire circumstances, because
the operating system may not guarantee integrity of the process resources
when a running thread is terminated.  Note that using \fIkill()\fR on a
pseudo\-\fIprocess()\fR may typically cause memory leaks, because the thread that
implements the pseudo-process does not get a chance to clean up its resources.
.IP "\fIexec()\fR" 8
.IX Item "exec()"
Calling \fIexec()\fR within a pseudo-process actually spawns the requested
executable in a separate process and waits for it to complete before
exiting with the same exit status as that process.  This means that the
process \s-1ID\s0 reported within the running executable will be different from
what the earlier Perl \fIfork()\fR might have returned.  Similarly, any process
manipulation functions applied to the \s-1ID\s0 returned by \fIfork()\fR will affect the
waiting pseudo-process that called \fIexec()\fR, not the real process it is
waiting for after the \fIexec()\fR.
.IP "\fIexit()\fR" 8
.IX Item "exit()"
\&\fIexit()\fR always exits just the executing pseudo\-process, after automatically
\&\fIwait()\fR\-ing for any outstanding child pseudo\-processes.  Note that this means
that the process as a whole will not exit unless all running pseudo-processes
have exited.
.IP "Open handles to files, directories and network sockets" 8
.IX Item "Open handles to files, directories and network sockets"
All open handles are \fIdup()\fR\-ed in pseudo\-processes, so that closing
any handles in one process does not affect the others.  See below for
some limitations.
.Sh "Resource limits"
.IX Subsection "Resource limits"
In the eyes of the operating system, pseudo-processes created via the \fIfork()\fR
emulation are simply threads in the same process.  This means that any
process-level limits imposed by the operating system apply to all
pseudo-processes taken together.  This includes any limits imposed by the
operating system on the number of open file, directory and socket handles,
limits on disk space usage, limits on memory size, limits on \s-1CPU\s0 utilization
etc.
.Sh "Killing the parent process"
.IX Subsection "Killing the parent process"
If the parent process is killed (either using Perl's \fIkill()\fR builtin, or
using some external means) all the pseudo-processes are killed as well,
and the whole process exits.
.Sh "Lifetime of the parent process and pseudo-processes"
.IX Subsection "Lifetime of the parent process and pseudo-processes"
During the normal course of events, the parent process and every
pseudo-process started by it will wait for their respective pseudo-children
to complete before they exit.  This means that the parent and every
pseudo-child created by it that is also a pseudo-parent will only exit
after their pseudo-children have exited.
.PP
A way to mark a pseudo-processes as running detached from their parent (so
that the parent would not have to \fIwait()\fR for them if it doesn't want to)
will be provided in future.
.Sh "\s-1CAVEATS\s0 \s-1AND\s0 \s-1LIMITATIONS\s0"
.IX Subsection "CAVEATS AND LIMITATIONS"
.IP "\s-1BEGIN\s0 blocks" 8
.IX Item "BEGIN blocks"
The \fIfork()\fR emulation will not work entirely correctly when called from
within a \s-1BEGIN\s0 block.  The forked copy will run the contents of the
\&\s-1BEGIN\s0 block, but will not continue parsing the source stream after the
\&\s-1BEGIN\s0 block.  For example, consider the following code:
.Sp
.Vb 5
\&    BEGIN {
\&        fork and exit;          # fork child and exit the parent
\&        print "inner\en";
\&    }
\&    print "outer\en";
.Ve
.Sp
This will print:
.Sp
.Vb 1
\&    inner
.Ve
.Sp
rather than the expected:
.Sp
.Vb 2
\&    inner
\&    outer
.Ve
.Sp
This limitation arises from fundamental technical difficulties in
cloning and restarting the stacks used by the Perl parser in the
middle of a parse.
.IP "Open filehandles" 8
.IX Item "Open filehandles"
Any filehandles open at the time of the \fIfork()\fR will be \fIdup()\fR\-ed.  Thus,
the files can be closed independently in the parent and child, but beware
that the \fIdup()\fR\-ed handles will still share the same seek pointer.  Changing
the seek position in the parent will change it in the child and vice\-versa.
One can avoid this by opening files that need distinct seek pointers
separately in the child.
.IP "Forking pipe \fIopen()\fR not yet implemented" 8
.IX Item "Forking pipe open() not yet implemented"
The \f(CW\*(C`open(FOO, "|\-")\*(C'\fR and \f(CW\*(C`open(BAR, "\-|")\*(C'\fR constructs are not yet
implemented.  This limitation can be easily worked around in new code
by creating a pipe explicitly.  The following example shows how to
write to a forked child:
.Sp
.Vb 15
\&    # simulate open(FOO, "|-")
\&    sub pipe_to_fork ($) {
\&        my $parent = shift;
\&        pipe my $child, $parent or die;
\&        my $pid = fork();
\&        die "fork() failed: $!" unless defined $pid;
\&        if ($pid) {
\&            close $child;
\&        }
\&        else {
\&            close $parent;
\&            open(STDIN, "<&=" . fileno($child)) or die;
\&        }
\&        $pid;
\&    }
.Ve
.Sp
.Vb 11
\&    if (pipe_to_fork('FOO')) {
\&        # parent
\&        print FOO "pipe_to_fork\en";
\&        close FOO;
\&    }
\&    else {
\&        # child
\&        while (<STDIN>) { print; }
\&        close STDIN;
\&        exit(0);
\&    }
.Ve
.Sp
And this one reads from the child:
.Sp
.Vb 15
\&    # simulate open(FOO, "-|")
\&    sub pipe_from_fork ($) {
\&        my $parent = shift;
\&        pipe $parent, my $child or die;
\&        my $pid = fork();
\&        die "fork() failed: $!" unless defined $pid;
\&        if ($pid) {
\&            close $child;
\&        }
\&        else {
\&            close $parent;
\&            open(STDOUT, ">&=" . fileno($child)) or die;
\&        }
\&        $pid;
\&    }
.Ve
.Sp
.Vb 11
\&    if (pipe_from_fork('BAR')) {
\&        # parent
\&        while (<BAR>) { print; }
\&        close BAR;
\&    }
\&    else {
\&        # child
\&        print "pipe_from_fork\en";
\&        close STDOUT;
\&        exit(0);
\&    }
.Ve
.Sp
Forking pipe \fIopen()\fR constructs will be supported in future.
.IP "Global state maintained by XSUBs" 8
.IX Item "Global state maintained by XSUBs"
External subroutines (XSUBs) that maintain their own global state may
not work correctly.  Such XSUBs will either need to maintain locks to
protect simultaneous access to global data from different pseudo\-processes,
or maintain all their state on the Perl symbol table, which is copied
naturally when \fIfork()\fR is called.  A callback mechanism that provides
extensions an opportunity to clone their state will be provided in the
near future.
.IP "Interpreter embedded in larger application" 8
.IX Item "Interpreter embedded in larger application"
The \fIfork()\fR emulation may not behave as expected when it is executed in an
application which embeds a Perl interpreter and calls Perl APIs that can
evaluate bits of Perl code.  This stems from the fact that the emulation
only has knowledge about the Perl interpreter's own data structures and
knows nothing about the containing application's state.  For example, any
state carried on the application's own call stack is out of reach.
.IP "Thread-safety of extensions" 8
.IX Item "Thread-safety of extensions"
Since the \fIfork()\fR emulation runs code in multiple threads, extensions
calling into non-thread-safe libraries may not work reliably when
calling \fIfork()\fR.  As Perl's threading support gradually becomes more
widely adopted even on platforms with a native \fIfork()\fR, such extensions
are expected to be fixed for thread\-safety.
.SH "BUGS"
.IX Header "BUGS"
.IP "\(bu" 8
Having pseudo-process IDs be negative integers breaks down for the integer
\&\f(CW\*(C`\-1\*(C'\fR because the \fIwait()\fR and \fIwaitpid()\fR functions treat this number as
being special.  The tacit assumption in the current implementation is that
the system never allocates a thread \s-1ID\s0 of \f(CW1\fR for user threads.  A better
representation for pseudo-process IDs will be implemented in future.
.IP "\(bu" 8
In certain cases, the OS-level handles created by the \fIpipe()\fR, \fIsocket()\fR,
and \fIaccept()\fR operators are apparently not duplicated accurately in
pseudo\-processes.  This only happens in some situations, but where it
does happen, it may result in deadlocks between the read and write ends
of pipe handles, or inability to send or receive data across socket
handles.
.IP "\(bu" 8
This document may be incomplete in some respects.
.SH "AUTHOR"
.IX Header "AUTHOR"
Support for concurrent interpreters and the \fIfork()\fR emulation was implemented
by ActiveState, with funding from Microsoft Corporation.
.PP
This document is authored and maintained by Gurusamy Sarathy
<gsar@activestate.com>.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
\&\*(L"fork\*(R" in perlfunc, perlipc

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.