I think choroba was suggesting this (untested):
$sem = IPC::Semaphore->new( 4321, 1, S_IRUSR | S_IWUSR | IPC_CREAT | I
+PC_EXCL );
if ( $sem ) {
# New semaphore
print "Semaphore created\n";
$sem->setval(0,1);
print "Semaphore initialised\n";
} else {
# Semaphore already exists so just open it
print "Semaphore already exists - just open it\n";
$sem = IPC::Semaphore->new( 4321, 1, S_IRUSR | S_IWUSR );
+ );
}
print "Locking other threads\n";
$sem->op(0, -1, SEM_UNDO);
But there is still a race condition, where the second process can attach to and use the semaphore after the first process creates it and before the first process initializes it.