/*
* semshare.c
*
* Created on: 2012-5-6
* Author: sangerhoo
*/
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
union semun{
int val;
struct semid_ds *buf;
unsigned short int array;
struct seminfo *_buf;
};
int main(int argc ,char *argv[])
{
int semid;
pid_t pid;
int proj_id;
key_t key;
int num;
int i,j;
union semun arg;
static struct sembuf acquire ={0,-1,SEM_UNDO};
static struct sembuf release ={0,1,SEM_UNDO};
if(argc != 2)
{
printf("usage: %s num\n",argv[0]);
return -1;
}
num = atoi(argv[1]);
proj_id=2;
key=ftok("/media/sf_workspace/sangerhoo",proj_id);
if(-1 == key)
{
perror("cannot generate the IPC key\n");
return -1;
}
semid=semget(key,1,IPC_CREAT|IPC_EXCL0666);
if(-1==semid)
{
perror("cannot craet seamphore set\n");
return -1;
}
static unsigned short start_val=1;//设置信号量集中的信号量集的初始化为1
arg.array=1;
if(-1==semctl(semid,0,SETVAL,arg))
{
perror("cannot set seamphore set");
return -1;
}
for(i=0;i<num;i++)
{
pid=fork();
if(pid<0)
{
perror("cannot creat new process\n");
return -1;
}
else if(pid==0)
{
semid=semget(key,1,0);
if(-1==semid)
{
perror("cannot let the processs get the acces right\n");
_exit(-1);
}
for(j=0;j<2;j++)
{
if(semop(semid,&acquire,1)==-1)
{
perror("cannot acuquire the resoure\n");
_exit(-1);
}
printf("----enter ther critical section-----\n");
printf("----pid: %ld-----\n",(long)getpid());
sleep(1);
printf("----leave ther critical section-----\n");
printf("----pid: %ld-----\n",(long)getpid());
if(semop(semid,&release,1)==-1)
{
perror("cannot release the resoure\n");
_exit(-1);
}
}
_exit(0);
}
}
for(i=0;i<num;i++)
{
wait(NULL);
}
if(-1==semctl(semid,0,IPC_RMID,0))
{
perror("cannot remove the seamphore set");
return -1;
}
return 0;
}
信号量共享
最新推荐文章于 2022-11-25 21:11:44 发布