共享內存是被多個進程共享的一部分物理內存。
共享內存的實現步驟:
1 創建共享內存
int shmget(key_t key, int size, int shmflg);
2 映射內存
int shmat(int shmid, char *shmaddr, int flag);
實例:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define PERM S_IRUSR|S_IWUSR
/* 共享內存 */
int main(int argc,char **argv)
{
int shmid;
char *p_addr,*c_addr;
if(argc!=2)
{
fprintf(stderr,"Usage:%s\n\a",argv[0]);
exit(1);
}
/* 創建共享內存 */
if((shmid=shmget(IPC_PRIVATE,1024,PERM))==-1)
{
fprintf(stderr,"Create Share Memory Error:%s\n\a",strerror(errno));
exit(1);
}
/* 創建子進程 */
if(fork()) // 父進程寫
{
p_addr=shmat(shmid,0,0);
memset(p_addr,'\0',1024);
strncpy(p_addr,argv[1],1024);
wait(NULL); // 釋放資源,不關心終止狀態
exit(0);
}
else // 子進程讀
{
sleep(1); // 暫停1秒
c_addr=shmat(shmid,0,0);
printf("Client get %s\n",c_addr);
exit(0);
}
}