Perl semop 函数



  • 描述

    semop 该函数对与KEY关联的信号灯ID执行由OPSTRING定义的信号灯操作。OPSTRING应该是semop结构的压缩数组,并且可以使用每个结构生成。
  • 句法

    以下是此函数的简单语法-
    
    semop KEY, OPSTRING
    
    
  • 返回值

    如果失败,此函数返回0,如果成功,则返回1。
  • 示例

    以下是显示其基本用法的示例代码-
     
    # 这个文件名为 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”输出右信号并将信号量重置为0。这一直持续到“left”完成其循环,然后使用semop()销毁信号量。
     
    # 这个文件名为 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....