示例
/*************************************************************************
> File Name: sema.c
> Author: XXDK
> Email: v.manstein@qq.com
> Created Time: Mon 20 Mar 2017 04:22:33 PM CST
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/types.h>
#include<fcntl.h>
union semnu {
int val;
};
int main(int argc, const char* argv[])
{
int semid;
key_t key;
union semnu sema, semb;
key = ftok("./.", 100);
semid = semget(key, 2, IPC_CREAT|IPC_EXCL|0666);
if(semid == -1) {
if(errno == EEXIST) {
semid = semget(key, 2, 0666);
} else {
perror("fail to semget");
}
} else {
sema.val =20;
semctl(semid, 0, SETVAL, sema);
semb.val = 50;
semctl(semid, 1, SETVAL, semb);
}
struct sembuf sbufa, sbufb;
sbufa.sem_num = 0;
sbufa.sem_op = -5;
sbufa.sem_flg = 0;
semop(semid, &sbufa, 1);
sbufb.sem_num = 0;
sbufb.sem_op = -5;
sbufb.sem_flg = 0;
semop(semid, &sbufb, 1);
printf("smea: %d\n", semctl(semid, 0, GETVAL));
printf("smea: %d\n", semctl(semid, 1, GETVAL));
return 0;
}