Linux编程:进程间通信--消息队列

7 篇文章 0 订阅
7 篇文章 0 订阅

一、问题描述

1.父进程创建消息队列和两个子进程p1和p2
2.子进程p1打开给定文件(如果没有,则创建文件),并向文件中写数据,写完关闭文件,然后向消息队列写入一条消息“ok”,目的是通知进程p2可以读取文件内容了。
3.子进程p2从消息队列读取消息,如果收到消息“ok”,则打开文件,读取文件内容,并将其输出道屏幕上,关闭文件。

二、代码部分

/*
 * 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值