#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)