在内存映射文件中给计数器+1

#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

  

posted @ 2022-10-13 13:46  东宫得臣  阅读(17)  评论(0编辑  收藏  举报