zoukankan      html  css  js  c++  java
  • 使用IPC_PRIVATE信号量简单的例子

    Linux 信号量的API都定义在sys/sem.h头文件中,主要包含3个系统调用:semget、semop、semctl。

    附上代码:

    #include <sys/sem.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/wait.h>
    
    union semun
    {
         int val;                  
         struct semid_ds* buf;     
         unsigned short int* array;
         struct seminfo* __buf;    
    };
    
    void pv( int sem_id, int op )
    {
        struct sembuf sem_b;
        sem_b.sem_num = 0;
        sem_b.sem_op = op;
        sem_b.sem_flg = SEM_UNDO;
        semop( sem_id, &sem_b, 1 );
    }
    
    int main( int argc, char* argv[] )
    {
        int sem_id = semget( IPC_PRIVATE, 1, 0666 );
    
        union semun sem_un;
        sem_un.val = 1;
        semctl( sem_id, 0, SETVAL, sem_un );
    
        pid_t id = fork();
        if( id < 0 )
        {
            return 1;
        }
        else if( id == 0 )
        {
            printf( "child try to get binary sem
    " );
            pv( sem_id, -1 );
            printf( "child get the sem and would release it after 5 seconds
    " );
            sleep( 5 );
            pv( sem_id, 1 );
            exit( 0 );
        }
        else
        {
            printf( "parent try to get binary sem
    " );
            pv( sem_id, -1 );
            printf( "parent get the sem and would release it after 5 seconds
    " );
            sleep( 5 );
            pv( sem_id, 1 );
        }
    
        waitpid( id, NULL, 0 );
        semctl( sem_id, 0, IPC_RMID, sem_un );
        return 0;
    }
  • 相关阅读:
    Http请求头与响应头
    获取ip位置方法
    简单的Http Server实现
    HTTP
    long、int与byte数组之间的相互转换
    GlusterFS简单配置
    创建线程池
    网络编程socket
    面向对象-进阶篇
    面向对象-初级篇
  • 原文地址:https://www.cnblogs.com/hgrical/p/6105555.html
Copyright © 2011-2022 走看看