linux 练习四 共享内存练习
来源:互联网 发布:深圳毕业生入户 知乎 编辑:程序博客网 时间:2024/05/21 10:35
题目:编写两个进程,a和b,利用共享内存技术,a向共享内存写字符串,b从共享内存把字符串读出来,并显示在屏幕上
/* 目标 编写两个进程a和b,利用共享内存技术, * a向共享内存写字符串,b从共享内存中读取 * 字符串并显示在屏幕上 */
shmwrite.c
#include <stdlib.h>#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <sys/ipc.h>#include <sys/shm.h>#include <string.h>int main(int argc, char * argv[]){ int fd; char buf[20]; char *shmaddr = NULL; char* tempstr = "write some data to share aread"; int shmd = shmget(IPC_PRIVATE,1000,O_RDWR|O_CREAT|0666); if(shmd < 0) { perror("shmget"); exit(1); } fd = open("shmaddr",O_WRONLY | O_CREAT | O_TRUNC,666); if(fd < 0) { perror("open"); exit(1); } sprintf(buf,"shmfd=%d\n",shmd); if( write(fd,buf,strlen(buf)) < 0) { perror("write"); exit(1); } shmaddr = shmat(shmd,NULL,0); printf("shmaddr =%p,shmd=%d\n",shmaddr,shmd); if(((long int)shmaddr) < 0) { shmctl(shmd,IPC_RMID,0); perror("shmat"); exit(1); } sprintf(buf,"i'm a process\n"); memcpy(shmaddr, tempstr,strlen(tempstr)); printf("%s\n",shmaddr); sleep(5); if(shmaddr[0] == 2) { printf("b process set 2\n"); } printf("wait 5s time over\n"); if(((int)(shmdt(shmaddr))) < 0) { printf("shmaddr =%p\n",shmaddr); perror("shmdt"); } if( shmctl(shmd,IPC_RMID,0) < 0) { perror("shmctl"); }}
//shmread.c#include <stdlib.h>#include <stdio.h>#include <sys/ipc.h>#include <sys/shm.h>#include <sys/types.h>#include <fcntl.h>#include <string.h>int main(int argc,char * argv[]){ int fd; char buf[30]; char *shmidprt; int shmid; char * shmaddr; if(argc < 2) { printf("please input file name\n"); exit(1); } fd = open(argv[1],O_RDONLY); if(fd < 3) { perror("open"); exit(1); } if((read(fd,buf,sizeof(buf)) < 0)) { perror("read"); exit(1); } if( close(fd) < 0) { perror("close"); } shmidprt = strchr(buf,'='); shmid = atoi(shmidprt+1); printf("shmid = %d\n",shmid); shmaddr = shmat(shmid,NULL,0); if((long int)(shmaddr) < 0) { perror("shmat"); exit(1); } printf("%s\n",shmaddr); *shmaddr = 2; if(shmdt(shmaddr) < 0) { perror("shmdt"); exit(1); }}
阅读全文
0 0
- linux 练习四 共享内存练习
- Linux编程练习 --SystemV共享内存
- 共享内存的练习
- 共享内存的编程练习
- Linux基础练习四
- Linux编程练习(一)—— 多线程+共享内存+线程信号量练习
- linux 内存 练习 1
- linux 内存 练习 2
- Linux基础练习(四)
- 练习四
- Linux动态共享库 ——练习
- Day 7 linux基础命令练习四
- linux练习
- linux练习
- linux练习
- Linux练习
- Linux练习
- linux练习
- 在Linux上安装hadoop教程
- 【Scikit-Learn 中文文档】协方差估计 / 经验协方差 / 收敛协方差 / 稀疏逆协方差 / Robust 协方差估计
- 安卓网络框架---volley的简单使用。
- Linux常用命令大全(多加练习识记20171129)
- Arduino常用函数(整理中)
- linux 练习四 共享内存练习
- 库房管理系统架构篇--MVC+三层+EasyUI
- eclipse中maven项目部署到tomcat(不是热部署)
- 【Scikit-Learn 中文文档】新异类和异常值检测
- 微信小程序初探
- Hibernate的HQL
- HDU2019
- Joda-Time 简介
- java8 lambda表达式的简单介绍