Perl semctl 函式



說明

此函式控制 System V 訊號量。您需要匯入 IPC:SysV 模組才能獲取 CMD 的正確定義。該函式呼叫系統 semctl() 函式。

語法

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

semctl ID, SEMNUM, CMD, ARG

返回值

此函式在失敗時返回 undef,在成功時返回 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 semaphore
$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& 以後臺形式執行以上程式,並編寫另一個程式。此處,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....
Left....
Right....
Left....
Right....
Left....
Right....
Left....
Right....
Left....
perl_function_references.htm
廣告
© . All rights reserved.