#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
-----------------------------------------------------------*/
阅读(979) | 评论(0) | 转发(0) |