⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 server.c

📁 Linux大学上机源码学习
💻 C
字号:
#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>#include <sys/shm.h>#include <stdio.h>#include <string.h>union semun{  int val;  struct semid_ds *buf;  unsigned short *array;}; int open_semaphore_set(int keyval,int numsems)   { int sid;     sid=semget(keyval,numsems,IPC_CREAT|0666);     return sid;  }int get_sem_val(int sid,int semnum){ return(semctl(sid,semnum,GETVAL,0));}void init_a_semaphore(int sid,int semnum,int initval){ union semun semopts;  semopts.val=initval;  semctl(sid,semnum,SETVAL,semopts);}/*void init_all_semaphore(int sid,int val_array[]){ union semun semopts;  semopts.array=val_array;  semctl(sid,0,SETALL,semopts);}*/int changemode(int sid,char *mode){ int rc;  union semun semopts;  struct semid_ds mysemds;  semopts.buf=&mysemds;  if((rc=semctl(sid,0,IPC_STAT,semopts))==-1)     return -1;  sscanf(mode,"%o",&semopts.buf->sem_perm.mode);  return(semctl(sid,0,IPC_SET,semopts)); }int rm_semaphore(int sid){ return(semctl(sid,0,IPC_RMID,0));}int semaphore_P(int sem_id){ struct sembuf sb;  sb.sem_num=0;  sb.sem_op=-1;  sb.sem_flg=SEM_UNDO;  semop(sem_id,&sb,1);  return 1;}int semaphore_V(int sem_id){ struct sembuf sb;  sb.sem_num=0;  sb.sem_op=1;  sb.sem_flg=SEM_UNDO;  semop(sem_id,&sb,1);  return 1;}main(){struct exchange{    char buf[BUFSIZ+80];    int seq; }*shm; int shmid; unsigned char *retval; int producer,consumer,i; consumer=open_semaphore_set(1234,1); init_a_semaphore(consumer,0,1); producer=open_semaphore_set(4321,1); init_a_semaphore(producer,0,0); shmid=shmget(5678,sizeof(struct exchange),0666|IPC_CREAT); retval=shmat(shmid,(unsigned char *)0,0); shm=(struct exchange *)retval; for(i=0;;i++){   semaphore_P(producer);   printf("data receive:%s,sequence:%d\n",shm->buf,shm->seq);   semaphore_V(consumer);   if(strncmp(shm->buf,"end",3)==0)       break;}rm_semaphore(producer);rm_semaphore(consumer);shmctl(shmid,IPC_RMID,0);exit(0);}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -