Perl Programming/Keywords/fork

Previous: foreach Keywords Next: format

The fork keyword edit

fork makes a fork(2) call to start the same program at the same point, returning the child PID to its parent process, 0 to the child process, or undef when it was unsuccessful. File descriptors with sometimes their locks are shared, while everything else is copied. Most systems supporting fork() implemented it extremely efficient.

Perl attempts to flush all opened files for output before forking the child process, but this may not be supported on some platforms. To be safe, you may need to set $| ($AUTOFLUSH in English) or call the autoflush() method of IO::Handle on all open handles so that duplicate output is avoided.

To fork without waiting for the children creates zombies. On some platforms like Windows, the fork() system call is not available, Perl can be built such that it emulates it in the Perl interpreter.

Syntax edit

  fork

Examples edit

 
$pid = fork();

if ($pid == 0) {
  print "I am the child of my parent\n";
  exit 0;
}
print "I am the parent process and have the child with the ID $pid\n";
exit 0;
returns
I am the parent process and have the child with the ID -6852
I am the child of my parent


Previous: foreach Keywords Next: format