大雪给解决一下

bm1408 2006-05-12 02:43:20
同步的时候,感到乱七八糟的
#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();
}

}


}
...全文
103 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
x86 2006-05-12
  • 打赏
  • 举报
回复
代码太多, 今天没法给你看了。多打一些调试信息看看吧。

23,216

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧