父子进程的时间是一起的 这个程序的运行 write1成功 2秒 write2成功 2秒后 read from pipe
- #include <unistd.h>
- #include <sys/types.h>
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define MAXLINE 4096 /* max line length */
- int main(void)
- {
- int n;
- int fd[2];
- pid_t pid;
- char line[MAXLINE];
- if (pipe(fd) < 0)//创建管道
- {
- printf("pipe create error/n");
- return -1;
- }
- pid = fork();//创建进程
- if (pid < 0)
- {
- printf("fork create error/n");
- return -1;
- }
- else if (pid > 0) //父进程
- {
- close(fd[0]);
- if(write(fd[1],"Hello",5)!=-1)
- printf("parent write1 success!/n");
- sleep(2);
- if(write(fd[1]," ipc Pipe",9)!=-1)
- printf("parent write2 success!/n");
- close(fd[1]);
- //sleep(2);
- waitpid(pid,NULL,0);//等待子进程中断或结束
- }
- else /* child */
- {
- close(fd[1]);
- sleep(3);
- close(fd[1]);
- n = read(fd[0], line, MAXLINE);
- if(n > 0)
- {
- printf("%d numbers read from the pipe is: %s/n",n,line);
- }
- close(fd[0]);
- exit(0);
- }
- return 0;
- }