This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perldiag: rewording
[perl5.git] / pod / perlfork.pod
CommitLineData
7766f137
GS
1=head1 NAME
2
c3c83ace 3perlfork - Perl's fork() emulation
7766f137
GS
4
5=head1 SYNOPSIS
6
c3c83ace
GS
7 NOTE: As of the 5.8.0 release, fork() emulation has considerably
8 matured. However, there are still a few known bugs and differences
9 from real fork() that might affect you. See the "BUGS" and
10 "CAVEATS AND LIMITATIONS" sections below.
c7fa416b 11
7766f137
GS
12Perl provides a fork() keyword that corresponds to the Unix system call
13of the same name. On most Unix-like platforms where the fork() system
14call is available, Perl's fork() simply calls it.
15
16On some platforms such as Windows where the fork() system call is not
17available, Perl can be built to emulate fork() at the interpreter level.
18While the emulation is designed to be as compatible as possible with the
106325ad 19real fork() at the level of the Perl program, there are certain
7766f137
GS
20important differences that stem from the fact that all the pseudo child
21"processes" created this way live in the same real process as far as the
22operating system is concerned.
23
24This document provides a general overview of the capabilities and
25limitations of the fork() emulation. Note that the issues discussed here
26are not applicable to platforms where a real fork() is available and Perl
27has been configured to use it.
28
29=head1 DESCRIPTION
30
31The fork() emulation is implemented at the level of the Perl interpreter.
32What this means in general is that running fork() will actually clone the
33running interpreter and all its state, and run the cloned interpreter in
34a separate thread, beginning execution in the new thread just after the
35point where the fork() was called in the parent. We will refer to the
36thread that implements this child "process" as the pseudo-process.
37
38To the Perl program that called fork(), all this is designed to be
39transparent. The parent returns from the fork() with a pseudo-process
40ID that can be subsequently used in any process manipulation functions;
41the child returns from the fork() with a value of C<0> to signify that
42it is the child pseudo-process.
43
44=head2 Behavior of other Perl features in forked pseudo-processes
45
46Most Perl features behave in a natural way within pseudo-processes.
47
48=over 8
49
50=item $$ or $PROCESS_ID
51
52This special variable is correctly set to the pseudo-process ID.
53It can be used to identify pseudo-processes within a particular
54session. Note that this value is subject to recycling if any
55pseudo-processes are launched after others have been wait()-ed on.
56
57=item %ENV
58
4375e838 59Each pseudo-process maintains its own virtual environment. Modifications
7766f137
GS
60to %ENV affect the virtual environment, and are only visible within that
61pseudo-process, and in any processes (or pseudo-processes) launched from
62it.
63
64=item chdir() and all other builtins that accept filenames
65
66Each pseudo-process maintains its own virtual idea of the current directory.
67Modifications to the current directory using chdir() are only visible within
68that pseudo-process, and in any processes (or pseudo-processes) launched from
69it. All file and directory accesses from the pseudo-process will correctly
70map the virtual working directory to the real working directory appropriately.
71
72=item wait() and waitpid()
73
74wait() and waitpid() can be passed a pseudo-process ID returned by fork().
75These calls will properly wait for the termination of the pseudo-process
76and return its status.
77
78=item kill()
79
80kill() can be used to terminate a pseudo-process by passing it the ID returned
81by fork(). This should not be used except under dire circumstances, because
82the operating system may not guarantee integrity of the process resources
83when a running thread is terminated. Note that using kill() on a
84pseudo-process() may typically cause memory leaks, because the thread that
85implements the pseudo-process does not get a chance to clean up its resources.
86
87=item exec()
88
89Calling exec() within a pseudo-process actually spawns the requested
90executable in a separate process and waits for it to complete before
91exiting with the same exit status as that process. This means that the
92process ID reported within the running executable will be different from
93what the earlier Perl fork() might have returned. Similarly, any process
94manipulation functions applied to the ID returned by fork() will affect the
95waiting pseudo-process that called exec(), not the real process it is
96waiting for after the exec().
97
1cb5e8fb
JD
98When exec() is called inside a pseudo-process then DESTROY methods and
99END blocks will still be called after the external process returns.
100
7766f137
GS
101=item exit()
102
103exit() always exits just the executing pseudo-process, after automatically
104wait()-ing for any outstanding child pseudo-processes. Note that this means
105that the process as a whole will not exit unless all running pseudo-processes
1d335e36 106have exited. See below for some limitations with open filehandles.
7766f137
GS
107
108=item Open handles to files, directories and network sockets
109
110All open handles are dup()-ed in pseudo-processes, so that closing
111any handles in one process does not affect the others. See below for
112some limitations.
113
114=back
115
116=head2 Resource limits
117
118In the eyes of the operating system, pseudo-processes created via the fork()
119emulation are simply threads in the same process. This means that any
120process-level limits imposed by the operating system apply to all
121pseudo-processes taken together. This includes any limits imposed by the
122operating system on the number of open file, directory and socket handles,
123limits on disk space usage, limits on memory size, limits on CPU utilization
124etc.
125
126=head2 Killing the parent process
127
128If the parent process is killed (either using Perl's kill() builtin, or
129using some external means) all the pseudo-processes are killed as well,
130and the whole process exits.
131
132=head2 Lifetime of the parent process and pseudo-processes
133
134During the normal course of events, the parent process and every
135pseudo-process started by it will wait for their respective pseudo-children
136to complete before they exit. This means that the parent and every
137pseudo-child created by it that is also a pseudo-parent will only exit
138after their pseudo-children have exited.
139
140A way to mark a pseudo-processes as running detached from their parent (so
141that the parent would not have to wait() for them if it doesn't want to)
142will be provided in future.
143
144=head2 CAVEATS AND LIMITATIONS
145
146=over 8
147
148=item BEGIN blocks
149
150The fork() emulation will not work entirely correctly when called from
151within a BEGIN block. The forked copy will run the contents of the
152BEGIN block, but will not continue parsing the source stream after the
153BEGIN block. For example, consider the following code:
154
155 BEGIN {
156 fork and exit; # fork child and exit the parent
157 print "inner\n";
158 }
159 print "outer\n";
160
161This will print:
162
163 inner
164
165rather than the expected:
166
167 inner
168 outer
169
170This limitation arises from fundamental technical difficulties in
171cloning and restarting the stacks used by the Perl parser in the
172middle of a parse.
173
174=item Open filehandles
175
176Any filehandles open at the time of the fork() will be dup()-ed. Thus,
177the files can be closed independently in the parent and child, but beware
178that the dup()-ed handles will still share the same seek pointer. Changing
179the seek position in the parent will change it in the child and vice-versa.
180One can avoid this by opening files that need distinct seek pointers
181separately in the child.
182
1d335e36
SP
183On some operating systems, notably Solaris and Unixware, calling C<exit()>
184from a child process will flush and close open filehandles in the parent,
185thereby corrupting the filehandles. On these systems, calling C<_exit()>
186is suggested instead. C<_exit()> is available in Perl through the
96d4712d 187C<POSIX> module. Please consult your system's manpages for more information
1d335e36
SP
188on this.
189
3ba4b5c1
JD
190=item Open directory handles
191
192Perl will completely read from all open directory handles until they
193reach the end of the stream. It will then seekdir() back to the
194original location and all future readdir() requests will be fulfilled
195from the cache buffer. That means that neither directory handle held
196by the parent process nor the one held by the child process will see
197any changes made to the directory after the fork() call.
198
199Note that rewinddir() has a similar limitation on Windows and will not
200force readdir() to read the directory again either. Only a newly
201opened directory handle will reflect changes to the directory.
202
030866aa
GS
203=item Forking pipe open() not yet implemented
204
205The C<open(FOO, "|-")> and C<open(BAR, "-|")> constructs are not yet
206implemented. This limitation can be easily worked around in new code
207by creating a pipe explicitly. The following example shows how to
208write to a forked child:
209
210 # simulate open(FOO, "|-")
211 sub pipe_to_fork ($) {
212 my $parent = shift;
213 pipe my $child, $parent or die;
214 my $pid = fork();
215 die "fork() failed: $!" unless defined $pid;
216 if ($pid) {
217 close $child;
218 }
219 else {
220 close $parent;
221 open(STDIN, "<&=" . fileno($child)) or die;
222 }
223 $pid;
224 }
225
226 if (pipe_to_fork('FOO')) {
227 # parent
228 print FOO "pipe_to_fork\n";
229 close FOO;
230 }
231 else {
232 # child
233 while (<STDIN>) { print; }
030866aa
GS
234 exit(0);
235 }
236
237And this one reads from the child:
238
239 # simulate open(FOO, "-|")
240 sub pipe_from_fork ($) {
241 my $parent = shift;
242 pipe $parent, my $child or die;
243 my $pid = fork();
244 die "fork() failed: $!" unless defined $pid;
245 if ($pid) {
246 close $child;
247 }
248 else {
249 close $parent;
250 open(STDOUT, ">&=" . fileno($child)) or die;
251 }
252 $pid;
253 }
254
255 if (pipe_from_fork('BAR')) {
256 # parent
257 while (<BAR>) { print; }
258 close BAR;
259 }
260 else {
261 # child
262 print "pipe_from_fork\n";
030866aa
GS
263 exit(0);
264 }
265
266Forking pipe open() constructs will be supported in future.
267
7766f137
GS
268=item Global state maintained by XSUBs
269
270External subroutines (XSUBs) that maintain their own global state may
271not work correctly. Such XSUBs will either need to maintain locks to
272protect simultaneous access to global data from different pseudo-processes,
273or maintain all their state on the Perl symbol table, which is copied
274naturally when fork() is called. A callback mechanism that provides
275extensions an opportunity to clone their state will be provided in the
276near future.
277
278=item Interpreter embedded in larger application
279
280The fork() emulation may not behave as expected when it is executed in an
281application which embeds a Perl interpreter and calls Perl APIs that can
282evaluate bits of Perl code. This stems from the fact that the emulation
283only has knowledge about the Perl interpreter's own data structures and
284knows nothing about the containing application's state. For example, any
285state carried on the application's own call stack is out of reach.
286
7e396c59
GS
287=item Thread-safety of extensions
288
289Since the fork() emulation runs code in multiple threads, extensions
290calling into non-thread-safe libraries may not work reliably when
291calling fork(). As Perl's threading support gradually becomes more
292widely adopted even on platforms with a native fork(), such extensions
293are expected to be fixed for thread-safety.
294
7766f137
GS
295=back
296
297=head1 BUGS
298
299=over 8
300
301=item *
302
303Having pseudo-process IDs be negative integers breaks down for the integer
304C<-1> because the wait() and waitpid() functions treat this number as
305being special. The tacit assumption in the current implementation is that
306the system never allocates a thread ID of C<1> for user threads. A better
307representation for pseudo-process IDs will be implemented in future.
308
309=item *
310
c3c83ace
GS
311In certain cases, the OS-level handles created by the pipe(), socket(),
312and accept() operators are apparently not duplicated accurately in
313pseudo-processes. This only happens in some situations, but where it
314does happen, it may result in deadlocks between the read and write ends
315of pipe handles, or inability to send or receive data across socket
316handles.
317
318=item *
319
7766f137
GS
320This document may be incomplete in some respects.
321
a45bd81d
GS
322=back
323
7766f137
GS
324=head1 AUTHOR
325
7e396c59
GS
326Support for concurrent interpreters and the fork() emulation was implemented
327by ActiveState, with funding from Microsoft Corporation.
7766f137
GS
328
329This document is authored and maintained by Gurusamy Sarathy
330E<lt>gsar@activestate.comE<gt>.
331
332=head1 SEE ALSO
333
334L<perlfunc/"fork">, L<perlipc>
335
336=cut