linux进程通信之(十二):综合应用2

1015阅读 0评论2010-11-09 andyluo324324
分类:LINUX

#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
-----------------------------------------------------------*/
上一篇:linux进程通信之(十一):综合应用1
下一篇:linux线程篇之(一):线程的创建与应用