1. Perl
  2. builtin functions
  3. here

fork function - branch process

You can use the fork function to branch a process into two . One forked process is the parent process and the other is the child process.

fork function

The fork function takes no arguments. The return value will be the process ID of the branched child process if the branched process is the parent process. 0 for child processes. If fork fails, undef is returned.

my $pid = fork;

Consider the return value of fork

For the parent process, for the child process, there are three ways to think about fork failure.

my $pid = fork;

# If fork fails
die "Cannot fork:$!" unless defined $pid;

if ($pid) {
  # For parent process ($pid is assigned the process ID of the child process)
}
else {
  # For child processes 0 is assigned to $pid
}

What fork is doing

What fork does is a copy of its process. Since it is a copy of its own process, the variable you were using up to that point can be used by both the parent and child processes. If you make changes to variable after forking, they will only be reflected in each process and will not affect each other.

For interprocess communication, see "Performing" interprocess communication "with Perl".

How to use fork

1. Process in parallel

If you do fork, you can process in parallel. It may be used when the performance cannot be satisfied by single tasking.

2. Sharing roles

In some situations, it may be simpler to branch the processes and have each process specialize in it, rather than having one process take care of everything.

3. Manage multiple processes

You can use a technique called fork-exec to replace a branched child process with a completely different process. For example, you can replace it with a process called vmstat that looks at CPU and memory usage. Since the parent process knows the process ID of the child process, it can control the child process through controlling the parent process.

fork example code

use strict;
use warnings;

my $pid = fork;

die "Cannot fork:$!" unless defined $pid;

if ($pid) {
  print "parent process (child process ID: $pid)\n";
}
else {
  print "child process\n";
}

Output

You can see that each branch is executing print statement. (Confirmed by Fedora 7)

Parent process (child process ID: 25229)
Child process

Notes on Windows

The fork function can be executed on Windows, but the fork function on Windows is different from the real fork because it is realized by using threads.

Related Informatrion