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

来源:互联网 发布:淘宝咋评价 编辑:程序博客网 时间:2024/05/16 12:34
首先先使用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;
}
命令行的第一个参数设为第一个程序输出的数字

Linux下内存共享的一个实例(设置共享内存,一个程序写,一个程序读) - 枯龙吟 - 枯龙吟
使用完以后可以使用
ipcrm -m 19562507
来删除该共享内存

http://blog.163.com/lixiangqiu_9202/blog/static/53575037201291014947937/
0 0
原创粉丝点击