|
|
发表于 2006-11-9 15:15:30
|
显示全部楼层
- #include <unistd.h>
- #include <sys/types.h>
- #include <errno.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- int main(int argc, char **argv)
- {
- int pipe_fd[2];
- pid_t pid;
- char r_buf[100];
- char w_buf[4];
- char *p_wbuf;
- int r_num;
- int cmd;
- memset(r_buf, 0, sizeof(r_buf));
- memset(w_buf, 0, sizeof(w_buf));
- p_wbuf=w_buf;
- if(pipe(pipe_fd) < 0)
- {
- printf("pipe create error!\n");
- return -1;
- }
- if((pid=fork()) == 0)
- {
- // printf("\n");
- close(pipe_fd[1]);
- while(1)
- {
- sleep(3);
- r_num=read(pipe_fd[0], r_buf, 100);
- printf("read num is %d", r_num);
- printf(" the data read from the pipe is %d\n", atoi(r_buf));
- }
- close(pipe_fd[0]);
- exit(1);
- }
- else if(pid >0)
- {
- close(pipe_fd[0]);
- strcpy(w_buf, "111");
- if(write(pipe_fd[1], w_buf, 4) != -1)
- {
- printf("parent write over\n");
- }
- sleep(10);
- close(pipe_fd[1]);
- printf("parent close fd[1] over\n");
- }
- }
复制代码
改一下代码,让父进程sleep(10)秒再去关闭pipe的写端,子进程还是照样先sleep(3)秒。执行结果是这样子的,父进程写完"111"串后就休眠10秒,子进程休眠3秒后苏醒读pipe,读到111,由于是一个永远为真的循环,再次休眠3秒后再次读pipe,这时候因为父进程不再写入数据,并且写端未被关闭,所以blocking,父进程休眠10秒时间到了以后苏醒关闭pipe的写端,那么子进程blocking的那次read就会返回,返回值是0。 |
|