1. 程式人生 > >Linux _share 記憶體共享 demo

Linux _share 記憶體共享 demo

main_r.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#define SHM_SIZE  100

int main(void)
{
    int shmid;
    char buff[SHM_SIZE];
    void
*shmadr; int ret; shmid = shmget((key_t)12345, SHM_SIZE, 0666|IPC_CREAT); if (shmid == -1) { printf("creat share memory failed!\n"); exit(1); } shmadr = shmat(shmid, 0, 0); if (shmadr == (void*)-1) { printf("shmat failed!\n"); exit(1); } memset
(buff, 0, sizeof(buff)); memcpy(buff, (char*)shmadr, sizeof(buff)); printf("get: %s\n", buff); ret = shmdt(shmadr); if (ret == -1) { printf("shmdt failed!\n"); exit(1); } return 0; }

main_w.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define SHM_SIZE 100 int main(void) { int shmid; char buff[SHM_SIZE]; void *shmadr; int ret; shmid = shmget((key_t)12345, SHM_SIZE, 0666|IPC_CREAT); if (shmid == -1) { printf("creat share memory failed!\n"); exit(1); } shmadr = shmat(shmid, 0, 0); if (shmadr == (void*)-1) { printf("shmat failed!\n"); exit(1); } strcpy(buff, "hello word!"); memcpy((char*)shmadr, buff, strlen(buff)+1); ret = shmdt(shmadr); if (ret == -1) { printf("shmdt failed!\n"); exit(1); } return 0; }