接收程序
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#define TEXT_SZ 2048
struct share_use_st
{
int written_by_you;
char text[TEXT_SZ];
};
int main()
{
int running = 1;
void *share_memory = (void *)0;
struct share_use_st *share_stuff;
int shmid;
shmid = shmget((key_t)1234, sizeof(struct share_use_st), 0666 | IPC_CREAT);
if(shmid == -1)
{
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
share_memory = shmat(shmid, (void *)0, 0);
if (share_memory == (void *)-1)
{
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %X\n", (int)share_memory);
share_stuff = (struct share_use_st *)share_memory;
share_stuff->written_by_you = 0;
while(running)
{
if(share_stuff->written_by_you)
{
printf("You write: %s", share_stuff->text);
sleep( rand()%4);
share_stuff->written_by_you = 0;
if (strncmp(share_stuff->text, "end", 3) == 0)
{
running = 0;
}
}
}
if (shmdt(share_memory) == -1)
{
fprintf(stderr, "shmid failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid, IPC_RMID, 0) == -1)
{
fprintf(stderr, "delete memory failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
发送程序
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#define TEXT_SZ 2048
struct share_use_st
{
int written_by_you;
char text[TEXT_SZ];
};
int main()
{
int running = 1;
char *share_memory ;
struct share_use_st *share_stuff;
char buffer[BUFSIZ];
int shmid;
shmid = shmget((key_t)1234, sizeof(struct share_use_st), 0666 | IPC_CREAT );
if (shmid == -1)
{
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
share_memory = shmat(shmid, (void *)0, 0);
if (share_memory == (void *)-1)
{
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %X\n", (int)share_memory);
share_stuff = (struct share_use_st *)share_memory;
while(running)
{
while(share_stuff->written_by_you == 1)
{
sleep(1);
printf("Wait for receive......\n");
}
printf("Enter some text:");
fgets(buffer, BUFSIZ, stdin);
strncpy(share_stuff->text, buffer, TEXT_SZ);
share_stuff->written_by_you == 1;
if (strncmp(buffer, "end", 3) == 0)
{
running = 0;
}
}
if (shmdt(share_memory) == -1)
{
fprintf(stderr, "shmdt failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
可是运行后怎么显示没有连上同一个内存块啊
[img]/home/freebird/桌面/1.png[/img]
}
关于共享内存的进程通信问题,求帮助
内核编译和嵌入式产品的设计与开发
前往
- 公告/注意事项
- ↳ 新闻和通知
- ↳ 软件推荐
- 系统安装
- ↳ 教学和常见问答
- ↳ 系统安装和升级
- ↳ 启动和引导
- ↳ 网卡无线拨号
- ↳ 硬件与内核
- ↳ 笔记本及便携设备
- ↳ Ubuntu衍生版
- ↳ 其他类Unix OS发行版
- ↳ Debian发行版
- 配置美化
- ↳ 中文显示和输入法
- ↳ 个人配置文件存放点
- ↳ 软件文档翻译
- ↳ 窗口管理器及美化
- ↳ 桌面展示
- 软件使用
- ↳ 办公、图像、机械电子设计等
- ↳ Vim和Emacs
- ↳ 开源模板库
- ↳ 互联网相关软件
- ↳ 影音多媒体
- ↳ 游戏和模拟器
- ↳ 虚拟机和虚拟化
- ↳ Wine及其分支
- ↳ 其它类软件
- 服务器管理
- ↳ 服务器运维
- ↳ 云计算和容器(K8S/KVM/Docker/WSL等)
- ↳ Ubuntu VPS
- 程序设计与开发
- ↳ Shell脚本
- ↳ 软件/网站开发
- ↳ 内核及嵌入式开发
- ↳ Ubuntu编译和打包
- ↳ 开源小工具
- ↳ 挑战任务
- 感想与交流
- ↳ 深度PK版
- ↳ Ubuntu故事和感慨
- ↳ 同城交流
- ↳ 校园社团
- ↳ 港澳台校区
- ↳ 国外校区
- 站务区
- ↳ 论坛管理
- ↳ Ubuntu中文网上商店