Search code examples
perlforkparent-child

Introduction to Parents/Childs and Forks Inquiry


I am attempting to learn the functionality of parents, children and pipes in perl. My goal is to create a single pipe (not bidirectional) that reads from the command line, and prints it through a pipe. Referencing the pids many many times.

The code so far:

#!/usr/bin/perl -w

use warnings;
use strict;


pipe(READPIPE, WRITEPIPE);
WRITEPIPE->autoflush(1);

my $parent = $$;
my $childpid = fork() // die "Fork Failed $!\n";

# This is the parent
if ($childpid) {  
    &parent ($childpid);
    waitpid ($childpid,0);
    close READPIPE;
    exit;
}
# This is the child
elsif (defined $childpid) {
    &child ($parent);
    close WRITEPIPE;

}
else {
}

sub parent { 
    print "The parent pid is: ",$parent, " and the message being received is:", $ARGV[0],"\n";
    print WRITEPIPE "$ARGV[0]\n";
    print "My parent pid is: $parent\n";
    print "My child pid is: $childpid\n";   
}

sub child {
    print "The child pid is: ",$childpid, "\n";
    my $line = <READPIPE>;
    print "I got this line from the pipe: $line and the child pid is $childpid \n";
}

The current output is:

perl lab5.2.pl "I am brain dead"
The parent pid is: 6779 and the message being recieved is:I am brain dead
My parent pid is: 6779
My child pid is: 6780
The child pid is: 0
I got this line from the pipe: I am brain dead
 and the child pid is 0 

I am trying to figure out why the childpid in the child subroutine is returning as 0, but in the parent it is referencing "accurate looking" pid #.

Is is supposed to return 0? (For instance if I made multiple subroutines would they be 0,1,2 etc.?)


Solution

  • Yes, it should be 0, and it would be 0 in every child process that comes out of a fork call.

    fork

    Does a fork(2) system call to create a new process running the same program at the same point. It returns the child pid to the parent process, 0 to the child process, or "undef" if the fork is unsuccessful.

    After the fork, $$ is changed in the child process to the new process id. So the child could read $$ to get the child process id (its own id).