05 Linux共享内存Demo
jim@ubuntu:/mnt/hgfs/git_win10/many-repositories/21_Linux共享内存Demo$ make
gcc -o server test_sharememory_comm.c test_sharememory_server.c
gcc -o client test_sharememory_comm.c test_sharememory_client.c
jim@ubuntu:/mnt/hgfs/git_win10/many-repositories/21_Linux共享内存Demo$ make run
./server &
./client
server write: hello world!
client get: hello world!
jim@ubuntu:/mnt/hgfs/git_win10/many-repositories/21_Linux共享内存Demo$
- Makefile
default:
gcc -o server test_sharememory_comm.c test_sharememory_server.c
gcc -o client test_sharememory_comm.c test_sharememory_client.c
run:
./server &
./client
clean:
rm server; rm client;
- test_sharememory_comm.c
#include <stdio.h>
#include <sys/types.h>
#include "test_sharememory_comm.h"
#define SHM_PATH "./"
#define SHM_PROJECT_ID 1
static int get_sharememory_id(int size, int flag)
{
key_t key = ftok(SHM_PATH, SHM_PROJECT_ID);
if (key < 0) {
printf("get key error\n");
return -1;
}
int id = shmget(key, size, flag);
if (id < 0) {
printf("get id error\n");
return -1;
}
return id;
}
int create_sharememory(int size)
{
return get_sharememory_id(size, IPC_CREAT | IPC_EXCL | 0666);
}
int get_sharememory(void)
{
return get_sharememory_id(0, IPC_CREAT | 0666);
}
int destroy_sharememory(int id)
{
return shmctl(id, IPC_RMID, NULL);
}
- test_sharememory_comm.h
#ifndef _TEST_SHAREMEMORY_COMM_H_
#define _TEST_SHAREMEMORY_COMM_H_
#include <sys/shm.h>
#define SHARE_MEMORY_SIZE 4096
extern int create_sharememory(int size);
extern int get_sharememory(void);
extern int destroy_sharememory(int id);
#endif
- test_sharememory_server.c
#include <stdio.h>
#include <string.h>
#include "test_sharememory_comm.h"
#define WRITE_STRING "hello world!"
int main()
{
int shmid = create_sharememory(SHARE_MEMORY_SIZE);
if (shmid < 0) {
printf("create share memory error\n");
return -1;
}
char *pshm = shmat(shmid, NULL, 0);
if (!pshm) {
printf("link share memory error\n");
return -1;
}
strcpy(pshm, WRITE_STRING);
printf("server write: %s\n", WRITE_STRING);
shmdt(pshm);
return 0;
}
- test_sharememory_client.c
#include <stddef.h>
#include <stdio.h>
#include "test_sharememory_comm.h"
int main()
{
int shmid = get_sharememory();
if (shmid < 0) {
printf("get share memory error\n");
return -1;
}
char *pshm = shmat(shmid, NULL, 0);
if (!pshm) {
printf("link share memory error\n");
return -1;
}
printf("client get: %s\n", pshm);
shmdt(pshm);
destroy_sharememory(shmid);
return 0;
}