In the Perl language, we can create many processes and manage them according to the needs of our program. The following functions are used for the purpose of process management in Perl:
The system
function in Perl is used to execute Unix commands. For example, if we wished to print all the files in a directory through the Perl script, we would execute the code below. The ls
command lists the names of all the files.
system( "ls");
The fork
function in Perl is used to create a child process that runs the same programs that were being executed before it. There are three possible return values when this function is called.
fork
returns the ID for the process, also known as pid
, to the parent process.fork
returns 0 to the child process itself.fork
returns undef
if the process cannot be forked successfully.As shown in the code below, we use fork
to create a process. First, we check whether the process ID stored in pid
is undefined. If it is undefined, we want to quit the script and print Process could not be forked successfully
.
However, if pid
is equal to 0, that means we are printing within the child process. In this case, we quit the script and print In child process
. Lastly, if pid
is neither 0 nor undefined, this means the process has been forked successfully and has a process ID. We then print the process ID.
The code below successfully forks in the parent process and prints its process ID. After the parent process, the code enters the child process to carry out the program. The code prints ‘nothing to do’ and dies.
$pid = fork();if(!defined($pid)) {die "Process could not be forked successfully";} elsif ($pid == 0) {print "In child process\n";die "nothing to do";} else {print "In parent process\n";print "process id: $pid\n";}
The waitpid
function waits for a child process to terminate and then prints its ID through the Perl script. The function waitpid
takes two arguments:
To execute a non-blocking wait, we set the flags as 0.
Below is an example of how you can do this. The code below is similar to the one above, only this time the output waits for all programs of the child process to finish executing before printing its completed process ID.
$pid = fork();if(!defined($pid)) {die "Process could not be forked successfully";} elsif ($pid == 0) {print "In child process\n";die "not executable";} else {print "In parent process\n";print "process id: $pid\n";$complete = waitpid($pid, 0);print "Completed process id: $complete\n";}
The kill
function in Perl is used to kill a process. kill
takes two arguments:
SIGNAL
– sent to the whole list of processesIf we wish to kill those processes, we must specify the signal as KILL
. The following is an example of how you can use the kill
function.
$pid = fork();kill('KILL', $pid);
Free Resources