prime_main v0.3.8

加入了两个变量给write_db提供新prime数据的参数,其实现在这个方法并不高性能而且多消耗了内存。
不过为了简单起见先用这个方法处理好write_db。
下面write_db可以动工了。

#!/usr/bin/perl -w
#use strict;
# file:prime_main
# main program of prime_project.
# by:leon 05/10/26 v0.3.8

use Socket;
use IO::Handle;
use read_write_db qw(read_db write_db);
use cal_prime qw(cal_prime_by_step);

# Bidirectional communication using socketpair
socketpair(CHILD, PARENT, AF_UNIX, SOCK_STREAM, PF_UNSPEC) or  die "socketpair: $!";
CHILD->autoflush(1);
PARENT->autoflush(1);

unless ($pid = fork) {
    # This is Child,for calculate prime
    die "cannot fork: $!" unless defined $pid;
    close CHILD;
    print "CHILD PID:$$\n";

    # Child ignore "ctrl+c"
    $SIG{INT} = ‘IGNORE’;

    # Read date from database for prepare calculate
    local (@prime_n_array,$prime_step_id,@new_prime_id_array,@new_prime_n_array);
    read_db(*prime_n_array,*prime_step_id);
    #print "@prime_n_array,$prime_step_id\n";

    while (1) {
        print PARENT "go_on?\n";
        chomp($line = <PARENT>);

        if ($line eq "go_on") {
            # Parent didn’t catch "ctrl+c" so we go on next step calculate

            $i = 0;
            while (++$i<3) {
            # Go into a calculate prime step
            print "step:$prime_step_id\n";
            cal_prime_by_step(*prime_n_array,*prime_step_id,*new_prime_id_array,*new_prime_n_array);
            print "new_id:    @new_prime_id_array\n";
            print "new_n:    @new_prime_n_array\n";
            write_db();
            }
            last;
        } elsif ($line eq "exit") {
            # Parent catch "ctrl+c" so we stop
            print "Child do something before exit\n";
            write_db();
            exit;
        } else {
            # For Extensions
            print "Child:I don’t understand What Parent say.\n";
            exit;
        }
    }

    print "CHILD end\n";

    close PARENT;
    exit;
} else {
    # This is Parent,for control Child
    close PARENT;

    # Catch ctrl+c,but don’t exit directly.Parent send a msg
    # to Child then exit after Child finish ending work
    $SIG{INT} = sub {$int_count++};

    while (chomp($line = <CHILD>)) {
        if ($int_count) {
            print CHILD "exit\n";
            last;    #jump out of "while"
        }

        if ($line eq "go_on?") {
            print CHILD "go_on\n";
        } else {
            # For Extensions
            print "Parent:I don’t understand What Child say.\n";
        }
    }

    print "Parent going to exit.\n";
    close CHILD;
    waitpid($pid,0);
}

Leave a Reply