While System V IPC isn't so widely used as sockets, it still has some
interesting uses. You can't, however, effectively use SysV IPC or
Berkeley 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 that 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 that 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 "$!";
The SysV IPC code above was written long ago, and it's definitely clunky
looking. It should at the very least be made to use strict
and
require "sys/ipc.ph"
. Better yet, perhaps someone should create an
IPC::SysV
module the way we have the Socket
module for normal
client-server communications.
(... time passes)
Voila! Check out the IPC::SysV modules written by Jack Shirazi. You can
find them at a CPAN store near you.
overview /
signals /
fifos /
pipes /
safe-pipes /
open2 /
sockets /
AF_INET /
AF_UNIX /
udp /