如果你想要比较深刻地理解fork的话, 也许应该看看unix 高级编程。

2009/8/4 Ericzhao82 <[email protected]>

> 多谢两位
>
> 2009/8/3 Lin <[email protected]>
>
> 我这有一个比较实用的例子...
>>
>> #!/usr/bin/perl
>> # achech.com
>> my $PID       = $$;
>> my $THREAD    = $$;
>> my $COUNT     = 0;
>> my $CONNECT   = 10;
>> my @kids      = ();
>> my $parentpid = 0;
>> ##########
>> &Init();
>> &Forker($CONNECT);
>> while (1) {
>>     $COUNT++;
>>     if ($parentpid) {
>>         &Running();
>>     }
>>     else {
>>         &Reaper();
>>     }
>> }
>> exit 0;
>> ##########
>>
>> sub Init {
>>     &debug(__LINE__,"Init...");
>>     # 将需要重用的信息在这里初始化吧...
>> }
>>
>> sub Forker {
>>     my $clients = shift;
>>     my $i       = 0;
>>     while ( $i++ < $clients ) {
>>         my $newpid = fork();
>>         if ( !defined $newpid ) {
>>             die "fork() error: $!\n";
>>         }
>>         elsif ( $newpid == 0 ) {
>>             $parentpid = $THREAD;
>>             $THREAD    = $$;
>>             @kids      = ();
>>             last;
>>         }
>>         else {
>>             &debug(__LINE__,"*进程 $$ 创建线程 $newpid");
>>             push( @kids, $newpid );
>>         }
>>     }
>> }
>>
>> sub Running {
>>     &debug(__LINE__,"  +线程 $$ 等待接收");
>>     # 在这里执行任务...
>>     my $sec = int(rand(10));
>>     &debug(__LINE__,"    TODO: 随机停顿 $sec 秒");
>>     sleep($sec);
>>     # 任务结束...
>>     &debug(__LINE__,"  +线程 $$ 处理完毕");
>> }
>>
>> sub Reaper {
>>     while ( my $kid = shift(@kids) ) {
>>         &debug(__LINE__,"*进程 $$ 回收线程 $kid");
>>         my $reaped = waitpid( $kid, 0 );
>>         unless ( $reaped == $kid ) {
>>             &debug(__LINE__,"waitpid $reaped: $?");
>>         }
>>     }
>> }
>>
>> sub debug{
>>     printf("[%04d] %s %s\n",shift,scalar(localtime(time)),shift);
>> }
>>
>>
>>
>
>
> --
> …………………………………………
>               Ericzhao
>
> Email:   [email protected]
> MSN:    [email protected]
> BLOG:   share82.freebsder.info
>
>
> >
>

--~--~---------~--~----~------------~-------~--~----~
您收到此信息是由于您订阅了 Google 论坛“PerlChina Mongers 讨论组”论坛。
 要在此论坛发帖,请发电子邮件到 [email protected]
 要退订此论坛,请发邮件至 [email protected]
 更多选项,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问该论坛
-~----------~----~----~----~------~----~------~--~---

回复