in reply to Anonymous User Add For Linux Shell

If it's possible that two or more people may be creating their own accounts at about the same time, shouldn't there be some sort of semaphore or other locking mechanism that encloses the "get next uid" and the "sudo useradd"? Given that you're reading /etc/passwd one line at a time, it's conceivable that two processes could read the same version of that file and both try to create an account with the same value of $uid.

For example, below is a module I adapted for my own use, based on an old Perl Journal article; with that module, you can just add a couple lines around the sensitive part:

use Semfile; ... my $lock = Semfile->new("/tmp/getuid.lock") or die "oops! $!"; # do your "get next uid" and your "sudo useradd" here $lock->release;
Here's the module (apologizes for the silly name):
package Semfile; use strict; use FileHandle; use Carp; # copied (and documented) by Dave Graff from # The Perl Journal, issue #23 (Vol.6 No.1): # "Resource Locking with Semaphore Files" # by Sean M. Burke. # (http://www.samag.com/documents/s=4075/sam1013019385270/sam0203i.htm +) # Create and manage semaphore files, which will guarantee that # simultaneous processes competing for a single resource do not # collide when using that resource. # The semaphore (locked) file has no content -- it is simply the # thing to check, and lock if it's available, before using/altering # the actual shared resource. sub new { my $class = shift(@_); my $filespec = shift(@_) or Carp::croak("What filespec?"); my $fh = new FileHandle; $fh->open( ">$filespec" ) or Carp::croak("Can't open semaphore file $filespec: $!"); chmod 0664, $filespec; # make it ug+rw use Fcntl 'LOCK_EX'; flock $fh, LOCK_EX; return bless {'fh' => $fh}, ref($class) || $class; } sub release { undef $_[0]{'fh'}; } 1; # End of module