linux两个程序通过共享内存通信的一个简单例子
写共享内存程序:
读共享内存的程序:
/*
* File: main.cpp
* Author: centos
*
说明:从共享内存中读取数据,显示到屏幕上。
* Created on 2010年3月2日, 上午10:47
*/
#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 114
/*
*
*/
int main(int argc, char** argv)
{
int shmid;
char *shmptr;
struct shmid_ds shmbuf;
char last_str[1024];
if ( ( shmid = shmget(MYKEY, BUF_SIZE, IPC_CREAT) ) == -1 )
{
printf("clinet shmget error!/n");
exit(1);
}
shmptr = (char *) shmat(shmid, 0, 0);
if ( -1 == (int) shmptr )
{
printf("clinet shmat error!/n");
fprintf(stderr, "Error: %d - %s/n", errno, strerror(errno));
exit(1);
}
while(1)
{
// if((strlen(last_str) != strlen(shmptr)) ||
if( ( 0 != strcmp(last_str,shmptr)))
{
printf("%s %s/n", last_str,shmptr);
strcpy(last_str,shmptr);
}
if (! strcmp(shmptr,"quit")) break;
}
shmdt(shmptr);
if(shmctl(shmid,IPC_RMID,&shmbuf) < 0) perror("Close 共享内存出错shmctl error");
return (EXIT_SUCCESS);
}