//----------- client.c ----------- //author: zengli //email: zengl@ics.ict.ac.cn #include #include #include #include #define SEGSIZE 1024 union semun { int val; struct semid_ds* buf; ushort* array; }; //打印程序执行时间 void secondpass(){ static long start=0; time_t timer; if (start == 0){ timer=time(NULL); start=(long)timer; } printf("second:%ld \n" ,(long)(time(NULL))-start); } int sem(key_t key){ union semun sem ; int semid; sem.val=0; semid=semget(key,0,0); if (semid ==-1){ printf("get semaphore error\n"); exit(-1); } return semid; } //等待信号量变成 0 void waitv(int semid){ struct sembuf sops={0,0,0}; semop(semid,&sops,1); } int main(){ key_t key; int shmid,semid; char* shm; char msg[100]; int i; key=ftok("/" , 0); shmid=shmget(key,SEGSIZE,0); if(shmid==-1){ printf("get shared momery error\n" ); return -1; }else printf("get shared monmery successfully\n"); shm=(char*)shmat(shmid,0,0); if((int)shm ==-1){ printf("attach shared momery error...from server\n" ); return -1; }else printf("attach shared momery successfully...from server\n"); semid=sem(key); for(i=0;i< 3;i++){ sleep(2); waitv(semid); printf("the msg get is: %s\n" ,shm); secondpass(); } shmdt(shm); printf("OK. Please be reminded that you are my everything.\n"); return 0; } //----------- server.c ----------- #include #include #include #define SEGSIZE 1024 #define READTIME 1 union semun { int val; struct semid_ds * buf; ushort * array; }; //生成信号量 int sem(key_t key){ union semun sem ; int semid; sem.val=0; semid=semget(key,1,IPC_CREAT|0666); if (semid ==-1){ printf("create semaphore error\n" ); exit(-1); } //初始化信号量 semctl(semid,0,SETVAL,sem); return semid; } //删除信号量 void d_sem(int semid){ union semun sem ; sem.val=0; semctl(semid,0,IPC_RMID,0); } int p(int semid){ struct sembuf sops={0,+1,IPC_NOWAIT}; return(semop(semid,&sops,1)); } int v(int semid){ struct sembuf sops={0,-1,IPC_NOWAIT}; return(semop(semid,&sops,1)); } int main(){ key_t key; int shmid,semid; char* shm; char msg[11]="wendywood"; char i; struct semid_ds buf; key=ftok("/" , 0); shmid=shmget(key,SEGSIZE,IPC_CREAT|0604); if(shmid ==-1){ printf("create shared momery error\n" ); return -1; }else printf("create shared monery successfully\n"); shm=(char*)shmat(shmid,0,0); if((int)shm ==-1){ printf("attach shared momery error\n" ); return -1; } else printf("attach shared monery successfully\n"); semid=sem(key); for(i=0;i<=3;i++){ sleep(1); p(semid); sleep(READTIME); msg[9]= '0'+i; memcpy(shm,msg,sizeof(msg)); printf("msg=%s\n",msg); sleep(5); v(semid); } shmdt(shm); shmctl(shmid,IPC_RMID,&buf); d_sem(semid); return 0; }