修正了一个bug:当程序开始读取database的数据,但还没开始开始计算的时候如果收到ctrl+c信号会保存已有数据,那样就造成了数据重复。
另外加强了界面友好性。
现在这个test1版本应该比较完善了。
#!/usr/bin/perl -w
#use strict;
# file:prime_main
# main program of prime_project.
# by:leon 05/10/27 v0.3.12
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;
# 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);
print "Child: Reading existing prime data from database\n";
read_db(*prime_n_array,*prime_step_id);
my $if_cal = 0;
print "Child: Reading finish\n";
print "Child: Now start calculate prime step by step\n";
while (1) {
$|=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
# print "\b";
print "In step:$prime_step_id\n";
$if_cal = 1;
cal_prime_by_step(*prime_n_array,*prime_step_id,*new_prime_id_array,*new_prime_n_array);
# When finish a step save data to database
write_db(*new_prime_id_array,*new_prime_n_array,*prime_step_id);
} elsif ($line eq "exit") {
# Parent catch "ctrl+c" so we stop
if ($if_cal==1) {
print "Child: Saving step data before exit\n";
write_db(*new_prime_id_array,*new_prime_n_array,*prime_step_id);
print "Child: Saved!\n";
print PARENT "child_finish\n";
} else {
print "Child: Needn’t save data case hav’t cal new prime\n";
print PARENT "child_finish\n";
}
last;
} else {
# For Extensions
print "Child: I don’t understand What Parent say.\n";
exit;
}
}
print "Child: Exiting\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++};
# When Child finish a step and ask Parent if go on or do something else
# Parent responses a answer
while (chomp($line = <CHILD>)) {
# Parent catch "ctrl+c" and ask Child to exit.
if ($int_count) {
# Now we should ignore ctrl+c!
$SIG{INT} = ‘IGNORE’;
# Do some ending job
print "Parent: Calling Child to finish job\n";
print CHILD "exit\n";
chomp($line = <CHILD>);
if ($line eq "child_finish") {
print "Parent: All job finish\n";
print "Parent: Exiting\n";
last;
} else {
print "Parent: I don’t understand What Child say.\n";
}
}
# Havn’t catch ctrl+c,so let Child go on next step
if ($line eq "go_on?") {
print CHILD "go_on\n";
} else {
# For Extensions
print "Parent: I don’t understand What Child say.\n";
}
}
close CHILD;
waitpid($pid,0);
}