prime_main v0.3.9

write_db也写好了,现在整个程序ok了!
prime_main加了个参数给write_db。

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

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<150) {
            # 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(*new_prime_id_array,*new_prime_n_array,*prime_step_id);
            }
            last;
        } elsif ($line eq "exit") {
            # Parent catch "ctrl+c" so we stop
            print "Child do something before exit\n";
            write_db(*new_prime_id_array,*new_prime_n_array);
            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