使用匿名管道实现父子进程通信

父子进程间通信

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<fcntl.h>
 
int main()
{
	int fd[2];								//定义文件描述符数组
	int ret = pipe(fd);						//创建管道
	int i=5;
	int fd1=open("02.txt",O_RDWR,0777);
	char q[5] = {"quit"};
	if (ret == -1)
	{
		perror("pipe");
		exit(1);
	}
	
	if(fd1 == -1){
		printf("can not open file ");
		return 1;
	}
	pid_t pid = fork();					//创建进程
	
	if (pid > 0)
	{
		//父进程—写
		close(fd[0]);						//关闭读端
		char *p = "hello\n";
		while(i--)
		{
			write(fd[1], p, strlen(p) + 1);			//写数据
			sleep(2);
			
		}
		write(fd[1], q, 5);
		close(fd[1]);
		wait(NULL);
	}
	else if (pid == 0)
	{
		//子进程—读
		close(fd[1]);						//关闭写端
		char buf[64] = { 0 };	
		while(read(fd[0], buf, sizeof(buf)))  //读数据
		{
			if(strcmp(buf,q)==0){
			exit(0);
			}else{
			write(fd1,buf,strlen(buf));
			}
		}

		close(fd[0]);
		//ret = write(1, buf, ret);		//将读到的数据写到标准输出
		//0标准输入    1标准输出    2标准错误   STDOUT_FILENO可更换
	}
	close(fd1);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值