#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
key_t key = ftok("/", 123);
if(key < 0)
{
perror("创建共享内存失败");
return 0;
}else{
printf("创建共享内存成功! \n");
}
printf("key = %d\n",key);
//2.获取共享内存ID
int shm_id = shmget(key, 4096, IPC_CREAT|0777);
if(shm_id < 0)
{
perror("获取共享内存描述符ID失败\n");
}else
{
printf("获取共享内存描述符ID成功!\n");
}
pid_t pid = fork();
if(pid == 0)//子进程时收
{
//3.映射共享内存
char *str = shmat(shm_id,NULL,0);
if(str != NULL)
{
printf("子进程映射成功\n");
}else{
perror("");
}
while (1)
{
printf("子进程接收到:%s\n",str);
sleep(2);
}
}
if(pid > 0)
{
//3.映射共享内存
char *str = shmat(shm_id,NULL,0);
if(str != NULL)
{
printf("父进程映射成功\n");
}else{
perror("");
}
while (1)
{
//放入数据到共享内存中
printf("请输入发送的信息\n");
scanf("%s",str);
}
}
while (1);
return 0;
}
效果: