大雪给解决一下
同步的时候,感到乱七八糟的
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include<sys/sem.h>
const GP_KEY = 55555;
#define sem_key 6998l
#define SEM_PERM 0600
static struct sembuf LockOp[2]=
{
0,0,0,
0,1,SEM_UNDO
};
static struct sembuf UnlckOp[1]=
{
0,-1,(IPC_NOWAIT|SEM_UNDO)
};
struct student
{
unsigned int nid;
char name[20];
};
struct stu_sys
{
struct student p[3];
}*STU;
int shmid,semid;
void LockSem()
{
if((semid=semget(sem_key,1,SEM_PERM|IPC_CREAT))==-1)
{
perror ("LockSem() Get semaphore error");
}
if(semop(semid,&LockOp[0],2)==-1)
{
perror("LockSem() Lock semaphore error");
}
}
/*解锁信号灯*/
void UnlockSem()
{
if((semid=semget(sem_key,1,SEM_PERM|IPC_CREAT))==-1)
{
perror("UnlkSem() Get semaphore error");
}
if(semop(semid,&UnlckOp[0],1)==-1)
{
perror("UnlkSem() Unlock semaphore error");
}
}
unsigned char *initshm(key_t key ,int size)
{
unsigned char *retval;
if((shmid = shmget(key,size,0666|IPC_CREAT))==-1)
{
printf("shmget failed \n");
exit(-1);
}
if((retval = shmat(shmid,(unsigned char *)0,0)) ==(unsigned char *)-1)
{
printf("shmat failed \n");
exit(-1);
}
return retval;
}
unsigned char *findid(int id )
{
STU = (struct stu_sys *) initshm(GP_KEY,sizeof(struct stu_sys));
if( STU->p[0].nid !=0)
{
printf("sorry! shared memory is empty\n");
exit(-1);
}
else
{
for(int i =1;i<3;i++)
if(STU->p[i].nid == id)
return STU->p[i].name;
}
return NULL;
}
int main()
{
STU = (struct stu_sys *) initshm(GP_KEY,sizeof(struct stu_sys));
if( STU->p[0].nid ==0)
{
STU->p[0].nid = 0;
strcpy(STU->p[0].name,"nobady");
STU->p[1].nid = 1002;
strcpy(STU->p[1].name,"wang");
STU->p[2].nid = 1005;
strcpy(STU->p[2].name,"zhang");
shmdt(STU);
}
else
{
printf("己读入shared memory \n");
}
pid_t cld;
if( (cld=fork())==0)
{
LockSem();
STU = (struct stu_sys *) initshm(GP_KEY,sizeof(struct stu_sys));
unsigned char *p = findid(1002);
printf("\nfind id is 1002 and name is %s\n",p);
shmdt(STU);
sleep(6);
UnlockSem();
}
for(int i =0;i<4;i++)
{
if((cld=fork())==0)
{
LockSem();
STU = (struct stu_sys *) initshm(GP_KEY,sizeof(struct stu_sys));
for(int i = 1;i<3;i++)
{
printf("\n%d\n",STU->p[i].nid);
printf("%s\n",STU->p[i].name);
}
shmdt(STU);
printf("\n %d",i);
UnlockSem();
}
}
}