[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Magic Money on a port



I wrote a little perl script to put the magic money server on a port.

This should help in writing a client program which doesn't require the user
to deal with sending repeated messages to the bank.

Most of it I just took from the perl manpage. It requires shlock.pl.

Please send bug reports.

#!/usr/local/bin/perl

($port) = @ARGV;
$port = 1992 unless $port;
$magicserver = "/home/infinity/nexbucks/s";
$waitlock = "/home/infinity/nexbucks/waiter.pid";
$processlock = "/home/infinity/nexbucks/processor.pid";

require 'sys/socket.ph';
require './shlock.pl';

# First check to see if the process is running
unless(&shlock($waitlock))
{
    print "Process already running\n";
    exit;
}

$sockaddr = 'S n a4 x8';

($name, $aliases, $proto) = getprotobyname('tcp');
($name, $aliases, $port) = getservbyname($port, 'tcp')
    unless $port =~ /^\d+$/;

$this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");

select(NS); $| = 1; select(stdout);

socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
bind(S, $this) || die "bind: $!";
listen(S, 5) || die "connect: $!";

select(S); $| = 1; select(stdout);

# Ok the socket has been setup. Fork, wait for the parent lock to die
# and then lock again
if(fork)
{
    exit;
}

# Wait for the old process to die
sleep 10 unless(&shlock($waitlock));

for (;;) {
#    print "Listening again\n";
    ($addr = accept(NS,S)) || die $!;
    unless(fork)
    {
#        print "accept ok\n";
	($af,$port,$inetaddr) = unpack($sockaddr,$addr);
	@inetaddr = unpack('C4',$inetaddr);
#	print "$af $port @inetaddr\n";

	$tmpin = "/tmp/mmin." . $$ ;
	$tmpout = "/tmp/mmout." . $$ ;

	open(TIN, ">$tmpin") || die $!;

	print NS "Submit to the Nexus Bank:\n";
	while (<NS>) {
	    print TIN;
	    last if /^-----END/ ;
	}
	close(TIN);

	# Wait for the process lock to stop

	unless(&shlock($processlock))
	{
	    print NS "Please wait for other requests to finish.";
	    do
	    {
		print NS "." ;
		sleep 10;
	    }
	    until(&shlock($processlock));
	}
	
	print NS "order processing.";

	# Run magic money
	open(MM, "| $magicserver > $tmpout");
	open(TIN, $tmpin);
	while(<TIN>)
	{
	    print NS "." ;
	    print MM;
	}
	close(TIN);
	close(MM);

	print NS "done.\n";
	open(OUTPUT, $tmpout);
	print NS <OUTPUT>;
	close OUTPUT;
	exit;
    }
}