mmap
to have shared memory so as to share a variable amongst several processes. That's because Perl would reallocate your string when you weren't wanting it to.
Here's a small example showing shared memory usage.
$IPC_PRIVATE = 0; $IPC_RMID = 0; $size = 2000; $key = shmget($IPC_PRIVATE, $size , 0777 ); die unless defined $key;
$message = "Message #1"; shmwrite($key, $message, 0, 60 ) || die "$!"; shmread($key,$buff,0,60) || die "$!";
print $buff,"\n";
print "deleting $key\n"; shmctl($key ,$IPC_RMID, 0) || die "$!";
Here's an example of a semaphore:
$IPC_KEY = 1234; $IPC_RMID = 0; $IPC_CREATE = 0001000; $key = semget($IPC_KEY, $nsems , 0666 | $IPC_CREATE ); die if !defined($key); print "$key\n";
Put this code in a separate file to be run in more than one process. Call the file take:
# create a semaphore
$IPC_KEY = 1234; $key = semget($IPC_KEY, 0 , 0 ); die if !defined($key);
$semnum = 0; $semflag = 0;
# 'take' semaphore # wait for semaphore to be zero $semop = 0; $opstring1 = pack("sss", $semnum, $semop, $semflag);
# Increment the semaphore count $semop = 1; $opstring2 = pack("sss", $semnum, $semop, $semflag); $opstring = $opstring1 . $opstring2;
semop($key,$opstring) || die "$!";
Put this code in a separate file to be run in more than one process. Call this file give:
# 'give' the semaphore # run this in the original process and you will see # that the second process continues
$IPC_KEY = 1234; $key = semget($IPC_KEY, 0, 0); die if !defined($key);
$semnum = 0; $semflag = 0;
# Decrement the semaphore count $semop = -1; $opstring = pack("sss", $semnum, $semop, $semflag);
semop($key,$opstring) || die "$!";