Perl 中的 shmctl函数

首页 / Perl入门教程 / Perl 中的 shmctl函数

描述

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

Command 	描述
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,返回0,但如果shmctl()的返回值为0,则返回true。

无涯教程网

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

#!/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();读取其内容。

链接:https://www.learnfk.comhttps://www.learnfk.com/perl/perl-shmctl.html

来源:LearnFk无涯教程网

#!/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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

趣谈网络协议 -〔刘超〕

快速上手Kotlin开发 -〔张涛〕

TensorFlow快速入门与实战 -〔彭靖田〕

从0开发一款iOS App -〔朱德权〕

Elasticsearch核心技术与实战 -〔阮一鸣〕

黄勇的OKR实战笔记 -〔黄勇〕

浏览器工作原理与实践 -〔李兵〕

Go 语言项目开发实战 -〔孔令飞〕

业务开发算法50讲 -〔黄清昊〕

好记忆不如烂笔头。留下您的足迹吧 :)