linux进程通信之(十二):综合应用2
时间:2010-11-09 来源:andyluo324324
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#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
-----------------------------------------------------------*/
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#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
-----------------------------------------------------------*/
相关阅读 更多 +