Perl shmctl 函数

描述

此函数控制 ID 引用的共享内存段,使用 CMD 和 ARG。 您将需要导入 IPC::SysV 模块以获取下表中定义的命令令牌。

Command 	Description
IPC_STAT 	Places the current value of each member of
   the data structure associated with ID into
   the scalar ARG

IPC_SET 	Sets the value of the following members o
   of the data structure associated with ID to
   the corresponding values found in the packed
   scalar ARG

IPC_RMID 	Removes the shared memory identifier specified
   by ID from the system and destroys the shared
   memory segment and data structure associated
   with it

SHM_LOCK 	Locks the shared memory segment specified by ID
   in memory

SHM_UNLOCK 	Unlocks the shared memory segment specified by ID

语法

以下是此函数的简单语法 −

shmctl ID, CMD, ARG

返回值

此函数在失败时返回 undef,如果 shmctl() 的返回值为 0,则返回 0 但为真。


示例

以下是显示其基本用法的示例代码 −

#!/usr/bin/perl

# Assume this file name is  writer.pl

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: $! ";

编写一个读取程序,它检索与 $key 对应的内存段并使用 shmread(); 读取其内容。

#!/usr/bin/perl

# Assume this file name is reader.pl

$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;

现在首先在后台运行 writer.pl 程序,然后运行 reader.pl,然后它将产生以下结果。

$perl writer.pl&
$perl reader.pl

Pennyfrathingale

❮ Perl 函数参考