Linux进程间的通信,信号量的使用,生产者消费者

这是简单的生产者消费者问题,只有一个缓冲区

 

#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<linux/sem.h> struct sembuf buf; int Psem(int sem_id); int Vsem(int sem_id); int cache; int main() { union semun arg; int mutexid; int full_sem; int empty_sem; mutexid=semget(IPC_PRIVATE,1,0666|IPC_CREAT); full_sem=semget(IPC_PRIVATE,1,0666|IPC_CREAT); empty_sem=semget(IPC_PRIVATE,1,0666|IPC_CREAT); arg.val=1; if(semctl(mutexid,0,SETVAL,arg)==-1) { perror("set the mutex error/n"); return -1; } arg.val=0; if(semctl(full_sem,0,SETVAL,arg)==-1) { perror("set the full_sem error/n"); return -1; } arg.val=1; if(semctl(empty_sem,0,SETVAL,arg)==-1) { perror("set the empty_sem error/n"); } pid_t pid; pid=fork(); //the father process while(1) { if(pid>0)//the producer { Psem(mutexid); Psem(empty_sem); printf("The producer are producing a product......waiting....."); sleep(1); printf("Done!/n"); Vsem(full_sem); Vsem(mutexid); } else//the consumer { Psem(mutexid); Psem(full_sem); printf("The consumer are consuming a product......waiting......"); sleep(1); printf("Done!/n"); Vsem(empty_sem); Vsem(mutexid); } } return 0; } int Psem(int sem_id) { buf.sem_num=0; buf.sem_op=-1; buf.sem_flg=SEM_UNDO; if(semop(sem_id,&buf,1)==-1) { perror("P failed!/n"); return 0; } return 1; } int Vsem(int sem_id) { buf.sem_num=0; buf.sem_op=1; buf.sem_flg=SEM_UNDO; if(semop(sem_id,&buf,1)==-1) { perror("V failed!/n"); return 0; } return 1; }  

你可能感兴趣的:(Linux进程间的通信,信号量的使用,生产者消费者)