您的位置:首页 > 运维架构 > Linux

Linux下内存共享的一个实例(设置共享内存,一个程序写,一个程序读)

2014-10-01 15:54 369 查看
首先先使用shmget建立一块共享内存,然后向该内存中写入数据并返回该共享内存shmid

使用另一个程序通过上一程序返回的shmid读该共享内存内的数据

建立共享内存并写入数据的程序

#include <stdio.h>

#include <string.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <stdlib.h>

#include <errno.h>

void get_buf(char *buf)

{

int i=0;

while((buf[i]=getchar())!='\n'&&i<1024)

i++;

}

int main(void)

{

int shmid;

shmid=shmget(IPC_PRIVATE,sizeof(char)*1024,IPC_CREAT|0666);

if(shmid==-1)

{

perror("shmget");

}

char *buf;

if((int)(buf=shmat(shmid,NULL,0))==-1)

{

perror("shmat");

exit(1);

}

get_buf(buf);

printf("%d\n",shmid);

return 0;

}

读取数据的程序

#include <stdio.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <stdlib.h>

int main(int argc,char **argv)

{

int shmid;

shmid=atoi(argv[1]);

char *buf;

if((int)(buf=shmat(shmid,NULL,0))==-1)

{

perror("shmat");

exit(1);

}

printf("%s\n",buf);

shmdt(buf);

return 0;

}

命令行的第一个参数设为第一个程序输出的数字





使用完以后可以使用

ipcrm -m 19562507

来删除该共享内存
http://blog.163.com/lixiangqiu_9202/blog/static/53575037201291014947937/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐