#!/usr/bin/perl

use strict;
use warnings;


use BerkeleyDB;

our $cfg;
my $count=2;

sub sig_handler {
    warn "Got SIG@_. Exiting gracefully!\n" if $cfg->{debug};
    exit 1;
}

sub db {
    for ('INT', 'TERM', 'PIPE', 'QUIT', 'HUP', 'SEGV') {
	$SIG{$_} = \&sig_handler unless $SIG{$_};
    }

    my $env = new BerkeleyDB::Env
      -Home   => '/tmp',
	-Flags => DB_CREATE | DB_INIT_MPOOL | DB_INIT_CDB,
	  -ErrFile => *STDERR,
	    -ThreadCount => 64,
	      -ErrPrefix => "[$$]:"
		or die $BerkeleyDB::Error;

    $env->set_isalive();
    if ($env->failchk == DB_RUNRECOVERY) {
	warn "Failed thread detected.\n";
    }

    my $dbh = new BerkeleyDB::Btree
      -Filename => '/tmp/test.db',
	-Flags => DB_CREATE,
	  -Env => $env
	    or die $BerkeleyDB::Error;

    return $dbh;
}

sub fetch_store {
    my $cpid;
    my $dbh=db();
    warn "[$$]: Init DB in fetch_store\n";



    return 1;
}


sub return_file {
	    my $dbh=$_[0];
	    warn "[$$]: Init DB in return_file\n";
	    $dbh->db_put('child', $$) && die $!;
	    return 1;
}

warn "[$$]: Parent\n";

while ($count--) {
    my $pid = fork;
    die $! unless defined $pid;
    if ($pid == 0) {
	my $write = "$$: $count";
	warn "[$$]: Write $write\n";
	db()->db_put('child', $write) && die $!;
	exit;
    }
    else {
	waitpid $pid, 0;
	db()->db_get('child', my $read) && die $!;
	warn "[$$]: Read $read\n";
    }
}
