利用两个管道进行进程间双向通信在第一篇练习已经大致作出说明,下面将进行一个更为综合的练习
首先看题目:
设有二元函数f(x,y) = f(x) + f(y)
其中: f(x) = f(x-1) * x (x >1)
f(x)=1 (x=1)
f(y) = f(y-1) + f(y-2) (y> 2)
f(y)=1 (y=1,2)
请编程建立3 个并发协作进程,它们分别完成f(x,y)、f(x)、f(y)
实现的方法很多,这里只用管道实现,大致流程如下:
1.在父进程代码中初始化四个管道,两个用于父-子进程1,另外两个父-子进程2;
2.父进程创建2个子进程,子进程1计算函数f(x),子进程2计算函数f(y);
3.父进程向子进程1、2发送数据;
4.子进程1、2均在管道里读出数据,并进行计算;
5.计算完毕后,子进程1、2向父进程发送结果;
6。父进程接受数据,打印出来
下面是实现过程:
- /*pipe3.c*/
- #include <unistd.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <stdio.h>
- #include <fcntl.h>
- #define MAXLINE 1024
- #define READ 0
- #define WRITE 1
- /*函数x*/
- int functionx(int nx);
- /*函数y*/
- int functiony(int ny);
- main(void)
- {
- pid_t pid_x,pid_y;
- int fdx1[2],fdy1[2],fdx2[2],fdy2[2];
- /*初始化管道*/
- pipe(fdx1);
- pipe(fdy1);
- pipe(fdx2);
- pipe(fdy2);
- /*创建子进程1*/
- pid_x = fork();
- if(pid_x < 0)
- {
- printf("Create process error!/n");
- exit(0);
- }
- if(pid_x == 0)
- {
- int numx,funx;
- printf("childx process ID:%d/n",getpid());
- close(fdx1[WRITE]);
- close(fdx2[READ]);
- /*从管道读出x*/
- read(fdx1[READ],&numx,sizeof(int));
- /*函数计算*/
- funx = functionx(numx);
- printf("childx x=%d/n",funx);
- /*向管道发送*/
- write(fdx2[WRITE],&funx,sizeof(int));
- close(fdx1[READ]);
- close(fdx2[WRITE]);
- }
- if(pid_x > 0)
- {
- /*创建子进程2*/
- pid_y =fork();
- if(pid_y < 0)
- {
- printf("Create process error!/n");
- exit(0);
- }
- if(pid_y == 0)
- {
- int numy,funy;
- printf("childy process ID:%d/n",getpid());
- close(fdy1[WRITE]);
- close(fdy2[READ]);
- /*从管道读出x*/
- read(fdy1[READ],&numy,sizeof(int));
- /*函数计算*/
- funy = functiony(numy);
- printf("childy y=%d/n",funy);
- /*向管道发送*/
- write(fdy2[WRITE],&funy,sizeof(int));
- }
- if(pid_y > 0)
- {
- int x,y,funxy;
- int fx,fy;
- sleep(1);
- printf("parentxy process ID:%d/n%",getpid());
- /*参数输入*/
- printf("enter x,y/n");
- scanf("%d,%d",&x,&y);
- close(fdx2[WRITE]);
- close(fdx1[READ]);
- close(fdy2[WRITE]);
- close(fdy1[READ]);
- /*管道发送*/
- write(fdx1[WRITE],&x,sizeof(int));
- write(fdy1[WRITE],&y,sizeof(int));
- /*等待子进程计算*/
- sleep(1);
- /*管道读入*/
- read(fdx2[READ],&fx,sizeof(int));
- read(fdy2[READ],&fy,sizeof(int));
- funxy = fx+fy;
- printf("f(x) = %d/nf(y) = %d/nfun(x,y) = %d",fx,fy,funxy);
- waitpid(pid_x,NULL,0);
- waitpid(pid_y,NULL,0);
- }
- }
- }
- int functionx(int nx)
- {
- int sum = 1;
- int i = 1;
- if(nx < 0)
- {
- printf("errorx!/n");
- exit(0);
- }
- while(i <= nx)
- {
- sum *=i++;
- }
- return sum;
- }
- int functiony(int ny)
- {
- int f1=1,f2=1,f3;
- int i =3;
- if(ny <= 2)
- return f1;
- while(i <= ny)
- {
- f3 = f1+f2;
- f1 = f2;
- f2 = f3;
- i++;
- }
- return f3;
- }
编译:
$ gcc pipe3.c -o pipe3
运行:
$ ./pipe
我们输入测试数据x=3,y=4
输出为f(x)=6,f(y)=3,f(x,y)=9
成功