< Perl Programming < Keywords

The fork keyword

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

  fork

Examples

$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
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.