Linuxc之信号量集合

源代码:
receive.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/sem.h>
int main()
{
 int semid,semval1,semval2;
 key_t key;
 key=ftok("./tt",1);
 semid=semget(key,2,IPC_CREAT|0666);
 int val;
 printf("等待接收----\n");
 while(1)
 {
  semval1=semctl(semid,0,GETVAL,0);
  semval2=semctl(semid,1,GETVAL,1);
  if(semval1==semval2)
  {
   printf("信号量1==信号量2\n");
   printf("hello\n");
   break;
  }
 }
 return 0;
}

send.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>

 
int main(int argc,char const *argv[])
{
 int semid;
 key_t key;
 key=ftok("./tt",1);
 semid=semget(key,2,IPC_CREAT|0666);
 if(semid<0)
 {
  printf("semget error\n");
  exit(1);
 }
 typedef union semnu{
  int value;
  struct semid_ds *buf;
  unsigned short int *array;
  struct seminfo *nbuf;
 }sem;
 sem sem0,sem1;
 sem0.value=1;
 sem1.value=3;
 semctl(semid,0,SETVAL,sem0);
 semctl(semid,1,SETVAL,sem1);
 semctl(semid,0,GETVAL);
 semctl(semid,1,GETVAL);
 struct sembuf buf_p[2];
 buf_p[0].sem_num = 0;
 buf_p[0].sem_op =1;
 buf_p[0].sem_flg = (IPC_NOWAIT|SEM_UNDO);
 
 buf_p[1].sem_num = 1;
 buf_p[1].sem_op = -1;
 buf_p[1].sem_flg = (IPC_NOWAIT|SEM_UNDO);
 int i=1;
while(1){
 int val0,val1;
 val0=semctl(semid,0,GETVAL);
 val1=semctl(semid,1,GETVAL);
 printf("第%d次\n",i);
 i++;
 printf("信号量1=%d  信号量2= %d\n\n",val0,val1);
 if(val0==val1)
 {
  printf("信号量1==信号量2------结束退出\n");
  break;
 }
 sleep(3);
 semop(semid,buf_p,2);
}
 return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37192076/article/details/80777945