Linuxではメモリマッピングファイルでカウンタに1を加算し続けます.

1284 ワード

#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
", (*ptr)++); sem_post(mutex); } exit(0); } for(i = 0; i < nloop; i++) { sem_wait(mutex); printf("parent: %d
", (*ptr)++); sem_post(mutex); } exit(0); }