Linux下在内存映射文件中给计数器持续加1
来源:互联网 发布:淘宝卖家体验中心 编辑:程序博客网 时间:2024/06/05 16:33
#include <unistd.h>#include <stdio.h>#include <fcntl.h> /* For O_* constants */#include <sys/stat.h> /* For mode constants */#include <semaphore.h>#include <stdlib.h>#include <sys/mman.h>#define SEM_NAME "chansem"#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)int main(int argc, char** argv){ int i, nloop; int fd, zero = 0; int *ptr; sem_t *mutex; if(argc != 3) { printf("usage: incr2 <#loops>"); } nloop = atoi(argv[2]); fd = open(argv[1], O_RDWR | O_CREAT, FILE_MODE); write(fd, &zero, sizeof(int)); ptr = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); mutex = sem_open(SEM_NAME, O_CREAT | O_EXCL, 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);}