Linux进程间通信之共享内存

server端不停的写,client端不停的读

comm.h

  1 #pragma once  
  2 
  3 #include <sys/ipc.h>
  4 #include <sys/shm.h>
  5 #include <sys/types.h>
  6 
  7 #define _PATH_NAME_ "/tmp"  
  8 #define _PROJ_ID_ 0x666  
  9 
 10 int create_shm(int size);
 11 int get_shm();
 12 int destroy_shm(int shm_id);
 13 void* at(int shm_id);
 14 int dt(void *addr);

comm.c

#include "comm.h"
  2 #include <stdio.h>
  3 
  4 static int comm_shm(int size, int flag)
  5 {
  6         key_t key = ftok(_PATH_NAME_, _PROJ_ID_);
  7             if (key < 0)
  8                     {
  9                                 perror("ftok");
 10                                         return -2;
 11                                             }
 12 
 13                 return shmget(key, size, flag);
 14 }
 15 
 16 int create_shm(int size)
 17 {
 18         int flag = IPC_CREAT | IPC_EXCL | 0644;
 19             return comm_shm(size, flag);
 20 }
 21 
 22 
 23 int get_shm()
 24 {
 25         int flag = IPC_CREAT;
 26             return comm_shm(0, flag);
 27 }
 28 
 29 int destroy_shm(int shm_id)
 30 {
 31         return shmctl(shm_id, IPC_RMID, NULL);
 32 }
 33 
 34 void* at(int shm_id)
 35 {
 36         return shmat(shm_id, NULL, 0);
 37 }
        int dt(void* addr)
 40 {
 41         return shmdt(addr);
 42 }

server.c 往共享内存中写数据

  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include "comm.h"
  4 
  5 
  6 int main()
  7 {
  8     int shm_id = create_shm(4096);
  9     char *addr = (char *)at(shm_id);
 10 
 11     int i = 0;
 12     while (1)
 13     {
 14         addr[i] = 'A';
 15         addr[i + 1] = 0;
 16 
 17         ++i;
 18         i %= 4096;
 19         sleep(1);
 20     }
 21 
 22     dt(addr);
 23     destroy_shm(shm_id);
 24 
 25     return 0;
 26 }     

client.c 从共享内存里面读数据

 #include <stdio.h>
  2 #include <unistd.h>
  3 #include "comm.h"
  4 
  5 
  6 int main()
  7 {
  8         int shm_id = get_shm();
  9             char *addr = (char *)at(shm_id);
 10 
 11                 int i = 0;
 12                     while (1)
 13                             {
 14                                         printf("%s\n", addr);
 15                                                 sleep(1);
 16                                                     }
 17 
 18                         dt(addr);
 19 
 20                             return 0;
 21 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值