> 如果你想要比较深刻地理解fork的话, 也许应该看看unix 高级编程。
是的, stevens的书讲的很清楚。不过perl的fork和这个一样吗?
> 2009/8/4 Ericzhao82 <ericzhao82@gmail.com>
>>
>> 多谢两位
>>
>> 2009/8/3 Lin <i@lxl.cn>
>>>
>>> 我这有一个比较实用的例子...
>>>
>>> #!/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: Ericzhao82@gmail.com
>> MSN: Ericzhao_82@hotmail.com
>> BLOG: share82.freebsder.info
>>
>>
>
>
> >
>
--~--~---------~--~----~------------~-------~--~----~
您收到此信息是由于您订阅了 Google 论坛"PerlChina Mongers 讨论组"论坛。
要在此论坛发帖,请发电子邮件到 perlchina@googlegroups.com
要退订此论坛,请发邮件至 perlchina+unsubscribe@googlegroups.com
更多选项,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问该论坛
-~----------~----~----~----~------~----~------~--~---
没有评论:
发表评论