开发者

how do I get all my fork(ing) children to execute at the same time?

I have a process where I want the main thread to run through a loop and produce n number of children, all of which should sleep for j seconds and then (more or less) simultaneously wake up and do their thing.

My code looks like this [Edited as per Dre's request]:

 #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

        }

What I'm seeing is that each child is executed in succession, but each one waits j seconds IN BETWEEN the next! This is not what I'm after (and frankly totally confusing). What am I do开发者_如何学编程ing wrong?

TIA


They should simultaneously wake up, and they do when I tested. My code:

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 emulation):

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

I suspect the problem is in the code you didn't show.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜