在IPC通信中,共享内存效率最高,以下是经过实验的example:
shared_memory_read.c:
#include
#include
#include
#include
#include
#include
#include
#include
#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
#include
#include
#include
#include
#include
#include
#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;
}
例子较为简单,需要的可以拿过去根据项目需要修改。