Linux编程:进程间通信--管道

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

一、问题描述

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

二、代码

/*
create by : Koalazb
...
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main()
{
	int filedes[2]; //Declare read or write parameter
	char buf[100]; //Declare buffer segment for pipe
	char buff[100]; //Declare buffer for file
	pid_t fpid,pid1,pid2; //Declare father process and two children processes
	fpid = getpid();
	pipe(filedes); //Create a pipe
	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 pipe!", 1,sizeof("hello pipe!")-1,fp );
			fclose(fp);
			fflush(fp);

			char s[] = "OK";
			write(filedes[1], s, sizeof(s));
			close(filedes[0]);
			close(filedes[1]);
		}
	}
	if((pid2 = fork()) == 0)
	{
		printf("Children process2's PID is: %d and its father process's PID is: %d\n",getpid(),getppid());
		read(filedes[0],buf,sizeof(buf));
		if(strcmp(buf,"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();
				printf("\n");
				fclose(fpr);
			}
			close(filedes[0]);
			close(filedes[1]);
		}
	}
	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、付费专栏及课程。

余额充值