
#{{{  Magic Startup

eval "exec $PERL $0 $*"           # Magic to invoke perl on this script
  if $untrue;                     # using the environment variable PERL.

#}}}  

require "sys/unistd.ph";
use Fcntl;


#A nasty hack to get round a perl instalation problem
#would prefer to use 'use POSIX ;' instead but this gives unwanted/
#unacceptable output
sub SEEK_SET
  {
  return 0;
  }


local ($code) = @_;
local ($flock, $status, $found, $line);

#First open and lock the shared file
# Create lock file if not exists
$share_file = "/design/tmp/dsmith/share.txt";

if (! -e $share_file)
  {
  if (system ("touch $share_file"))
    {
    die("can't create share file $share_file: $!");
    }
  }

for($i=1; $i<=10; $i++)
  {
  # Open share file (in read + append)

  if (!open (LOCKFD, "+>> $share_file"))
    {
    die("unable to open $share_file :$!");
    }

  $flock = pack ("sslll",
		 &F_WRLCK,
		 &SEEK_SET,
		 0,
		 0,
		 $$);

  ($status = fcntl (LOCKFD, &F_SETLK, $flock)) || ($status = -1);

  if ($status == -1)
    {
    print STDERR "Another session of runtests is accessing the share file, waiting for if it to finish\n";
    }

  $status = fcntl (LOCKFD, &F_SETLKW, $flock);

  if ($status ne "0 but true")
    {
    die ("something bad with share file: $share_file");
    }
  #move to EOF

  while(defined($input_line = <LOCKFD>))
    {
    if ($input_line =~ /$ENV{"HOSTNAME"}/)
      {
      print STDERR "Hello\n";
      }
    }

  printf LOCKFD ("hostname %s jobid %d attempt $i\n", $ENV{"HOSTNAME"}, $ENV{"LSB_JOBID"});

  $flock = pack ("sslll",
		 &F_UNLCK,
		 &SEEK_SET,
		 0,
		 0,
		 $$);

  ($status = fcntl (LOCKFD, &F_SETLK, $flock)) || ($status = -1);

  if ($status == -1)
    {
    die ("something bad with unlocking share file: $share_file\n");
    }

  close (LOCKFD);
  }

