• perl semctl()函数


    转自:http://www.yiibai.com/perl/perl_semctl.html

    描述

    perl semctl()函数例子,semctl()函数实例代码 - 控制系统V信号量。


     

    语法

    semctl ID, SEMNUM, CMD, ARG

    定义和用法

    控制系统V信号量。 你将需要进口IPCSysV的模块,以获得正确的定义CMD。 该函数调用系统调用semctl()函数。

    返回值

    • undef - 失败时

    • 0 但真(true)成功时

    例子

    试试下面的例子:创建一个信号量,增加它的值

    #!/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.yiibai.com
    $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信号和右键打印右键和复位信号为0。这种情况持续下去,直到左键完成其循环后,它破坏了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....
  • 相关阅读:
    多说社交评论插件学习《一》
    《转》每天起床时,优秀创业者都会问自己这3个问题
    老赵面试题参考答案(二)《转》
    老赵面试题参考答案(一)《转》
    20个开源项目托管站点推荐
    .NET面试题(二)
    .NET面试题(一)
    Python笔记(28)-----继承
    pytorch实战(2)-----回归例子
    深度学习之入门Pytorch(1)------基础
  • 原文地址:https://www.cnblogs.com/yiibaicom/p/2666934.html
Copyright © 2020-2023  润新知