山东大学操作系统实验二

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

int f_x(int x) {
	if(x==1) return 1;
	else return f_x(x-1)*x;
}

int f_y( int y ){
	if(y==1||y==2) return 1;
	return f_y(y-1) + f_y(y-2);
}

int f_xy(int x,int y){
	return f_x(x) + f_y(y);
}

int main(){
	int pid1,pid2;
	int pipe1[2],pipe2[2];
	int x,y;
	printf("input x y\n");
	scanf("%d %d",&x,&y);
	if(pipe(pipe1)<0 || pipe(pipe2)<0){
		perror("pipe not create");	
		exit(EXIT_FAILURE);}
	pid1 = fork();
	if(pid1 ==0){
		close(pipe1[0]);
		close(pipe2[0]);
		close(pipe2[1]);
		int result = f_x(x);
		printf("child1 %d caculate f_x(%d) = %d\n",getpid(),x,result);
		write(pipe1[1],&result,sizeof(int));
		close(pipe1[1]);
		exit(EXIT_SUCCESS);
	}
	pid2 = fork();
	if(pid2 ==0){
		close(pipe1[0]);
		close(pipe2[0]);
		close(pipe1[1]);
		int result2 = f_y(y);
		printf("child2 %d caculate f_y(%d) = %d\n",getpid(),y,result2);
		write(pipe2[1],&result2,sizeof(int));
		close(pipe2[1]);
	}
	else {
		close(pipe1[1]);
		close(pipe2[1]);
		int fx;
		read(pipe1[0],&fx,sizeof(int));
		int fy;
		read(pipe2[0],&fy,sizeof(int));
		int fxy = fx+fy;
		printf("father %d caculate f(%d,%d) = %d +%d = %d\n",getpid(),x,y,fx,fy,fxy);
		close(pipe1[0]);
		close(pipe2[0]);
	}
	return EXIT_SUCCESS;
}

Makefile

cc = gcc
CFLAGS = -Wall -g
TARGET = prac2
SRCS = prac2.c

all: $(TARGET)
$(TARGET): $(SRCS)
	$(CC) $(CFLAGS) -o $(TARGET) $(SRCS)
clean:
	rm -f $(TARGET)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值