共同 增加同一个变量的值 最终输出19999
#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 != 3)
printf("usage: incr2 <pathname> <#loops>\n");
nloop = atoi(argv[2]);
/* 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, fd, 0);
close(fd);
/* 4create, initialize, and unlink semaphore */
mutex = sem_open(SEM_NAME, O_CREAT | O_EXCL, FILE_MODE, 1);
sem_unli