linux共享内存

余生颓废 提交于 2021-01-05 10:03:46

 本文使用system v  api,利用共享内存实现了简单的IPC通信。

 头文件svshm_xfr.h

#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define SHM_KEY 0x1234

#define OBJ_PERMS (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)

#define WRITE_SEM 0
#define READ_SEM 1

#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif

struct shmseg
{
    int cnt;
    char buf[BUF_SIZE];
};

写程序svshm_xfr_writer.c,从标准输入写入共享内存。

#include "svshm_xfr.h"

int main(int argc, char **argv)
{
    int shmid, bytes, xfrs;
    struct shmseg *shmp;

    shmid = shmget(SHM_KEY, sizeof(struct shmseg), IPC_CREAT | OBJ_PERMS);
    if (shmid == -1)
        return -1;

    shmp = shmat(shmid, NULL, 0);
    if (shmp == (void *)-1)
        return -1;

    for (xfrs = 0, bytes = 0;; xfrs++, bytes += shmp->cnt)
    {
        shmp->cnt = read(STDIN_FILENO, shmp->buf, BUF_SIZE);
        if (shmp->cnt == -1)
            return -1;

        if (shmp->cnt == 0)
            break;

        sleep(5);
    }
}

读程序svshm_xfr_reader.c,从共享内存读出并打印到标准输出。

#include "svshm_xfr.h"

int main(int argc, char **argv)
{
    int shmid, xfrs, bytes;
    struct shmseg *shmp;

    shmid = shmget(SHM_KEY, 0, 0);

    shmp = shmat(shmid, NULL, SHM_RDONLY);
    for (xfrs = 0, bytes = 0;; xfrs++)
    {
        if (shmp->cnt == 0)
            break;

        bytes += shmp->cnt;

        if (write(STDOUT_FILENO, shmp->buf, shmp->cnt) != shmp->cnt)
            return -1;
        sleep(5);
    }
    shmdt(shmp);
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!