读取一个写段已经关闭的管道。
所有数据被读取后,read返回0,表示达到了文件尾部。
/*************************************************************************
> File Name: broken_pipe.c
> Author: CC
> Mail: [email protected]
> Created Time: 2018年09月08日 星期六 17时58分42秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<wait.h>
int main(void)
{
int fd[2];
if(pipe(fd) < 0){
perror("pipe error!\n");
exit(1);
}
pid_t pid;
pid = fork();
if(pid < 0){
perror("fork error!\n");
exit(1);
}else if(pid > 0){
//parent read,close write
close(fd[1]);
//写端关闭读数据,形成不完整管道,保证子进程先运行即可。
sleep(10);
while(1){
char c;
if((read(fd[0],&c,1)) == 0){
printf("\nwrite over!\n");
break;
}else{
printf("%c",c);
}
}
close(fd[0]);
wait(0);
}else{
//child wirte ,close read
close(fd[0]);
char *s = "Today is a lucky day!";
if((write(fd[1],s,sizeof(s))) != sizeof(s)){
perror("write error!\n");
exit(1);
}
close(fd[1]);
}
}
写一个读端已经被关闭的管道。
如果写一个已经被关闭的管道,则产生信号SIGPIPE,如果该信号或捕捉该信号并从处理程序返回,则write返回-1,同时errno设置为EPIPE。
/*************************************************************************
> File Name: broken_pipe2.c
> Author: CC
> Mail: [email protected]
> Created Time: 2018年09月08日 星期六 18时28分28秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
#include<errno.h>
#include<string.h>
#include<wait.h>
void sig_handler(int signo){
if(signo == SIGPIPE){
printf("SIGPIPE already get!\n");
}
}
int main(void)
{
int fd[2];
if(pipe(fd) < 0){
perror("pipe error!\n");
exit(1);
}
pid_t pid;
pid = fork();
if(pid < 0){
perror("fork error!\n");
exit(1);
}else if(pid == 0){
//child
//close all fd
close(fd[0]);
close(fd[1]);
}else{
//parent
//写入到不完整管道
sleep(10);
close(fd[0]);
//登记信号捕获函数
if(signal(SIGPIPE,sig_handler) == SIG_ERR){
perror("signal sigpipe error!\n");
exit(1);
}
char *s = "123";
if( write(fd[1],s,sizeof(s)) != sizeof(s)){
fprintf(stderr,"%s,%s\n",strerror(errno),(errno == EPIPE) ? "EPIPE" : "UNKONW");
}
close(fd[1]);
wait(0);
}
return 0;
}