multithreading - Threaded code exits before all tasks are complete -
i trying take portion of existing script , have run multiple nmap scans simultaneously increase speed of script.
i tried using fork, suggested me should using threads instead doing on windows box. modified code snippet found online , partially works.
i using list of 23 ip addresses. have been able open 10 threads , scan first 10 addresses, code exits. ideally, code open new thread each time 1 exits there 10 threads running, until reaches remainder, in case there three. 3 threads open.
this entire code needs run inside subroutine have in original sequential code. using ping instead of nmap command test.
#!/usr/bin/perl use strict; use threads; $i = 0; @lines; # define number of threads $num_of_threads = 10; # use initthreads subroutine create array of threads. @threads = initthreads(); @files = glob( "./ping.txt" ) or die "can't open cms hostinventory$!"; # open cms host inventory csv files parsing foreach $file ( @files ) { open (config, '<', $file) or die "can't ip360_dns file$!"; @lines = <config>; chomp (@lines); } # loop through array: foreach ( @threads ) { # tell each thread perform our 'dooperation()' subroutine. $_ = threads->create(\&dooperation); } # tells main program keep running until threads have finished. foreach ( @threads ) { $_->join(); } print "\nprogram done!\npress enter exit"; $a = <>; ####################### subroutines ############################ sub initthreads{ @initthreads; ( $i = 1; $i <= $num_of_threads; $i++ ) { push(@initthreads, $i); } return @initthreads; } sub dooperation{ # thread id. allows each thread identified. $id = threads->tid(); $ip = ($id - 1); system("ping $lines[$ip] >> ./input/$lines[$ip].txt"); print "thread $id done!\n"; # exit thread threads->exit(); }
Comments
Post a Comment