IPC 程序例子二

12 篇文章 1 订阅
7 篇文章 0 订阅

共享内存


#include <sys/ipc.h>
#include <sys/shm.h>

通过程序建立了一个共享内存

# ipcs -m    建立并且存放了数据

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0x74006dfa 2293760    root      600        4          0                       
0x00000000 2654209    root      644        80         2                       
0x74006df9 2260994    root      600        4          0                       
0x00000000 2686979    root      644        16384      2                       
0x00000000 2719748    root      644        280        2                       
0x000003e8 2949125   root      666        512        0                       

# ipcs -m 读取清除之后

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0x74006dfa 2293760    root      600        4          0                       
0x00000000 2654209    root      644        80         2                       
0x74006df9 2260994    root      600        4          0                       
0x00000000 2686979    root      644        16384      2                       
0x00000000 2719748    root      644        280        2 


程序举例:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_KEY 1000L
#define SHM_SIZ 512
#define BUF_SIZ 50

int main() {
    pid_t pid;
    int shmid;
    if ((shmid = shmget(SHM_KEY, SHM_SIZ, IPC_CREAT | 0666)) < 0) {
        perror("shmget error");
        exit(0);
    }
    printf("shared memory id = %d\n", shmid);
    if ((pid = fork() < 0)) {
        perror("fork error");
    }
    if (pid == 0) {
        char *address = shmat(shmid, NULL, 0);
        if (address == NULL) {
            perror("attatch error");
        }
        strcpy(address, "this is a shared momery test!");
        shmdt(address);
        sleep(1);
    }
    char *address = shmat(shmid, NULL, 0);
    if (address == NULL) {
        perror("attatch error");
    }
    printf("read data :%s\n", address);
    shmdt(address);
    shmctl(shmid, IPC_RMID, NULL);
    return 0;
}

运行结果:

shared memory id = 2949125
read data :this is a shared momery test!
运行 FINISHED; Segmentation fault; 实时:  1s; 用户:  0ms; 系统:  0ms





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值