当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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 semctl Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。