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

perl shmwrite()函數

perl shmwrite()函數例子,shmwrite()函數實例代碼 - 從位置POS的SIZE個字節寫入字符到指定ID的共享內存段。

語法

shmwrite ID, STRING, POS, SIZE


定義和用法

從位置POS的SIZE個字節寫入字符到指定ID的共享內存段。大小SIZE大於字符串的長度。 shmwrite追加空字節填充的大小字節。

返回值

  • 0 on failure

  • 1 on success

例子

試試下麵的例子:

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

# 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