⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 perlfork.pod

📁 MSYS在windows下模拟了一个类unix的终端
💻 POD
字号:
=head1 NAMEperlfork - Perl's fork() emulation (EXPERIMENTAL, subject to change)=head1 SYNOPSIS    WARNING:  As of the 5.6.1 release, the fork() emulation continues    to be an experimental feature.  Use in production applications is    not recommended.  See the "BUGS" and "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.=head1 DESCRIPTIONThe 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 C<0> to signify thatit is the child pseudo-process.=head2 Behavior of other Perl features in forked pseudo-processesMost Perl features behave in a natural way within pseudo-processes.=over 8=item $$ or $PROCESS_IDThis 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.=item %ENVEach 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.=item chdir() and all other builtins that accept filenamesEach 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.=item 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.=item kill()kill() can be used to terminate a pseudo-process by passing it the ID returnedby fork().  This should not be used except under dire circumstances, becausethe operating system may not guarantee integrity of the process resourceswhen a running thread is terminated.  Note that using kill() on apseudo-process() may typically cause memory leaks, because the thread thatimplements the pseudo-process does not get a chance to clean up its resources.=item 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().=item 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.=item Open handles to files, directories and network socketsAll open handles are dup()-ed in pseudo-processes, so that closingany handles in one process does not affect the others.  See below forsome limitations.=back=head2 Resource limitsIn 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.=head2 Killing the parent processIf 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.=head2 Lifetime of the parent process and pseudo-processesDuring 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.A way to mark a pseudo-processes as running detached from their parent (sothat the parent would not have to wait() for them if it doesn't want to)will be provided in future.=head2 CAVEATS AND LIMITATIONS=over 8=item BEGIN blocksThe 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:    BEGIN {        fork and exit;		# fork child and exit the parent	print "inner\n";    }    print "outer\n";This will print:    innerrather than the expected:    inner    outerThis limitation arises from fundamental technical difficulties incloning and restarting the stacks used by the Perl parser in themiddle of a parse.=item Open filehandlesAny 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.=item Forking pipe open() not yet implementedThe C<open(FOO, "|-")> and C<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:    # 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;    }    if (pipe_to_fork('FOO')) {	# parent	print FOO "pipe_to_fork\n";	close FOO;    }    else {	# child	while (<STDIN>) { print; }	close STDIN;	exit(0);    }And this one reads from the child:    # 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;    }    if (pipe_from_fork('BAR')) {	# parent	while (<BAR>) { print; }	close BAR;    }    else {	# child	print "pipe_from_fork\n";	close STDOUT;	exit(0);    }Forking pipe open() constructs will be supported in future.=item 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.=item Interpreter embedded in larger applicationThe 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.=item Thread-safety of extensionsSince 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.=back=head1 BUGS=over 8=item *Perl's regular expression engine currently does not play very nicelywith the fork() emulation.  There are known race conditions arisingfrom the regular expression engine modifying state carried in the opcodetree at run time (the fork() emulation relies on the opcode tree beingimmutable).  This typically happens when the regex contains paren groupsor variables interpolated within it that force a run time recompilationof the regex.  Due to this major bug, the fork() emulation is notrecommended for use in production applications at this time.=item *Having pseudo-process IDs be negative integers breaks down for the integerC<-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 C<1> for user threads.  A betterrepresentation for pseudo-process IDs will be implemented in future.=item *This document may be incomplete in some respects.=back=head1 AUTHORSupport for concurrent interpreters and the fork() emulation was implementedby ActiveState, with funding from Microsoft Corporation.This document is authored and maintained by Gurusamy SarathyE<lt>gsar@activestate.comE<gt>.=head1 SEE ALSOL<perlfunc/"fork">, L<perlipc>=cut

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -