perl function fork
The fork()
function in Perl creates a new child process that is a duplicate of the calling process. The child process starts execution from the same point as the parent process but has its own copy of the memory space and resources.
Here's an example of using fork()
in Perl:
#!/usr/bin/perl use strict; use warnings; my $pid = fork(); if ($pid == 0) { # This code runs in the child process print "Child process PID is $$\n"; sleep(5); print "Child process exiting\n"; exit(0); } elsif ($pid > 0) { # This code runs in the parent process print "Parent process PID is $$\n"; my $wait_pid = waitpid($pid, 0); print "Child process with PID $wait_pid has exited\n"; } else { die "Failed to fork: $!\n"; }
In this example, the fork()
function is called to create a new child process. The if
block is executed in the child process, while the elsif
block is executed in the parent process.
The child process prints its PID using $$
, sleeps for 5 seconds, and then exits using exit(0)
.
The parent process waits for the child process to exit using waitpid()
, and then prints the PID of the exited child process.
When you run this script, you'll see output like this:
Parent process PID is 1234 Child process PID is 1235 Child process exiting Child process with PID 1235 has exited
Note that the order of the output may vary, depending on how the processes are scheduled by the operating system.