共享内存创建实现卖票系统
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <string.h>
#include <time.h>
typedef struct _shm
{
int flag;
int ticket;
}SHM;
void sellTicket(SHM* pshm)
{
while(1)
{
int time=rand()%10+1;
usleep(time*100000);
if(pshm->flag==1)
{
pshm->flag=0;
if(pshm->ticket==0)
{
pshm->flag=1;
break;
}
printf("卖掉一张票,座位号是:%d\n",pshm->ticket);
pshm->ticket--;
pshm->flag=1;
}
}
}
int main(int argc,char **argv)
{
srand((unsigned int)time(NULL));
int shmid=shmget((key_t)1234,sizeof(SHM),0666|IPC_CREAT);
if(shmid==-1)
{
perror("shmget");
return -1;
}
SHM* pshm=(SHM*)shmat(shmid,NULL,0);
if(pshm==(SHM*)-1)
{
perror("shmat");
return -1;
}
if(argc==2)
{
pshm->flag=1;
pshm->ticket=100;
}
sellTicket(pshm);
if(argc==2)
{
shmctl(shmid,IPC_RMID,NULL);
}
return 0;
}