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('KILL', ...)" can be used to terminate a pseudo-process
76 by passing it the ID returned by fork(). The outcome of kill on
77 a pseudo-process is unpredictable and it should not be used
78 except under dire circumstances, because the operating system
79 may not guarantee integrity of the process resources when a
80 running thread is terminated. The process which implements the
81 pseudo-processes can be blocked and the Perl interpreter hangs.
82 Note that using "kill('KILL', ...)" on a pseudo-process() may
83 typically cause memory leaks, because the thread that
84 implements the pseudo-process does not get a chance to clean up
85 its resources.
86
87 "kill('TERM', ...)" can also be used on pseudo-processes, but
88 the signal will not be delivered while the pseudo-process is
89 blocked by a system call, e.g. waiting for a socket to connect,
90 or trying to read from a socket with no data available.
91 Starting in Perl 5.14 the parent process will not wait for
92 children to exit once they have been signalled with
93 "kill('TERM', ...)" to avoid deadlock during process exit. You
94 will have to explicitly call waitpid() to make sure the child
95 has time to clean-up itself, but you are then also responsible
96 that the child is not blocking on I/O either.
97
98 exec() Calling exec() within a pseudo-process actually spawns the
99 requested executable in a separate process and waits for it to
100 complete before exiting with the same exit status as that
101 process. This means that the process ID reported within the
102 running executable will be different from what the earlier Perl
103 fork() might have returned. Similarly, any process
104 manipulation functions applied to the ID returned by fork()
105 will affect the waiting pseudo-process that called exec(), not
106 the real process it is waiting for after the exec().
107
108 When exec() is called inside a pseudo-process then DESTROY
109 methods and END blocks will still be called after the external
110 process returns.
111
112 exit() exit() always exits just the executing pseudo-process, after
113 automatically wait()-ing for any outstanding child pseudo-
114 processes. Note that this means that the process as a whole
115 will not exit unless all running pseudo-processes have exited.
116 See below for some limitations with open filehandles.
117
118 Open handles to files, directories and network sockets
119 All open handles are dup()-ed in pseudo-processes, so that
120 closing any handles in one process does not affect the others.
121 See below for some limitations.
122
123 Resource limits
124 In the eyes of the operating system, pseudo-processes created via the
125 fork() emulation are simply threads in the same process. This means
126 that any process-level limits imposed by the operating system apply to
127 all pseudo-processes taken together. This includes any limits imposed
128 by the operating system on the number of open file, directory and
129 socket handles, limits on disk space usage, limits on memory size,
130 limits on CPU utilization etc.
131
132 Killing the parent process
133 If the parent process is killed (either using Perl's kill() builtin, or
134 using some external means) all the pseudo-processes are killed as well,
135 and the whole process exits.
136
137 Lifetime of the parent process and pseudo-processes
138 During the normal course of events, the parent process and every
139 pseudo-process started by it will wait for their respective pseudo-
140 children to complete before they exit. This means that the parent and
141 every pseudo-child created by it that is also a pseudo-parent will only
142 exit after their pseudo-children have exited.
143
144 Starting with Perl 5.14 a parent will not wait() automatically for any
145 child that has been signalled with "kill('TERM', ...)" to avoid a
146 deadlock in case the child is blocking on I/O and never receives the
147 signal.
148
150 BEGIN blocks
151 The fork() emulation will not work entirely correctly when
152 called from within a BEGIN block. The forked copy will run the
153 contents of the BEGIN block, but will not continue parsing the
154 source stream after the BEGIN block. For example, consider the
155 following code:
156
157 BEGIN {
158 fork and exit; # fork child and exit the parent
159 print "inner\n";
160 }
161 print "outer\n";
162
163 This will print:
164
165 inner
166
167 rather than the expected:
168
169 inner
170 outer
171
172 This limitation arises from fundamental technical difficulties
173 in cloning and restarting the stacks used by the Perl parser in
174 the middle of a parse.
175
176 Open filehandles
177 Any filehandles open at the time of the fork() will be
178 dup()-ed. Thus, the files can be closed independently in the
179 parent and child, but beware that the dup()-ed handles will
180 still share the same seek pointer. Changing the seek position
181 in the parent will change it in the child and vice-versa. One
182 can avoid this by opening files that need distinct seek
183 pointers separately in the child.
184
185 On some operating systems, notably Solaris and Unixware,
186 calling "exit()" from a child process will flush and close open
187 filehandles in the parent, thereby corrupting the filehandles.
188 On these systems, calling "_exit()" is suggested instead.
189 "_exit()" is available in Perl through the "POSIX" module.
190 Please consult your system's manpages for more information on
191 this.
192
193 Open directory handles
194 Perl will completely read from all open directory handles until
195 they reach the end of the stream. It will then seekdir() back
196 to the original location and all future readdir() requests will
197 be fulfilled from the cache buffer. That means that neither
198 the directory handle held by the parent process nor the one
199 held by the child process will see any changes made to the
200 directory after the fork() call.
201
202 Note that rewinddir() has a similar limitation on Windows and
203 will not force readdir() to read the directory again either.
204 Only a newly opened directory handle will reflect changes to
205 the directory.
206
207 Forking pipe open() not yet implemented
208 The "open(FOO, "|-")" and "open(BAR, "-|")" constructs are not
209 yet implemented. This limitation can be easily worked around
210 in new code by creating a pipe explicitly. The following
211 example shows how to write to a forked child:
212
213 # simulate open(FOO, "|-")
214 sub pipe_to_fork ($) {
215 my $parent = shift;
216 pipe my $child, $parent 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(STDIN, "<&=" . fileno($child)) or die;
225 }
226 $pid;
227 }
228
229 if (pipe_to_fork('FOO')) {
230 # parent
231 print FOO "pipe_to_fork\n";
232 close FOO;
233 }
234 else {
235 # child
236 while (<STDIN>) { print; }
237 exit(0);
238 }
239
240 And this one reads from the child:
241
242 # simulate open(FOO, "-|")
243 sub pipe_from_fork ($) {
244 my $parent = shift;
245 pipe $parent, my $child or die;
246 my $pid = fork();
247 die "fork() failed: $!" unless defined $pid;
248 if ($pid) {
249 close $child;
250 }
251 else {
252 close $parent;
253 open(STDOUT, ">&=" . fileno($child)) or die;
254 }
255 $pid;
256 }
257
258 if (pipe_from_fork('BAR')) {
259 # parent
260 while (<BAR>) { print; }
261 close BAR;
262 }
263 else {
264 # child
265 print "pipe_from_fork\n";
266 exit(0);
267 }
268
269 Forking pipe open() constructs will be supported in future.
270
271 Global state maintained by XSUBs
272 External subroutines (XSUBs) that maintain their own global
273 state may not work correctly. Such XSUBs will either need to
274 maintain locks to protect simultaneous access to global data
275 from different pseudo-processes, or maintain all their state on
276 the Perl symbol table, which is copied naturally when fork() is
277 called. A callback mechanism that provides extensions an
278 opportunity to clone their state will be provided in the near
279 future.
280
281 Interpreter embedded in larger application
282 The fork() emulation may not behave as expected when it is
283 executed in an application which embeds a Perl interpreter and
284 calls Perl APIs that can evaluate bits of Perl code. This
285 stems from the fact that the emulation only has knowledge about
286 the Perl interpreter's own data structures and knows nothing
287 about the containing application's state. For example, any
288 state carried on the application's own call stack is out of
289 reach.
290
291 Thread-safety of extensions
292 Since the fork() emulation runs code in multiple threads,
293 extensions calling into non-thread-safe libraries may not work
294 reliably when calling fork(). As Perl's threading support
295 gradually becomes more widely adopted even on platforms with a
296 native fork(), such extensions are expected to be fixed for
297 thread-safety.
298
300 In portable Perl code, "kill(9, $child)" must not be used on forked
301 processes. Killing a forked process is unsafe and has unpredictable
302 results. See "kill()", above.
303
305 • Having pseudo-process IDs be negative integers breaks down for
306 the integer "-1" because the wait() and waitpid() functions
307 treat this number as being special. The tacit assumption in
308 the current implementation is that the system never allocates a
309 thread ID of 1 for user threads. A better representation for
310 pseudo-process IDs will be implemented in future.
311
312 • In certain cases, the OS-level handles created by the pipe(),
313 socket(), and accept() operators are apparently not duplicated
314 accurately in pseudo-processes. This only happens in some
315 situations, but where it does happen, it may result in
316 deadlocks between the read and write ends of pipe handles, or
317 inability to send or receive data across socket handles.
318
319 • This document may be incomplete in some respects.
320
322 Support for concurrent interpreters and the fork() emulation was
323 implemented by ActiveState, with funding from Microsoft Corporation.
324
325 This document is authored and maintained by Gurusamy Sarathy
326 <gsar@activestate.com>.
327
329 "fork" in perlfunc, perlipc
330
331
332
333perl v5.36.3 2023-11-30 PERLFORK(1)