我有一个进程,我希望主线程运行循环并生成n个子节点,所有这些节点应该休眠j秒,然后(或多或少)同时唤醒并执行它们的操作。
我的代码看起来像[根据Dre的请求编辑]:
#THE IDEA HERE IS SOMETIMES I WANT TO HOLD THE
SMS DELIVERY FOR $smsDelay number of seconds
if($smsDelay){
my $forkPid = fork();
if($forkPid){
next;
}
elsif($forkPid == 0){
#db connection disappears while children wait, so, need to reconnect (probably not the best way to handle THIS either! :)
$myDbC = DBI->connect([DBLOGIN STUFF]) or myDie("can not connect to db");
&logData("WAITING $smsDelay SECONDS TO SEND SMS");
sleep($smsDelay * 1);
$t = time();
print "sending SMS";
&send_sms_message($userPN, $smsText , $smsCampaignId);
print "SMS sent";
my $smsVerification = &getDeliveryStatus($userPN, '.smslog');
&logData("SMS delivery for $userPN, filename:$filename. Status = $smsVerification");
#save mms, sms, response code in db
&runSQL([SQL HERE]);
exit; #this should only exit the fork, not the entire process!
}
}else{
#HERE I WOULD SEND SMS IMMEDIATELY WITHOUT DELAY
}
我所看到的是每个孩子都被连续执行,但是每个孩子在下一个孩子之间等待j秒!这不是我所追求的(坦率地说完全令人困惑)。我做错了什么?
TIA
答案 0 :(得分:1)
他们应该同时醒来,他们在我测试时会这样做。我的代码:
print "parent: ".localtime."\n";
for (1..3) {
my $pid = fork();
if ($pid == 0){
sleep(3);
print "$$: ".localtime."\n";
exit(0);
}
}
1 while wait != -1;
Unix的:
parent: Wed Mar 9 22:21:27 2011
29757: Wed Mar 9 22:21:30 2011
29755: Wed Mar 9 22:21:30 2011
29756: Wed Mar 9 22:21:30 2011
Windows(fork仿真):
parent: Thu Mar 10 01:19:39 2011
-3836: Thu Mar 10 01:19:42 2011
-4600: Thu Mar 10 01:19:42 2011
-4400: Thu Mar 10 01:19:42 2011
我怀疑问题出现在您未显示的代码中。