我正在嘗試做一個基本的多處理任務,這就是我所擁有的。首先,我不知道將此程序作爲非阻塞程序的正確方法,因爲當我等待孩子的響應(使用waitpid
)時,其他進程也必須在隊列中等待,但,如果某些子進程在之前死亡(我的意思是進程死於無序)會發生什麼?所以,我一直在尋找,我發現我可以得到剛剛死亡的進程的PID,因爲我使用的是waitpid(-1, WNOHANG)
。我總是得到一個警告,WNOHANG
不是一個數字,但是當我添加lib sys_wait_h時,我沒有得到那個錯誤,但腳本從未等待PID,可能是什麼錯誤?在Perl中進行多處理任務時出現問題
#!/usr/bin/perl #use POSIX ":sys_wait_h"; #if I use this library, I dont get the error, but it wont wait for the return of the child use warnings; main(@ARGV); sub main{ my $num = 3; for(1..$num){ my $pid = fork(); if ($pid) { print "Im going to wait (Im the parent); my child is: $pid\n"; push(@childs, $pid); } elsif ($pid == 0) { my $slp = 5 * $_; print "$_ : Im going to execute my code (Im a child) and Im going to wait like $slp seconds\n"; sleep $slp; print "$_ : I finished my sleep\n"; exit(0); } else { die "couldn’t fork: $!\n"; } } foreach (@childs) { print "Im waiting for: $_\n"; my $ret = waitpid(-1, WNOHANG); #waitpid($_, 0); print "Ive just finish waiting for: $_; the return: $ret \n"; } }
在此先感謝,再見!
謝謝!我正在使用wait(),它的工作原理!謝謝! – pablomarti 2010-10-27 15:34:25