同一マシンプロセス間通信-信号量


効率的なプロセス間通信共有メモリ:リアルタイム性が最も優れている
しんごうりょう
#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
"
, 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
"
, 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("
"
); 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; }