Chinaunix首页 | 论坛 | 博客
  • 博客访问: 108249
  • 博文数量: 74
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 757
  • 用 户 组: 普通用户
  • 注册时间: 2013-10-20 22:42
个人简介

相信生命中的无限潜能

文章分类

全部博文(74)

文章存档

2016年(1)

2015年(30)

2014年(30)

2013年(13)

我的朋友

分类: C/C++

2014-02-21 11:41:08


  1. #include <stdio.h>
  1. #include <sys/ipc.h>
  1. #include <sys/shm.h>
  1. #include <unistd.h>
  1. #include <signal.h>
  1. #include <string.h>
  1. #include <stdlib.h>
  1. int i=0;
  1. key_t key;
  1. int *p;
  1. int shmid;
  1. void deal(int s)
  1. {
  1.     if(s == 2)
  1.     {
  1.         /*卸载共享内存*/
  1.         shmdt(p);
  1.         /*删除共享内存*/
  1.         shmctl(shmid,IPC_RMID,0);
  1.         exit(0);
  1.     }
  1. }
  1. int main()
  1. {
  1.     signal(SIGINT,deal);
  1.     /*创建共享内存shmget*/
  1.     key=ftok(".",255);
  1.     if(key==-1)printf("ftok error:%m\n"),exit(-1);

  1.     int shmid=shmget(key,4,IPC_CREAT|IPC_EXCL|0666);
  1.     if(shmid==-1)printf("sheget error:%m\n"),exit(-1);
  1.     /*挂载/映射成虚拟地址shmat*/
  1.       p=shmat(shmid,0,0);
  1.       if(p==(int*)-1)printf("error:%m\n"),exit(-1);
  1.     /*使用*/
  1.     while(1)
  1.     {
  1.         *p=i;
  1.         sleep(1);
  1.         printf("%d\n",*p);
  1.         i++;
  1.     }
  1.     /*卸载虚拟内存shmdt*/
  1.     /*shmdt(p);*/
  1.     /*删除共 享内存shmctl*/
  1.     /*shmctl(shmid,IPC_RMID,0);*/

  1.     return 0;
  1. }


  1. #include <stdio.h>
  1. #include <sys/ipc.h>
  1. #include <sys/shm.h>
  1. #include <unistd.h>
  1. #include <signal.h>
  1. #include <string.h>
  1. #include <stdlib.h>
  1. int i=0;
  1. key_t key;
  1. int *p;
  1. void deal(int s)
  1. {
  1.     if(s==SIGINT)
  1.     {

  1.     /*卸载内存shmdt*/
  1.         shmdt(p);
  1.         exit(0);
  1.     }
  1. }
  1. int main()
  1. {
  1.     signal(SIGINT,deal);
  1.     key_t key;
  1.     /*创建共享内存shmget*/
  1.     key=ftok(".",255);
  1.     if(key==-1)printf("ftok error:%m\n"),exit(-1);

  1.     int shmid=shmget(key,4,0);
  1.     if(shmid==-1)printf("sheget error:%m\n"),exit(-1);
  1.     /*挂载/映射成虚拟地址shmat*/
  1.       int *p;
  1.       p=shmat(shmid,0,0);
  1.       if(p==(int*)-1)printf("error:%m\n"),exit(-1);
  1.     /*使用*/
  1.     while(1)
  1.     {
  1.         sleep(1);
  1.         printf("%d\n",*p);
  1.     }
  1.     /*卸载虚拟内存shmdt*/
  1.     /*shmdt(p);*/
  1.     /*删除共 享内存shmctl*/
  1.     /*shmctl(shmid,IPC_RMID,0);*/

  1.     return 0;
  1. }



阅读(652) | 评论(0) | 转发(0) |
0

上一篇:pipe

下一篇:socket

给主人留下些什么吧!~~