Re: [問題] 同時丟很多程式, 但是要等它跑完....

看板Perl作者 (薑餅)時間14年前 (2011/04/21 11:08), 編輯推噓0(002)
留言2則, 1人參與, 最新討論串3/3 (看更多)
感謝 a 大, 後來我 google 到解決方案了, 其實就是用 fork 和 waitpid, 因為我就是在 Unix 執行的.... ^^ 底下是程式碼, 從別的網頁找到修改的, 給大家參考吧, my @pids; for (my $i=1;$i<=4;$i++){ # 假設我要跑4個 process die "could not fork" unless defined(my $pid = fork); unless ($pid) { #child execs exec "A input.$i"; die "exec of A failed"; } push @pids, $pid; #parent stores children's pids } #wait for all children to finish for my $pid (@pids) { waitpid $pid, 0; } ※ 引述《abliou (把青春freeze)》之銘言: : ※ 引述《jumpings (薑餅)》之銘言: : : 就是呢, 為了要加快速度, 我同時要丟很多個軟體一起跑, : : 我是用 & 丟到背景來完成的, 但是我程式要等這些軟體跑完, : : 才能去 parse output, 這樣程式要怎麼寫 ? : : 舉例來說, 我要執行A軟體三次, 但是輸入檔案不一樣, 如下 : : : system "A input1 &"; : : system "A input2 &"; : : system "A input3 &"; : : 接著我要讀 output1, output2, output3, 但是如果我這時候寫 : : : read output1; : : read output2; : : read output3; : : 這時候 output 都還沒有出來, 所以會讀不到檔案, 有沒有什麼辦法 : : 可以讓軟體丟到背景之後等待, 然後等跑完再繼續執行 ? : : 感謝大家的回覆.... : 本來有想過用pid 不過pid支援度只有在UNIX like的作業系統支援度才會比較好 : (事實上我以前做過的實驗 在win32系統上沒有成功過 那是幾年前的事) : 所以如果真的想丟多執行緒的話 就還是用多執行緒的模組試看看 : psudocode大概是這樣 : ===== : use 5.010 ; : use threads ; : $th1 = threads->create(\&sendjob , input1) ; : $th2 = threads->create(\&sendjob , input2) ; : $th3 = threads->create(\&sendjob , input3) ; : $th1->join ; : $th2->join ; : $th3->join ; : read output1; : read output2; : read output3; : sub sendjob{ : system "A $_[0]" ; : } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.109.22.142

04/21 11:09, , 1F
對了, 要注意一點 exec 裡面不用加 "&", 否則會失敗....
04/21 11:09, 1F

04/21 11:09, , 2F
昨晚為了這個bug de了好久...... Orz
04/21 11:09, 2F
文章代碼(AID): #1Dhv_0Ez (Perl)
文章代碼(AID): #1Dhv_0Ez (Perl)