Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.87 KB | None | 0 0
  1. #!/usr/software/bin/perl
  2. # Example 2 - To get URLs in parallel when they are stored in a file.
  3. use Parallel::ForkManager;
  4. use LWP::Simple;
  5.  
  6. my $heredoc = <<ENDS;
  7. # =============================================================== #
  8. # ERROR: Missing arguments. See usage below.
  9. # Usage: perl $0  
  10. #   E.g. perl $0 10 FB_inputFile.txt
  11. # Author: suresh.saggar\@gmail.com
  12. # =============================================================== #
  13. ENDS
  14.  
  15. if($#ARGV != 1){
  16.     printf $heredoc;
  17.     exit;
  18. }
  19.  
  20. my $num_of_processes = $ARGV[0];
  21. # Create a file handle
  22. open FH, "$ARGV[1]" or die "Cannot open filename[$filename]:$!\n";
  23.  
  24. my @URLs = undef;
  25. chomp(@URL = ); # trim trailing spaces.
  26.  
  27. my $pm = new Parallel::ForkManager($num_of_processes);
  28.  
  29. #
  30. # Setup a callback for when a child finishes up so we can get it's exit code
  31. #
  32. $pm->run_on_finish(
  33.     sub {
  34.         my ($pid, $exit_code, $ident) = @_;
  35.         print "** ID[$ident] just got out of the pool with PID[$pid] and exit code[$exit_code] \n";
  36.     }
  37. );
  38.  
  39. $pm->run_on_start(
  40.     sub {
  41.         my ($pid, $ident)=@_;
  42.         print "** ID[$ident] started with PID[$pid] \n";
  43.     }
  44. );
  45.  
  46. $pm->run_on_wait(
  47.     sub {
  48.         print "** Have to wait for one children ...\n"
  49.     },
  50.     0.5
  51. );
  52.  
  53. my $id = 0;
  54.  
  55. for my $link (@URL) {
  56.     $pm->start($id++) and next;
  57.     my ($fn) = $link =~ /^.*\/(.*?)$/;
  58.     if (!$fn) {
  59.         warn "Cannot determine filename[$fn] from link[$link]\n";
  60.         warn "Make sure you prefix each URL with http(s):/\/\ \n";
  61.     } else {
  62.         $0 .= " ".$fn;
  63.         print "Getting [$fn] from [$link]\n";
  64.         my $rc = getstore($link, $fn);
  65.         print "[$link] downloaded. response code:[$rc]\n";
  66.     };
  67.     $pm->finish;
  68.  
  69. };
  70.  
  71. # Close the file handle
  72. close FH;
  73.  
  74. print "Waiting for Children...\n";
  75. $pm->wait_all_children;
  76. print "Everybody[$num_of_processes] is out of the pool!\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement