linux多线程 & IPC【】system V匿名内存共享

    在shmget函数中使用   IPC_PRIVATE的场合,发生在具有亲缘关系的进程间通信的场合。

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <sys/shm.h>


struct st
{
    sem_t mutex;
    int value;
};

int main()
{
    int id;
    pid_t pt;
    
    id = shmget(IPC_PRIVATE, sizeof(struct st), IPC_CREAT|0666);
    if(id==-1)
    {
        printf("shmget fail\n");
        return 1;
    }
    printf("shmid: %d\n", id);
    
    //映射
    struct st*p;
    p = shmat(id, NULL, 0);
    
    //初始化
    sem_init(&(p->mutex),1,1);
    p->value=0;
    
    // fork
    pt = fork();
    if(pt<0)
    {
        shmdt(p);
        shmctl(id, IPC_RMID, NULL);
        return 3;
    }
    else if(pt==0)  //子进程
    {
        while(1)
        {
            printf("child! ");
            sem_wait( &(p->mutex));
            
            if(p->value<100)
            {
                p->value++;
                printf("plus: %d by %d\n", p->value, getpid());
            }else
            {
               
               // shmctl(id, IPC_RMID, NULL);
               sem_post( &(p->mutex));
               // shmdt(p);
                break;
            }
            sem_post( &(p->mutex));
        }
        
        
    }else
    {
        while(1)
        {
            printf("father! ");
            sem_wait( &(p->mutex));
            
            if(p->value<100)
            {
                p->value+=2;
                printf("plus 2: %d by %d\n", p->value, getpid());
            }else
            {
               // p->value-=2;
               // printf("minus 2: %d by %d\n", p->value, getpid());  
              
              sem_post( &(p->mutex));
               break;
            }
            sem_post( &(p->mutex));
        }
    }
//    shmdt(p);
    shmctl(id, IPC_RMID, NULL);
    
    
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值