标签:sharememory ipc
【版权声明:尊重原创,转载请保留出处:blog.csdn.net/shallnet 或 .../gentleliu,文章仅供学习交流,请勿用于商业用途】       #include <sys/mman.h>
       #include <sys/stat.h> /* For mode constants */
       #include <fcntl.h> /* For O_* constants */
       int shm_open(const char *name, int oflag, mode_t mode);
       Link with -lrt.参数name为将要被打开或创建的共享内存对象,需要指定为/name的格式。#define SHM_IPC_FILENAME "sln_shm_file" #define SHM_IPC_MAX_LEN 1024
int sln_shm_get(char *shm_file, void **shm, int mem_len)
{ 
    int fd;
    fd = shm_open(shm_file, O_RDWR | O_CREAT, 0644);
    if (fd < 0) {
        printf("shm_open <%s> failed: %s\n", shm_file, strerror(errno));
        return -1;
    }
    ftruncate(fd, mem_len);
    *shm = mmap(NULL, mem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (MAP_FAILED == *shm) {
        printf("mmap: %s\n", strerror(errno));
        return -1;
    }
    close(fd);
    return 0;
}
int main(int argc, const char *argv[])
{
    char *shm_buf = NULL;
    sln_shm_get(SHM_IPC_FILENAME, (void **)&shm_buf, SHM_IPC_MAX_LEN);
    snprintf(shm_buf, SHM_IPC_MAX_LEN, "ipc client get: hello posix share memory ipc! This is write by server.");
    return 0;
}编译执行结果如下:# ./server # ./client ipc client get: hello posix share memory ipc! This is write by server. #
# ll /dev/shm/ -rw-r--r-- 1 root root 8193 Oct 30 14:13 sln_shm_file #
标签:sharememory ipc
原文地址:http://blog.csdn.net/shallnet/article/details/41038853