huangcheng@ubuntu:~$ ./a.out recv sig=13 err=Broken pipe
父进程睡眠1s确保所有读端文件描述符都已经关闭,如果没有安装SIGPIPE信号的处理函数,则默认终止当前进程,即write函数不会返回,现在write错误返回-1,并置errno=EPIPE,对应的出错信息是Broken pipe。
四、如果所有管道写端对应的文件描述符被关闭(管道写端的引用计数等于0),那么管道中剩余的数据都被读取后,再次read会返回0
示例程序如下:
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<signal.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
void handler(int sig)
{
printf("recv sig=%d\n", sig);
}
int main(int argc, char *argv[])
{
signal(SIGPIPE, handler);
int pipefd[2];
if (pipe(pipefd) == -1)
ERR_EXIT("pipe error");
pid_t pid;
pid = fork();
if (pid == -1)
ERR_EXIT("fork error");
if (pid == 0)
{
close(pipefd[1]);
exit(EXIT_SUCCESS);
}
close(pipefd[1]);
sleep(1);
char buf[10] = {0};
int ret = read(pipefd[0], buf, 10);
printf("ret = %d\n", ret);
return 0;
}输出测试如下:
huangcheng@ubuntu:~$ ./a.out ret = 0同样地父进程睡眠1s确保所有的写端文件描述符都已经关闭,read返回0。
五、当要写入的数据量不大于PIPE_BUF时,linux将保证写入的原子性;当要写入的数据量大于PIPE_BUF时,linux将不再保证写入的原子性。
On Linux,PIPE_BUFis 4096 bytes。
The precise semantics depend on whether the file descriptor is nonblocking (O_NONBLOCK),whether there are multiple writers to the pipe, and on n, the number of bytes to be written。即由文件描述符的标志,是否有多个进程向管道写入以及写入的字节数所决定准确的语义,总共分4种情况,具体可man一下。
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-34100-3.html
家用电器设计寿命一般是多少年
俺发的你确定都看过