#include <stdio.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <semaphore.h> #include <stdlib.h> #include <sys/mman.h> #define SEM_NAME "mysem" const int maxline=4096; int main(int argc, char **argv) { int fd, i, nloop, zero=0; int *ptr; sem_t *mutex; 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, &zero, sizeof(int)) != sizeof(int)) { fprintf(stderr, "write error.\n"); exit(-1); } if((ptr=mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0))==MAP_FAILED) { fprintf(stderr, "mmap error.\n"); exit(-1); } close(fd); if((mutex=sem_open(SEM_NAME, O_CREAT|O_EXCL, 0644, 1))==SEM_FAILED) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "sem_open error: %s\n", errbuff); exit(-1); } sem_unlink(SEM_NAME); setbuf(stdout, NULL); if(fork()==0) { for(i=0;i<nloop;i++) { sem_wait(mutex); printf("child: %d\n", (*ptr)++); sem_post(mutex); } exit(0); } for(i=0;i<nloop;i++) { sem_wait(mutex); printf("parent: %d\n", (*ptr)++); sem_post(mutex); } exit(0); }
运行结果如下:
$ gcc incr2.c -pthread $ ./a.out tmp 5 parent: 0 parent: 1 parent: 2 child: 3 child: 4 child: 5 child: 6 parent: 7 parent: 8 child: 9
标签:parent,映射,int,计数器,fd,内存,child,fprintf,include From: https://www.cnblogs.com/donggongdechen/p/16787920.html