管道的时间问题

来源:互联网 发布:xp php环境搭建 编辑:程序博客网 时间:2024/05/03 16:01

父子进程的时间是一起的  这个程序的运行 write1成功 2秒 write2成功  2秒后 read from pipe

 

Code:
  1. #include <unistd.h>  
  2. #include <sys/types.h>  
  3. #include <errno.h>  
  4. #include <stdio.h>  
  5. #include <stdlib.h>  
  6.  
  7.  
  8. #define MAXLINE 4096   /* max line length */   
  9.   
  10. int main(void)   
  11. {   
  12.  int n;   
  13.  int fd[2];   
  14.  pid_t pid;   
  15.  char line[MAXLINE];   
  16.   
  17.  if (pipe(fd) < 0)//创建管道   
  18.  {   
  19.   printf("pipe create error/n");   
  20.   return -1;   
  21.  }   
  22.  pid = fork();//创建进程   
  23.  if (pid < 0)    
  24.  {   
  25.   printf("fork  create error/n");   
  26.   return -1;   
  27.  }   
  28.  else if (pid > 0) //父进程   
  29.  {     
  30.   close(fd[0]);   
  31.   if(write(fd[1],"Hello",5)!=-1)   
  32.    printf("parent write1 success!/n");   
  33.      
  34.   sleep(2);   
  35.   if(write(fd[1]," ipc Pipe",9)!=-1)   
  36.    printf("parent write2 success!/n");   
  37.   close(fd[1]);   
  38.   //sleep(2);   
  39.   waitpid(pid,NULL,0);//等待子进程中断或结束   
  40.  }    
  41.  else /* child */  
  42.  {     
  43.   close(fd[1]);   
  44.   sleep(3);    
  45.   close(fd[1]);   
  46.   n = read(fd[0], line, MAXLINE);   
  47.   if(n > 0)   
  48.   {   
  49.    printf("%d numbers read from the pipe is: %s/n",n,line);   
  50.   }   
  51.   close(fd[0]);   
  52.   exit(0);   
  53.  }   
  54.  return 0;   
  55. }   
  56.