Perl-semget

提供:Dev Guides
移動先:案内検索

Perl semget関数

説明

この関数は、システム関数semget()を使用して、KEYに関連付けられたセマフォIDを返します。 KEYに関連付けられているセマフォを検索します。

構文

以下は、この関数の簡単な構文です-

semget KEY, NSEMS, FLAGS

戻り値

この関数は失敗するとundefを返し、成功すると0を返します。

以下は、セマフォを作成し、その値をインクリメントする基本的な使用法を示すコード例です-

#!/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&を使用して上記のプログラムをバックグラウンドで実行し、次の別のプログラムを記述します。 ここで、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....