Linux IPC之共享內存

在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;

}

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章