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

首先先使用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/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值