Linux编程:进程间通信--消息队列
来源:互联网 发布:星型网络 编辑:程序博客网 时间:2024/05/18 03:13
1.父进程创建消息队列和两个子进程p1和p2
2.子进程p1打开给定文件(如果没有,则创建文件),并向文件中写数据,写完关闭文件,然后向消息队列写入一条消息“ok”,目的是通知进程p2可以读取文件内容了。
3.子进程p2从消息队列读取消息,如果收到消息“ok”,则打开文件,读取文件内容,并将其输出道屏幕上,关闭文件。
代码部分:
/* * quque.c * * Created on: Nov 10, 2016 * Author: koala *//* * quque.c * * Created on: Nov 10, 2016 * Author: koala */#include <stdio.h>#include <unistd.h>#include <string.h>#include <sys/msg.h>typedef struct mymsg{ long mytype; char mytext[128];}mymsg;int main(){ pid_t fpid,pid1,pid2; //Declare father process and two children processes fpid = getpid(); struct mymsg msg; char buff[100]; //Get key identification //Create a msg queue int queueid = msgget(ftok(".",'t'),0660 | IPC_CREAT); printf("The father process's PID is: %d\n",fpid); char dir[100];//Declare file direction if((pid1 = fork()) == 0) { printf("Children process1's PID is: %d and its father process's PID is: %d\n",getpid(),getppid()); FILE *fp; printf("Please enter the file direction:\n"); fgets(dir,sizeof(dir)-1,stdin); fp = fopen(dir,"w+");//Open file"hello pipe.txt",if failed then create if(fp == NULL) { printf("The file cannot be open or create!\n"); } else { //Write data to file fwrite ("hello queue!", 1,sizeof("hello queue!")-1,fp ); fclose(fp); fflush(fp); strcat(msg.mytext ,"OK"); msgsnd(queueid,msg.mytext,sizeof(msg.mytext),IPC_NOWAIT); } } wait(0); if((pid2 = fork()) == 0) { printf("Children process2's PID is: %d and its father process's PID is: %d\n",getpid(),getppid()); msgrcv(queueid,msg.mytext,sizeof(msg.mytext),0,IPC_NOWAIT); if(strcmp(msg.mytext,"OK")) { FILE *fpr; fpr = fopen(dir,"r"); if(fpr == NULL) { printf("The file does not exist!\n"); } else { while(fgets(buff,1024 ,fpr)!= NULL) { fprintf(stderr,"%s",buff); } getchar(); fclose(fpr); } } } pid_t childpid = wait(NULL); printf("Process of %d exited\n",childpid); return 0;}
运行截图:
0 0
- Linux编程:进程间通信--消息队列
- linux编程---进程通信---消息队列
- Linux系统编程——进程间通信:消息队列
- Linux系统编程——进程间通信:消息队列
- 【Linux系统编程】进程间通信--消息队列
- Linux系统编程——进程间通信:消息队列
- Linux进程间通信: 消息队列
- Linux进程间通信: 消息队列
- linux进程间通信之消息队列
- linux C-(进程间通信 消息队列)
- linux进程间通信之消息队列
- Linux高级进程间通信:消息队列
- linux进程间通信之消息队列
- Linux进程间通信之消息队列
- Linux消息队列完成进程间通信
- linux 进程间通信之消息队列
- Linux环境进程间通信-消息队列
- Linux 进程间通信--- 消息队列
- POJ 1595 Prime Cuts 未完成
- 玲珑学院ACM比赛 Round #5 Aplus B
- Java Web J2EE下的两大框架SSH和SSM对比
- Longest Substring Without Repeating Characters 最长不重复子串【中】
- bellman ford 算法 判断是否存在负环
- Linux编程:进程间通信--消息队列
- FreeBSD下配置vim和ctags
- Tensorflow系列——基本用法
- 火狐粉丝见面会总结
- org.hibernate.PropertyValueException: not-null property references a null or transient value : xxx
- Android自动化压力测试图解教程——Monkey工具
- qwdqwdqw
- java对excel文件的解析操作
- javascript高程三第三章笔记