[技術] Linux Semaphores PV操作程式
Written on 8:36 下午 by Yu Lai
From: http://blog.csdn.net/lcrystal623/archive/2007/03/16/1531189.aspx
多程序實現PV操作,子程序為生產者,倉庫可以容納5個物品,每次檢查倉庫是否滿,若不滿則執行P操作,生產一個物品放入倉庫。父程序檢驗倉庫是否空,若不空則消耗一個物品,執行V操作。sleep函數是隨即設置生產或消費所用時間。
程式主要目的是展示Semaphores的使用,以備以後參考。
#include <stdio.h>If you enjoyed this post Subscribe to our feed
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/types.h>
int main()
{
int semID,ret,num;
int sleepTime;
struct sembuf buf;
semID = semget(IPC_PRIVATE,1,0666);
if(semID < 0)
{
printf("建立Semaphores出錯\n");
exit(1);
}
if(fork() == 0)
{
while(1)
{
num = semctl(semID,0,GETVAL,NULL);
if(num < 5)
{
sleepTime = rand() % 5;
sleep(sleepTime);
buf.sem_num = 0;
buf.sem_op = 1;
buf.sem_flg = 0;
ret = semop(semID,&buf,1);
if(ret < 0)
{
printf("執行P操作失敗!\n");
exit(1);
}
num = semctl(semID,0,GETVAL,NULL);
printf("生產者生產了一個物品放入了倉庫...倉庫中現有物品%d個\n",num);
}
}
}
else
{
while(1)
{
num = semctl(semID,0,GETVAL,NULL);
if(num > 0)
{
sleepTime = rand() % 5;
sleep(sleepTime);
buf.sem_num = 0;
buf.sem_op = -1;
buf.sem_flg = 0;
ret = semop(semID,&buf,1);
if(ret < 0)
{
printf("執行V操作失敗!\n");
exit(1);
}
num = semctl(semID,0,GETVAL,NULL);
printf("消費者從倉庫中消耗了一個物品...倉庫中現有物品%d個\n",num);
}
}
}
return 0;
}