描述
此函數控製 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 semget用法及代碼示例
- Perl semop用法及代碼示例
- Perl setpriority用法及代碼示例
- Perl send用法及代碼示例
- Perl setpwent用法及代碼示例
- Perl sethostent用法及代碼示例
- Perl setgrent用法及代碼示例
- Perl setsockopt用法及代碼示例
- Perl seekdir用法及代碼示例
- Perl setprotoent用法及代碼示例
- Perl setnetent用法及代碼示例
- Perl setservent用法及代碼示例
- Perl select用法及代碼示例
- Perl sin()用法及代碼示例
- Perl split用法及代碼示例
- Perl shmctl用法及代碼示例
- Perl splice用法及代碼示例
注:本文由純淨天空篩選整理自 Perl semctl Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。