实现一个简单的进程同步程序
#include <stdio.h> #include <unistd.h> #include <sys/mman.h> #include <semaphore.h> int *pbuff=0; sem_t *s1,*s2; int main() { //printf("Hello World! "); int pid=0; int tc,tf; pbuff=(int *)mmap(0,sizeof(int),PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON,-1,0); s1=(sem_t *)mmap(0,sizeof(sem_t),PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON,-1,0); s2=(sem_t *)mmap(0,sizeof(sem_t),PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON,-1,0); *pbuff=0; sem_init(s1,1,1); sem_init(s2,1,0); pid=fork(); if(pid==0) { l: tc=*pbuff; tc++; sem_wait(s1); *pbuff=tc; sem_post(s2); if(tc>=10) return 0; else goto l; } else if(pid>0) { L: sem_wait(s2); tf=*pbuff; sem_post(s1); if(tf>0) printf("%d ",tf); if(tf==10) return 0; else goto L; } return 0; }