进程一将数据写入共享内存,进程二从共享内存读取数据
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
int main(int argc, char* argv[])
{
key_t key = ftok("/etc/passwd", 'a');
if( -1 == key )
{
fprintf(stderr, "Creat Key Error:%s\n", strerror(errno));
return -1;
}
/*
if your IPC are used by processes related bya fork()
(parent-children-grandchildren) use IPC_PRIVATE as the key
*/
int shm_id=shmget( key, 1024, IPC_CREAT |0660);
if( shm_id == -1 )
{
if ( shmctl(shm_id, IPC_RMID, NULL) == -1 )
{
fprintf(stderr, "shmctl remove shmid error:%s\n", strerror(errno ));
return -1;
}
shm_id=shmget( key, 1024, IPC_CREAT |0660);
if( shm_id == -1 )
{
fprintf(stderr, "shmget create error:%s\n", strerror(errno) );
return -1;
}
}
char* pMap = (char *)shmat(shm_id, NULL, 0);
if( (int)pMap == -1)
{
fprintf(stderr, "shmat create error:%s\n", strerror(errno) );
shmctl(shm_id, IPC_RMID, NULL);
return -1;
}
strcpy( pMap, "Bujiwu Swallow");
getchar();
shmdt(pMap);
shmctl(shm_id, IPC_RMID, NULL);
return 0;
}
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
int main(int argc, char* argv[])
{
key_t key = ftok("/etc/passwd", 'a');
if( -1 == key )
{
fprintf(stderr, "Creat Key Error:%s\n", strerror(errno));
return -1;
}
/*
if your IPC are used by processes related bya fork()
(parent-children-grandchildren) use IPC_PRIVATE as the key
*/
int shm_id=shmget( key, 1024, IPC_CREAT|0660);
if( shm_id == -1 )
{
if ( shmctl(shm_id, IPC_RMID, NULL) == -1 )
{
fprintf(stderr, "shmctl remove shmid error:%s\n", strerror(errno ));
return -1;
}
shm_id=shmget( key, 1024, IPC_CREAT |0660);
if( shm_id == -1 )
{
fprintf(stderr, "shmget create error:%s\n", strerror(errno) );
return -1;
}
}
char* pMap = (char *)shmat(shm_id, NULL, 0);
if( (int)pMap == -1)
{
fprintf(stderr, "shmat create error:%s\n", strerror(errno) );
shmctl(shm_id, IPC_RMID, NULL);
return -1;
}
printf("Shared memory::%s\n", pMap);
shmdt(pMap);
shmctl(shm_id, IPC_RMID, NULL);
return 0;
}
http://www.cppblog.com/Files/bujiwu/ShareMemory.rar