#include <stdio.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <stdlib.h>
#include <error.h>
#include <string.h>
int sem_id;
int deng[4]={0};
void creat_sem();
int get_key();
void init_sem();
void request_sem(int nsem_id);
void release_sem(int nsem_id);
void sem_del();
void print();
int main()
{
atexit(sem_del);
creat_sem();
init_sem();
printf("\033[0;0H\033[2J");
do
{
release_sem(0);
release_sem(3);
request_sem(1);
request_sem(2);
print();
request_sem(0);
request_sem(3);
release_sem(1);
release_sem(2);
print();
}while(1);
}
void creat_sem()
{
key_t key=get_key();
sem_id=semget(key,4,IPC_CREAT|0600);
if(sem_id==-1)
{
perror("semget error");
exit(1);
}
}
int get_key()
{
int key;
key=ftok(".",'a');
return key;
}
void init_sem()
{
int i;
int val=1;
int ret;
for(i=0;i<4;i++)
{
ret=semctl(sem_id,i,SETVAL,val);
if(ret==-1)
{
perror("semctl error");
exit(1);
}
}
}
void request_sem(int nsem_id)
{
struct sembuf sbuf;
sbuf.sem_num=nsem_id;
sbuf.sem_op=-1;
sbuf.sem_flg=IPC_NOWAIT;
//printf("索引%d申请资源\n",nsem_id);
if(semop(sem_id,&sbuf,1)==-1)
{
perror("request semop error");
exit(1);
}
//printf("\033[32m%d--->绿灯\t\033[0m",nsem_id);
deng[nsem_id]=1;
}
void release_sem(int nsem_id)
{
struct sembuf sbuf;
sbuf.sem_num=nsem_id;
sbuf.sem_op=1;
sbuf.sem_flg=IPC_NOWAIT;
//printf("索引%d释放资源\n",nsem_id);
if(semop(sem_id,&sbuf,1)==-1)
{
perror("release semop error");
exit(1);
}
//printf("\033[31m%d--->红灯\t\033[0m",nsem_id);
deng[nsem_id]=0;
}
void sem_del()
{
if(semctl(sem_id,0,IPC_RMID,0)==-1)
{
perror("rmid error");
exit(1);
}
}
void print()
{
int i=0;
char sstr[4][20]={'\0'};
char *str[4]={sstr[0],sstr[1],sstr[2],sstr[3]};
for(i=0;i<4;i++)
{
if(deng[i]==1)
{
strcpy(str[i],"\033[32m绿\033[0m");
}
else if(deng[i]==0)
{
strcpy(str[i],"\033[31m红\033[0m");
}
}
for(i=4;i>=0;i--)
{
printf("\033[u\033[s 北 \n");
printf(" time:%d | %s | \n",i,str[0]);
printf(" | | \n");
printf(" | | \n");
printf(" | | \n");
printf(" ----------------- ----------------\n");
printf(" \n");
printf("西 %s %s 东 \n",str[1],str[2]);
printf(" \n");
printf(" ----------------- ----------------\n");
printf(" | | \n");
printf(" | | \n");
printf(" | | \n");
printf(" | %s | \n",str[3]);
printf(" 南 \n");
//if(i!=0)
sleep(1);
}
}