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

📄 client.c

📁 Linux大学上机源码学习
💻 C
字号:
#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>#include <sys/shm.h>#include <sys/types.h>#include <stdio.h>#include <string.h>union semun{  int val;  struct semid_ds *buf;  unsigned short *array;} ;//int kk; /*int open_semaphore_set(key_t 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; char readbuf[256]; consumer=semget(1234,1,IPC_CREAT|0666);//(ftok("consumer",0),1);// init_a_semaphore(consumer,0,1); producer=semget(4321,1,IPC_CREAT|0666);//(ftok("producer",0),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(consumer);   printf("enter some text:");   fgets(readbuf,200,stdin);   shm->seq=i;   sprintf(shm->buf,"%s message recevied from %d",readbuf,getpid());   semaphore_V(producer);   if(strncmp(readbuf,"end",3)==0)       break;}exit(0);}

⌨️ 快捷键说明

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