目的:linux 信号量简单尝试
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
typedef int sem_t;
union semun{
int val;
struct semid_ds *buf;
unsigned short *arry;
}arg;
sem_t CreateSem(key_t key, int value)
{
union semun sem;
sem_t semid;
sem.val = value;
semid = semget(key, 1, IPC_CREAT|0660);
if (semid == -1)
{
printf("create error!");
return -1;
}
semctl(semid, 0, SETVAL, sem); // 发出命令 建立value个初始值信号量
return semid;
}
int Sem_P(sem_t semid)
{
struct sembuf sops = {0, +1, IPC_NOWAIT};
return (semop(semid, &sops, 1));
}
int Sem_V(sem_t semid)
{
struct sembuf sops = {0, -1, IPC_NOWAIT};
return (semop(semid, &sops, 1));
}
int GetvalueSem(sem_t semid)
{
union semun sem;
sem.val = 0;
return semctl(semid, 0, GETVAL, sem);
}
void DestroySem(sem_t semid)
{
union semun sem;
sem.val = 0;
semctl(semid, 0, IPC_RMID, sem);
}
int main(void)
{
key_t key;
int semid;
char i;
struct semid_ds buf;
int value = 0;
key = ftok("./server.c",'a');
if (key == -1)
{
printf("ftok error\n");
return 0;
}
semid = CreateSem(key, 100);
for (i = 0; i <= 3; i++)
{
Sem_P(semid);
Sem_V(semid);
}
value = GetvalueSem(semid);
printf("Value:%d\n", value);
DestroySem(semid);
return 0;
}