一,創建共享內存
void *shmat(int shmid, void *shmaddr, int shmflg);該系統調用將shmid 對應的共享內存區映射到進程的虛擬地址空間中,shmaddr 爲指定的映射起始地址,其值爲NULL 時,映射空間由系統確定;shmflg 爲標誌字,其值一般指定爲0。
/* * mkshm.c - Create and initialize shared memory segment */ #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <stdlib.h> #define BUFSZ 4096 /* Size of the segment */ int main(void) { int shmid; if((shmid = shmget(IPC_PRIVATE, BUFSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(EXIT_FAILURE); } printf("segment created: %d\n", shmid); system("ipcs -m"); exit(EXIT_SUCCESS); }
查看目前已有的共享內存命令:ipcs -m
二,向共享內存中寫入數據
/*
* wrshm.c - Write data to a shared memory segment
*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ctype.h>
#include <unistd.h>
#define BUFSZ 4096
int main(int argc, char *argv[])
{
int shmid; /* Segment ID */
char *shmbuf; /* Address in process */
key_t key;
char *msg;
int len;
key = ftok("/tmp", 0);
if((shmid = shmget(key, BUFSZ, IPC_CREAT|0666)) < 0) {
perror("shmget");
exit(EXIT_FAILURE);
}
printf("segment created: %d\n", shmid);
system("ipcs -m");
/* Attach the segment */
if((shmbuf = (char *)shmat(shmid, 0, 0)) < 0) {
perror("shmat");
exit(EXIT_FAILURE);
}
/* Write message to the segment */
msg = "this is the message written by wrshm program.";
len = strlen(msg);
strcpy(shmbuf, msg);
printf("%s\nTotal %d characters written to shared memory.\n", msg, len);
/* De-attach the segment */
if(shmdt(shmbuf) < 0) {
perror("shmdt");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
三,從共享內存中讀入數據
/*
* wrshm.c - Write data to a shared memory segment
*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ctype.h>
#include <unistd.h>
#define BUFSZ 4096
int main(int argc, char *argv[])
{
int shmid; /* Segment ID */
char *shmbuf; /* Address in process */
key_t key;
int len;
key = ftok("/tmp", 0);
/* get the same share memory block */
if((shmid = shmget(key, 0, 0)) < 0) {
perror("shmget");
exit(EXIT_FAILURE);
}
/* Attach the segment */
if((shmbuf = (char *)shmat(shmid, 0, 0)) < 0) {
perror("shmat");
exit(EXIT_FAILURE);
}
/* read from share memory */
printf("Info read form shared memory is:\n%s\n", shmbuf);
/* De-attach the segment */
if(shmdt(shmbuf) < 0) {
perror("shmdt");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}