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

perl semop()函數

perl semop()函數例子,semop()函數實例代碼 - 執行定義通過OPSTRING與KEY的信號量ID的信號操作。

語法

semop KEY, OPSTRING


定義和用法

執行定義通過OPSTRING與KEY的信號量ID的信號操作。OPSTRING應該是一個包執行semop結構的數組,每個結構可以生成。

返回值

  • 0 on failure

  • 1 on success

例子

試試下麵的例子:創建一個信號量,讓它的值增加

#!/usr/bin/perl -w

# Assume this file nam eis 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 by www.gitbook.net
$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&到後台,並寫另一個程序。這裡左鍵設置為2的信號和右鍵打印Right和複位信號為0。這種情況持續下去,直到左鍵完成其循環後,它破壞了semctl()的信號:

#!/usr/bin/perl -w
#by www.gitbook.net

# 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....