CLOSE

A possible solution for the countlogin.pl program is as follows:

  1. #! /usr/bin/perl
  2.  
  3. # countlogin.pl - count the number of login processes for each user name
  4. # in the ps output saved in the file "psout"
  5. #
  6. # The "psout" file contains the output of the ps command. The
  7. # first line contains column headers. Each line after that contains
  8. # an entry for each process running on the machine. The first field
  9. # is the username (login id), the second field is the process id (PID),
  10. # and the last field is the command. You can determine that a process
  11. # is a login shell because it starts with a minus sign ("-"), followed
  12. # by the name of the shell.
  13. #
  14. # USER PID START TIME COMMAND
  15. # krish 396 Oct01 0:03 sshd: krish@pts/3
  16. # krish 397 Oct01 0:00 -ksh
  17. # bedros 1299 Oct06 0:00 /bin/bash /g/home/pbs/torq...
  18. #
  19. # In this sample, only process # 397, which is owned by user "krish"
  20. # is a login shell. For this program, you can ignore all the other
  21. # processes which do not match the pattern for a login shell.
  22. #
  23.  
  24. use strict;
  25. use warnings;
  26.  
  27. use IO::File;
  28.  
  29. # open the file "psout" for reading, $fh contains a filehandle
  30. my $fh = IO::File->new("<psout") or die $!;
  31.  
  32. # read the first line and ignore it (scalar prevents the read operation
  33. # from defaulting to reading the whole file as a list)
  34. scalar <$fh>;
  35.  
  36. # initialize the hash table you will use to count the logins
  37. my %count = ();
  38.  
  39. # read the remainder of the file, line by line
  40. while (<$fh>)
  41. {
  42. next unless ( /\s-\w+$/ ); # skip if not a shell
  43. my ($login) = ( /^(\w+)\s/ ); # grab user name, first column
  44. $count{$login} = 0 # initialize hash entry if new
  45. unless (exists $count{$login});
  46. $count{$login}++; # increment count for user
  47. }
  48.  
  49. # close the file
  50. $fh->close;
  51.  
  52. # print a list of the usernames and the process count, sorted by name
  53. foreach my $login (sort keys %count)
  54. {
  55. printf("%9s %3d\n", $login, $count{$login});
  56. }
  57.  

CLOSE