计数器和信号量都在共享内存区中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <semaphore.h>
#include <stdlib.h>
#include <sys/mman.h>
 
const int maxline=4096;
 
struct shared{
    sem_t mutex;
    int count;
}shared;
 
int main(int argc, char **argv) {
    int fd, i, nloop;
    struct shared *ptr;
    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, &shared, sizeof(struct shared)) != sizeof(struct shared)) {
        fprintf(stderr, "write error.\n");
        exit(-1);
    }
 
    if((ptr=mmap(NULL, sizeof(struct shared), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0))==MAP_FAILED) {
        fprintf(stderr, "mmap error.\n");
        exit(-1);
    }
    close(fd);
 
    if(sem_init(&ptr->mutex, 1, 1)==-1) {
        strerror_r(errno, errbuff, maxline);
        fprintf(stderr, "sem_init error: %s\n", errbuff);
        exit(-1);
    }
 
    setbuf(stdout, NULL);
 
    if(fork()==0) {
        for(i=0;i<nloop;i++) {
            sem_wait(&ptr->mutex);
            printf("child: %d\n", ptr->count++);
            sem_post(&ptr->mutex);
        }
        exit(0);
    }
 
    for(i=0;i<nloop;i++) {
        sem_wait(&ptr->mutex);
        printf("parent: %d\n", ptr->count++);
        sem_post(&ptr->mutex);
    }
    exit(0);
}

  

posted @   东宫得臣  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示