计数器和信号量都在共享内存区中
#include <stdio.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <semaphore.h> #include <stdlib.h> #include <sys/mman.h> const int maxline=4096; struct shared{ sem_t mutex; int count; }shared; int main(int argc, char **argv) { int fd, i, nloop; struct shared *ptr; char errbuff[maxline]; if(argc!=3) { fprintf(stderr, "usage: ./a.out <pathname> <#nloops>\n"); exit(-1); } nloop=atoi(argv[2]); fd=open(argv[1], O_RDWR|O_CREAT, 0644); if(write(fd, &shared, sizeof(struct shared)) != sizeof(struct shared)) { fprintf(stderr, "write error.\n"); exit(-1); } if((ptr=mmap(NULL, sizeof(struct shared), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0))==MAP_FAILED) { fprintf(stderr, "mmap error.\n"); exit(-1); } close(fd); if(sem_init(&ptr->mutex, 1, 1)==-1) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "sem_init error: %s\n", errbuff); exit(-1); } setbuf(stdout, NULL); if(fork()==0) { for(i=0;i<nloop;i++) { sem_wait(&ptr->mutex); printf("child: %d\n", ptr->count++); sem_post(&ptr->mutex); } exit(0); } for(i=0;i<nloop;i++) { sem_wait(&ptr->mutex); printf("parent: %d\n", ptr->count++); sem_post(&ptr->mutex); } exit(0); }