Loading ...
Sorry, an error occurred while loading the content.

[PBML] New to Perl - with a tricky question....please help!

Expand Messages
  • news@faico.net
    Hello, I am very new to Perl. I have wrote a simple program - testbuf.pl (code attached below), just to see how safe is perl in a very busy server
    Message 1 of 1 , Aug 3 2:00 AM

      I am very new to Perl. I have wrote a simple program - "testbuf.pl"
      (code attached below), just to see how "safe" is perl
      in a very busy server environment, with many people accessing the same
      script / files.

      testbuf.pl is a very simple program, which read a number from a file,
      increase it by 1, then
      write back to the file.... to emulate a busy server I add a loop of
      1..2000, so the file will
      be read and opened 2,000 times... which means if I put 0 in the file to
      start with, the result
      after 2000 executions is simply - 2000.

      Now if I run "testbuf.pl" FOUR times, the end result is 8000...

      However, if I run "testbuf.pl &" in the backgroup FOUR times from the
      command line, start a new instance before
      the previous one finished... there seemed to be a problem.... the end
      result is almost random,
      but always less than 8000... sometimes 6000, sometimes 3000....

      Obviously.... there was a problem while multiple perl scripts try to
      open / write to the same file intensively.

      My question
      Is there an efficient, safe way to OPEN / WRITE to file in a
      multiusers, busy environment?

      Is there any way to make the end result always 8000... even if I run
      the four instance of "testbuf.pl"
      at the same time?

      Many thanks for your kind help

      Godfrey Ko


      #!/usr/bin/perl -w

      for ($runa=1;$runa<=2000;$runa++)

      open (FILE, "<count.txt");
      $i = (<FILE>);

      open (FILE, ">count.txt");
      $| = 1;
      flock (FILE,2);
      print FILE $i;
      close (FILE);

    Your message has been successfully submitted and would be delivered to recipients shortly.