- 论坛徽章:
- 0
|
以下有两段代码,两段代码的区别就是在fork后if判断大于0还是等于0那里,其他代码都是一样的。
我想验证断开的管道的现象,据说是读端关闭后进行写操作会发送SIGPIPE信号导致进程终止,所以我在父进程(代码一)和子进程(代码二)分别写了一下管道,写之前sleep操作,同时另一个进程关闭读端。
问题:
1执行结果代码一在父进程write时提示了断开的管道,代码二在子进程write时直接退出了没有任何提示,这是为什么?
2write时如果读端已经关闭,write不是返回-1置errno为EPIPE吗,为什么没有显示write返回值啊,难道收到SIGPIPE信号进程直接退出了,write的说明有问题吗?
请高手不吝赐教。
代码一:- #include <unistd.h>
- #include <sys/types.h>
- main()
- {
- int pfd[2];
- int rt=0;
- char buf[10];
- pid_t pid;
- rt=pipe(pfd);
- printf("pfd[0]=%d pfd[2]=%d\n",pfd[0],pfd[1]);
- if((pid=fork())<0)
- perror("fork");
- else if(pid==0)
- { close(pfd[0]);
- close(pfd[1]);
- printf("p1 exit\n");
- exit(0);
- }
- else
- {
- printf("p20\n");
- sleep(3);
- printf("p21\n");
- close(pfd[0]);
- printf("p22\n");
- rt=write(pfd[1],"hello",6);
- printf("p2rt=%d\n",rt);
- close(pfd[1]);
- printf("p2exit\n");
- exit(0);
- }
- }
复制代码 执行结果:- [root@localhost 8]# ./a.out
- pfd[0]=3 pfd[2]=4
- p1 exit
- p20
- p21
- p22
- 断开的管道
- [root@localhost 8]#
复制代码 代码二:- #include <unistd.h>
- #include <sys/types.h>
- main()
- {
- int pfd[2];
- int rt=0;
- char buf[10];
- pid_t pid;
- rt=pipe(pfd);
- printf("pfd[0]=%d pfd[2]=%d\n",pfd[0],pfd[1]);
- if((pid=fork())<0)
- perror("fork");
- else if(pid>0)
- { close(pfd[0]);
- close(pfd[1]);
- printf("p1 exit\n");
- exit(0);
- }
- else
- {
- printf("p20\n");
- sleep(3);
- printf("p21\n");
- close(pfd[0]);
- printf("p22\n");
- rt=write(pfd[1],"hello",6);
- printf("p2rt=%d\n",rt);
- close(pfd[1]);
- printf("p2exit\n");
- exit(0);
- }
- }
复制代码- [root@localhost 8]# ./a.out
- pfd[0]=3 pfd[2]=4
- p20
- p1 exit
- [root@localhost 8]# p21
- p22
复制代码 |
|