linux共享內存

 本文使用system v  api,利用共享內存實現了簡單的IPC通訊。api

 頭文件svshm_xfr.hcode

#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,從共享內存讀出並打印到標準輸出。get

#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);
}
相關文章
相關標籤/搜索