/*
Author: KMDJ
PublishedOn: CSDN
Filename: Exp2.c
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
typedef void(*sighandler_t)(int);
void sigcat(){
}
int calculatex(int x){
int ix = x;
if(ix > 1) return ix*calculatex(ix-1);
else return ix;
}
int calculatey(int y){
int iy = y;
if(iy > 1) return iy*calculatey(iy-1);
else return iy;
}
int main(int argc, char *argv[]){
int pid1; //pid1算f(x)
int pid2; //pid2算f(y)
int x=atoi(argv[1]);
int y=atoi(argv[2]);
int pipex1[2];
int pipex2[2];
int pipey1[2];
int pipey2[2];
signal(SIGINT, (sighandler_t)sigcat);
if(pipe(pipex1)<0){
perror("pipe not create");
exit(EXIT_FAILURE);
}
if(pipe(pipex2)<0){
perror("pipe not create");
exit(EXIT_FAILURE);
}
if(pipe(pipey1)<0){
perror("pipe not create");
exit(EXIT_FAILURE);
}
if(pipe(pipey2)<0){
perror("pipe not create");
exit(EXIT_FAILURE);
}
if((pid1=fork())<0){
perror("process not create");
exit(EXIT_FAILURE);
}
else if(pid1==0){
//子进程1从管道x1的0端读,管道x2的1端写
//所以关闭管道x1的1端和管道x2的0端
close(pipex1[1]);
close(pipex2[0]);
read(pipex1[0], &x, sizeof(int));
x = calculatex(x);
write(pipex2[1], &x, sizeof(int));
close(pipex1[0]);
close(pipex2[1]);
if(kill(getppid(), SIGINT)>=0)
pause();
exit(EXIT_SUCCESS);
}
else{
if((pid2=fork())<0){
perror("process not create");
exit(EXIT_FAILURE);
}
else if(pid2==0){
//子进程2从管道y1的0端读,管道y2的1端写
//所以关闭管道x1的1端和管道x2的0端
close(pipey1[1]);
close(pipey2[0]);
read(pipey1[0], &y, sizeof(int));
y = calculatey(y);
write(pipey2[1], &y, sizeof(int));
close(pipey1[0]);
close(pipey2[1]);
if(kill(getppid(), SIGINT)>=0)
pause();
exit(EXIT_SUCCESS);
}
else{
close(pipex1[0]);
close(pipex2[1]);
close(pipey1[0]);
close(pipey2[1]);
write(pipex1[1], &x, sizeof(int));
pause();
read(pipex2[0], &x, sizeof(int));
write(pipey1[1], &y, sizeof(int));
pause();
read(pipey2[0], &y, sizeof(int));
close(pipex1[1]);
close(pipex2[0]);
close(pipey1[1]);
close(pipey2[0]);
printf("f(x) = %d\n",x);
printf("f(y) = %d\n",y);
int result = x + y;
printf("f(x, y) = %d\n", result);
}
}
return EXIT_SUCCESS;
}