Perl shmwrite Function



This function writes STRING from the position POS for SIZE bytes into the shared memory segment specified by ID. The SIZE is greater than the length of STRING. shmwrite appends null bytes to fill out to SIZE bytes.


Following is the simple syntax for this function −

shmwrite ID, STRING, POS, SIZE

Return Value

This function returns 0 on failure and 1 on success.


Following is the example code showing its basic usage −


# Assume this file name is

use IPC::SysV;

#use these next two lines if the previous use fails.
eval 'sub IPC_CREAT {0001000}' unless defined &IPC_CREAT;
eval 'sub IPC_RMID {0}'        unless defined &IPC_RMID;

$key  = 12345;
$size = 80;
$message = "Pennyfarthingale.";

# Create the shared memory segment

$key = shmget($key, $size, &IPC_CREAT | 0777 ) or 
			die "Can't shmget: $!";

# Place a string in itl
shmwrite( $id, $message, 0, 80 ) or die "Can't shmwrite: $!";

sleep 20;

# Delete it;

shmctl( $id, &OPC_RMID, 0 ) or die "Can't shmctl: $! ";

Write a reader program which retrieves the memory segment corresponding to $key and reads its contents using shmread();.


# Assume this file name is

$key = 12345;
$size = 80;

# Identify the shared memory segment
$id = shmget( $key, $size, 0777 ) or die "Can't shmget: $!";

# Read its contents itno a string
shmread($id, $var, 0, $size) or die "Can't shmread: $!";

print $var;

Now First run program in background and then then it will produces the following result.