#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <semaphore.h>
#define SEM_NAME "mysem"
#define FILE_MODE (0600 | 0400)
int
main(int argc, char **argv)
{
int fd, i, nloop, zero = 0;
int *ptr;
sem_t *mutex;
if (argc != 2)
printf("usage: incr2 <#loops>\n");
nloop = atoi(argv[1]);
/* 4open file, initialize to 0, map into memory */
//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 | MAP_ANON, -1, 0);
//close(fd);
/* 4create, initialize, and unlink semaphore */
mutex = sem_open(SEM_NAME, O_CREAT | O_EXCL, FILE_MODE, 1);
sem_unlink(SEM_NAME);
setbuf(stdout, NULL); /* stdout is unbuffered */
if (fork() == 0) { /* child */
for (i = 0; i < nloop; i++) {
sem_wait(mutex);
printf("child: %d\n", (*ptr)++);
sem_post(mutex);
}
exit(0);
}
/* 4parent */
for (i = 0; i < nloop; i++) {
sem_wait(mutex);
printf("parent: %d\n", (*ptr)++);
sem_post(mutex);
}
exit(0);
}
共享内存 --BSD匿名内存映射 (计数加一)
最新推荐文章于 2023-08-13 08:55:27 发布