Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) Perl interprocess communicatio ...Semantics of numbers and numer ... (Berikutnya)
Language Reference

Perl's fork() emulation

Daftar Isi

NAME

perlfork - Perl's fork() emulation

SYNOPSIS

  1. NOTE: As of the 5.8.0 release, fork() emulation has considerably
  2. matured. However, there are still a few known bugs and differences
  3. from real fork() that might affect you. See the "BUGS" and
  4. "CAVEATS AND LIMITATIONS" sections below.

Perl provides a fork() keyword that corresponds to the Unix system callof the same name. On most Unix-like platforms where the fork() systemcall is available, Perl's fork() simply calls it.

On some platforms such as Windows where the fork() system call is notavailable, Perl can be built to emulate fork() at the interpreter level.While the emulation is designed to be as compatible as possible with thereal fork() at the level of the Perl program, there are certainimportant differences that stem from the fact that all the pseudo child"processes" created this way live in the same real process as far as theoperating system is concerned.

This document provides a general overview of the capabilities andlimitations of the fork() emulation. Note that the issues discussed hereare not applicable to platforms where a real fork() is available and Perlhas been configured to use it.

DESCRIPTION

The fork() emulation is implemented at the level of the Perl interpreter.What this means in general is that running fork() will actually clone therunning interpreter and all its state, and run the cloned interpreter ina separate thread, beginning execution in the new thread just after thepoint where the fork() was called in the parent. We will refer to thethread that implements this child "process" as the pseudo-process.

To the Perl program that called fork(), all this is designed to betransparent. The parent returns from the fork() with a pseudo-processID that can be subsequently used in any process-manipulation functions;the child returns from the fork() with a value of 0 to signify thatit is the child pseudo-process.

Behavior of other Perl features in forked pseudo-processes

Most Perl features behave in a natural way within pseudo-processes.

  • $$ or $PROCESS_ID

    This special variable is correctly set to the pseudo-process ID.It can be used to identify pseudo-processes within a particularsession. Note that this value is subject to recycling if anypseudo-processes are launched after others have been wait()-ed on.

  • %ENV

    Each pseudo-process maintains its own virtual environment. Modificationsto %ENV affect the virtual environment, and are only visible within thatpseudo-process, and in any processes (or pseudo-processes) launched fromit.

  • 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 chdir() are only visible withinthat pseudo-process, and in any processes (or pseudo-processes) launched fromit. All file and directory accesses from the pseudo-process will correctlymap the virtual working directory to the real working directory appropriately.

  • wait() and waitpid()

    wait() and waitpid() can be passed a pseudo-process ID returned by fork().These calls will properly wait for the termination of the pseudo-processand return its status.

  • kill()

    kill('KILL', ...) can be used to terminate a pseudo-process bypassing it the ID returned by fork(). The outcome of kill on a pseudo-processis unpredictable and it should not be used exceptunder dire circumstances, because the operating system may notguarantee integrity of the process resources when a running thread isterminated. The process which implements the pseudo-processes can be blockedand the Perl interpreter hangs. Note that using kill('KILL', ...) on apseudo-process() may typically cause memory leaks, because the threadthat implements the pseudo-process does not get a chance to clean upits resources.

    kill('TERM', ...) can also be used on pseudo-processes, but thesignal will not be delivered while the pseudo-process is blocked by asystem call, e.g. waiting for a socket to connect, or trying to readfrom a socket with no data available. Starting in Perl 5.14 theparent process will not wait for children to exit once they have beensignalled with kill('TERM', ...) to avoid deadlock during processexit. You will have to explicitly call waitpid() to make sure thechild has time to clean-up itself, but you are then also responsiblethat the child is not blocking on I/O either.

  • exec()

    Calling exec() within a pseudo-process actually spawns the requestedexecutable in a separate process and waits for it to complete beforeexiting with the same exit status as that process. This means that theprocess ID reported within the running executable will be different fromwhat the earlier Perl fork() might have returned. Similarly, any processmanipulation functions applied to the ID returned by fork() will affect thewaiting pseudo-process that called exec(), not the real process it iswaiting for after the exec().

    When exec() is called inside a pseudo-process then DESTROY methods andEND blocks will still be called after the external process returns.

  • exit()

    exit() always exits just the executing pseudo-process, after automaticallywait()-ing for any outstanding child pseudo-processes. Note that this meansthat the process as a whole will not exit unless all running pseudo-processeshave exited. See below for some limitations with open filehandles.

  • Open handles to files, directories and network sockets

    All open handles are dup()-ed in pseudo-processes, so that closingany handles in one process does not affect the others. See below forsome limitations.

Resource limits

In the eyes of the operating system, pseudo-processes created via the fork()emulation are simply threads in the same process. This means that anyprocess-level limits imposed by the operating system apply to allpseudo-processes taken together. This includes any limits imposed by theoperating system on the number of open file, directory and socket handles,limits on disk space usage, limits on memory size, limits on CPU utilizationetc.

Killing the parent process

If the parent process is killed (either using Perl's kill() builtin, orusing some external means) all the pseudo-processes are killed as well,and the whole process exits.

Lifetime of the parent process and pseudo-processes

During the normal course of events, the parent process and everypseudo-process started by it will wait for their respective pseudo-childrento complete before they exit. This means that the parent and everypseudo-child created by it that is also a pseudo-parent will only exitafter their pseudo-children have exited.

Starting with Perl 5.14 a parent will not wait() automaticallyfor any child that has been signalled with sig('TERM', ...)to avoid a deadlock in case the child is blocking on I/O andnever receives the signal.

CAVEATS AND LIMITATIONS

  • BEGIN blocks

    The fork() emulation will not work entirely correctly when called fromwithin a BEGIN block. The forked copy will run the contents of theBEGIN block, but will not continue parsing the source stream after theBEGIN block. For example, consider the following code:

    1. BEGIN {
    2. fork and exit;# fork child and exit the parent
    3. print "inner\n";
    4. }
    5. print "outer\n";

    This will print:

    1. inner

    rather than the expected:

    1. inner
    2. outer

    This limitation arises from fundamental technical difficulties incloning and restarting the stacks used by the Perl parser in themiddle of a parse.

  • Open filehandles

    Any filehandles open at the time of the fork() will be dup()-ed. Thus,the files can be closed independently in the parent and child, but bewarethat the dup()-ed handles will still share the same seek pointer. Changingthe 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 pointersseparately in the child.

    On some operating systems, notably Solaris and Unixware, calling exit()from a child process will flush and close open filehandles in the parent,thereby corrupting the filehandles. On these systems, calling _exit()is suggested instead. _exit() is available in Perl through the POSIX module. Please consult your system's manpages for more informationon this.

  • Open directory handles

    Perl will completely read from all open directory handles until theyreach the end of the stream. It will then seekdir() back to theoriginal location and all future readdir() requests will be fulfilledfrom the cache buffer. That means that neither the directory handle heldby the parent process nor the one held by the child process will seeany changes made to the directory after the fork() call.

    Note that rewinddir() has a similar limitation on Windows and will notforce readdir() to read the directory again either. Only a newlyopened directory handle will reflect changes to the directory.

  • Forking pipe open() not yet implemented

    The open(FOO, "|-") and open(BAR, "-|") constructs are not yetimplemented. This limitation can be easily worked around in new codeby creating a pipe explicitly. The following example shows how towrite to a forked child:

    1. # simulate open(FOO, "|-")
    2. sub pipe_to_fork ($) {
    3. my $parent = shift;
    4. pipe my $child, $parent or die;
    5. my $pid = fork();
    6. die "fork() failed: $!" unless defined $pid;
    7. if ($pid) {
    8. close $child;
    9. }
    10. else {
    11. close $parent;
    12. open(STDIN, "<&=" . fileno($child)) or die;
    13. }
    14. $pid;
    15. }
    16. if (pipe_to_fork('FOO')) {
    17. # parent
    18. print FOO "pipe_to_fork\n";
    19. close FOO;
    20. }
    21. else {
    22. # child
    23. while (<STDIN>) { print; }
    24. exit(0);
    25. }

    And this one reads from the child:

    1. # simulate open(FOO, "-|")
    2. sub pipe_from_fork ($) {
    3. my $parent = shift;
    4. pipe $parent, my $child or die;
    5. my $pid = fork();
    6. die "fork() failed: $!" unless defined $pid;
    7. if ($pid) {
    8. close $child;
    9. }
    10. else {
    11. close $parent;
    12. open(STDOUT, ">&=" . fileno($child)) or die;
    13. }
    14. $pid;
    15. }
    16. if (pipe_from_fork('BAR')) {
    17. # parent
    18. while (<BAR>) { print; }
    19. close BAR;
    20. }
    21. else {
    22. # child
    23. print "pipe_from_fork\n";
    24. exit(0);
    25. }

    Forking pipe open() constructs will be supported in future.

  • Global state maintained by XSUBs

    External subroutines (XSUBs) that maintain their own global state maynot work correctly. Such XSUBs will either need to maintain locks toprotect simultaneous access to global data from different pseudo-processes,or maintain all their state on the Perl symbol table, which is copiednaturally when fork() is called. A callback mechanism that providesextensions an opportunity to clone their state will be provided in thenear future.

  • Interpreter embedded in larger application

    The fork() emulation may not behave as expected when it is executed in anapplication which embeds a Perl interpreter and calls Perl APIs that canevaluate bits of Perl code. This stems from the fact that the emulationonly has knowledge about the Perl interpreter's own data structures andknows nothing about the containing application's state. For example, anystate carried on the application's own call stack is out of reach.

  • Thread-safety of extensions

    Since the fork() emulation runs code in multiple threads, extensionscalling into non-thread-safe libraries may not work reliably whencalling fork(). As Perl's threading support gradually becomes morewidely adopted even on platforms with a native fork(), such extensionsare expected to be fixed for thread-safety.

PORTABILITY CAVEATS

In portable Perl code, kill(9, $child) must not be used on forked processes.Killing a forked process is unsafe and has unpredictable results.See kill(), above.

BUGS

  • Having pseudo-process IDs be negative integers breaks down for the integer-1 because the wait() and waitpid() functions treat this number asbeing special. The tacit assumption in the current implementation is thatthe system never allocates a thread ID of 1 for user threads. A betterrepresentation for pseudo-process IDs will be implemented in future.

  • In certain cases, the OS-level handles created by the pipe(), socket(),and accept() operators are apparently not duplicated accurately inpseudo-processes. This only happens in some situations, but where itdoes happen, it may result in deadlocks between the read and write endsof pipe handles, or inability to send or receive data across sockethandles.

  • This document may be incomplete in some respects.

AUTHOR

Support for concurrent interpreters and the fork() emulation was implementedby ActiveState, with funding from Microsoft Corporation.

This document is authored and maintained by Gurusamy Sarathy<[email protected]>.

SEE ALSO

fork, perlipc

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Perl interprocess communicatio ...Semantics of numbers and numer ... (Berikutnya)