unix 父子进程间通信-无名管道

网友投稿 560 2022-09-23

unix 父子进程间通信-无名管道

unix 父子进程间通信-无名管道

#include  #include  #include  #include  #include  #include  #include     #define MAXLINE 100  char buf[MAXLINE];    int main(int argc, char** agrv) {         int pipefd[2];         int ret;                  if(0 != pipe(pipefd))//创建管道         {                 perror("pipe\n");                 exit(1);         }         //创建子程序         if((ret=fork()) < 0)//创建失败         {                 perror("fork\n");                 exit(1);                 }         else if(ret == 0)//子程序         {                 FILE* fp;                                  close(pipefd[0]);//关闭管道可读端                                  fp = fopen("./main.c","r"); //打开已存在可读文件                 if(NULL == fp)                 {                         perror("fopen\n");                         exit(1);                                 }                                  while(fgets(buf,MAXLINE,fp) != NULL)//将文件内容全部读入管道                 {                         int n = strlen(buf);                         if(n != write(pipefd[1],buf,n))                         {                                 perror("write\n");                                 exit(1);                                                    }                 }//end while                                                   if(ferror(fp))//在读的过程文件是否有报错                 {                         perror("ferror\n");                         exit(1);                                    }                                  close(pipefd[1]);//关闭文件可写端                 exit(0);//退出子程序         }         else         {                 close(pipefd[1]);//关闭管道可写端                                  if(-1 == wait(NULL))//等待子程序完全将文件内容读入到管道                 {                         perror("wait\n");                         exit(1);                                  }                                  if(dup2(pipefd[0],STDIN_FILENO) != STDIN_FILENO)//重新设置标准输入为管道可读端                 {                         perror("dup2\n");                         exit(1);                                           }                                  if(execl("/bin/more","more",(char*)0) < 0 )//分页程序 自动调用标准输入文件 显示管道内容                 {                         perror("execl\n");                         exit(1);                                   }                  }         return 0; }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:IBM存储配件FC号及描述翻译(unix360.part03)
下一篇:45道Python面试问题与解答(面试python常见问题)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~