linux共享内存的例子zz
(2008-10-31 14:04:58)
标签:
it
#include
#include
#include
#include
#include
#include
#include
#define CHILMES "this is the client's message"
#define PAREMES "this is the father's message"
#define SHM_SIZE 1000
int main(void)
{
int fd;
fd =
open("./shmap.txt",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR|S_IXUSR);
int shmid;
shmid = shmget(IPC_PRIVATE,SHM_SIZE,0600);
char *shmptr;
shmptr = shmat(shmid,0,0);
mmap(shmptr,SHM_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
close(fd);
pid_t pid;
if((pid=fork())<0)
{
printf("pid error\n");
exit(2);
}
else if(pid == 0)//子进程
{
sleep(3); //让父进程先写内存
memcpy(shmptr+sizeof(PAREMES),CHILMES,sizeof(CHILMES));
}
else
{
memcpy(shmptr,PAREMES,sizeof(PAREMES));
}
msync(shmptr,SHM_SIZE,MS_SYNC);
}
意图在于创建一个文件映射到共享内存中,父子进程均对其进行操作,将更改后信息写在文件里,现在程序执行完文件里没有东西。。。。。
分享:
喜欢
0
赠金笔
加载中,请稍候......
评论加载中,请稍候...
发评论
登录名: 密码: 找回密码 注册记住登录状态
昵 称:
发评论
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。