Perl shmwrite 函数

  • 描述

    shmwrite将位置POS中的SIZE个字节的STRING写入ID指定的共享内存段。SIZE大于STRING的长度。shmwrite追加空字节以填充到SIZE个字节。
  • 句法

    以下是此函数的简单语法-
    
    shmwrite ID, STRING, POS, SIZE
    
  • 返回值

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

    以下是显示其基本用法的示例代码-
     
    # Assume this file name is  writer.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_RMID {0}'        unless defined &IPC_RMID;
    
    $key  = 12345;
    $size = 80;
    $message = "Pennyfarthingale.";
    
    # Create the shared memory segment
    
    $key = shmget($key, $size, &IPC_CREAT | 0777 ) or die "Can't shmget: $!";
    
    # Place a string in itl
    shmwrite( $id, $message, 0, 80 ) or die "Can't shmwrite: $!";
    
    sleep 20;
    
    # Delete it;
    
    shmctl( $id, &OPC_RMID, 0 ) or die "Can't shmctl: $! ";
    
    编写一个读取程序,该程序检索与$ key相对应的内存段,并使用shmwrite();读取其内容。
     
    # Assume this file name is reader.pl
    
    $key = 12345;
    $size = 80;
    
    # Identify the shared memory segment
    $id = shmget( $key, $size, 0777 ) or die "Can't shmget: $!";
    
    # Read its contents itno a string
    shmread($id, $var, 0, $size) or die "Can't shmread: $!";
    
    print $var;
    
    现在,首先在后台运行writer.pl程序,然后在reader.pl中运行,它将产生以下结果。
    
    $perl writer.pl&
    $perl reader.pl
    
    Pennyfrathingale