Solved

How to create a parallel  (forked) process  in Perl

Posted on 2011-03-24
9
570 Views
Last Modified: 2012-05-11
Hi,
How can I create a parallel  (forked) process  in Perl?

Let's say I have system call in my Perl code. And I don't want the rest of the code to be interrupted due to a problem in my section of the entire code.

Note : The rest of the code does not rely on my code at all.

Here is my current code:

SOME OTHER CODE IS IN HERE

my $nb_sec = 60;
timeout $nb_secs => sub {
        system("java -jar myfile.java");
  } ;
  if ($@){

    Send e-mail from a1@domain.com to a2@domain.com with a subject of "Logging Timed out" and with a message of "System call interrupted due to time out"

     }
        if ($? == -1) {

           Send email from a1@domain.com to a2@domain.com with a subject line of "Logging Failed" and with a message of "failed to execute: $!\n"

        } elsif ($? & 127) {
             my $signal = ($? & 127);
            my $woCoredump = ($? & 128) ? 'with' : 'without';
            
         Send email from a1@domain.com to a2@domain.com with a subject line of Logging Failed and a message line of "Child died with signal $signal, $woCodedump coredump\n"

        }
    }

SOME OTHER CODE IS IN HERE

Open in new window


Thanks,
0
Comment
Question by:Tolgar
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 26

Accepted Solution

by:
wilcoxon earned 475 total points
Comment Utility
This should do it...
if (fork == 0) {
   ## your code goes here
   exit;
}

Open in new window

0
 

Author Comment

by:Tolgar
Comment Utility
So under which condition fork may not be equal to 0?

Can you please explain a little bit how this works?

Thanks,
0
 
LVL 8

Expert Comment

by:point_pleasant
Comment Utility
Here is a simpleexample.  put the process you don't want to wait for in the Child Process section

defined (my $pid = fork) or die "Cannot fork: $!\n";

   if ($pid)
   {
     # Parent Process...

     push(@children, $pid);
     wait();
     my $ret = $?;

     if ($ret)
     {
      warn("Abnormal child exit: $!\n");
      $daemon = undef;
      last;
     }
   }
   else
   {
    # Child Process...
    exit(0);
   }
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 25 total points
Comment Utility
> So under which condition fork may not be equal to 0?
perldoc -f fork
       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.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 26

Assisted Solution

by:wilcoxon
wilcoxon earned 475 total points
Comment Utility
As ozo said, fork returns 0 to the child and returns the pid to the parent so the code inside the if is only executed in the child and the parent happily goes on to doing whatever is after the if.
0
 
LVL 8

Expert Comment

by:point_pleasant
Comment Utility
tolgar,

be careful of using the above code.  Not using a wait statement in the parent process can cause unexpected results.  for example the below code with the wait commented out.

if (fork == 0) {
        print "in child\n";
        $actual = sleep(10);
        print "after sleep $actual\n";
        exit;
} else {
        print "in parent\n";
        #$waitis = wait;
        #print "$waitis\n";
}


when run perl forktest.pl the following is the output
in child
in parent
root@172.30.157.19 #  after sleep 10

the parent process has exited, the child is orphaned and completes to seconds later with the parent having know idea of success or failure.  with the wait uncommented the following is the output

in child
in parent  <-------- can't see it here but thete is a 10 second delay between this and the following line
after sleep 10
6630
root@172.30.157.19

0
 

Author Comment

by:Tolgar
Comment Utility
@ wilcoxon and ozo :

What do you think about this comment?


@ point_pleasant:

If I put wait then does parent wait until child completes the process? If this is the case, then this is not what I really want


Thanks,

0
 
LVL 26

Expert Comment

by:wilcoxon
Comment Utility
He is correct but it very rarely makes a difference in practice.  wait will cause the parent to wait for the child to finish which does allow doing error checking in the parent process.  However, you can always add code in the child process to catch any errors therein.
0
 

Author Comment

by:Tolgar
Comment Utility
ok .

Thanks everyone...
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now