pipe管道简单搭建

#include <stdio.h> 
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>

int main(void)
{
   int fd[2];
   pid_t pid;
   char str[1024] = "helloworld";
   char buf[1024];
   //先创建管道,然后fork,创建子进程,即使子进程继承管道
   //pipe为单工模式,想要双向通信,可以创建两个管道
   if(pipe(fd)<0)
   {
	  perror("pipe");
    exit(1);
   }
   pid= fork();
   //父写子读
   //fd[0]读端
   //fd[1]写端
   if(pid>0)
   {
    //父进程关闭读
     close(fd[0]);
     sleep(2);
     write(fd[1],str, strlen(str));
     close(fd[1]);//管道用完关闭
     wait(NULL);
   }
   else if(pid ==0)
   {
      int len,flags;
      //子进程关闭写
      close(fd[1]);
      //改变文件描述符为非阻塞模式
      flags=fcntl(fd[0], F_GETFL);
      flags|=O_NONBLOCK;
      fcntl(fd[0], F_SETFL, flags);

      tryagain:
          len = read(fd[0], buf, sizeof(buf));
          if(len==-1){
            //读到为空
            if(errno==EAGAIN){
              write(STDOUT_FILENO, "try again\n", 10);
              goto tryagain;
            }
            else{
              perror("read");
              close(fd[0]);
              exit(1);
            }
          }
      write(STDOUT_FILENO,buf, len);
      close(fd[0]);//管道用完关闭
   }
   else
   {
    perror("fork");
    exit(1);
   }
 return 0;
}         

猜你喜欢

转载自blog.csdn.net/qq_22753933/article/details/83343311