Chinaunix首页 | 论坛 | 博客
  • 博客访问: 686856
  • 博文数量: 240
  • 博客积分: 3616
  • 博客等级: 大校
  • 技术积分: 2663
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-21 23:59
文章分类

全部博文(240)

文章存档

2013年(6)

2012年(80)

2011年(119)

2010年(35)

分类: LINUX

2010-11-09 17:34:14

#include
#include
#include
#include
#include
#include
#define BUFSZ 2048
int main()
{
 int shmid,i,fd,nwrite,nread;
 char *shmadd;
 char buf[5];
 if((shmid=shmget(IPC_PRIVATE,BUFSZ,0666))<0)//创建共享内存
 {
  perror("shmget");
  exit(1);
 }
 else
 {
  printf("create shared-memory:%d\n",shmid);
 }
 if((shmadd=shmat(shmid,0,0))<(char *)0)//映射共享内存
 {
  perror("shmat");
  exit(1); 
 }
 else
 {
  printf("attached shared-memory\n"); 
 }
 shmadd="hello";
 if((fd=open("share",O_CREAT|O_RDWR,0666))<0)
 {
  perror("open");
  exit(1); 
 }
 else
 {
  printf("open success !\n"); 
 }
 if((nwrite=write(fd,shmadd,5))<0)
 {
  perror("write");
  exit(1); 
 }
 else
 {
  printf("write success !\n"); 
 }
 lseek(fd,0,SEEK_SET);
 if((nread=read(fd,buf,5))<0)
 {
  perror("read");
  exit(1); 
 }
 else
 {
  printf("read %d from file:%s\n",nread,buf); 
 }
 if((shmdt(shmadd))<0)
 {
  perror("shmdt");
  exit(1); 
 }
 else
 {
  printf("deleted shared-memory\n"); 
 }
 exit(0);

}
/*-------------------------------------------------------
1.利用共享内存实现文件的打开,读写操作。
2.实验:
[root@localhost the_eight_step]# ./exec2
[root@localhost the_eight_step]# ./exec2
create shared-memory:360457
attached shared-memory
open success !
write success !
read 5 from file:hello  ?
shmdt: Invalid argument
-----------------------------------------------------------*/
阅读(943) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~