利用进程间通信的方式,实现进程1从文件file中读取1个字符,进程2按照字符的内容,若是1,则打印hello若是0则打印 world,方式可自由选择

在这里插入图片描述
pipe.c文件

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void write_data(int *pipes)
{
	close(pipes[0]);
	size_t len =1;
	int buf[5];
	int fd = open("file",O_RDONLY);
    if(fd == -1)
    {
		printf("Fail to open file");
        exit(0);
    }
    read(fd,buf,len);
    write(pipes[1],buf,len);
    close(pipes[1]);
	close(fd);
    exit(0);
}

void read_data(int *pipes)
{
	close(pipes[1]);
	size_t len = 1;
	char buf[5];
    while(read(pipes[0],buf,len) > 0);
    if(buf[0] == '1')
	printf("hello\n");
    else
    	printf("world\n");
    close(pipes[0]);
        exit(0);
}

int main()
{
	int fd[2];
	if(pipe(fd) != 0)
	{
		printf("Fail to create pipe\n");
		return 0;
	}
	pid_t pid = fork();
	if(pid < 0)
	{
		printf("Fail to create fork\n");
		return 0;
	}
	else if(pid > 0)
	{
		write_data(fd);
	}
	else
	{
		read_data(fd);
	}
	return 0;
}

Makefile文件

CC = gcc
pipe:pipe.o
        $(CC) -o pipe pipe.o
pipe.o:pipe.c
        $(CC) -c pipe.c
clean:
        rm -f *.o
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值