操作系统--线程和进程/线程管道通信实验

来源:互联网 发布:linux 启动应用程序 编辑:程序博客网 时间:2024/06/06 02:50

ppipe.c文件:

#include <stdio.h>#include <unistd.h>#include <stdlib.h>int main(int argc, char *argv[]){  int pid1;  int pid2;//进程号  int pipe1[2]; //存放第一个无名管道标号  int pipe2[2]; //存放第二个无名管道标号  int x;  int y;  int fx;  int fy;// 存放要传递的整数  printf("Please input x and y\n");//输入  scanf("%d %d",&x,&y);//使用 pipe()系统调用建立两个无名管道。建立不成功程序退出,执行终止  if(pipe(pipe1) < 0){   perror("pipe not create");   exit(EXIT_FAILURE);   }  if(pipe(pipe2) < 0){   perror("pipe not create");   exit(EXIT_FAILURE);   }//使用 fork()系统调用建立子进程,建立不成功程序退出,执行终止  if((pid1=fork()) <0){   perror("process not create");   exit(EXIT_FAILURE);   }//子进程号等于 0 表示子进程在执行,   else if(pid1 == 0){//子进程负责从管道 2 的 1 端写,//所以关掉管道 1 的 1 端、0端、管道2的0端。   close(pipe1[1]);   close(pipe1[0]);   close(pipe2[0]);   fx=Fx(x);// 进行函数运算,将函数的运算结果f(x)写入管道2的1端   printf("child pid is %d f(x)=%d (x=%d) \n",getpid(),fx,x);   write(pipe2[1],&fx,sizeof(int));   //完成后关闭管道2的1端     close(pipe2[1]);      exit(EXIT_FAILURE);   }   else{   //使用 fork()系统调用建立子进程,建立不成功程序退出,执行终止      if((pid2=fork()) <0){       perror("process not create");       exit(EXIT_FAILURE);       }  //子进程号等于 0 表示子进程在执行,       else if(pid2 == 0){  //子进程负责从管道 1 的 1 端写,  //所以关掉管道 2 的 1 端、0端、管道1的0端。       close(pipe2[1]);       close(pipe2[0]);       close(pipe1[0]);       fy = Fy(y); //进行函数运算,将函数的运算结果f(y)写入管道1的1端       printf("child pid is %d f(y)=%d (y=%d) \n",getpid(),fy,y);       write(pipe1[1],&fy,sizeof(int));       close(pipe1[1]);       exit(EXIT_FAILURE);       }   }   //父进程负责从管道 2 的 0 端读,管道 1 的 0 端读,   //所以关掉管道2的1端、管道1的0端       close(pipe2[1]);       close(pipe1[1]);       read(pipe2[0],&fx,sizeof(int));       read(pipe1[0],&fy,sizeof(int));       printf("parent pid is %d f(x,y)=%d (x=%d,y=%d) \n",getpid(),fx+fy,x,y);       close(pipe1[0]);       close(pipe2[0]);        //父进程执行结束    return EXIT_SUCCESS;}//计算f(x)int Fx(const int x){    if(x==1)    return 1;    else    return Fx(x-1)*x;}//计算f(y)int Fy(const int y){    if(y==1||y==2)    return 1;    else    return Fy(y-1)+Fy(y-2); }
makefile文件

srcs = ppipe.c

objs = ppipe.o

opts = -g -c

all: ppipe

ppipe: $(objs)

gcc $(objs) -o ppipe

ppipe.o: $(srcs)

gcc $(opts) $(srcs)

clean:

rm ppipe *.o



0 0
原创粉丝点击