linux-ipc-共享内存
介绍
linux下共享内存方便多了,就四个api
shmget 创建/获取
shmat 映射到进程内
shmdt 取消映射
shmctl 删除共享内存
Demo
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
#include <memory.h>
int main()
{
int id = shmget(1, 100, IPC_CREAT);
if(id == -1)
{
perror("shmget err:");
return -1;
}
pid_t pid = vfork();
if(pid == 0)
{
//child
void* addr = shmat(id, NULL, 0);
if(addr == (void*)-1)
{
perror("shmat err:");
return -1;
}
char buf[32] = { 0 };
sprintf(buf, "asddsa123321");
memcpy(addr, buf, sizeof(buf));
shmdt(addr);
exit(0);
}
else if(pid > 0)
{
//parent
sleep(1);
void* addr = shmat(id, NULL, 0);
if(addr == (void*)-1)
{
perror("shmat err:");
return -1;
}
char buf[32] = { 0 };
memcpy(buf, addr, sizeof(buf));
std::cout << buf << std::endl;
wait(&pid);
shmdt(addr);
shmctl(id, IPC_RMID, 0);
}
else
{
//error
}
return 0;
}