资源简介

代码实现了共享内存和信号量的结合,实现进程间通信及其同步问题。通过此代码可以理解共享内存及信号量基本函数的使用及实现原理。

资源截图

代码片段和文件信息

#include “semtest.h“

static int comm_sem( int numsint semflag)
{

    key_t key = ftok(SEM_PATHNAMESEM_PROJ_ID);
    if(key < 0)
    {
        perror(“ftok“);
        return -1;
    }

    int semid = semget(key nums semflag);
    if(semid < 0)
    {
        perror(“semget“);
        return -1;
    }

    return semid;

}


int create_sems(int nums)
{
    return comm_sem(numsIPC_CREAT|IPC_EXCL|666);

}

int get_sems(int nums)
{
    return comm_sem(numsIPC_CREAT);
}

union semun{
    int val;
    struct semid_ds *buf;
    unsigned short *array;
    struct seminfo * __buf;
};


int init_sems(int semid int which int value)
{
    union semun _semun;
    _semun.val = value;
    int ret = semctl(semidwhichSETVAL_semun);
    if(ret < 0)
    {
        perror(“init_sem“);
        return -1;
    }
    return 0;

}


int destory_sems(int semid)
{

    int ret = semctl(semid0IPC_RMIDNULL);
    if(ret <0)
    {
        perror(“rm_sem“);
        return -1;
    }
    return 0;
}

static int comm_sem_op(int semid int which int op)
{
    struct sembuf _sembuf;
    _sembuf.sem_num = which;
    _sembuf.sem_op = op;
    _sembuf.sem_flg = 0;
    return semop(semid&_sembuf1);
}

int P(int semidint which)
{
    return comm_sem_op(semidwhich-1);
}

int V(int semid int which)
{
    return comm_sem_op(semidwhich1);
}


int getnums(int semidint which){
    int ret;
    int value;
    union semun _semun;
    printf(“111 which === %d value === %d\n“which_semun.val);
    ret = semctl(semidwhichGETVAL_semun.val);
    value = _semun.val;
    printf(“222 which === %d value === %d\n“which_semun.val);

    return ret;
}




























































评论

共有 条评论