當前位置:首頁 » Perl » perl shmctl()函數

perl shmctl()函數

perl shmctl()函數例子,shmctl()函數實例代碼 -

語法

shmctl ID, CMD, ARG


定義和用法

控製共享內存段中所提到的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

返回值

  • undef - 失敗時

  • 0 但為真(true)如果shmctl()返回值是0.

例子

試試下麵的例子:

#!/usr/bin/perl
#by www.gitbook.net
# 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
#by www.gitbook.net

$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