Perl 中的 semctl函数

首页 / Perl入门教程 / 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 );

Run the above program in background using $left.pl& and write following another program. Here Left sets the semaphore to 2 and Right prints Right and resets the semaphore to 0. This continues until Left finishes its loop after which it destroys the semaphore with 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....

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术与商业案例解读 -〔徐飞〕

Vue开发实战 -〔唐金州〕

分布式系统案例课 -〔杨波〕

技术管理案例课 -〔许健〕

WebAssembly入门课 -〔于航〕

实用密码学 -〔范学雷〕

Web漏洞挖掘实战 -〔王昊天〕

李智慧 · 高并发架构实战课 -〔李智慧〕

后端工程师的高阶面经 -〔邓明〕

好记忆不如烂笔头。留下您的足迹吧 :)