linux使用共享内存实现进程间通信源码

写的部分

#include<stdio.h>
#include<sys/shm.h>
#include<stdlib.h>
#include<string.h>
#include<sys/ipc.h>
int main()
{
        int shmid;
        char *shmaddr;

        key_t key;
        key = ftok(".",1);//获取key的ID值

        shmid = shmget(key,1024*4,IPC_CREAT|0666);//创建共享内存
        if(shmid == -1){//测试是否创建成功,-1为创建失败
                printf("shmget no OK\n");
                exit(-1);
        }

        shmaddr = shmat(shmid,0,0);//映射
        printf("shmat ok\n");
        strcpy(shmaddr,"liuzhihao");//传递数据

        sleep(5);//睡5秒

        shmdt(shmaddr);//释放共享内存数据
        shmctl(shmid,IPC_RMID,0);删除共享内存
        printf("quit\n");//打印退出
        return 0;
}
~                                                                                                                  
~                       

读的部分

#include<stdio.h>
#include<sys/shm.h>
#include<stdlib.h>
#include<string.h>
#include<sys/ipc.h>
int main()
{
        int shmid;
        char *shmaddr;

        key_t key;
        key = ftok(".",1);//获取key的ID值

        shmid = shmget(key,1024*4,0);//创建共享内存
        if(shmid == -1){
                printf("shmget no OK\n");
                exit(-1);
        }

        shmaddr = shmat(shmid,0,0);//映射
        printf("shmat ok\n");
        printf("data:%s \n",shmaddr);//打印输出数据

        shmdt(shmaddr);//释放读取的数据
        printf("quit\n");//打印关闭
        return 0;
}
~      

写的界面显示
CLC@Embed_Learn:~/liuzhihao$ ./w
shmat ok
quit

读的界面显示
CLC@Embed_Learn:~/liuzhihao$ ./r
shmat ok
data:liuzhihao
quit

查看删除共享内存
CLC@Embed_Learn:~/liuzhihao$ ipcs -m

------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000000 0 CLC 600 393216 2 dest
0x00000000 32769 CLC 600 393216 2 dest
0x01056453 524290 CLC 666 4096 0

CLC@Embed_Learn:~/liuzhihao$ ipcrm -m 524290
CLC@Embed_Learn:~/liuzhihao$ ipcs -m

------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000000 0 CLC 600 393216 2 dest
0x00000000 32769 CLC 600 393216 2 dest

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值