相同机器进程间通信-信号量

高效的进程间通信
共享内存 — 实时性最好

信号量

#include "io.h"
#include 


int init(int semnums, int value)
{
    key_t key = ftok("/etc", 100);
    int semid = -1;

    semid = semget(key, semnums, 0600 | IPC_CREAT | IPC_EXCL);
    if (semid < 0) {
        /*已经存在*/
        semid = semget(key, semnums, 0600);
        if (semid < 0) exit(0);
        return semid;

    }

    union semun {
        int val;
        struct semid_ds* buf;
        unsigned short * array;
    } va;
    va.array = (unsigned short *)calloc(semnums, sizeof(unsigned short));
    int i = 0;
    for (i  = 0; i < semnums; i++) {
        va.array[i] = value;
    }
    semctl(semid, semnums, SETALL, va);
    free(va.array);
    va.array = NULL;
    return semid;
}

void D(int semid)
{
    semctl(semid, 0, IPC_RMID);
}

int P(int semid, int nums, int val)/*-,dierge参数是第几个*/
{
    struct sembuf buf[1] = {
        {nums, -val, SEM_UNDO}
    };
    if (semop(semid, buf, 1) < 0) {
        fprintf(stderr, "semop + error:%s\n", strerror(errno));
        return -1;
    }
    return 0;
}

int V(int semid, int nums, int val)/*+*/
{
    struct sembuf buf[1] = {
        {0, +val, SEM_UNDO}
    };
    if (semop(semid, buf, sizeof(buf) / sizeof(struct(sembuf))) < 0) {
        fprintf(stderr, "semop - error:%s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void display(int semid, int nums)
{
    union semun {
        int val;
        struct semid_ds* buf;
        unsigned short* array;
    } buffer;
    buffer.array = (unsigned short *) calloc (nums, sizeof(unsigned short));
    semctl(semid, nums, GETALL, buffer);
    int i = 0;
    for (i = 0; i < nums; i++) {
        printf("%d ", buffer.array[i]);
    }
    printf("\n");
    free(buffer.array);
    buffer.array = NULL;
    semctl(semid, nums, GETALL, buffer);

}

int main(int argc, char const *argv[])
{
    int sid = init(10, 1);
    display(sid, 10);
    P(sid, 4, 1);
    display(sid, 10);
    P(sid, 4, 1);
    D(sid);
    return 0;
}

你可能感兴趣的:(系统编程,Linux)