歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> Linux IPC之共享內存

Linux IPC之共享內存

日期:2017/3/3 12:06:05   编辑:Linux技術

在IPC通信中,共享內存效率最高,以下是經過實驗的example:

shared_memory_read.c:

#include<stdlib.h>

#include<stdio.h>

#include<string.h>

#include<errno.h>

#include<sys/types.h>

#include<sys/shm.h>

#include<sys/ipc.h>

#include<unistd.h>

#define BUF_SIZE 1024

#define MYKEY 999

int main(int argc, char **argv){

int shmid = 0;

char *shmptr = NULL;

if((shmid = shmget(MYKEY, BUF_SIZE, IPC_CREAT)) == -1){

printf("shmget errors!\n");

fprintf(stderr, "errno number:%d--%s\n", errno ,strerror(errno));

exit(1);

}

shmptr = (char *)shmat(shmid, 0, 0);

if(-1 == (int)shmptr){

printf("shmat error-read!\n");

exit(1);

}

while(1){

printf("==shmptr:%s==\n", shmptr);

if(!strcmp(shmptr, "quit")){

break;

}

memset(shmptr, '\0', BUF_SIZE);

sleep(3);

}

// shmdt(shmptr);

if(shmctl(shmid, IPC_RMID, &shmbuf) != 0){

perror("close shared memory error!\n");

}

return 0;

}

shared_memory_write.c:

#include<stdlib.h>

#include<stdio.h>

#include<string.h>

#include<errno.h>

#include<sys/types.h>

#include<sys/ipc.h>

#include<sys/shm.h>

#define BUF_SIZE 1024

#define MYKEY 999

int main(int argc, char **argv){

int shmid;

char *shmptr;

struct shmid_ds shmbuf;

shmid = shmget(MYKEY, BUF_SIZE, (IPC_CREAT|0777));

if(-1 == shmid){

printf("shmget error!\n");

fprintf(stderr, "Error:%d - %s\n", errno, strerror(errno));

exit(1);

}

shmptr = (char *)(shmat(shmid, 0, 0));

if(-1 == (int)shmptr){

printf("shmat error!\n");

if(shmctl(shmid, IPC_RMID, &shmbuf) < 0){

perror("shmctl error");

fprintf(stderr, "Error:%d - %s\n", errno, strerror(errno));

}

exit(1);

}

strcpy(shmptr, "this is test--read\n");

while(1){

printf("please input:");

scanf("%s", shmptr);

while('\n' != getchar());

if(!strncmp(shmptr, "quit", sizeof("quit"))){

break;

}

}

shmdt(shmptr);

if(shmctl(shmid, IPC_RMID, &shmbuf) < 0){

perror("shmctl error");

}

return 0;

}

例子較為簡單,需要的可以拿過去根據項目需要修改。

本文出自 “記錄生活點滴” 博客,請務必保留此出處http://qiangguozky.blog.51cto.com/3831429/1786512

Copyright © Linux教程網 All Rights Reserved