Perl semget函式



描述

此函式使用系統函式semget()返回與KEY關聯的訊號量ID,即找到與KEY關聯的訊號量。

語法

以下是此函式的簡單語法 -

semget KEY, NSEMS, FLAGS

返回值

此函式在失敗時返回未定義,在成功時返回0但為true。

示例

以下是顯示其基本用法,建立訊號量並遞增其值的示例程式碼 -

#!/usr/bin/perl -w

# Assume this file name is left.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_EXCL {0002000}'  unless defined &IPC_EXCL;
eval 'sub IPC_RMID {0}'        unless defined &IPC_RMID;

$key = 1066;

$| = 1;
$num = 0;
$flag = 0;

# Create the semaphor
$id = semget ( $key, 1, &IPC_EXCL|&IPC_CREAT|0777 ) or 
	die "Can't semget: $!";
foreach( 1..5) {
   $op  = 0;
   $operation = pack( "s*", $num, $op, $flags );
   semop( $id, $operation ) or die "Can't semop: $! ";
   print "Left....\n";
   sleep 1;
   $op = 2;
   $operation = pack( "s*", $num, $op, $flags );
   # add 2 to the semaphore ( now 2 )
   semop( $id, $operation ) or die "Can't semop $! ";
}
semctl (  $id, 0, &IPC_RMID, 0 );

使用$ left.pl和amp;在後臺執行以上程式,並編寫以下另一個程式。在這裡,Left將訊號量設定為2,Right列印Right並將訊號量重置為0。這將持續到Left完成其迴圈,之後它將使用semctl()銷燬訊號量

#!/usr/bin/perl -w

# Assume this file name is right.pl

$key = 1066;

$| = 1;
$num = 0;
$flags = 0;

# Identify the semaphore created by left.
$id = semget( $key, 1, 0 ) or die ("Can't semgt : $!" );

foreach( 1..5) {
   $op = -1;
   $operation =  pack( "s*", $num, $op, $flags );
   # Add -1 to the semaphore (now 1)
   semop( $id, $operation ) or die " Can't semop $!";
   print "Right....\n";
   sleep 1;
   $operation = pack( "s*", $num, $op, $flags );
   # Add -1 to the semaphore (now  0)
   semop( $id, $operation ) or die "Can't semop $! ";
}

執行上述程式碼時,會產生以下結果。現在執行right.pl並得到以下結果 -

Right....
Left....
Right....
Left....
Right....
Left....
Right....
Left....
Right....
Left....
perl_function_references.htm
廣告
© . All rights reserved.