💾 Archived View for thrig.me › blog › 2022 › 12 › 15 › code-review.gmi captured on 2023-09-28 at 16:31:50. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2023-04-19)

➡️ Next capture (2023-11-14)

-=-=-=-=-=-=-

Code Review

The Code

It was claimed that chatgpt produced this code. Regardless of whether that is true, the code is not good.

     1  #!/usr/bin/perl
     2  
     3  use strict;
     4  use warnings;
     5  use POSIX ":sys_wait_h";
     6  
     7  my $pid = fork();
     8  
     9  if ($pid == 0) {
    10      # this is the child process
    11      sleep(30);
    12      kill("USR1", getppid());
    13      exit(0);
    14  } else {
    15      # this is the parent process
    16      local $SIG{USR1} = sub {
    17          print "Received SIGUSR1 signal from child.\n";
    18      };
    19      while (1) {
    20          print scalar(localtime()), "\n";
    21          sleep(1);
    22      }
    23  }

Errors

I would not let this code past a code review.

Concerns

Rewrite

     1  #!/usr/bin/env perl
     2  # forkpractice - wait for a USR1 in parent sent by child and exit
     3  
     4  use strict;
     5  use warnings;
     6  use feature 'say';
     7  use IO::Pipe;
     8  use POSIX '_exit';
     9  use Time::Piece;
    10  
    11  my $pipe = IO::Pipe->new;
    12  my $pid  = fork() // die "fork failed: $!\n";
    13  
    14  if ( $pid == 0 ) {    # child
    15      $pipe->reader;
    16      sysread $pipe, my $ch, 1;    # block until parent ready
    17      kill USR1 => getppid;
    18      _exit(0);
    19  
    20  } else {    # parent
    21      STDOUT->autoflush(1);
    22      $pipe->writer;
    23      my $looping = 1;
    24      $SIG{USR1} = sub { say "received SIGUSR1"; $looping = 0 };
    25  
    26      my $odds = 0;
    27      while ($looping) {
    28          say localtime->strftime("%H:%M:%S");
    29          if ( rand() < $odds ) {
    30              say "closing pipe...";
    31              close $pipe;
    32          }
    33          sleep 1;
    34          $odds += 0.01;
    35      }
    36  }

Commentary

I prefer to keep most of the comments or documentation separate from the code, e.g. any Plain Old Documentation (POD), not present here, will be placed at the end of the file. Others mix POD into the script itself; I find this distracts from the code and makes searches more difficult: with the code and documentation distinct, you can stop a code search when the search wanders into the end-of-file documentation.

A good exercise might be to implement this code in some other language.

See Also

tags #perl #butlarianjihad #unix

bphflog links

bphflog index

next: Duplicate Environment Variables