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